@siphon-project/control 0.5.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.
package/dist/index.js CHANGED
@@ -110,6 +110,19 @@ var SipVerb = {
110
110
  Progress: "progress",
111
111
  Reject: "reject",
112
112
  Hangup: "hangup",
113
+ /**
114
+ * Abandon an **unanswered** call with nothing on the wire: no final response,
115
+ * no CANCEL, and the call released so the stack stops tracking it.
116
+ *
117
+ * The third way out of a parked call, and the only silent one. `reject` and an
118
+ * unanswered `hangup` both answer, and on a publicly reachable SIP port that
119
+ * answer is the prize: a `404` to an INVITE for a number nobody claims
120
+ * confirms the number to an enumeration sweep, where silence leaves it unable
121
+ * to tell a missing extension from a filtered one. Refused
122
+ * (`invalid_state`) on an answered call, whose dialog is owed a BYE
123
+ * (RFC 3261 §15) — that is {@link SipVerb.Hangup}'s job.
124
+ */
125
+ Drop: "drop",
113
126
  Refer: "refer",
114
127
  Route: "route",
115
128
  /**
@@ -152,6 +165,9 @@ function transferOutcome(event) {
152
165
  function isBridgeFinal(name) {
153
166
  return name === "ChannelBridged" || name === "BridgeFailed";
154
167
  }
168
+ function isDialFinal(name) {
169
+ return name === "DialAnswered" || name === "DialFailed";
170
+ }
155
171
 
156
172
  // src/internal.ts
157
173
  var AsyncQueue = class {
@@ -649,7 +665,15 @@ function stringValue(result) {
649
665
  return null;
650
666
  }
651
667
  function originateArgs(channel, to, media, options) {
652
- const args = { channel, to };
668
+ return originateCommonArgs({ channel, to }, media, options);
669
+ }
670
+ function originateAorArgs(channel, aor, media, options, ring) {
671
+ const args = originateCommonArgs({ channel, aor }, media, options);
672
+ if (ring?.strategy !== void 0) args.strategy = ring.strategy;
673
+ if (ring?.totalTimeout !== void 0) args.total_timeout = ring.totalTimeout;
674
+ return args;
675
+ }
676
+ function originateCommonArgs(args, media, options) {
653
677
  if ("anchor" in media) {
654
678
  args.media = true;
655
679
  if (media.profile !== void 0) args.profile = media.profile;
@@ -725,8 +749,30 @@ function dialArgs(targets, options) {
725
749
  args.p_asserted_identity = options.pAssertedIdentity;
726
750
  }
727
751
  if (options.privacy !== void 0) args.privacy = options.privacy;
752
+ if (options.ringback !== void 0 && options.onAnswer !== "bridge") {
753
+ throw new TypeError(
754
+ `dial "ringback" requires onAnswer: "bridge" \u2014 a connecting dial gives the caller the phones' own ringback, and siphon refuses it there`
755
+ );
756
+ }
757
+ if (options.onAnswer !== void 0) args.on_answer = options.onAnswer;
758
+ if (options.ringback !== void 0) args.ringback = options.ringback;
728
759
  return args;
729
760
  }
761
+ function branchList(value) {
762
+ if (!Array.isArray(value)) return void 0;
763
+ const branches = [];
764
+ for (const entry of value) {
765
+ if (typeof entry !== "object" || entry === null) continue;
766
+ const { leg_id, leg_sip_call_id, target, aor } = entry;
767
+ if (typeof leg_id !== "string" || typeof leg_sip_call_id !== "string" || typeof target !== "string") {
768
+ continue;
769
+ }
770
+ const branch = { leg_id, leg_sip_call_id, target };
771
+ if (typeof aor === "string") branch.aor = aor;
772
+ branches.push(branch);
773
+ }
774
+ return branches;
775
+ }
730
776
  function recordStartArgs(options) {
731
777
  const args = {};
732
778
  if (!options) return args;
@@ -885,6 +931,48 @@ var Call = class {
885
931
  async hangup(reason) {
886
932
  await this.terminate(reason);
887
933
  }
934
+ /**
935
+ * Abandon this **unanswered** call with nothing on the wire — no final
936
+ * response, no CANCEL — and release it.
937
+ *
938
+ * The third way out of a parked call, and the only silent one.
939
+ * {@link Call.reject} and an unanswered {@link Call.hangup} both answer, and
940
+ * on a SIP port reachable from the internet that answer is the prize: a `404`
941
+ * to an INVITE for a number nobody claims confirms the number to an
942
+ * enumeration sweep, where silence leaves it unable to tell a missing
943
+ * extension from a filtered one. Your controller holds the only knowledge of
944
+ * which numbers are real, so it is the only thing that can decide an INVITE is
945
+ * unsolicited.
946
+ *
947
+ * Not a way to hang up: an answered dialog is owed a BYE (RFC 3261 §15), so an
948
+ * answered call rejects with `code === "invalid_state"` rather than being
949
+ * orphaned — use {@link Call.hangup} there. A call that has already ended
950
+ * rejects with `code === "not_found"`.
951
+ *
952
+ * `reason` is for the record, not the wire: it reaches siphon's log and the
953
+ * CDR (`sip_reason`, beside `disconnect_initiator: "control"` and no response
954
+ * code), so a dropped call reads as deliberate rather than as a leak.
955
+ *
956
+ * `options.ban` makes the verdict stick: siphon also scores the caller's
957
+ * source address in the `security.failed_auth_ban` store, so a source the
958
+ * controller keeps dropping is banned at the transport before its next INVITE
959
+ * is parsed. The weight follows how far the address can be believed — a
960
+ * strong signal over TCP / TLS / WS / WSS, whose handshake proved it, and
961
+ * weight 1 over UDP, where one datagram can name any address. A no-op without
962
+ * `security.failed_auth_ban`; `trusted_cidrs` are never scored; only a
963
+ * successful drop scores, so a refused one leaves the source alone. Sent only
964
+ * when `true`.
965
+ */
966
+ async drop(reason, options) {
967
+ const args = {};
968
+ if (reason !== void 0) {
969
+ args.reason = reason;
970
+ }
971
+ if (options?.ban === true) {
972
+ args.ban = true;
973
+ }
974
+ await this.sip(SipVerb.Drop, args);
975
+ }
888
976
  /**
889
977
  * Send an in-dialog REFER on the A-leg (blind transfer).
890
978
  *
@@ -956,7 +1044,11 @@ var Call = class {
956
1044
  * The first 2xx answers the caller with the winner's SDP and the pair becomes
957
1045
  * an ordinary two-leg call, still owned by this app. A failure or timeout
958
1046
  * arrives as a `DialFailed` event with the caller still ringing and still
959
- * parked, so the app decides what happens next.
1047
+ * parked, so the app decides what happens next. Every branch is named as it is
1048
+ * created (`DialBranch`) and as it ends (`DialBranchFailed` / `DialAnswered`),
1049
+ * by its `leg_id` and `leg_sip_call_id` — see
1050
+ * {@link import("./protocol").DialBranchPayload} — and `DialFailed` lists them
1051
+ * all.
960
1052
  *
961
1053
  * Each target is a URI (dialed as written) or an `{aor}` (forked to every
962
1054
  * registered contact over its own flow) — see {@link DialTarget}, and note
@@ -974,6 +1066,23 @@ var Call = class {
974
1066
  * answered, which is what this verb exists to avoid), `"bad_request"` (an
975
1067
  * empty or malformed target list) or `"unsupported_verb"` (a strategy siphon
976
1068
  * does not implement).
1069
+ *
1070
+ * A caller the app answered on purpose, to play it prompts first, is what
1071
+ * `onAnswer: "bridge"` is for (see {@link DialOptions.onAnswer}): the phones
1072
+ * ring while the caller hears `ringback`, and the first to answer is bridged
1073
+ * to it. The reply then also carries `onAnswer`, `groupId`, `totalTimeout`,
1074
+ * `ringback` and the `branches` rung. It refuses with `"invalid_state"` a
1075
+ * caller that is not answered, not anchored, already bridged or already has
1076
+ * phones ringing for it.
1077
+ *
1078
+ * ```ts
1079
+ * await call.answerAnchored();
1080
+ * await call.play({ file: "/prompts/menu.wav" });
1081
+ * await call.dial([{ aor: "sip:204@pbx.example" }], {
1082
+ * onAnswer: "bridge",
1083
+ * ringback: "ringback_eu",
1084
+ * });
1085
+ * ```
977
1086
  */
978
1087
  async dial(targets, options) {
979
1088
  const result = await this.sip(SipVerb.Dial, dialArgs(targets, options));
@@ -991,7 +1100,15 @@ var Call = class {
991
1100
  channel: text("channel") ?? this.channelId,
992
1101
  targets: count("targets"),
993
1102
  strategy: text("strategy"),
994
- timeout: count("timeout")
1103
+ timeout: count("timeout"),
1104
+ onAnswer: text("on_answer"),
1105
+ groupId: text("group_id"),
1106
+ totalTimeout: count("total_timeout"),
1107
+ ringback: (() => {
1108
+ const value = result?.ringback;
1109
+ return typeof value === "string" || typeof value === "boolean" ? value : void 0;
1110
+ })(),
1111
+ branches: branchList(result?.branches)
995
1112
  };
996
1113
  }
997
1114
  /**
@@ -1185,23 +1302,55 @@ var Call = class {
1185
1302
  await this.sip(SipVerb.Unhold, {});
1186
1303
  }
1187
1304
  /**
1188
- * Attach a WebSocket audio tee — stream a copy of the call's decoded audio to
1189
- * `wsUri` while the call keeps relaying. siphon-rtp backend only: rtpengine /
1190
- * rtpproxy reject with `code === "unsupported_verb"` (`error.isUnsupportedVerb()`).
1305
+ * Attach a WebSocket audio stream to `wsUri`: an additive tee (the default)
1306
+ * or a takeover bridge, as `options.mode` says.
1307
+ *
1308
+ * ```ts
1309
+ * // Transcribe the caller at 16 kHz; the call keeps relaying.
1310
+ * // siphon expands `{call_id}` to the call's SIP Call-ID.
1311
+ * await call.streamStart("wss://ai.example/stream/{call_id}", {
1312
+ * direction: "caller",
1313
+ * sampleRate: 16000,
1314
+ * });
1315
+ * // Hand the leg to a voice agent; the agent is now the far side, with the
1316
+ * // server's `voice_ai` profile's rate, echo cancellation and barge-in.
1317
+ * await call.streamStart("wss://ai.example/agent", { mode: "bridge", profile: "voice_ai" });
1318
+ * ```
1319
+ *
1320
+ * A bridge on a leg that already has one re-points it in place. `wsUri` may
1321
+ * use `{call_id}` / `{from_tag}` / `{from_user}` / `{to_user}`, which siphon
1322
+ * expands before the engine sees it: `{call_id}` expands to the call's SIP
1323
+ * Call-ID ({@link Call.sipCallId}), not the control-plane `callId`. An
1324
+ * unknown placeholder rejects with `bad_request`. siphon-rtp backend only: rtpengine / rtpproxy
1325
+ * reject with `code === "unsupported_verb"` (`error.isUnsupportedVerb()`).
1191
1326
  */
1192
1327
  async streamStart(wsUri, options) {
1193
- const args = { ws_uri: wsUri };
1328
+ const args = {
1329
+ ws_uri: wsUri,
1330
+ mode: options?.mode ?? "tee"
1331
+ };
1194
1332
  if (options?.direction !== void 0) {
1195
1333
  args.direction = options.direction;
1196
1334
  }
1197
1335
  if (options?.channels !== void 0) {
1198
1336
  args.channels = options.channels;
1199
1337
  }
1338
+ if (options?.sampleRate !== void 0) {
1339
+ args.sample_rate = options.sampleRate;
1340
+ }
1341
+ if (options?.profile !== void 0) {
1342
+ args.profile = options.profile;
1343
+ }
1200
1344
  await this.sip(SipVerb.StreamStart, args);
1201
1345
  }
1202
- /** Detach the WebSocket audio tee (idempotent on siphon-rtp). */
1203
- async streamStop() {
1204
- await this.sip(SipVerb.StreamStop, {});
1346
+ /**
1347
+ * Detach the WebSocket stream of `options.mode` (`"tee"` by default, sent
1348
+ * explicitly). A tee detach is idempotent. A bridge detach is not: the
1349
+ * engine refuses one where there is no relay to hand the call back to, and
1350
+ * that rejects rather than leaving a live call with no audio path.
1351
+ */
1352
+ async streamStop(options) {
1353
+ await this.sip(SipVerb.StreamStop, { mode: options?.mode ?? "tee" });
1205
1354
  }
1206
1355
  /**
1207
1356
  * Record this call's decoded audio to a wav file.
@@ -1278,10 +1427,14 @@ var CallStream = class {
1278
1427
  var SipFacade = class {
1279
1428
  handler = null;
1280
1429
  callQueue = null;
1430
+ appHandler = null;
1281
1431
  channels = /* @__PURE__ */ new Map();
1282
1432
  setHandler(handler) {
1283
1433
  this.handler = handler;
1284
1434
  }
1435
+ setAppHandler(handler) {
1436
+ this.appHandler = handler;
1437
+ }
1285
1438
  setStream() {
1286
1439
  const queue = new AsyncQueue();
1287
1440
  this.callQueue = queue;
@@ -1322,6 +1475,12 @@ var SipFacade = class {
1322
1475
  }
1323
1476
  } else if (frame.channel) {
1324
1477
  this.route(frame.channel, callEventFromFrame(frame));
1478
+ } else {
1479
+ this.appHandler?.({
1480
+ kind: sipEventKind(frame.event),
1481
+ payload: frame.payload ?? null,
1482
+ frame
1483
+ });
1325
1484
  }
1326
1485
  }
1327
1486
  reattach(snapshot, transport) {
@@ -1389,6 +1548,15 @@ var SipClient = class _SipClient {
1389
1548
  calls() {
1390
1549
  return this.facade.setStream();
1391
1550
  }
1551
+ /**
1552
+ * Register a handler for application-level events — the ones an app opts
1553
+ * into with `control.apps[].events` (`RegistrationChanged`,
1554
+ * `DialogStateChanged`), which concern no channel and so reach no call.
1555
+ * Replaces any previous handler.
1556
+ */
1557
+ onAppEvent(handler) {
1558
+ this.facade.setAppHandler(handler);
1559
+ }
1392
1560
  /** Drive the supervised connection loop (reconnect + resync). */
1393
1561
  run() {
1394
1562
  return this.client.run();
@@ -1433,6 +1601,62 @@ var SipClient = class _SipClient {
1433
1601
  sipCallId: text("sip_call_id")
1434
1602
  };
1435
1603
  }
1604
+ /**
1605
+ * Ring every phone registered at `aor` under a caller-supplied channel id —
1606
+ * {@link SipClient.originate} for a phone rather than a URI.
1607
+ *
1608
+ * A phone registered over TCP, TLS or WSS behind NAT is reachable only on the
1609
+ * connection it registered over, and one registered through an edge proxy
1610
+ * only through its Path, so resolving its Contact as a `to` reaches nothing.
1611
+ * This rings each registered contact over its own flow and Path (RFC 5626
1612
+ * §5.3, RFC 3327 §5.3), each as its own originated call with `options`
1613
+ * applied. The first phone to answer wins; every other one still ringing is
1614
+ * CANCELled. `ring` says how the phones are rung ({@link OriginateRing}).
1615
+ *
1616
+ * An AoR with nobody registered rejects with `code === "not_found"` and
1617
+ * `details.reason === "no_contacts"`, with nothing on the wire.
1618
+ *
1619
+ * While the phones ring the channel is bound to the group: its events carry
1620
+ * the {@link OriginatedGroup.groupId} as their `call_id`, and each leg's own
1621
+ * Call-ID is in the payload (`DialBranch`, `DialBranchFailed`). From
1622
+ * `DialAnswered` on, the channel is the winning phone's call. A `hangup`
1623
+ * while they ring CANCELs every one; `drop` is refused (`invalid_state`),
1624
+ * since siphon is their caller and there is no response to withhold.
1625
+ *
1626
+ * ```ts
1627
+ * const group = await client.originateAor(
1628
+ * "wake-201",
1629
+ * "sip:201@pbx.example",
1630
+ * { anchor: true },
1631
+ * { from: "sip:reception@pbx.example", timeout: 25 },
1632
+ * { strategy: "parallel" },
1633
+ * );
1634
+ * ```
1635
+ */
1636
+ async originateAor(channel, aor, media, options, ring) {
1637
+ const result = await this.client.command(
1638
+ MODULE_SIP,
1639
+ "originate",
1640
+ null,
1641
+ originateAorArgs(channel, aor, media, options, ring)
1642
+ );
1643
+ const text = (name) => {
1644
+ const value = result?.[name];
1645
+ return typeof value === "string" ? value : void 0;
1646
+ };
1647
+ const count = (name) => {
1648
+ const value = result?.[name];
1649
+ return typeof value === "number" ? value : void 0;
1650
+ };
1651
+ return {
1652
+ channel: text("channel") ?? channel,
1653
+ groupId: text("group_id"),
1654
+ aor: text("aor"),
1655
+ strategy: text("strategy"),
1656
+ totalTimeout: count("total_timeout"),
1657
+ branches: branchList(result?.branches) ?? []
1658
+ };
1659
+ }
1436
1660
  /** Send a raw command on any module (the generic escape hatch). */
1437
1661
  command(module, verb, target, args) {
1438
1662
  return this.client.command(module, verb, target, args);
@@ -1481,6 +1705,6 @@ var SipServer = class _SipServer {
1481
1705
  }
1482
1706
  };
1483
1707
 
1484
- export { Call, CallStream, ControlClient, ControlError, ControlServer, DESCRIBE, EventStream, GET_VAR, HELLO, MODULE_SIP, MODULE_SMPP, MODULE_SS7, PROTOCOL_VERSION, RESYNC, SET_VAR, SUBPROTOCOL, SipClient, SipServer, SipVerb, dialArgs, encodeCommand, isBridgeFinal, isTransferFinal, originateArgs, parseInboundFrame, recordStartArgs, recordStopArgs, sipEventKind, transferOutcome };
1708
+ export { Call, CallStream, ControlClient, ControlError, ControlServer, DESCRIBE, EventStream, GET_VAR, HELLO, MODULE_SIP, MODULE_SMPP, MODULE_SS7, PROTOCOL_VERSION, RESYNC, SET_VAR, SUBPROTOCOL, SipClient, SipServer, SipVerb, dialArgs, encodeCommand, isBridgeFinal, isDialFinal, isTransferFinal, originateAorArgs, originateArgs, parseInboundFrame, recordStartArgs, recordStopArgs, sipEventKind, transferOutcome };
1485
1709
  //# sourceMappingURL=index.js.map
1486
1710
  //# sourceMappingURL=index.js.map