@siphon-project/control 0.5.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;
@@ -731,8 +755,30 @@ function dialArgs(targets, options) {
731
755
  args.p_asserted_identity = options.pAssertedIdentity;
732
756
  }
733
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;
734
765
  return args;
735
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
+ }
736
782
  function recordStartArgs(options) {
737
783
  const args = {};
738
784
  if (!options) return args;
@@ -891,6 +937,48 @@ var Call = class {
891
937
  async hangup(reason) {
892
938
  await this.terminate(reason);
893
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
+ }
894
982
  /**
895
983
  * Send an in-dialog REFER on the A-leg (blind transfer).
896
984
  *
@@ -962,7 +1050,11 @@ var Call = class {
962
1050
  * The first 2xx answers the caller with the winner's SDP and the pair becomes
963
1051
  * an ordinary two-leg call, still owned by this app. A failure or timeout
964
1052
  * arrives as a `DialFailed` event with the caller still ringing and still
965
- * 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.
966
1058
  *
967
1059
  * Each target is a URI (dialed as written) or an `{aor}` (forked to every
968
1060
  * registered contact over its own flow) — see {@link DialTarget}, and note
@@ -980,6 +1072,23 @@ var Call = class {
980
1072
  * answered, which is what this verb exists to avoid), `"bad_request"` (an
981
1073
  * empty or malformed target list) or `"unsupported_verb"` (a strategy siphon
982
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
+ * ```
983
1092
  */
984
1093
  async dial(targets, options) {
985
1094
  const result = await this.sip(SipVerb.Dial, dialArgs(targets, options));
@@ -997,7 +1106,15 @@ var Call = class {
997
1106
  channel: text("channel") ?? this.channelId,
998
1107
  targets: count("targets"),
999
1108
  strategy: text("strategy"),
1000
- 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)
1001
1118
  };
1002
1119
  }
1003
1120
  /**
@@ -1191,23 +1308,51 @@ var Call = class {
1191
1308
  await this.sip(SipVerb.Unhold, {});
1192
1309
  }
1193
1310
  /**
1194
- * Attach a WebSocket audio tee — stream a copy of the call's decoded audio to
1195
- * `wsUri` while the call keeps relaying. siphon-rtp backend only: rtpengine /
1196
- * 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()`).
1197
1331
  */
1198
1332
  async streamStart(wsUri, options) {
1199
- const args = { ws_uri: wsUri };
1333
+ const args = {
1334
+ ws_uri: wsUri,
1335
+ mode: options?.mode ?? "tee"
1336
+ };
1200
1337
  if (options?.direction !== void 0) {
1201
1338
  args.direction = options.direction;
1202
1339
  }
1203
1340
  if (options?.channels !== void 0) {
1204
1341
  args.channels = options.channels;
1205
1342
  }
1343
+ if (options?.sampleRate !== void 0) {
1344
+ args.sample_rate = options.sampleRate;
1345
+ }
1206
1346
  await this.sip(SipVerb.StreamStart, args);
1207
1347
  }
1208
- /** Detach the WebSocket audio tee (idempotent on siphon-rtp). */
1209
- async streamStop() {
1210
- 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" });
1211
1356
  }
1212
1357
  /**
1213
1358
  * Record this call's decoded audio to a wav file.
@@ -1284,10 +1429,14 @@ var CallStream = class {
1284
1429
  var SipFacade = class {
1285
1430
  handler = null;
1286
1431
  callQueue = null;
1432
+ appHandler = null;
1287
1433
  channels = /* @__PURE__ */ new Map();
1288
1434
  setHandler(handler) {
1289
1435
  this.handler = handler;
1290
1436
  }
1437
+ setAppHandler(handler) {
1438
+ this.appHandler = handler;
1439
+ }
1291
1440
  setStream() {
1292
1441
  const queue = new AsyncQueue();
1293
1442
  this.callQueue = queue;
@@ -1328,6 +1477,12 @@ var SipFacade = class {
1328
1477
  }
1329
1478
  } else if (frame.channel) {
1330
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
+ });
1331
1486
  }
1332
1487
  }
1333
1488
  reattach(snapshot, transport) {
@@ -1395,6 +1550,15 @@ var SipClient = class _SipClient {
1395
1550
  calls() {
1396
1551
  return this.facade.setStream();
1397
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
+ }
1398
1562
  /** Drive the supervised connection loop (reconnect + resync). */
1399
1563
  run() {
1400
1564
  return this.client.run();
@@ -1439,6 +1603,62 @@ var SipClient = class _SipClient {
1439
1603
  sipCallId: text("sip_call_id")
1440
1604
  };
1441
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
+ }
1442
1662
  /** Send a raw command on any module (the generic escape hatch). */
1443
1663
  command(module, verb, target, args) {
1444
1664
  return this.client.command(module, verb, target, args);
@@ -1509,7 +1729,9 @@ exports.SipVerb = SipVerb;
1509
1729
  exports.dialArgs = dialArgs;
1510
1730
  exports.encodeCommand = encodeCommand;
1511
1731
  exports.isBridgeFinal = isBridgeFinal;
1732
+ exports.isDialFinal = isDialFinal;
1512
1733
  exports.isTransferFinal = isTransferFinal;
1734
+ exports.originateAorArgs = originateAorArgs;
1513
1735
  exports.originateArgs = originateArgs;
1514
1736
  exports.parseInboundFrame = parseInboundFrame;
1515
1737
  exports.recordStartArgs = recordStartArgs;