@siphon-project/control 0.7.0 → 0.9.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
@@ -94,6 +94,8 @@ await client.command("sip", "answer", { channel: "ch1" }, { code: 200 });
94
94
  | Method | Wire verb (`module`) | Notes |
95
95
  | --- | --- | --- |
96
96
  | `answer(options?)` | `answer` (`sip`) | UAS 2xx (default `200 OK`) |
97
+ | `answerAnchored(options?)` | `answer` (`sip`) | answer and anchor the caller's media on the media engine in one act (`profile`, `wsUri`); what `play`, `hold` and `dial` with `onAnswer: "bridge"` need |
98
+ | `ring(reason?)` | `ring` (`sip`) | `180 Ringing`: alerting only, no early media |
97
99
  | `progress(options?)` | `progress` (`sip`) | UAS 1xx / early media (default `183`) |
98
100
  | `reject(code, reason?)` | `reject` (`sip`) | final non-2xx + teardown |
99
101
  | `terminate(reason?)` | `hangup` (`sip`) | primary teardown name |
@@ -106,16 +108,25 @@ await client.command("sip", "answer", { channel: "ch1" }, { code: 200 });
106
108
  | `getHeader(name)` | `get_header` (`sip`) | returns `string \| null` |
107
109
  | `setVar(key, value)` | `set_var` (substrate) | per-call variable |
108
110
  | `getVar(key)` | `get_var` (substrate) | returns `string \| null` |
109
- | `removeHeader(name)` | `remove_header` (`sip`) | ‡ |
110
- | `acceptRefer(options?)` | `accept_refer` (`sip`) | ‡ |
111
- | `rejectRefer(code, reason?)` | `reject_refer` (`sip`) | ‡ |
111
+ | `removeHeader(name)` | `remove_header` (`sip`) | on the stored A-leg INVITE |
112
+ | `route(targets, strategy?, headers?)` | `route` (`sip`) | hand the call back to siphon with a routing decision: the targets are tried in order. A target's `route` is the route set its INVITE carries, topmost first. Refused `invalid_state` while a `dial` still rings; `cancelDial` first |
113
+ | `acceptRefer(options?)` | `accept_refer` (`sip`) | accept a pending inbound REFER (a `TransferRequested` event). `mode` is `"terminate"` (siphon dials the target), `"transparent"` (siphon relays the REFER) or `"controller"` (siphon answers `202` and dials nothing; this app moves the parties and reports with `completeRefer` within `timeout` seconds, default 60, at most 180). `target` is a URI string or `{ aor }`, a registered address-of-record dialled over the flow its phone registered on, every registered contact rung and the first to answer kept. `from`, `fromDisplay`, `pAssertedIdentity`, `privacy` and `headers` shape the leg the transfer dials, and `numberPolicy` (a number policy configured on the server) or `format` says how the numbers in them are written. `{ aor }` and the identity options go with `"terminate"`; `"controller"` takes `timeout` only, and `timeout` goes with no other mode. The server refuses the rest |
114
+ | `rejectRefer(code, reason?)` | `reject_refer` (`sip`) | decline a pending inbound REFER with a final non-2xx |
115
+ | `completeRefer(code, reason?)` | `complete_refer` (`sip`) | report how a transfer accepted with `acceptRefer({ mode: "controller" })` went: the referrer gets the sipfrag NOTIFY that ends its subscription, a 2xx for success. Report before releasing the referrer's leg |
112
116
  | `bridge(withChannel, options?)` | `bridge` (`sip`) | join two answered legs; the verdict arrives as `ChannelBridged` / `BridgeFailed` |
113
117
  | `unbridge(reason?)` | `unbridge` (`sip`) | break the bridge — both legs stay answered, owned and held |
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 |
118
+ | `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. A `{uri}` target may carry `route`, the route set its INVITE carries, topmost first (`["<sip:term@scscf.example;lr;odi=4f1c>"]`), which is how an IMS application server sends a session back through the S-CSCF; a `route` on `{aor}` 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 |
119
+ | `cancelDial(reason?)` | `cancel_dial` (`sip`) | give up on the dial ringing for this call and leave the caller alone: the phones are CANCELled, each reported by `DialBranchFailed` (cause `cancelled`), and the dial ends in `DialFailed` with code 487. `reason` is the `cause` of a bridging dial's `DialFailed` (default `cancelled`). Refused `invalid_state` when nothing is ringing, and once a phone has answered and is being bridged |
120
+ | `replacePeer(target, options?)` | `replace_peer` (`sip`) | swap one party of this answered call for a freshly dialled target, no REFER involved; the replaced leg stays up while the target rings. `target` is a URI string or `{ aor }`, and `options` takes `nextHop`, `replaceALeg`, `profile`, `timeout` and the identity options of `acceptRefer`. The verdict arrives as `PeerReplaced` / `ReplaceFailed` |
115
121
  | `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 |
116
122
  | `recordStop(recordingId?)` | `record_stop` (`sip`) | stop one recording, or every recording on the call when no id is given |
117
- | `playFile(file)` | `play` (`sip`) | ‡ media |
118
- | `dtmf(digits)` | `dtmf` (`sip`) | ‡ media |
123
+ | `play(source, options?)` | `play` (`sip`) | play `{ file }`, `{ dbId }`, `{ blob }`, `{ tone }` (a preset or a cadence) or `{ url }` (HTTP or HTTPS) on the caller's media. `options.repeat` is a total play count, or `"inf"` to play until stopped (`stop` ends it); also `startMs`, `durationMs`, `gainDecibels`, `toTag`. Needs an anchored media session (`not_found` without one) |
124
+ | `playFile(file)` | `play` (`sip`) | `play({ file })` with default options |
125
+ | `stop()` | `stop` (`sip`) | stop the announcement that is playing |
126
+ | `dtmf(digits, options?)` | `dtmf` (`sip`) | inject DTMF digits toward the caller (`durationMs`, `volumeDbm0`, `pauseMs`, `toTag`) |
127
+ | `hold()` / `unhold()` | `hold` / `unhold` (`sip`) | silence, then restore, the call's media on the engine. A media gate, not a SIP hold; refused `invalid_state` on a call the engine only relays |
128
+ | `streamStart(wsUri, options?)` | `stream_start` (`sip`) | stream the call's audio to a WebSocket server: `mode: "tee"` (default, a copy) or `"bridge"` (a takeover). siphon-rtp only |
129
+ | `streamStop(options?)` | `stream_stop` (`sip`) | detach the stream of `options.mode` |
119
130
  | `command(verb, args?)` | (`sip`) | arbitrary SIP-adapter verb |
120
131
  | `nextEvent()` / `events()` | — | per-call event stream |
121
132
 
@@ -127,12 +138,13 @@ addressing one:
127
138
 
128
139
  | Method | Wire verb (`module`) | Notes |
129
140
  | --- | --- | --- |
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` |
141
+ | `originate(channel, to, media, options?)` | `originate` (`sip`) | one URI, resolved as written; resolves once the INVITE is on the wire to the `Call` it placed, whose `nextEvent()` carries the answer, a rejection or the ring timeout. An id still live on this client is `conflict`, refused before anything is sent |
142
+ | `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? }`. The result carries the placed `call`. Nobody registered is `not_found` (`no_contacts`); `drop` is refused while the phones ring, use `hangup` |
132
143
 
133
- ‡ Accepted verb names the Phase-1 server answers with a `ControlError` whose
134
- `.code === "unsupported_verb"` (`error.isUnsupportedVerb()`) until it implements
135
- them. They send a real command — nothing is stubbed client-side.
144
+ The server implements every verb in these tables. `unsupported_verb`
145
+ (`error.isUnsupportedVerb()`) is what a verb answers when the configured media
146
+ backend cannot carry it out: `streamStart` / `streamStop` and `recordStart` /
147
+ `recordStop` on rtpengine or rtpproxy, and `play` with `repeat: "inf"` there.
136
148
 
137
149
  ## Errors
138
150
 
@@ -144,10 +156,10 @@ Transport / handshake / timeout failures throw a `ControlError` with a `.kind`
144
156
 
145
157
  ```ts
146
158
  try {
147
- await call.playFile("/prompts/welcome.wav");
159
+ await call.streamStart("wss://transcriber.example.com/stream");
148
160
  } catch (error) {
149
161
  if (error instanceof ControlError && error.isUnsupportedVerb()) {
150
- // media isn't wired server-side yet — fall back gracefully
162
+ // the configured media backend cannot stream — carry on without it
151
163
  }
152
164
  }
153
165
  ```
package/dist/index.cjs CHANGED
@@ -23,8 +23,9 @@ var ControlError = class _ControlError extends Error {
23
23
  Object.setPrototypeOf(this, _ControlError.prototype);
24
24
  }
25
25
  /**
26
- * True when this is a server-side `unsupported_verb` rejection — the state a
27
- * media verb (`playFile`/`dtmf`/…) lands in until the server implements it.
26
+ * True when this is a server-side `unsupported_verb` rejection — what a verb
27
+ * answers when the configured media backend cannot carry it out (streaming
28
+ * and recording on anything but siphon-rtp).
28
29
  */
29
30
  isUnsupportedVerb() {
30
31
  return this.kind === "command" && this.code === "unsupported_verb";
@@ -86,10 +87,10 @@ function encodeCommand(id, module, verb, target, args) {
86
87
  frame.args = args ?? null;
87
88
  return JSON.stringify(frame);
88
89
  }
89
- function parseInboundFrame(text) {
90
+ function parseInboundFrame(text2) {
90
91
  let value;
91
92
  try {
92
- value = JSON.parse(text);
93
+ value = JSON.parse(text2);
93
94
  } catch {
94
95
  return null;
95
96
  }
@@ -136,11 +137,19 @@ var SipVerb = {
136
137
  * the channel. Channel-addressed, unlike `originate`, which creates one.
137
138
  */
138
139
  Dial: "dial",
140
+ /**
141
+ * Give up on the dial ringing for this channel's caller and leave the caller
142
+ * alone: the phones are CANCELled and the dial ends in `DialFailed` with code
143
+ * 487. Refused (`invalid_state`) when nothing is ringing, and once a phone
144
+ * has answered and is being bridged.
145
+ */
146
+ CancelDial: "cancel_dial",
139
147
  SetHeader: "set_header",
140
148
  GetHeader: "get_header",
141
149
  RemoveHeader: "remove_header",
142
150
  AcceptRefer: "accept_refer",
143
151
  RejectRefer: "reject_refer",
152
+ CompleteRefer: "complete_refer",
144
153
  Bridge: "bridge",
145
154
  Unbridge: "unbridge",
146
155
  ReplacePeer: "replace_peer",
@@ -254,7 +263,7 @@ var Session = class {
254
263
  return Promise.reject(ControlError.closed());
255
264
  }
256
265
  const id = `c-${this.nextId.value++}`;
257
- const text = encodeCommand(id, module, verb, target, args);
266
+ const text2 = encodeCommand(id, module, verb, target, args);
258
267
  return new Promise((resolve, reject) => {
259
268
  const timer = setTimeout(() => {
260
269
  this.pending.delete(id);
@@ -262,7 +271,7 @@ var Session = class {
262
271
  }, this.replyTimeoutMs);
263
272
  this.pending.set(id, { resolve, reject, timer });
264
273
  try {
265
- this.socket.send(text);
274
+ this.socket.send(text2);
266
275
  } catch (error) {
267
276
  this.pending.delete(id);
268
277
  clearTimeout(timer);
@@ -270,8 +279,8 @@ var Session = class {
270
279
  }
271
280
  });
272
281
  }
273
- onMessage(text) {
274
- const frame = parseInboundFrame(text);
282
+ onMessage(text2) {
283
+ const frame = parseInboundFrame(text2);
275
284
  if (frame === null) {
276
285
  return;
277
286
  }
@@ -642,10 +651,29 @@ function responseArgs(options) {
642
651
  }
643
652
  return args;
644
653
  }
654
+ function insertTransferIdentity(args, identity) {
655
+ if (identity?.from !== void 0) args.from = identity.from;
656
+ if (identity?.fromDisplay !== void 0) args.from_display = identity.fromDisplay;
657
+ if (identity?.pAssertedIdentity !== void 0) {
658
+ args.p_asserted_identity = identity.pAssertedIdentity;
659
+ }
660
+ if (identity?.privacy !== void 0) args.privacy = identity.privacy;
661
+ if (identity?.numberPolicy !== void 0) args.number_policy = identity.numberPolicy;
662
+ if (identity?.format !== void 0) args.format = identity.format;
663
+ if (identity?.headers !== void 0) args.headers = identity.headers;
664
+ }
665
+ function routeSetToWire(route) {
666
+ if (route === void 0 || route === null) return void 0;
667
+ if (!Array.isArray(route) || route.some((entry) => typeof entry !== "string")) {
668
+ throw new TypeError(`a target's "route" is an array of Route entry strings`);
669
+ }
670
+ return route.length === 0 ? void 0 : [...route];
671
+ }
645
672
  function routeTargetToWire(target) {
646
673
  if (typeof target === "string") {
647
674
  return target;
648
675
  }
676
+ const route = routeSetToWire(target.route);
649
677
  const object = { uri: target.uri };
650
678
  if (target.nextHop !== void 0) {
651
679
  object.next_hop = target.nextHop;
@@ -659,6 +687,9 @@ function routeTargetToWire(target) {
659
687
  if (target.rerouteAfterProgress === true) {
660
688
  object.reroute_after_progress = true;
661
689
  }
690
+ if (route !== void 0) {
691
+ object.route = route;
692
+ }
662
693
  return object;
663
694
  }
664
695
  function stringValue(result) {
@@ -670,6 +701,10 @@ function stringValue(result) {
670
701
  }
671
702
  return null;
672
703
  }
704
+ function text(result, name) {
705
+ const value = result?.[name];
706
+ return typeof value === "string" ? value : void 0;
707
+ }
673
708
  function originateArgs(channel, to, media, options) {
674
709
  return originateCommonArgs({ channel, to }, media, options);
675
710
  }
@@ -718,6 +753,11 @@ function dialTargetToWire(target) {
718
753
  const aor = target.aor;
719
754
  const nextHop = target.nextHop;
720
755
  const headers = target.headers;
756
+ const to = target.to;
757
+ const route = routeSetToWire(target.route);
758
+ if (to !== void 0 && typeof to !== "string") {
759
+ throw new TypeError(`a dial target's "to" is a SIP URI string`);
760
+ }
721
761
  if (typeof uri === "string" && typeof aor === "string") {
722
762
  throw new TypeError(
723
763
  'a dial target names "uri" or "aor", never both \u2014 siphon reads the aor and ignores the uri beside it, so this would place a different call'
@@ -729,17 +769,27 @@ function dialTargetToWire(target) {
729
769
  `an aor target takes no "nextHop": each of its branches routes over its own contact's captured flow`
730
770
  );
731
771
  }
772
+ if (route !== void 0) {
773
+ throw new TypeError(
774
+ `an aor target takes no "route": each of its branches follows its own contact's Path`
775
+ );
776
+ }
732
777
  const object2 = { aor };
733
778
  if (headers !== void 0) object2.headers = headers;
779
+ if (to !== void 0) object2.to = to;
734
780
  return object2;
735
781
  }
736
782
  if (typeof uri !== "string") {
737
783
  throw new TypeError('a dial target requires a string "uri" or "aor"');
738
784
  }
739
- if (nextHop === void 0 && headers === void 0) return uri;
785
+ if (nextHop === void 0 && headers === void 0 && to === void 0 && route === void 0) {
786
+ return uri;
787
+ }
740
788
  const object = { uri };
741
789
  if (nextHop !== void 0) object.next_hop = nextHop;
742
790
  if (headers !== void 0) object.headers = headers;
791
+ if (to !== void 0) object.to = to;
792
+ if (route !== void 0) object.route = route;
743
793
  return object;
744
794
  }
745
795
  function dialArgs(targets, options) {
@@ -798,6 +848,10 @@ function playArgs(source, options) {
798
848
  args.file = source.file;
799
849
  } else if ("dbId" in source) {
800
850
  args.db_id = source.dbId;
851
+ } else if ("tone" in source) {
852
+ args.tone = source.tone;
853
+ } else if ("url" in source) {
854
+ args.url = source.url;
801
855
  } else {
802
856
  args.blob = Buffer.from(source.blob).toString("base64");
803
857
  }
@@ -810,6 +864,9 @@ function playArgs(source, options) {
810
864
  if (options?.durationMs !== void 0) {
811
865
  args.duration_ms = options.durationMs;
812
866
  }
867
+ if (options?.gainDecibels !== void 0) {
868
+ args.gain_decibels = options.gainDecibels;
869
+ }
813
870
  if (options?.toTag !== void 0) {
814
871
  args.to_tag = options.toTag;
815
872
  }
@@ -979,6 +1036,32 @@ var Call = class {
979
1036
  }
980
1037
  await this.sip(SipVerb.Drop, args);
981
1038
  }
1039
+ /**
1040
+ * Give up on the dial ringing for this call and leave the caller alone.
1041
+ *
1042
+ * Every phone still ringing is CANCELled (RFC 3261 §9.1), each reported by
1043
+ * `DialBranchFailed` with cause `cancelled`, and the dial ends in
1044
+ * `DialFailed` with code 487. The caller is exactly as the dial found it —
1045
+ * answered and anchored for an `onAnswer: "bridge"` dial, unanswered and
1046
+ * parked otherwise — still this app's, and free to be dialled for again.
1047
+ * {@link Call.hangup} ends the caller as well.
1048
+ *
1049
+ * `reason` is reported as the `cause` of a bridging dial's `DialFailed`
1050
+ * (default `cancelled`), so the handler that hears it can tell its own cancel
1051
+ * from a dial that failed by itself.
1052
+ *
1053
+ * Rejects with `invalid_state` when nothing is ringing (`details.reason` is
1054
+ * `no_dial_in_progress`), and once a phone has answered and is being bridged
1055
+ * (`dial_answered`), whose outcome arrives as `DialAnswered` or
1056
+ * `BridgeFailed`.
1057
+ */
1058
+ async cancelDial(reason) {
1059
+ const args = {};
1060
+ if (reason !== void 0) {
1061
+ args.reason = reason;
1062
+ }
1063
+ await this.sip(SipVerb.CancelDial, args);
1064
+ }
982
1065
  /**
983
1066
  * Send an in-dialog REFER on the A-leg (blind transfer).
984
1067
  *
@@ -1015,7 +1098,7 @@ var Call = class {
1015
1098
  *
1016
1099
  * `targets` is a non-empty list of carriers tried cheapest-first: each entry
1017
1100
  * is a bare URI string or a {@link RouteTargetObject}
1018
- * (`{uri, nextHop?, headers?, timeout?, rerouteAfterProgress?}`). A target
1101
+ * (`{uri, nextHop?, headers?, timeout?, rerouteAfterProgress?, route?}`). A target
1019
1102
  * that has shown progress keeps the call past its `timeout` unless it sets
1020
1103
  * `rerouteAfterProgress`. `strategy` defaults to
1021
1104
  * `"sequential"` (v1 supports only sequential/single — anything else rejects
@@ -1092,7 +1175,7 @@ var Call = class {
1092
1175
  */
1093
1176
  async dial(targets, options) {
1094
1177
  const result = await this.sip(SipVerb.Dial, dialArgs(targets, options));
1095
- const text = (name) => {
1178
+ const text2 = (name) => {
1096
1179
  const value = result?.[name];
1097
1180
  return typeof value === "string" ? value : void 0;
1098
1181
  };
@@ -1103,12 +1186,12 @@ var Call = class {
1103
1186
  return {
1104
1187
  // The server echoes the channel back; fall back to the one addressed
1105
1188
  // rather than returning an empty id.
1106
- channel: text("channel") ?? this.channelId,
1189
+ channel: text2("channel") ?? this.channelId,
1107
1190
  targets: count("targets"),
1108
- strategy: text("strategy"),
1191
+ strategy: text2("strategy"),
1109
1192
  timeout: count("timeout"),
1110
- onAnswer: text("on_answer"),
1111
- groupId: text("group_id"),
1193
+ onAnswer: text2("on_answer"),
1194
+ groupId: text2("group_id"),
1112
1195
  totalTimeout: count("total_timeout"),
1113
1196
  ringback: (() => {
1114
1197
  const value = result?.ringback;
@@ -1124,6 +1207,9 @@ var Call = class {
1124
1207
  * `b2bua.default_refer_mode`. No pending REFER (already decided, timed out, or
1125
1208
  * the call is gone) rejects with `code === "not_found"`.
1126
1209
  *
1210
+ * `mode: "controller"` leaves the transfer to this application — see
1211
+ * {@link AcceptReferOptions.mode} and {@link Call.completeRefer}.
1212
+ *
1127
1213
  * `profile` names the media profile for the pairing the transfer creates —
1128
1214
  * see {@link AcceptReferOptions.profile}, which is required at an SRTP edge.
1129
1215
  */
@@ -1141,8 +1227,32 @@ var Call = class {
1141
1227
  if (options?.profile !== void 0) {
1142
1228
  args.profile = options.profile;
1143
1229
  }
1230
+ if (options?.timeout !== void 0) {
1231
+ args.timeout = options.timeout;
1232
+ }
1233
+ insertTransferIdentity(args, options);
1144
1234
  await this.sip(SipVerb.AcceptRefer, args);
1145
1235
  }
1236
+ /**
1237
+ * Report how a transfer accepted with `acceptRefer({ mode: "controller" })`
1238
+ * went: the server sends the referrer the sipfrag NOTIFY that ends its
1239
+ * subscription. `code` is the status in it (200-699), a 2xx for a transfer
1240
+ * that succeeded, and `reason` its reason phrase, used as given. Nothing
1241
+ * else happens to the call.
1242
+ *
1243
+ * **Report before releasing the referrer's leg.** The NOTIFY travels on its
1244
+ * dialog, so once that leg is hung up or replaced this rejects with
1245
+ * `code === "not_found"`. With no such transfer open on the call — already
1246
+ * reported, past its deadline, or its referrer hung up — it rejects with
1247
+ * `code === "invalid_state"` (`details.reason === "no_transfer_pending"`).
1248
+ */
1249
+ async completeRefer(code, reason) {
1250
+ const args = { code };
1251
+ if (reason !== void 0) {
1252
+ args.reason = reason;
1253
+ }
1254
+ await this.sip(SipVerb.CompleteRefer, args);
1255
+ }
1146
1256
  /**
1147
1257
  * Reject a *pending inbound* REFER with a final non-2xx (default
1148
1258
  * `603 Decline`). No pending REFER rejects with `code === "not_found"`.
@@ -1249,6 +1359,7 @@ var Call = class {
1249
1359
  if (options.replaceALeg !== void 0) args.replace_a_leg = options.replaceALeg;
1250
1360
  if (options.profile !== void 0) args.profile = options.profile;
1251
1361
  if (options.timeout !== void 0) args.timeout = options.timeout;
1362
+ insertTransferIdentity(args, options);
1252
1363
  return this.sip(SipVerb.ReplacePeer, args);
1253
1364
  }
1254
1365
  /** Set a header on the stored A-leg INVITE. */
@@ -1299,11 +1410,17 @@ var Call = class {
1299
1410
  async dtmf(digits, options) {
1300
1411
  await this.sip(SipVerb.Dtmf, dtmfArgs(digits, options));
1301
1412
  }
1302
- /** Hold the A-leg media via silence. */
1413
+ /**
1414
+ * Silence the call's media in both directions on the media engine.
1415
+ *
1416
+ * A media gate, not a SIP hold: nothing is sent on either dialog, so no
1417
+ * phone shows a held call. Rejects with `invalid_state` on a call the engine
1418
+ * only relays; to hold one party of a bridge, use {@link Call.unbridge}.
1419
+ */
1303
1420
  async hold() {
1304
1421
  await this.sip(SipVerb.Hold, {});
1305
1422
  }
1306
- /** Resume the A-leg media after a {@link Call.hold}. */
1423
+ /** Restore the call's media after a {@link Call.hold}. */
1307
1424
  async unhold() {
1308
1425
  await this.sip(SipVerb.Unhold, {});
1309
1426
  }
@@ -1379,13 +1496,13 @@ var Call = class {
1379
1496
  SipVerb.RecordStart,
1380
1497
  recordStartArgs(options)
1381
1498
  );
1382
- const text = (name) => {
1499
+ const text2 = (name) => {
1383
1500
  const value = result?.[name];
1384
1501
  return typeof value === "string" ? value : void 0;
1385
1502
  };
1386
1503
  return {
1387
- channel: text("channel") ?? this.channelId,
1388
- recordingId: text("recording_id")
1504
+ channel: text2("channel") ?? this.channelId,
1505
+ recordingId: text2("recording_id")
1389
1506
  };
1390
1507
  }
1391
1508
  /**
@@ -1504,6 +1621,25 @@ var SipFacade = class {
1504
1621
  );
1505
1622
  this.dispatch(call);
1506
1623
  }
1624
+ /**
1625
+ * Open the event queue of a call this client is placing, before its
1626
+ * `originate` goes out: siphon sends no `StasisStart` for it, and its first
1627
+ * event can overtake the reply. `null` when the channel is already live here,
1628
+ * which must not be taken over.
1629
+ */
1630
+ openChannel(channel) {
1631
+ if (this.channels.has(channel)) {
1632
+ return null;
1633
+ }
1634
+ const queue = new AsyncQueue();
1635
+ this.channels.set(channel, queue);
1636
+ return queue;
1637
+ }
1638
+ /** Close a channel {@link SipFacade.openChannel} opened for a refused originate. */
1639
+ closeChannel(channel) {
1640
+ this.channels.get(channel)?.close();
1641
+ this.channels.delete(channel);
1642
+ }
1507
1643
  route(channel, event) {
1508
1644
  this.channels.get(channel)?.push(event);
1509
1645
  }
@@ -1576,8 +1712,14 @@ var SipClient = class _SipClient {
1576
1712
  *
1577
1713
  * The one verb that *creates* a channel rather than addressing one, which is
1578
1714
  * why it lives here and not on {@link Call}. It resolves as soon as the
1579
- * INVITE is on the wire — the call is `calling`, and the answer, failure or
1580
- * timeout arrives later as an event on the channel.
1715
+ * INVITE is on the wire — the call is `calling` — to the {@link Call} it
1716
+ * placed: the answer, failure or timeout arrives on {@link Call.nextEvent},
1717
+ * exactly as a handed-over call's does, and `hangup` CANCELs or BYEs it.
1718
+ *
1719
+ * siphon sends no `StasisStart` for a channel its controller created, so the
1720
+ * channel is opened here before the command goes out (a fast 180 can
1721
+ * overtake the reply). An id still live on this client rejects with
1722
+ * `code === "conflict"` before anything is sent.
1581
1723
  *
1582
1724
  * ```ts
1583
1725
  * const call = await client.originate(
@@ -1589,23 +1731,8 @@ var SipClient = class _SipClient {
1589
1731
  * ```
1590
1732
  */
1591
1733
  async originate(channel, to, media, options) {
1592
- const result = await this.client.command(
1593
- MODULE_SIP,
1594
- "originate",
1595
- null,
1596
- originateArgs(channel, to, media, options)
1597
- );
1598
- const text = (name) => {
1599
- const value = result?.[name];
1600
- return typeof value === "string" ? value : void 0;
1601
- };
1602
- return {
1603
- // The server echoes the id back; fall back to the one we asked for
1604
- // rather than returning an empty channel a caller cannot address.
1605
- channel: text("channel") ?? channel,
1606
- callId: text("call_id"),
1607
- sipCallId: text("sip_call_id")
1608
- };
1734
+ const { result, queue } = await this.place(channel, originateArgs(channel, to, media, options));
1735
+ return this.placedCall(channel, text(result, "call_id"), text(result, "sip_call_id"), result, queue);
1609
1736
  }
1610
1737
  /**
1611
1738
  * Ring every phone registered at `aor` under a caller-supplied channel id —
@@ -1640,29 +1767,51 @@ var SipClient = class _SipClient {
1640
1767
  * ```
1641
1768
  */
1642
1769
  async originateAor(channel, aor, media, options, ring) {
1643
- const result = await this.client.command(
1644
- MODULE_SIP,
1645
- "originate",
1646
- null,
1770
+ const { result, queue } = await this.place(
1771
+ channel,
1647
1772
  originateAorArgs(channel, aor, media, options, ring)
1648
1773
  );
1649
- const text = (name) => {
1650
- const value = result?.[name];
1651
- return typeof value === "string" ? value : void 0;
1652
- };
1653
- const count = (name) => {
1654
- const value = result?.[name];
1655
- return typeof value === "number" ? value : void 0;
1656
- };
1774
+ const groupId = text(result, "group_id");
1775
+ const totalTimeout = result?.total_timeout;
1657
1776
  return {
1658
- channel: text("channel") ?? channel,
1659
- groupId: text("group_id"),
1660
- aor: text("aor"),
1661
- strategy: text("strategy"),
1662
- totalTimeout: count("total_timeout"),
1777
+ // The server echoes the id back; fall back to the one we asked for
1778
+ // rather than returning an empty channel a caller cannot address.
1779
+ channel: text(result, "channel") ?? channel,
1780
+ // Until a phone answers, the group stands in for the call, as its events say.
1781
+ call: this.placedCall(channel, groupId, groupId, result, queue),
1782
+ groupId,
1783
+ aor: text(result, "aor"),
1784
+ strategy: text(result, "strategy"),
1785
+ totalTimeout: typeof totalTimeout === "number" ? totalTimeout : void 0,
1663
1786
  branches: branchList(result?.branches) ?? []
1664
1787
  };
1665
1788
  }
1789
+ /** Open `channel`, send the originate, and close it again if the server refuses. */
1790
+ async place(channel, args) {
1791
+ const queue = this.facade.openChannel(channel);
1792
+ if (queue === null) {
1793
+ throw ControlError.command("conflict", `channel ${channel} is already live on this client`);
1794
+ }
1795
+ try {
1796
+ const result = await this.client.command(MODULE_SIP, "originate", null, args);
1797
+ return { result, queue };
1798
+ } catch (error) {
1799
+ this.facade.closeChannel(channel);
1800
+ throw error;
1801
+ }
1802
+ }
1803
+ placedCall(channel, callId, sipCallId, reply, queue) {
1804
+ return new Call(
1805
+ this.client.commander(),
1806
+ channel,
1807
+ callId ?? null,
1808
+ sipCallId ?? null,
1809
+ null,
1810
+ reply,
1811
+ false,
1812
+ queue
1813
+ );
1814
+ }
1666
1815
  /** Send a raw command on any module (the generic escape hatch). */
1667
1816
  command(module, verb, target, args) {
1668
1817
  return this.client.command(module, verb, target, args);