sigelo-contact 0.1.21 → 0.1.22

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.
Files changed (69) hide show
  1. package/GROUPS-REFERENCE.md +165 -0
  2. package/GROUPS.md +53 -0
  3. package/LICENSE +235 -21
  4. package/README.md +4 -5
  5. package/call.mjs +89 -28
  6. package/carrier.mjs +230 -51
  7. package/control.mjs +2 -2
  8. package/create.mjs +2 -2
  9. package/device.mjs +2 -2
  10. package/enrol.mjs +2 -2
  11. package/envelope.mjs +6 -6
  12. package/file.mjs +2 -2
  13. package/fixtures/carrier-v0.json +1 -1
  14. package/fixtures/envelope-v0.json +1 -1
  15. package/fixtures/group-v2.json +2999 -0
  16. package/gen-carrier.mjs +2 -2
  17. package/gen-device.mjs +1 -1
  18. package/gen-envelope.mjs +2 -2
  19. package/gen-group2.mjs +291 -0
  20. package/gen-invite.mjs +2 -2
  21. package/gen-short.mjs +1 -1
  22. package/group.mjs +116 -17
  23. package/group2.mjs +1534 -0
  24. package/home-wire.mjs +812 -0
  25. package/invite.mjs +3 -3
  26. package/kdf.mjs +2 -2
  27. package/kin.mjs +62 -0
  28. package/link.mjs +6 -6
  29. package/package.json +25 -8
  30. package/page.mjs +507 -57
  31. package/photo.mjs +2 -2
  32. package/platform-node.mjs +6 -6
  33. package/prekeys.mjs +3 -3
  34. package/public.mjs +2 -2
  35. package/qr-decode.mjs +1 -1
  36. package/qr.mjs +2 -2
  37. package/relays.mjs +2 -2
  38. package/restore.mjs +2 -2
  39. package/rtc-web.mjs +3 -3
  40. package/short.mjs +2 -2
  41. package/store.mjs +22 -9
  42. package/test-carrier.mjs +32 -11
  43. package/test-device.mjs +3 -3
  44. package/test-enrol.mjs +9 -4
  45. package/test-envelope.mjs +2 -2
  46. package/test-file.mjs +2 -2
  47. package/test-group-move.mjs +225 -0
  48. package/test-group.mjs +1 -1
  49. package/test-group2.mjs +202 -0
  50. package/test-home.mjs +225 -0
  51. package/test-invite.mjs +1 -1
  52. package/test-link.mjs +3 -3
  53. package/test-platform.mjs +2 -2
  54. package/test-presence.mjs +2 -2
  55. package/test-push.mjs +5 -5
  56. package/test-relay-lane.mjs +3 -3
  57. package/test-short.mjs +1 -1
  58. package/test-tier.mjs +8 -2
  59. package/test-transfer-web.mjs +7 -7
  60. package/test-transfer.mjs +6 -6
  61. package/test-voice.mjs +2 -2
  62. package/test-ws.mjs +1 -1
  63. package/transfer-engine.mjs +6 -6
  64. package/transfer-node.mjs +5 -5
  65. package/transfer-web.mjs +3 -3
  66. package/transfer.mjs +8 -8
  67. package/voice-web.mjs +2 -2
  68. package/voice.mjs +7 -3
  69. package/words-lock.mjs +2 -2
package/call.mjs CHANGED
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: MIT
2
- // Voice calls (design/calls.md): 1:1 audio between two paired people, the media WebRTC (Opus, DTLS-SRTP) in the page's
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Voice calls (THREAT-MODEL §2.20, §3.17; apps/agent/UI-API.md "Calls"): 1:1 audio between two paired people, the media WebRTC (Opus, DTLS-SRTP) in the page's
3
3
  // own RTCPeerConnection, the signalling `sigelo-call/0` messages inside the pairing's signed envelopes. No import: the
4
4
  // computer's page loads this file as it is (`/call.mjs`, beside ui.js), the phone app through its import map.
5
5
  //
@@ -10,7 +10,7 @@
10
10
  // Phone the page's (ui.js): the microphone, the RTCPeerConnection (a fresh DTLS certificate per call), batched
11
11
  // candidates, the ICE timers and restarts, mute; it reaches its Line only through /api/calls*.
12
12
  //
13
- // The messages (design §2), content {typ, id, …}, id 32 hex, kept apart by the carrier (CALL_LABEL, CALL_SEND: never in
13
+ // The messages, content {typ, id, …}, id 32 hex, kept apart by the carrier (CALL_LABEL, CALL_SEND: never in
14
14
  // the inbox, the log, MCP; `watch` answers a ring `end unavailable`):
15
15
  // ring caller {attempt: 1, sdp (the offer, no address in it: ringSdp), exp (iat + 60 s), text (what an older app shows), pad}
16
16
  // ringing callee {} (only to a contact this side shares presence with: it says "online")
@@ -30,7 +30,7 @@
30
30
  // "Could not connect, not even through the relay host."). TURN (2026-11-26, for everyone): the Line's host asks its relay
31
31
  // for a credential (carrier.turnServer, relay/turn.mjs) at each connection (GET /api/calls/turn), again at a restart once
32
32
  // within TURN_FRESH_S of its expiry; the policy stays "all" (a direct pair preferred); the screen says "Via relay" while
33
- // the selected pair has a relayed candidate (getStats). "Always relay my media" (design §6, 2026-11-26: Settings, per
33
+ // the selected pair has a relayed candidate (getStats). "Always relay my media" (Settings, per
34
34
  // profile; SIGELO_ICE_POLICY=relay on a computer): GET /api/calls/turn says policy "relay", the connection is made with
35
35
  // iceTransportPolicy "relay" and only relayed candidates leave this page, their related address zeroed (relayOnly):
36
36
  // the contact never learns this device's addresses; a relay with no TURN to offer: RELAY_ONLY at once, nothing rung;
@@ -42,11 +42,13 @@
42
42
  // three bars. Signalling late or out of order: candidates wait for their description, a repeat is dropped, a restart's
43
43
  // candidates that come before it wait for it, an end that comes before its ring makes that ring a missed call. Glare (two rings crossing): the call
44
44
  // of the smaller original DID stands, the other side drops its own and takes the ring at once (both wanted the call).
45
- // A second call while one is live gets `end busy`. busy and unavailable, like ringing, go only to a contact shown this
46
- // side's presence (each says the carrier runs): another one hears nothing and its call rings out ("No answer").
45
+ // A second call while one is live gets `end busy`; so does a ring while the phone is in another app's call (a GSM call, another
46
+ // VoIP app: the host's alert answers { busy }, nothing rings), which stays here as a "Missed call". busy and unavailable, like
47
+ // ringing, go only to a contact shown this side's presence (each says the carrier runs): another one hears nothing and its call
48
+ // rings out ("No answer").
47
49
  //
48
- // Ringing with the app closed (design §5): not here. A ring waits at the relay; whatever wakes the app within its 60 s
49
- // (the push build, design/push.md) finds it in the first drain and rings through Line's `alert` hook; later than that
50
+ // Ringing with the app closed: not here. A ring waits at the relay; whatever wakes the app within its 60 s
51
+ // (the push build, apps/agent/UI-API.md "Push") finds it in the first drain and rings through Line's `alert` hook; later than that
50
52
  // it is a "Missed call". That hook is the seam: alert({on, id, did, name}) — the phone app's ringtone and heads-up today.
51
53
 
52
54
  export const CALL_LABEL = 'sigelo-call/0';
@@ -57,7 +59,7 @@ export const RING_S = 45, EXP_S = 60;
57
59
  /** Milliseconds: gathering before an answer or a restart goes (the ring waits for none), before the late candidates go; ICE after the answer; a disconnection
58
60
  * before the restart, then before the call is lost; a page's last poll for a ring to wait for it; an ended call shown. */
59
61
  export const GATHER_MS = 1000, LATE_MS = 5000, ICE_MS = 15000, DISCONNECTED_MS = 2000, RETRY_MS = 8000, LOST_MS = 30000, PAGE_MS = 10000, KEEP_MS = 30000;
60
- /** Weak links (2026-11-24): Opus at most MAX_BPS, at least MIN_BPS, stepped by the far end's RTCP every STATS_MS. */
62
+ /** Weak links: Opus at most MAX_BPS, at least MIN_BPS, stepped by the far end's RTCP every STATS_MS. */
61
63
  export const MAX_BPS = 16000, MIN_BPS = 8000, STEP_BPS = 4000, STATS_MS = 3000;
62
64
  /** A contact's busy or unavailable answers: at most one per REPLY_MS (a flood of rings costs this side one message a while). */
63
65
  export const REPLY_MS = 30000;
@@ -72,6 +74,8 @@ export const policyOf = (...v) => (v.some((x) => x === true || x === 'relay') ?
72
74
  /** Seconds: a TURN credential this close to its expiry is fetched again before an ICE restart gathers. */
73
75
  export const TURN_FRESH_S = 600;
74
76
  export const STUN_PORT = 3478;
77
+ /** A call's audio outputs where the host has a shell that switches them (the Android app: CallService), in the screen's order. */
78
+ export const ROUTES = Object.freeze(['earpiece', 'speaker', 'bluetooth', 'wired']);
75
79
 
76
80
  const ID = /^[0-9a-f]{32}$/;
77
81
  const bad = (check, message, status = 400) => { throw Object.assign(new Error(message), { check, status }); };
@@ -160,7 +164,7 @@ export function padded(content) {
160
164
  return { ...content, pad: '.'.repeat(Math.max(0, PAD - len)) };
161
165
  }
162
166
 
163
- /** The chat line a call leaves: { text, state } (design §4: "Call · 4:12", "Missed call", "Declined"). */
167
+ /** The chat line a call leaves: { text, state } ("Call · 4:12", "Missed call", "Declined"). */
164
168
  export function lineOf(call, nowMs) {
165
169
  if (call.connected !== null) {
166
170
  const s = Math.max(0, Math.floor(((call.ended ?? nowMs) - call.connected) / 1000));
@@ -180,11 +184,13 @@ export function lineOf(call, nowMs) {
180
184
  * send(did, content) → Promise the carrier's send, label CALL_LABEL, internal CALL_SEND
181
185
  * contact(did) → { did, name, online, … } | null a live contact by its (original) DID
182
186
  * allowed(c) → may that contact ring here ("Can call me"); shares(c) → may it see this side online (presence)
183
- * person(c) → is that contact a person (design §1: calls are between people; an agent's ring is refused silently,
187
+ * person(c) → is that contact a person (calls are between people; an agent's ring is refused silently,
184
188
  * no line, nothing said back, only refused({ did, id, check: 'call_agent' }) for the host's log)
185
189
  * me() → this identity's original DID (glare)
186
190
  * line({ did, dir, text, call: { id, state, secs } }) a chat line kept in the history
187
- * alert({ on, id, did, name }) the ring here (the seam above); audio({ on, id, name }) the call's audio mode (the
191
+ * alert({ on, id, did, name }) the ring here (the seam above); for on, it may answer (a value or a Promise) { busy: true }:
192
+ * the phone is in another app's call, nothing rang: the ring ends as a "Missed call" here and `end busy` goes back (to a
193
+ * contact shown presence), "Ringing…" only once it said not busy; audio({ on, id, name }) the call's audio mode (the
188
194
  * phone app's CallService); changed() after anything the page shows moved
189
195
  * o: { ringS, expS, pageMs, keepMs } (tests shorten them)
190
196
  */
@@ -234,7 +240,9 @@ export class Line {
234
240
  const now = this.now();
235
241
  if (rtc) this.pageAt = now;
236
242
  let c = this.current();
237
- if (!c) { for (const x of this.calls.values()) if (x.ended !== null && now - x.ended < this.o.keepMs && (!c || x.ended > c.ended)) c = x; }
243
+ if (c?.checking) return null; // a ring the host is still asking about (busy elsewhere?): not on a screen yet
244
+ // An ended call stays KEEP_MS for the screen; one that never rang here (busy elsewhere) is only its chat line.
245
+ if (!c) { for (const x of this.calls.values()) if (x.ended !== null && !x.unshown && now - x.ended < this.o.keepMs && (!c || x.ended > c.ended)) c = x; }
238
246
  for (const [id, x] of this.calls) if (x.ended !== null && now - x.ended >= this.o.keepMs) this.calls.delete(id);
239
247
  if (!c) return null;
240
248
  const secs = c.connected === null ? 0 : Math.max(0, Math.floor(((c.ended ?? now) - c.connected) / 1000));
@@ -313,7 +321,7 @@ export class Line {
313
321
  await this.#say(call, { typ: 'end', id, reason: r }).catch(() => {});
314
322
  return this.view();
315
323
  }
316
- /** The live call ended from outside the page (the phone's notification's Hang up). */
324
+ /** The live call ended from outside the page (the Hang up in the phone notification). */
317
325
  async hangup() { const c = this.current(); return c ? this.end(c.id, 'hangup') : null; }
318
326
 
319
327
  #finish(call, reason, by, { quiet = false } = {}) {
@@ -364,7 +372,7 @@ export class Line {
364
372
  if (this.seen.has(x.id)) return; // a repeat of one already taken
365
373
  this.#seen(x.id);
366
374
  const now = this.now(), nowS = Math.floor(now / 1000);
367
- // An agent rings no human (design §1): no ring, no line, nothing back; the host logs it.
375
+ // An agent rings no human: no ring, no line, nothing back; the host logs it.
368
376
  if (!this.person(c)) { this.dropped++; try { this.refused({ did: c.did, id: x.id, check: 'call_agent' }); } catch {} return; }
369
377
  // Not allowed to ring here (a quiet contact, the switch off) or past its life: a line, nothing said back.
370
378
  if (!this.allowed(c) || x.exp <= nowS || this.gone.has(`${c.did} ${x.id}`)) return this.#missed(c, x.id);
@@ -387,8 +395,20 @@ export class Line {
387
395
  const call = { id: x.id, did: c.did, name: c.name, dir: 'in', state: 'incoming', at: now, answered: null, connected: null, ended: null, reason: null, by: null, glare, attempt: 1, n: 0, signals: [], offer: x.sdp, exp, audio: false };
388
396
  this.calls.set(x.id, call); this.live = x.id;
389
397
  // "Ringing…" says this side is online: only to a contact that may see it (decision 2026-11-17).
390
- if (this.shares(c)) void this.send(c.did, { typ: 'ringing', id: x.id }).catch(() => {});
391
- if (!glare) this.alert({ on: true, id: x.id, did: c.did, name: c.name });
398
+ const ringing = () => { if (call.state === 'incoming' && this.shares(c)) void this.send(c.did, { typ: 'ringing', id: x.id }).catch(() => {}); };
399
+ let rang;
400
+ try { rang = glare ? undefined : this.alert({ on: true, id: x.id, did: c.did, name: c.name }); } catch {}
401
+ if (typeof rang?.then === 'function') {
402
+ // The host asks its shell first (the phone app: is another app's call going on?): "Ringing…" once it says no.
403
+ call.checking = true;
404
+ void Promise.resolve(rang).then((a) => a, () => null).then((a) => {
405
+ call.checking = false;
406
+ if (call.state !== 'incoming') return;
407
+ if (a?.busy === true) return this.#busyElsewhere(call, c);
408
+ ringing(); this.changed();
409
+ });
410
+ } else if (rang?.busy === true) { this.#busyElsewhere(call, c); return; }
411
+ else ringing();
392
412
  this.#after(call, Math.max(0, exp * 1000 - now), () => { if (call.state === 'incoming') this.#finish(call, 'no_answer', 'them'); });
393
413
  // No page here that can take a call (none polled with rtc lately): unavailable, once the page had its chance.
394
414
  const check = () => {
@@ -401,16 +421,29 @@ export class Line {
401
421
  if (now - this.pageAt > this.o.pageMs) this.#after(call, this.o.pageMs, check);
402
422
  this.changed();
403
423
  }
404
- close() { for (const c of this.calls.values()) this.#clear(c); }
424
+ /** The phone is in another app's call (the host's alert said busy): no ring, a "Missed call" here, `end busy` to a
425
+ * contact that may see this side online (as for a second sigelo call); else its call rings out. */
426
+ #busyElsewhere(call, c) {
427
+ call.unshown = true;
428
+ this.#finish(call, 'busy', 'me');
429
+ if (this.shares(c)) this.#reply(c.did, { typ: 'end', id: call.id, reason: 'busy' });
430
+ }
431
+ /** The Line done (the page halted): its timers off, and a ring still sounding here stopped (its exp timer is gone with them). */
432
+ close() {
433
+ for (const c of this.calls.values()) {
434
+ this.#clear(c);
435
+ if (c.state === 'incoming') { try { this.alert({ on: false, id: c.id, did: c.did, name: c.name }); } catch {} }
436
+ }
437
+ }
405
438
  }
406
439
 
407
440
  /**
408
441
  * The /api/calls* routes over one Line (UI-API.md "Calls"). contactOf(did) → the contact (refuses an unknown one);
409
442
  * callable(c) → whether this side may call it now (a person, present); stun(c) → the STUN list; turn() → { urls, username,
410
- * credential, exp } | null (the relay's TURN credential: carrier.turnServer); can: { speaker, mic, ring }
411
- * (ring: the host rings itself, the page plays no tone);
412
- * hooks: { speaker(on), mic(), micSettings() } where the host has them (the phone app); allow(c, on) / allowOf(c) the
413
- * "Can call me" switch.
443
+ * credential, exp } | null (the relay's TURN credential: carrier.turnServer); can: { speaker, mic, ring, route }
444
+ * (ring: the host rings itself, the page plays no tone; route: the host switches the audio output);
445
+ * hooks: { speaker(on), mic(), micSettings(), route(to?) → { current, available, held } } where the host has them (the
446
+ * phone app); allow(c, on) / allowOf(c) the "Can call me" switch.
414
447
  */
415
448
  export function callRoutes({ line, contactOf, callable, stun, turn = async () => null, policy = () => 'all', can = {}, hooks = {}, allow, allowOf }) {
416
449
  const idOf = (b) => (typeof b['id'] === 'string' && ID.test(b['id']) ? b['id'] : bad('body', 'id: a call id (32 hex digits)'));
@@ -419,7 +452,7 @@ export function callRoutes({ line, contactOf, callable, stun, turn = async () =>
419
452
  'GET /api/calls': (_, q) => {
420
453
  const to = q?.get?.('to'), c = to ? contactOf(to) : null, call = line.view({ rtc: q?.get?.('rtc') === '1' });
421
454
  const peer = c ?? (call ? contactOf(call.did) : null);
422
- return { call, stun: stun(peer), can: { speaker: can.speaker === true, mic: can.mic === true, ring: can.ring === true } };
455
+ return { call, stun: stun(peer), can: { speaker: can.speaker === true, mic: can.mic === true, ring: can.ring === true, route: can.route === true } };
423
456
  },
424
457
  // A TURN server for a connection starting now; null: STUN alone. Asked at each connection, never in the poll.
425
458
  // policy: "relay" with "Always relay my media" on (the page then refuses to connect without TURN), else "all".
@@ -441,6 +474,12 @@ export function callRoutes({ line, contactOf, callable, stun, turn = async () =>
441
474
  'POST /api/calls/connected': (b) => ({ call: line.connected(idOf(b)) }),
442
475
  'POST /api/calls/end': async (b) => ({ call: await line.end(idOf(b), b['reason'] ?? 'hangup') }),
443
476
  ...(typeof hooks.speaker === 'function' && { 'POST /api/calls/speaker': async (b) => { if (typeof b['on'] !== 'boolean') bad('body', 'on: true or false'); await hooks.speaker(b['on']); return { speaker: b['on'] }; } }),
477
+ // The audio output: to one of ROUTES, or (no to) the state only → { current, available, held }.
478
+ ...(typeof hooks.route === 'function' && { 'POST /api/calls/route': async (b) => {
479
+ if (b['to'] !== undefined && !ROUTES.includes(b['to'])) bad('body', `to: ${ROUTES.join(', ')}`);
480
+ const r = (await hooks.route(b['to'])) ?? {};
481
+ return { current: ROUTES.includes(r.current) ? r.current : null, available: ROUTES.filter((x) => Array.isArray(r.available) && r.available.includes(x)), held: r.held === true };
482
+ } }),
444
483
  ...(typeof hooks.mic === 'function' && { 'POST /api/calls/mic': async () => ({ granted: await hooks.mic() }) }),
445
484
  ...(typeof hooks.micSettings === 'function' && { 'POST /api/calls/mic-settings': async () => { await hooks.micSettings(); return { opened: true }; } }),
446
485
  'POST /api/calls/allow': (b) => {
@@ -454,7 +493,7 @@ export function callRoutes({ line, contactOf, callable, stun, turn = async () =>
454
493
 
455
494
  // ================================================================ the page's half
456
495
  /**
457
- * Opus for weak links (design §3, 2026-11-24), asked of the far end's encoder through the SDP it is given: mono,
496
+ * Opus for weak links, asked of the far end's encoder through the SDP it is given: mono,
458
497
  * DTX (no packets in silence), in-band FEC, at most MAX_BPS, 20 ms frames (a=ptime:20). Applied to every remote description.
459
498
  */
460
499
  export function opusTune(sdp) {
@@ -492,7 +531,9 @@ export const AUDIO = Object.freeze({ echoCancellation: true, noiseSuppression: t
492
531
  * onState(view) at every change (the call screen); onStream(stream | null) the far end's audio
493
532
  * o: { gatherMs, lateMs, iceMs, disconnectedMs, lostMs, pollMs }
494
533
  * phone.tick() reads GET /api/calls?rtc=1 and acts on it (the page's poll calls it; while a call is live it polls itself).
495
- * phone.place(did), accept(), decline(), hangup(), mute(on), speaker(on); phone.view() → what the screen shows.
534
+ * phone.place(did), accept(), decline(), hangup(), mute(on), speaker(on), route(to?); phone.routed({ current, available, held })
535
+ * (the shell's route event); phone.view() → what the screen shows. held: another call (GSM, another VoIP app) took the
536
+ * phone's voice focus: the microphone paused here (and the far end's sound on the screen) until it comes back.
496
537
  */
497
538
  export class Phone {
498
539
  constructor({ api, RTC = globalThis.RTCPeerConnection, media, onState = () => {}, onStream = () => {}, timers = globalThis, now = () => Date.now(), o = {} }) {
@@ -502,12 +543,13 @@ export class Phone {
502
543
  this.stun = [];
503
544
  this.turn = null; // the TURN server of this connection (GET /api/calls/turn), or null
504
545
  this.policy = 'all'; // its ICE policy (the same answer): "relay" with "Always relay my media" on
505
- this.can = { speaker: false, mic: false };
546
+ this.can = { speaker: false, mic: false, route: false };
506
547
  this.#reset();
507
548
  }
508
549
  #reset() {
509
550
  this.pc = null; this.stream = null; this.id = null; this.attempt = 1; this.applied = 0; this.pending = []; this.remote = false;
510
551
  this.ever = false; this.muted = false; this.speakerOn = false; this.phase = null; this.error = null; this.place_ = null;
552
+ this.audioRoute = null; this.held = false;
511
553
  this.reconnecting = false; this.quality = null; this.bps = MAX_BPS; this.clean = 0; this.prevIn = null; this.loss = null; this.rtt = null; this.relayed = null; this.turn = null;
512
554
  for (const k of ['ice', 'disc', 'retry', 'lost', 'stats', 'poll']) this.#stop(k);
513
555
  }
@@ -520,7 +562,7 @@ export class Phone {
520
562
  /** What the screen shows: the Line's view and this page's own (the phase, an error, mute and speaker). */
521
563
  view() {
522
564
  const c = this.call;
523
- return { call: c, phase: this.phase, error: this.error, muted: this.muted, speaker: this.speakerOn, can: this.can, reconnecting: this.reconnecting,
565
+ return { call: c, phase: this.phase, error: this.error, muted: this.muted, speaker: this.speakerOn, can: this.can, reconnecting: this.reconnecting, route: this.audioRoute, held: this.held,
524
566
  quality: this.reconnecting ? 0 : this.quality, relayed: this.relayed === true, bps: this.bps, loss: this.loss, rtt: this.rtt, live: Boolean(c && c.state !== 'ended') || this.phase === 'mic' || this.phase === 'placing' };
525
567
  }
526
568
  #changed() { try { this.onState(this.view()); } catch {} }
@@ -638,6 +680,7 @@ export class Phone {
638
680
  const r = await this.api('POST', '/api/calls/start', { to: did, sdp: ringSdp(pc.localDescription.sdp) });
639
681
  this.id = r.call.id; this.call = r.call; this.phase = null;
640
682
  this.#changed(); this.#loop();
683
+ void this.route().catch(() => {}); // the output the call started on (a headset if there is one)
641
684
  return r.call;
642
685
  } catch (e) {
643
686
  this.#fail(e); this.#close(); this.phase = 'failed'; this.#changed();
@@ -663,6 +706,7 @@ export class Phone {
663
706
  this.#start('ice', this.o.iceMs, () => this.#noPath());
664
707
  void this.#late(pc, 1, sdp);
665
708
  this.#changed(); this.#loop();
709
+ void this.route().catch(() => {});
666
710
  } catch (e) {
667
711
  this.#fail(e); this.phase = 'failed';
668
712
  // Relay only with no TURN here: the caller hears "Could not connect" (no_path), not a hang-up.
@@ -678,8 +722,25 @@ export class Phone {
678
722
  if (r?.call) this.call = r.call;
679
723
  this.#close(); this.#changed();
680
724
  }
681
- mute(on) { this.muted = on === true; for (const t of this.stream?.getAudioTracks() ?? []) t.enabled = !this.muted; this.#changed(); }
725
+ mute(on) { this.muted = on === true; this.#tracks(); this.#changed(); }
726
+ #tracks() { for (const t of this.stream?.getAudioTracks() ?? []) t.enabled = !this.muted && !this.held; }
682
727
  async speaker(on) { if (!this.can.speaker) return; await this.api('POST', '/api/calls/speaker', { on: on === true }); this.speakerOn = on === true; this.#changed(); }
728
+ /** The audio output to <to> (ROUTES), or (none) the state asked → { current, available, held }; null where the host has no routes. */
729
+ async route(to) {
730
+ if (!this.can.route) return null;
731
+ const r = await this.api('POST', '/api/calls/route', ROUTES.includes(to) ? { to } : {});
732
+ this.routed(r);
733
+ return this.audioRoute;
734
+ }
735
+ /** The host's route state (its answer, or the shell's {ev:"route"}): the output, the choices, another call holding the audio. */
736
+ routed(r) {
737
+ if (!r || typeof r !== 'object') return;
738
+ this.audioRoute = { current: ROUTES.includes(r.current) ? r.current : null, available: ROUTES.filter((x) => Array.isArray(r.available) && r.available.includes(x)) };
739
+ this.speakerOn = this.audioRoute.current === 'speaker';
740
+ this.held = r.held === true && this.view().live;
741
+ this.#tracks();
742
+ this.#changed();
743
+ }
683
744
  /** The page leaves the call screen for good (Close on the ended state). */
684
745
  dismiss() { if (!this.view().live) { this.call = null; this.phase = null; this.error = null; this.#changed(); } }
685
746