@siphon-project/control 0.4.0 → 0.6.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;
@@ -718,8 +742,37 @@ function dialArgs(targets, options) {
718
742
  if (options.strategy !== void 0) args.strategy = options.strategy;
719
743
  if (options.timeout !== void 0) args.timeout = options.timeout;
720
744
  if (options.headers !== void 0) args.headers = options.headers;
745
+ if (options.profile !== void 0) args.profile = options.profile;
746
+ if (options.from !== void 0) args.from = options.from;
747
+ if (options.fromDisplay !== void 0) args.from_display = options.fromDisplay;
748
+ if (options.pAssertedIdentity !== void 0) {
749
+ args.p_asserted_identity = options.pAssertedIdentity;
750
+ }
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;
721
759
  return args;
722
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
+ }
723
776
  function recordStartArgs(options) {
724
777
  const args = {};
725
778
  if (!options) return args;
@@ -878,6 +931,48 @@ var Call = class {
878
931
  async hangup(reason) {
879
932
  await this.terminate(reason);
880
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
+ }
881
976
  /**
882
977
  * Send an in-dialog REFER on the A-leg (blind transfer).
883
978
  *
@@ -949,7 +1044,11 @@ var Call = class {
949
1044
  * The first 2xx answers the caller with the winner's SDP and the pair becomes
950
1045
  * an ordinary two-leg call, still owned by this app. A failure or timeout
951
1046
  * arrives as a `DialFailed` event with the caller still ringing and still
952
- * 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.
953
1052
  *
954
1053
  * Each target is a URI (dialed as written) or an `{aor}` (forked to every
955
1054
  * registered contact over its own flow) — see {@link DialTarget}, and note
@@ -967,6 +1066,23 @@ var Call = class {
967
1066
  * answered, which is what this verb exists to avoid), `"bad_request"` (an
968
1067
  * empty or malformed target list) or `"unsupported_verb"` (a strategy siphon
969
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
+ * ```
970
1086
  */
971
1087
  async dial(targets, options) {
972
1088
  const result = await this.sip(SipVerb.Dial, dialArgs(targets, options));
@@ -984,7 +1100,15 @@ var Call = class {
984
1100
  channel: text("channel") ?? this.channelId,
985
1101
  targets: count("targets"),
986
1102
  strategy: text("strategy"),
987
- 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)
988
1112
  };
989
1113
  }
990
1114
  /**
@@ -1178,23 +1302,51 @@ var Call = class {
1178
1302
  await this.sip(SipVerb.Unhold, {});
1179
1303
  }
1180
1304
  /**
1181
- * Attach a WebSocket audio tee — stream a copy of the call's decoded audio to
1182
- * `wsUri` while the call keeps relaying. siphon-rtp backend only: rtpengine /
1183
- * 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.
1316
+ * await call.streamStart("wss://ai.example/agent", { mode: "bridge" });
1317
+ * ```
1318
+ *
1319
+ * A bridge on a leg that already has one re-points it in place. `wsUri` may
1320
+ * use `{call_id}` / `{from_tag}` / `{from_user}` / `{to_user}`, which siphon
1321
+ * expands before the engine sees it: `{call_id}` expands to the call's SIP
1322
+ * Call-ID ({@link Call.sipCallId}), not the control-plane `callId`. An
1323
+ * unknown placeholder rejects with `bad_request`. siphon-rtp backend only: rtpengine / rtpproxy
1324
+ * reject with `code === "unsupported_verb"` (`error.isUnsupportedVerb()`).
1184
1325
  */
1185
1326
  async streamStart(wsUri, options) {
1186
- const args = { ws_uri: wsUri };
1327
+ const args = {
1328
+ ws_uri: wsUri,
1329
+ mode: options?.mode ?? "tee"
1330
+ };
1187
1331
  if (options?.direction !== void 0) {
1188
1332
  args.direction = options.direction;
1189
1333
  }
1190
1334
  if (options?.channels !== void 0) {
1191
1335
  args.channels = options.channels;
1192
1336
  }
1337
+ if (options?.sampleRate !== void 0) {
1338
+ args.sample_rate = options.sampleRate;
1339
+ }
1193
1340
  await this.sip(SipVerb.StreamStart, args);
1194
1341
  }
1195
- /** Detach the WebSocket audio tee (idempotent on siphon-rtp). */
1196
- async streamStop() {
1197
- await this.sip(SipVerb.StreamStop, {});
1342
+ /**
1343
+ * Detach the WebSocket stream of `options.mode` (`"tee"` by default, sent
1344
+ * explicitly). A tee detach is idempotent. A bridge detach is not: the
1345
+ * engine refuses one where there is no relay to hand the call back to, and
1346
+ * that rejects rather than leaving a live call with no audio path.
1347
+ */
1348
+ async streamStop(options) {
1349
+ await this.sip(SipVerb.StreamStop, { mode: options?.mode ?? "tee" });
1198
1350
  }
1199
1351
  /**
1200
1352
  * Record this call's decoded audio to a wav file.
@@ -1271,10 +1423,14 @@ var CallStream = class {
1271
1423
  var SipFacade = class {
1272
1424
  handler = null;
1273
1425
  callQueue = null;
1426
+ appHandler = null;
1274
1427
  channels = /* @__PURE__ */ new Map();
1275
1428
  setHandler(handler) {
1276
1429
  this.handler = handler;
1277
1430
  }
1431
+ setAppHandler(handler) {
1432
+ this.appHandler = handler;
1433
+ }
1278
1434
  setStream() {
1279
1435
  const queue = new AsyncQueue();
1280
1436
  this.callQueue = queue;
@@ -1315,6 +1471,12 @@ var SipFacade = class {
1315
1471
  }
1316
1472
  } else if (frame.channel) {
1317
1473
  this.route(frame.channel, callEventFromFrame(frame));
1474
+ } else {
1475
+ this.appHandler?.({
1476
+ kind: sipEventKind(frame.event),
1477
+ payload: frame.payload ?? null,
1478
+ frame
1479
+ });
1318
1480
  }
1319
1481
  }
1320
1482
  reattach(snapshot, transport) {
@@ -1382,6 +1544,15 @@ var SipClient = class _SipClient {
1382
1544
  calls() {
1383
1545
  return this.facade.setStream();
1384
1546
  }
1547
+ /**
1548
+ * Register a handler for application-level events — the ones an app opts
1549
+ * into with `control.apps[].events` (`RegistrationChanged`,
1550
+ * `DialogStateChanged`), which concern no channel and so reach no call.
1551
+ * Replaces any previous handler.
1552
+ */
1553
+ onAppEvent(handler) {
1554
+ this.facade.setAppHandler(handler);
1555
+ }
1385
1556
  /** Drive the supervised connection loop (reconnect + resync). */
1386
1557
  run() {
1387
1558
  return this.client.run();
@@ -1426,6 +1597,62 @@ var SipClient = class _SipClient {
1426
1597
  sipCallId: text("sip_call_id")
1427
1598
  };
1428
1599
  }
1600
+ /**
1601
+ * Ring every phone registered at `aor` under a caller-supplied channel id —
1602
+ * {@link SipClient.originate} for a phone rather than a URI.
1603
+ *
1604
+ * A phone registered over TCP, TLS or WSS behind NAT is reachable only on the
1605
+ * connection it registered over, and one registered through an edge proxy
1606
+ * only through its Path, so resolving its Contact as a `to` reaches nothing.
1607
+ * This rings each registered contact over its own flow and Path (RFC 5626
1608
+ * §5.3, RFC 3327 §5.3), each as its own originated call with `options`
1609
+ * applied. The first phone to answer wins; every other one still ringing is
1610
+ * CANCELled. `ring` says how the phones are rung ({@link OriginateRing}).
1611
+ *
1612
+ * An AoR with nobody registered rejects with `code === "not_found"` and
1613
+ * `details.reason === "no_contacts"`, with nothing on the wire.
1614
+ *
1615
+ * While the phones ring the channel is bound to the group: its events carry
1616
+ * the {@link OriginatedGroup.groupId} as their `call_id`, and each leg's own
1617
+ * Call-ID is in the payload (`DialBranch`, `DialBranchFailed`). From
1618
+ * `DialAnswered` on, the channel is the winning phone's call. A `hangup`
1619
+ * while they ring CANCELs every one; `drop` is refused (`invalid_state`),
1620
+ * since siphon is their caller and there is no response to withhold.
1621
+ *
1622
+ * ```ts
1623
+ * const group = await client.originateAor(
1624
+ * "wake-201",
1625
+ * "sip:201@pbx.example",
1626
+ * { anchor: true },
1627
+ * { from: "sip:reception@pbx.example", timeout: 25 },
1628
+ * { strategy: "parallel" },
1629
+ * );
1630
+ * ```
1631
+ */
1632
+ async originateAor(channel, aor, media, options, ring) {
1633
+ const result = await this.client.command(
1634
+ MODULE_SIP,
1635
+ "originate",
1636
+ null,
1637
+ originateAorArgs(channel, aor, media, options, ring)
1638
+ );
1639
+ const text = (name) => {
1640
+ const value = result?.[name];
1641
+ return typeof value === "string" ? value : void 0;
1642
+ };
1643
+ const count = (name) => {
1644
+ const value = result?.[name];
1645
+ return typeof value === "number" ? value : void 0;
1646
+ };
1647
+ return {
1648
+ channel: text("channel") ?? channel,
1649
+ groupId: text("group_id"),
1650
+ aor: text("aor"),
1651
+ strategy: text("strategy"),
1652
+ totalTimeout: count("total_timeout"),
1653
+ branches: branchList(result?.branches) ?? []
1654
+ };
1655
+ }
1429
1656
  /** Send a raw command on any module (the generic escape hatch). */
1430
1657
  command(module, verb, target, args) {
1431
1658
  return this.client.command(module, verb, target, args);
@@ -1474,6 +1701,6 @@ var SipServer = class _SipServer {
1474
1701
  }
1475
1702
  };
1476
1703
 
1477
- 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 };
1704
+ 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 };
1478
1705
  //# sourceMappingURL=index.js.map
1479
1706
  //# sourceMappingURL=index.js.map