@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/README.md CHANGED
@@ -98,6 +98,7 @@ await client.command("sip", "answer", { channel: "ch1" }, { code: 200 });
98
98
  | `reject(code, reason?)` | `reject` (`sip`) | final non-2xx + teardown |
99
99
  | `terminate(reason?)` | `hangup` (`sip`) | primary teardown name |
100
100
  | `hangup(reason?)` | `hangup` (`sip`) | alias for `terminate` |
101
+ | `drop(reason?, options?)` | `drop` (`sip`) | abandon an **unanswered** call with nothing on the wire — no final response, no CANCEL. Refused on an answered call, whose dialog is owed a BYE; the reason goes to the log and the CDR. `{ ban: true }` also scores the caller's source toward `security.failed_auth_ban` (strong over TCP/TLS/WS/WSS, weight 1 over UDP; a no-op without the ban store) |
101
102
  | `refer(to)` | `refer` (`sip`) | in-dialog REFER (blind transfer) |
102
103
  | `transfer(to)` | `refer` (`sip`) | alias for `refer` |
103
104
  | `referReplaces(to, replaces)` | `refer` (`sip`) | attended transfer (RFC 3891) |
@@ -110,7 +111,7 @@ await client.command("sip", "answer", { channel: "ch1" }, { code: 200 });
110
111
  | `rejectRefer(code, reason?)` | `reject_refer` (`sip`) | ‡ |
111
112
  | `bridge(withChannel, options?)` | `bridge` (`sip`) | join two answered legs; the verdict arrives as `ChannelBridged` / `BridgeFailed` |
112
113
  | `unbridge(reason?)` | `unbridge` (`sip`) | break the bridge — both legs stay answered, owned and held |
113
- | `dial(targets, options?)` | `dial` (`sip`) | ring B-legs while the caller stays **unanswered** and this app keeps the channel. A target is `{uri}` (dialed as written) or `{aor}` (forked to every registered contact over its own flow); one naming both, or neither, throws |
114
+ | `dial(targets, options?)` | `dial` (`sip`) | ring B-legs while the caller stays **unanswered** and this app keeps the channel. A target is `{uri}` (dialed as written) or `{aor}` (forked to every registered contact over its own flow); one naming both, or neither, throws. `onAnswer: "bridge"` rings phones for an **answered**, anchored caller and bridges the first to pick up, with `ringback` playing meanwhile; `ringback` without it throws |
114
115
  | `recordStart(options?)` | `record_start` (`sip`) | record the call's decoded audio to a wav file; the reply names the `recordingId`, `RecordingFinished` says the file is closed. siphon-rtp only |
115
116
  | `recordStop(recordingId?)` | `record_stop` (`sip`) | stop one recording, or every recording on the call when no id is given |
116
117
  | `playFile(file)` | `play` (`sip`) | ‡ media |
@@ -121,6 +122,14 @@ await client.command("sip", "answer", { channel: "ch1" }, { code: 200 });
121
122
  Identity/context getters: `channelId`, `callId`, `sipCallId`, `app`, `payload`,
122
123
  `reattached`.
123
124
 
125
+ Placing a call lives on `SipClient`, since it creates a channel rather than
126
+ addressing one:
127
+
128
+ | Method | Wire verb (`module`) | Notes |
129
+ | --- | --- | --- |
130
+ | `originate(channel, to, media, options?)` | `originate` (`sip`) | one URI, resolved as written; resolves once the INVITE is on the wire |
131
+ | `originateAor(channel, aor, media, options?, ring?)` | `originate` (`sip`) | ring every phone registered at `aor` over its own flow and Path; first to answer wins. `ring` is `{ strategy?, totalTimeout? }`. Nobody registered is `not_found` (`no_contacts`); `drop` is refused while the phones ring, use `hangup` |
132
+
124
133
  ‡ Accepted verb names the Phase-1 server answers with a `ControlError` whose
125
134
  `.code === "unsupported_verb"` (`error.isUnsupportedVerb()`) until it implements
126
135
  them. They send a real command — nothing is stubbed client-side.
package/dist/index.cjs CHANGED
@@ -116,6 +116,19 @@ var SipVerb = {
116
116
  Progress: "progress",
117
117
  Reject: "reject",
118
118
  Hangup: "hangup",
119
+ /**
120
+ * Abandon an **unanswered** call with nothing on the wire: no final response,
121
+ * no CANCEL, and the call released so the stack stops tracking it.
122
+ *
123
+ * The third way out of a parked call, and the only silent one. `reject` and an
124
+ * unanswered `hangup` both answer, and on a publicly reachable SIP port that
125
+ * answer is the prize: a `404` to an INVITE for a number nobody claims
126
+ * confirms the number to an enumeration sweep, where silence leaves it unable
127
+ * to tell a missing extension from a filtered one. Refused
128
+ * (`invalid_state`) on an answered call, whose dialog is owed a BYE
129
+ * (RFC 3261 §15) — that is {@link SipVerb.Hangup}'s job.
130
+ */
131
+ Drop: "drop",
119
132
  Refer: "refer",
120
133
  Route: "route",
121
134
  /**
@@ -158,6 +171,9 @@ function transferOutcome(event) {
158
171
  function isBridgeFinal(name) {
159
172
  return name === "ChannelBridged" || name === "BridgeFailed";
160
173
  }
174
+ function isDialFinal(name) {
175
+ return name === "DialAnswered" || name === "DialFailed";
176
+ }
161
177
 
162
178
  // src/internal.ts
163
179
  var AsyncQueue = class {
@@ -655,7 +671,15 @@ function stringValue(result) {
655
671
  return null;
656
672
  }
657
673
  function originateArgs(channel, to, media, options) {
658
- const args = { channel, to };
674
+ return originateCommonArgs({ channel, to }, media, options);
675
+ }
676
+ function originateAorArgs(channel, aor, media, options, ring) {
677
+ const args = originateCommonArgs({ channel, aor }, media, options);
678
+ if (ring?.strategy !== void 0) args.strategy = ring.strategy;
679
+ if (ring?.totalTimeout !== void 0) args.total_timeout = ring.totalTimeout;
680
+ return args;
681
+ }
682
+ function originateCommonArgs(args, media, options) {
659
683
  if ("anchor" in media) {
660
684
  args.media = true;
661
685
  if (media.profile !== void 0) args.profile = media.profile;
@@ -724,8 +748,37 @@ function dialArgs(targets, options) {
724
748
  if (options.strategy !== void 0) args.strategy = options.strategy;
725
749
  if (options.timeout !== void 0) args.timeout = options.timeout;
726
750
  if (options.headers !== void 0) args.headers = options.headers;
751
+ if (options.profile !== void 0) args.profile = options.profile;
752
+ if (options.from !== void 0) args.from = options.from;
753
+ if (options.fromDisplay !== void 0) args.from_display = options.fromDisplay;
754
+ if (options.pAssertedIdentity !== void 0) {
755
+ args.p_asserted_identity = options.pAssertedIdentity;
756
+ }
757
+ if (options.privacy !== void 0) args.privacy = options.privacy;
758
+ if (options.ringback !== void 0 && options.onAnswer !== "bridge") {
759
+ throw new TypeError(
760
+ `dial "ringback" requires onAnswer: "bridge" \u2014 a connecting dial gives the caller the phones' own ringback, and siphon refuses it there`
761
+ );
762
+ }
763
+ if (options.onAnswer !== void 0) args.on_answer = options.onAnswer;
764
+ if (options.ringback !== void 0) args.ringback = options.ringback;
727
765
  return args;
728
766
  }
767
+ function branchList(value) {
768
+ if (!Array.isArray(value)) return void 0;
769
+ const branches = [];
770
+ for (const entry of value) {
771
+ if (typeof entry !== "object" || entry === null) continue;
772
+ const { leg_id, leg_sip_call_id, target, aor } = entry;
773
+ if (typeof leg_id !== "string" || typeof leg_sip_call_id !== "string" || typeof target !== "string") {
774
+ continue;
775
+ }
776
+ const branch = { leg_id, leg_sip_call_id, target };
777
+ if (typeof aor === "string") branch.aor = aor;
778
+ branches.push(branch);
779
+ }
780
+ return branches;
781
+ }
729
782
  function recordStartArgs(options) {
730
783
  const args = {};
731
784
  if (!options) return args;
@@ -884,6 +937,48 @@ var Call = class {
884
937
  async hangup(reason) {
885
938
  await this.terminate(reason);
886
939
  }
940
+ /**
941
+ * Abandon this **unanswered** call with nothing on the wire — no final
942
+ * response, no CANCEL — and release it.
943
+ *
944
+ * The third way out of a parked call, and the only silent one.
945
+ * {@link Call.reject} and an unanswered {@link Call.hangup} both answer, and
946
+ * on a SIP port reachable from the internet that answer is the prize: a `404`
947
+ * to an INVITE for a number nobody claims confirms the number to an
948
+ * enumeration sweep, where silence leaves it unable to tell a missing
949
+ * extension from a filtered one. Your controller holds the only knowledge of
950
+ * which numbers are real, so it is the only thing that can decide an INVITE is
951
+ * unsolicited.
952
+ *
953
+ * Not a way to hang up: an answered dialog is owed a BYE (RFC 3261 §15), so an
954
+ * answered call rejects with `code === "invalid_state"` rather than being
955
+ * orphaned — use {@link Call.hangup} there. A call that has already ended
956
+ * rejects with `code === "not_found"`.
957
+ *
958
+ * `reason` is for the record, not the wire: it reaches siphon's log and the
959
+ * CDR (`sip_reason`, beside `disconnect_initiator: "control"` and no response
960
+ * code), so a dropped call reads as deliberate rather than as a leak.
961
+ *
962
+ * `options.ban` makes the verdict stick: siphon also scores the caller's
963
+ * source address in the `security.failed_auth_ban` store, so a source the
964
+ * controller keeps dropping is banned at the transport before its next INVITE
965
+ * is parsed. The weight follows how far the address can be believed — a
966
+ * strong signal over TCP / TLS / WS / WSS, whose handshake proved it, and
967
+ * weight 1 over UDP, where one datagram can name any address. A no-op without
968
+ * `security.failed_auth_ban`; `trusted_cidrs` are never scored; only a
969
+ * successful drop scores, so a refused one leaves the source alone. Sent only
970
+ * when `true`.
971
+ */
972
+ async drop(reason, options) {
973
+ const args = {};
974
+ if (reason !== void 0) {
975
+ args.reason = reason;
976
+ }
977
+ if (options?.ban === true) {
978
+ args.ban = true;
979
+ }
980
+ await this.sip(SipVerb.Drop, args);
981
+ }
887
982
  /**
888
983
  * Send an in-dialog REFER on the A-leg (blind transfer).
889
984
  *
@@ -955,7 +1050,11 @@ var Call = class {
955
1050
  * The first 2xx answers the caller with the winner's SDP and the pair becomes
956
1051
  * an ordinary two-leg call, still owned by this app. A failure or timeout
957
1052
  * arrives as a `DialFailed` event with the caller still ringing and still
958
- * parked, so the app decides what happens next.
1053
+ * parked, so the app decides what happens next. Every branch is named as it is
1054
+ * created (`DialBranch`) and as it ends (`DialBranchFailed` / `DialAnswered`),
1055
+ * by its `leg_id` and `leg_sip_call_id` — see
1056
+ * {@link import("./protocol").DialBranchPayload} — and `DialFailed` lists them
1057
+ * all.
959
1058
  *
960
1059
  * Each target is a URI (dialed as written) or an `{aor}` (forked to every
961
1060
  * registered contact over its own flow) — see {@link DialTarget}, and note
@@ -973,6 +1072,23 @@ var Call = class {
973
1072
  * answered, which is what this verb exists to avoid), `"bad_request"` (an
974
1073
  * empty or malformed target list) or `"unsupported_verb"` (a strategy siphon
975
1074
  * does not implement).
1075
+ *
1076
+ * A caller the app answered on purpose, to play it prompts first, is what
1077
+ * `onAnswer: "bridge"` is for (see {@link DialOptions.onAnswer}): the phones
1078
+ * ring while the caller hears `ringback`, and the first to answer is bridged
1079
+ * to it. The reply then also carries `onAnswer`, `groupId`, `totalTimeout`,
1080
+ * `ringback` and the `branches` rung. It refuses with `"invalid_state"` a
1081
+ * caller that is not answered, not anchored, already bridged or already has
1082
+ * phones ringing for it.
1083
+ *
1084
+ * ```ts
1085
+ * await call.answerAnchored();
1086
+ * await call.play({ file: "/prompts/menu.wav" });
1087
+ * await call.dial([{ aor: "sip:204@pbx.example" }], {
1088
+ * onAnswer: "bridge",
1089
+ * ringback: "ringback_eu",
1090
+ * });
1091
+ * ```
976
1092
  */
977
1093
  async dial(targets, options) {
978
1094
  const result = await this.sip(SipVerb.Dial, dialArgs(targets, options));
@@ -990,7 +1106,15 @@ var Call = class {
990
1106
  channel: text("channel") ?? this.channelId,
991
1107
  targets: count("targets"),
992
1108
  strategy: text("strategy"),
993
- timeout: count("timeout")
1109
+ timeout: count("timeout"),
1110
+ onAnswer: text("on_answer"),
1111
+ groupId: text("group_id"),
1112
+ totalTimeout: count("total_timeout"),
1113
+ ringback: (() => {
1114
+ const value = result?.ringback;
1115
+ return typeof value === "string" || typeof value === "boolean" ? value : void 0;
1116
+ })(),
1117
+ branches: branchList(result?.branches)
994
1118
  };
995
1119
  }
996
1120
  /**
@@ -1184,23 +1308,51 @@ var Call = class {
1184
1308
  await this.sip(SipVerb.Unhold, {});
1185
1309
  }
1186
1310
  /**
1187
- * Attach a WebSocket audio tee — stream a copy of the call's decoded audio to
1188
- * `wsUri` while the call keeps relaying. siphon-rtp backend only: rtpengine /
1189
- * rtpproxy reject with `code === "unsupported_verb"` (`error.isUnsupportedVerb()`).
1311
+ * Attach a WebSocket audio stream to `wsUri`: an additive tee (the default)
1312
+ * or a takeover bridge, as `options.mode` says.
1313
+ *
1314
+ * ```ts
1315
+ * // Transcribe the caller at 16 kHz; the call keeps relaying.
1316
+ * // siphon expands `{call_id}` to the call's SIP Call-ID.
1317
+ * await call.streamStart("wss://ai.example/stream/{call_id}", {
1318
+ * direction: "caller",
1319
+ * sampleRate: 16000,
1320
+ * });
1321
+ * // Hand the leg to a voice agent; the agent is now the far side.
1322
+ * await call.streamStart("wss://ai.example/agent", { mode: "bridge" });
1323
+ * ```
1324
+ *
1325
+ * A bridge on a leg that already has one re-points it in place. `wsUri` may
1326
+ * use `{call_id}` / `{from_tag}` / `{from_user}` / `{to_user}`, which siphon
1327
+ * expands before the engine sees it: `{call_id}` expands to the call's SIP
1328
+ * Call-ID ({@link Call.sipCallId}), not the control-plane `callId`. An
1329
+ * unknown placeholder rejects with `bad_request`. siphon-rtp backend only: rtpengine / rtpproxy
1330
+ * reject with `code === "unsupported_verb"` (`error.isUnsupportedVerb()`).
1190
1331
  */
1191
1332
  async streamStart(wsUri, options) {
1192
- const args = { ws_uri: wsUri };
1333
+ const args = {
1334
+ ws_uri: wsUri,
1335
+ mode: options?.mode ?? "tee"
1336
+ };
1193
1337
  if (options?.direction !== void 0) {
1194
1338
  args.direction = options.direction;
1195
1339
  }
1196
1340
  if (options?.channels !== void 0) {
1197
1341
  args.channels = options.channels;
1198
1342
  }
1343
+ if (options?.sampleRate !== void 0) {
1344
+ args.sample_rate = options.sampleRate;
1345
+ }
1199
1346
  await this.sip(SipVerb.StreamStart, args);
1200
1347
  }
1201
- /** Detach the WebSocket audio tee (idempotent on siphon-rtp). */
1202
- async streamStop() {
1203
- await this.sip(SipVerb.StreamStop, {});
1348
+ /**
1349
+ * Detach the WebSocket stream of `options.mode` (`"tee"` by default, sent
1350
+ * explicitly). A tee detach is idempotent. A bridge detach is not: the
1351
+ * engine refuses one where there is no relay to hand the call back to, and
1352
+ * that rejects rather than leaving a live call with no audio path.
1353
+ */
1354
+ async streamStop(options) {
1355
+ await this.sip(SipVerb.StreamStop, { mode: options?.mode ?? "tee" });
1204
1356
  }
1205
1357
  /**
1206
1358
  * Record this call's decoded audio to a wav file.
@@ -1277,10 +1429,14 @@ var CallStream = class {
1277
1429
  var SipFacade = class {
1278
1430
  handler = null;
1279
1431
  callQueue = null;
1432
+ appHandler = null;
1280
1433
  channels = /* @__PURE__ */ new Map();
1281
1434
  setHandler(handler) {
1282
1435
  this.handler = handler;
1283
1436
  }
1437
+ setAppHandler(handler) {
1438
+ this.appHandler = handler;
1439
+ }
1284
1440
  setStream() {
1285
1441
  const queue = new AsyncQueue();
1286
1442
  this.callQueue = queue;
@@ -1321,6 +1477,12 @@ var SipFacade = class {
1321
1477
  }
1322
1478
  } else if (frame.channel) {
1323
1479
  this.route(frame.channel, callEventFromFrame(frame));
1480
+ } else {
1481
+ this.appHandler?.({
1482
+ kind: sipEventKind(frame.event),
1483
+ payload: frame.payload ?? null,
1484
+ frame
1485
+ });
1324
1486
  }
1325
1487
  }
1326
1488
  reattach(snapshot, transport) {
@@ -1388,6 +1550,15 @@ var SipClient = class _SipClient {
1388
1550
  calls() {
1389
1551
  return this.facade.setStream();
1390
1552
  }
1553
+ /**
1554
+ * Register a handler for application-level events — the ones an app opts
1555
+ * into with `control.apps[].events` (`RegistrationChanged`,
1556
+ * `DialogStateChanged`), which concern no channel and so reach no call.
1557
+ * Replaces any previous handler.
1558
+ */
1559
+ onAppEvent(handler) {
1560
+ this.facade.setAppHandler(handler);
1561
+ }
1391
1562
  /** Drive the supervised connection loop (reconnect + resync). */
1392
1563
  run() {
1393
1564
  return this.client.run();
@@ -1432,6 +1603,62 @@ var SipClient = class _SipClient {
1432
1603
  sipCallId: text("sip_call_id")
1433
1604
  };
1434
1605
  }
1606
+ /**
1607
+ * Ring every phone registered at `aor` under a caller-supplied channel id —
1608
+ * {@link SipClient.originate} for a phone rather than a URI.
1609
+ *
1610
+ * A phone registered over TCP, TLS or WSS behind NAT is reachable only on the
1611
+ * connection it registered over, and one registered through an edge proxy
1612
+ * only through its Path, so resolving its Contact as a `to` reaches nothing.
1613
+ * This rings each registered contact over its own flow and Path (RFC 5626
1614
+ * §5.3, RFC 3327 §5.3), each as its own originated call with `options`
1615
+ * applied. The first phone to answer wins; every other one still ringing is
1616
+ * CANCELled. `ring` says how the phones are rung ({@link OriginateRing}).
1617
+ *
1618
+ * An AoR with nobody registered rejects with `code === "not_found"` and
1619
+ * `details.reason === "no_contacts"`, with nothing on the wire.
1620
+ *
1621
+ * While the phones ring the channel is bound to the group: its events carry
1622
+ * the {@link OriginatedGroup.groupId} as their `call_id`, and each leg's own
1623
+ * Call-ID is in the payload (`DialBranch`, `DialBranchFailed`). From
1624
+ * `DialAnswered` on, the channel is the winning phone's call. A `hangup`
1625
+ * while they ring CANCELs every one; `drop` is refused (`invalid_state`),
1626
+ * since siphon is their caller and there is no response to withhold.
1627
+ *
1628
+ * ```ts
1629
+ * const group = await client.originateAor(
1630
+ * "wake-201",
1631
+ * "sip:201@pbx.example",
1632
+ * { anchor: true },
1633
+ * { from: "sip:reception@pbx.example", timeout: 25 },
1634
+ * { strategy: "parallel" },
1635
+ * );
1636
+ * ```
1637
+ */
1638
+ async originateAor(channel, aor, media, options, ring) {
1639
+ const result = await this.client.command(
1640
+ MODULE_SIP,
1641
+ "originate",
1642
+ null,
1643
+ originateAorArgs(channel, aor, media, options, ring)
1644
+ );
1645
+ const text = (name) => {
1646
+ const value = result?.[name];
1647
+ return typeof value === "string" ? value : void 0;
1648
+ };
1649
+ const count = (name) => {
1650
+ const value = result?.[name];
1651
+ return typeof value === "number" ? value : void 0;
1652
+ };
1653
+ return {
1654
+ channel: text("channel") ?? channel,
1655
+ groupId: text("group_id"),
1656
+ aor: text("aor"),
1657
+ strategy: text("strategy"),
1658
+ totalTimeout: count("total_timeout"),
1659
+ branches: branchList(result?.branches) ?? []
1660
+ };
1661
+ }
1435
1662
  /** Send a raw command on any module (the generic escape hatch). */
1436
1663
  command(module, verb, target, args) {
1437
1664
  return this.client.command(module, verb, target, args);
@@ -1502,7 +1729,9 @@ exports.SipVerb = SipVerb;
1502
1729
  exports.dialArgs = dialArgs;
1503
1730
  exports.encodeCommand = encodeCommand;
1504
1731
  exports.isBridgeFinal = isBridgeFinal;
1732
+ exports.isDialFinal = isDialFinal;
1505
1733
  exports.isTransferFinal = isTransferFinal;
1734
+ exports.originateAorArgs = originateAorArgs;
1506
1735
  exports.originateArgs = originateArgs;
1507
1736
  exports.parseInboundFrame = parseInboundFrame;
1508
1737
  exports.recordStartArgs = recordStartArgs;