@ghostlytools/cli 1.11.0 → 1.11.2

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 (104) hide show
  1. package/README.md +24 -16
  2. package/dist/assets/{api-CTqIcdu7.js → api-BM3PsXbB.js} +372 -123
  3. package/dist/assets/api-BM3PsXbB.js.map +1 -0
  4. package/dist/assets/{api-B-52sVYp.js → api-CtXgscmK.js} +2 -2
  5. package/dist/assets/{apiKit-CZq4Lq4f.js → apiKit-lCTQ0EBG.js} +17 -7
  6. package/dist/assets/apiKit-lCTQ0EBG.js.map +1 -0
  7. package/dist/assets/appFetch-BKHy5H8J.js +194 -0
  8. package/dist/assets/appFetch-BKHy5H8J.js.map +1 -0
  9. package/dist/assets/{apps-kRsY9S2S.js → apps-DO_gAZgm.js} +1 -1
  10. package/dist/assets/{apps-C_X0zgSG.js → apps-Do26w3c7.js} +44 -40
  11. package/dist/assets/apps-Do26w3c7.js.map +1 -0
  12. package/dist/assets/{arkade-_aaB7VbW.js → arkade-CZrLbz-M.js} +2 -2
  13. package/dist/assets/{arkade-_aaB7VbW.js.map → arkade-CZrLbz-M.js.map} +1 -1
  14. package/dist/assets/{backup-DBg388Ke.js → backup-D21x1f5P.js} +1 -1
  15. package/dist/assets/{backup-OTvrmk-w.js → backup-j47AzDvG.js} +84 -33
  16. package/dist/assets/backup-j47AzDvG.js.map +1 -0
  17. package/dist/assets/{bitcoind-CZchoh43.js → bitcoind-CdSmvy2y.js} +3 -3
  18. package/dist/assets/{bitcoind-CZchoh43.js.map → bitcoind-CdSmvy2y.js.map} +1 -1
  19. package/dist/assets/{bitcoindProvider-DGw3xBSa.js → bitcoindProvider-BvoRh0D5.js} +2 -2
  20. package/dist/assets/{bitcoindProvider-DGw3xBSa.js.map → bitcoindProvider-BvoRh0D5.js.map} +1 -1
  21. package/dist/assets/{buttons-DUu7hxxT.js → buttons-CiGlBVBT.js} +18 -7
  22. package/dist/assets/buttons-CiGlBVBT.js.map +1 -0
  23. package/dist/assets/buttons-D2l2bVCG.js +2 -0
  24. package/dist/assets/{childEnv-BVOQK9EA.js → childEnv-K_IzUqQx.js} +4 -3
  25. package/dist/assets/childEnv-K_IzUqQx.js.map +1 -0
  26. package/dist/assets/{client-DDpZP1R1.js → client-raIncVtF.js} +31 -3
  27. package/dist/assets/client-raIncVtF.js.map +1 -0
  28. package/dist/assets/{codec-DrryGcPT.js → codec-DcG2AeyE.js} +2 -2
  29. package/dist/assets/{codec-DrryGcPT.js.map → codec-DcG2AeyE.js.map} +1 -1
  30. package/dist/assets/endpoint-DarqblYE.js +5052 -0
  31. package/dist/assets/endpoint-DarqblYE.js.map +1 -0
  32. package/dist/assets/{envelope-Q_rMgoE9.js → envelope-Dud6lntA.js} +2 -2
  33. package/dist/assets/{envelope-Q_rMgoE9.js.map → envelope-Dud6lntA.js.map} +1 -1
  34. package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-DRKRSw14.js} +6 -3
  35. package/dist/assets/fedimintSdk-DRKRSw14.js.map +1 -0
  36. package/dist/assets/{fixedHosts-BV5GDiTU.js → fixedHosts-CNX7QiUD.js} +3 -3
  37. package/dist/assets/{fixedHosts-BV5GDiTU.js.map → fixedHosts-CNX7QiUD.js.map} +1 -1
  38. package/dist/assets/{host-BlUzZgQL.js → host-8RskzQgB.js} +306 -84
  39. package/dist/assets/host-8RskzQgB.js.map +1 -0
  40. package/dist/assets/{hyperdhtRelay-BvI_uNZO.js → hyperdhtRelay-uAThbFub.js} +2 -2
  41. package/dist/assets/{hyperdhtRelay-BvI_uNZO.js.map → hyperdhtRelay-uAThbFub.js.map} +1 -1
  42. package/dist/assets/{irohWeb-CqPN8VPY.js → irohWeb-DGelfgDJ.js} +695 -40
  43. package/dist/assets/irohWeb-DGelfgDJ.js.map +1 -0
  44. package/dist/assets/jsonOut-POtMBS_V.js +16 -0
  45. package/dist/assets/jsonOut-POtMBS_V.js.map +1 -0
  46. package/dist/assets/{main-vQjlgEnt.js → main-BC33ooYg.js} +175 -107
  47. package/dist/assets/main-BC33ooYg.js.map +1 -0
  48. package/dist/assets/{mainline-p6HOW7sb.js → mainline-DYrjsS1t.js} +27 -8
  49. package/dist/assets/mainline-DYrjsS1t.js.map +1 -0
  50. package/dist/assets/{networkReason-DMffkiJ6.js → networkReason-n2oBs4by.js} +3 -3
  51. package/dist/assets/{networkReason-DMffkiJ6.js.map → networkReason-n2oBs4by.js.map} +1 -1
  52. package/dist/assets/{nwc-2vH18oNy.js → nwc-Do3VSlIS.js} +6 -5
  53. package/dist/assets/nwc-Do3VSlIS.js.map +1 -0
  54. package/dist/assets/{nwcProvider-DpeDy0bV.js → nwcProvider-Du5aWNIn.js} +6 -3
  55. package/dist/assets/{nwcProvider-DpeDy0bV.js.map → nwcProvider-Du5aWNIn.js.map} +1 -1
  56. package/dist/assets/{ownDid-iKz8u_fM.js → ownDid-CwwYu8s2.js} +3 -3
  57. package/dist/assets/{ownDid-iKz8u_fM.js.map → ownDid-CwwYu8s2.js.map} +1 -1
  58. package/dist/assets/{ownStatus-BlRKnM5F.js → ownStatus-D7dB4zJB.js} +4 -3
  59. package/dist/assets/{ownStatus-BlRKnM5F.js.map → ownStatus-D7dB4zJB.js.map} +1 -1
  60. package/dist/assets/{profiles-B5e0TyvS.js → profiles-NyF5FnYF.js} +82 -6
  61. package/dist/assets/profiles-NyF5FnYF.js.map +1 -0
  62. package/dist/assets/{registry-Cc_PQb3k.js → registry-C734VrO9.js} +1 -1
  63. package/dist/assets/{registry-CnFO2Pp5.js → registry-DKDInr0A.js} +75 -23
  64. package/dist/assets/registry-DKDInr0A.js.map +1 -0
  65. package/dist/assets/{resolve-DI8uAM_Y.js → resolve-3Tqh9AWQ.js} +4 -3
  66. package/dist/assets/resolve-3Tqh9AWQ.js.map +1 -0
  67. package/dist/assets/{server-DdtPxkqI.js → server-B6PQ6iae.js} +430 -868
  68. package/dist/assets/server-B6PQ6iae.js.map +1 -0
  69. package/dist/assets/{src-BnpEQqzk.js → src-ChJijTlM.js} +1139 -243
  70. package/dist/assets/src-ChJijTlM.js.map +1 -0
  71. package/dist/assets/{sshForges-cdIAraDw.js → sshForges-Brf0fslM.js} +2 -2
  72. package/dist/assets/{sshForges-cdIAraDw.js.map → sshForges-Brf0fslM.js.map} +1 -1
  73. package/dist/assets/{translate-kNopA04L.js → translate-xLme9Rdh.js} +10 -8
  74. package/dist/assets/translate-xLme9Rdh.js.map +1 -0
  75. package/dist/assets/{types-C4_KafL_.js → types-Clyb52K2.js} +2 -1
  76. package/dist/assets/types-Clyb52K2.js.map +1 -0
  77. package/dist/assets/{usdt-CDaLhEYh.js → usdt-CSU5KzTV.js} +3 -3
  78. package/dist/assets/{usdt-CDaLhEYh.js.map → usdt-CSU5KzTV.js.map} +1 -1
  79. package/dist/ghostly.mjs +1 -1
  80. package/npm-shrinkwrap.json +3592 -0
  81. package/package.json +5 -3
  82. package/dist/assets/api-CTqIcdu7.js.map +0 -1
  83. package/dist/assets/apiKit-CZq4Lq4f.js.map +0 -1
  84. package/dist/assets/apps-C_X0zgSG.js.map +0 -1
  85. package/dist/assets/backup-OTvrmk-w.js.map +0 -1
  86. package/dist/assets/buttons-4EKtQl-7.js +0 -2
  87. package/dist/assets/buttons-DUu7hxxT.js.map +0 -1
  88. package/dist/assets/childEnv-BVOQK9EA.js.map +0 -1
  89. package/dist/assets/client-DDpZP1R1.js.map +0 -1
  90. package/dist/assets/endpoint-DWHkXWVM.js +0 -419
  91. package/dist/assets/endpoint-DWHkXWVM.js.map +0 -1
  92. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +0 -1
  93. package/dist/assets/host-BlUzZgQL.js.map +0 -1
  94. package/dist/assets/irohWeb-CqPN8VPY.js.map +0 -1
  95. package/dist/assets/main-vQjlgEnt.js.map +0 -1
  96. package/dist/assets/mainline-p6HOW7sb.js.map +0 -1
  97. package/dist/assets/nwc-2vH18oNy.js.map +0 -1
  98. package/dist/assets/profiles-B5e0TyvS.js.map +0 -1
  99. package/dist/assets/registry-CnFO2Pp5.js.map +0 -1
  100. package/dist/assets/resolve-DI8uAM_Y.js.map +0 -1
  101. package/dist/assets/server-DdtPxkqI.js.map +0 -1
  102. package/dist/assets/src-BnpEQqzk.js.map +0 -1
  103. package/dist/assets/translate-kNopA04L.js.map +0 -1
  104. package/dist/assets/types-C4_KafL_.js.map +0 -1
@@ -1,15 +1,15 @@
1
- import { As as signalHasVideo, Cs as answersOffer, Es as callSignalHeardAt, Oa as ACTIVE_DHT_POLL_MS, Os as extractParamsFromSdp, Ss as RTC_CONFIG, Ts as callRtcConfig, Uu as setLinkTraceSink, as as DAEMON_WATCH_PEER_IDLE_MS, ba as isPublicAddress, bi as checkPushEndpoint, bs as CALL_SIGNAL_MAX_AGE_MS, fd as fromBase64Url, ks as parseCallSignal, ws as buildSdpFromSignal } from "./src-BnpEQqzk.js";
1
+ import { As as callSignalHeardAt, Ds as answersOffer, Es as RTC_CONFIG, Ma as ACTIVE_DHT_POLL_MS, Ms as extractParamsFromSdp, Ns as parseCallSignal, Os as buildSdpFromSignal, Ps as signalHasVideo, Qr as STATUS_IDLE_AFTER_MS, _d as fromBase64Url, ks as callRtcConfig, ls as DAEMON_WATCH_PEER_IDLE_MS, qu as setLinkTraceSink, wa as isPublicAddress, wi as checkPushEndpoint, ws as CALL_SIGNAL_MAX_AGE_MS } from "./src-ChJijTlM.js";
2
2
  import { p as fileStore } from "./idb-CEuoNsTv.js";
3
- import { r as irohRelayProblem } from "./irohWeb-CqPN8VPY.js";
4
- import { n as fedimintSdkOn } from "./fedimintSdk-CqTeMdF0.js";
3
+ import { r as irohRelayProblem } from "./irohWeb-DGelfgDJ.js";
4
+ import { n as fedimintSdkOn } from "./fedimintSdk-DRKRSw14.js";
5
5
  import { r as asCliError, t as CliError } from "./errors-Dt-ZnyOX.js";
6
- import { A as sinceSeq, s as findChat, u as findOwnNamedChat } from "./apiKit-CZq4Lq4f.js";
7
- import { _ as resumeHolds, d as servedApps, f as nodeLocalFetch, g as groupMessageJson, h as groupJson, l as paymentJson, m as chatMessageJson, p as chatJson, r as callApi, u as reportAppFrames, v as flushCardUpdates } from "./api-CTqIcdu7.js";
8
- import { C as privateFolder, b as ownFolder, n as RESTORED_MARK, r as acquireLock, v as startingPath, w as runtimePath, x as ownProfile } from "./profiles-B5e0TyvS.js";
9
- import { _ as isCallRate, c as newDaemonSecret, f as DEFAULT_RATE, g as frameSamples, h as frameBytes, l as proof, m as bytesToMs, p as PlaybackQueue, s as greeting, u as removeDaemonSecret, v as monotonic } from "./client-DDpZP1R1.js";
6
+ import { A as sinceSeq, s as findChat, u as findOwnNamedChat } from "./apiKit-lCTQ0EBG.js";
7
+ import { _ as groupPayTwins, d as servedApps, f as nodeLocalFetch, g as groupMessageJson, h as groupJson, l as paymentJson, m as chatMessageJson, p as chatJson, r as callApi, u as reportAppFrames, v as resumeHolds, y as flushCardUpdates } from "./api-BM3PsXbB.js";
8
+ import { C as ownProfile, E as runtimePath, S as ownFolder, T as privateFolder, b as startingPath, n as RESTORED_MARK, r as acquireLock } from "./profiles-NyF5FnYF.js";
9
+ import { _ as frameSamples, c as greeting, d as removeDaemonSecret, g as frameBytes, h as bytesToMs, l as newDaemonSecret, m as PlaybackQueue, p as DEFAULT_RATE, u as proof, v as isCallRate, y as monotonic } from "./client-raIncVtF.js";
10
10
  import { createRequire } from "node:module";
11
- import { appendFileSync, chmodSync, closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, truncateSync, writeFileSync, writeSync } from "node:fs";
12
- import { readFile } from "node:fs/promises";
11
+ import { appendFileSync, chmodSync, closeSync, existsSync, fstatSync, fsync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, truncateSync, writeFileSync, writeSync } from "node:fs";
12
+ import { open, readFile } from "node:fs/promises";
13
13
  import { dirname, join } from "node:path";
14
14
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
15
15
  import { networkInterfaces } from "node:os";
@@ -20,6 +20,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
20
20
  import { Worker } from "node:worker_threads";
21
21
  import { request } from "node:https";
22
22
  import { lookup } from "node:dns";
23
+ import { WebSocket } from "ws";
23
24
  import { deserialize, serialize } from "node:v8";
24
25
  import { IDBFactory, IDBKeyRange, IDBTransaction } from "fake-indexeddb";
25
26
  //#region src/announce.ts
@@ -75,6 +76,21 @@ function clearAudioSockets(profileDir) {
75
76
  } catch {}
76
77
  }
77
78
  /**
79
+ * The socket's handlers for a call's queue: what the program writes is queued, and a program that takes the socket
80
+ * (the first, or one that replaces the last) starts on a queue of its own (`PlaybackQueue.newWriter`): the last
81
+ * one's leftover, half a sample included, would otherwise shift all of its audio by a byte.
82
+ */
83
+ function feedQueue(queue) {
84
+ return {
85
+ onAudio: (chunk) => {
86
+ queue.push(chunk);
87
+ },
88
+ onClient: (connected) => {
89
+ if (connected) queue.newWriter();
90
+ }
91
+ };
92
+ }
93
+ /**
78
94
  * Serves one call's audio to one program at a time: what the program writes is handed to `onAudio` as it comes (raw
79
95
  * PCM, any amount); `write` gives it the caller's audio. A second connection replaces the first. `close` ends the
80
96
  * program's connection (it reads EOF) and removes the socket.
@@ -259,6 +275,10 @@ var RtpWriter = class {
259
275
  this.timestamp = this.timestamp + 960 >>> 0;
260
276
  return Buffer.concat([header, payload]);
261
277
  }
278
+ /** Moves the timestamp on by frames that were never sent (their time went by), the sequence as it is. */
279
+ skip(frames) {
280
+ this.timestamp = this.timestamp + frames * 960 >>> 0;
281
+ }
262
282
  };
263
283
  /** The most frames a gap in the packets becomes (concealed by the decoder, see CallAudio). */
264
284
  var MAX_LOST_FRAMES = 3;
@@ -521,11 +541,13 @@ var CallAudio = class {
521
541
  * slower than a frame for a while (every 40 ms under a large file) keeps up, and a program writing at real time
522
542
  * stays there. The contact's jitter buffer takes the short burst. A stall past MAX_CATCH_UP_MS is not replayed: the
523
543
  * clock starts again and what the program wrote during it is dropped, or it would be heard that much late for the
524
- * rest of the call.
544
+ * rest of the call. The frames it skipped still move the RTP timestamp on (the sampling time, RFC 3550), so the
545
+ * contact's jitter buffer does not take the gap for seconds of jitter.
525
546
  */
526
547
  catchUp(late) {
527
548
  const now = this.options.now ?? monotonic;
528
549
  if (late > 1e3) {
550
+ this.writer.skip(Math.round(late / 20));
529
551
  this.owed = late;
530
552
  this.kept = this.ahead;
531
553
  this.owedUntil = now() + MAX_CATCH_UP_MS;
@@ -1457,7 +1479,7 @@ var CallManager = class {
1457
1479
  */
1458
1480
  async attach(call, create) {
1459
1481
  const queue = call.queue = new PlaybackQueue(call.rate);
1460
- const socket = await AudioSocket.open(audioSocketPath(this.host.profileDir, call.id), call.rate, { onAudio: (chunk) => queue.push(chunk) });
1482
+ const socket = await AudioSocket.open(audioSocketPath(this.host.profileDir, call.id), call.rate, feedQueue(queue));
1461
1483
  if (call.ended) {
1462
1484
  await socket.close();
1463
1485
  return;
@@ -1772,6 +1794,40 @@ function readAuto(path) {
1772
1794
  return off;
1773
1795
  }
1774
1796
  }
1797
+ //#endregion
1798
+ //#region src/daemonPresence.ts
1799
+ /** How often a daemon that shares its presence says `active` again: well within the engine's 10 minutes to `idle`. */
1800
+ var PRESENCE_EVERY_MS = STATUS_IDLE_AFTER_MS / 2;
1801
+ /**
1802
+ * A headless profile's presence (WISP 401 § Presence and status): off unless `settings set daemonPresence true`. On,
1803
+ * a running daemon says `active` to every paired contact whose app offers `status/1`, as a page does on input, and keeps
1804
+ * saying it while it runs; contacts see its dot. Turned off, it is taken back at once. When the daemon stops, its
1805
+ * sessions end and presence with them. A one-shot command never says it: it is gone a moment later.
1806
+ */
1807
+ var DaemonPresence = class {
1808
+ node;
1809
+ timer;
1810
+ constructor(node) {
1811
+ this.node = node;
1812
+ }
1813
+ /** Follows the setting in each state the engine draws. */
1814
+ check(state) {
1815
+ const on = state.settings.daemonPresence === true;
1816
+ if (on === (this.timer !== void 0)) return;
1817
+ if (!on) {
1818
+ this.stop();
1819
+ this.node.setPresence({ presence: null });
1820
+ return;
1821
+ }
1822
+ this.node.setPresence({ presence: "active" });
1823
+ this.timer = setInterval(() => this.node.setPresence({ presence: "active" }), PRESENCE_EVERY_MS);
1824
+ this.timer.unref?.();
1825
+ }
1826
+ stop() {
1827
+ clearInterval(this.timer);
1828
+ this.timer = void 0;
1829
+ }
1830
+ };
1775
1831
  /** A journal past this is trimmed, and only this much of its end is ever read. */
1776
1832
  var JOURNAL_MAX_BYTES = 33554432;
1777
1833
  /**
@@ -2654,6 +2710,8 @@ var EventHub = class {
2654
2710
  this.reactions(chat, group, messages, quiet);
2655
2711
  const files = [];
2656
2712
  const cutoff = this.now() - SEEN_KEEP_MS;
2713
+ let twinLines;
2714
+ const twins = () => twinLines ??= group ? groupPayTwins(messages, new Map(messages.flatMap((m) => m.groupPay ? [[m.groupPay.id, m.groupPay]] : [])), this.state?.payments ?? {}, this.state?.groups.find((g) => g.id === group)) : /* @__PURE__ */ new Map();
2657
2715
  for (const message of messages) {
2658
2716
  present.add(message.id);
2659
2717
  if (message.file && this.fileMessages.get(message.file.id) !== message.id) {
@@ -2663,7 +2721,7 @@ var EventHub = class {
2663
2721
  let state = stateOf(message);
2664
2722
  const note = known.get(message.id), before = note === void 0 ? void 0 : stateIn(note);
2665
2723
  const at = activityOf(message);
2666
- const json = () => group ? groupMessageJson(message, this.state?.groups.find((g) => g.id === group)) : chatMessageJson(message, this.state?.links.find((l) => l.id === chat));
2724
+ const json = () => group ? groupMessageJson(message, this.state?.groups.find((g) => g.id === group), twins().get(message.id)) : chatMessageJson(message, this.state?.links.find((l) => l.id === chat));
2667
2725
  if (before === void 0 && cameAt(message) < cutoff) {
2668
2726
  if (at < cutoff) continue;
2669
2727
  const noted = noteOf(state, at);
@@ -2717,8 +2775,9 @@ var EventHub = class {
2717
2775
  if (message.sender === "peer" && message.press) this.pressed(chat, group, message, json());
2718
2776
  continue;
2719
2777
  }
2720
- if (message.sender === "peer" && message.press && !pressedIn(before)) this.pressed(chat, group, message, json());
2721
- if (group && mentionedIn(state) && !mentionedIn(before) && this.mentionsNoted) this.emit("group.mentioned", `group.mentioned:${group}:${message.id}`, {
2778
+ const mentioned = !!group && mentionedIn(state) && !mentionedIn(before) && this.mentionsNoted;
2779
+ if (message.sender === "peer" && message.press && !pressedIn(before)) this.pressed(chat, group, message, json(), !!group && !mentioned);
2780
+ if (mentioned) this.emit("group.mentioned", `group.mentioned:${group}:${message.id}`, {
2722
2781
  group,
2723
2782
  messageId: message.id,
2724
2783
  message: json()
@@ -2788,9 +2847,9 @@ var EventHub = class {
2788
2847
  * profile gave the chat, as `chat list` gives it; null without one, and in a group) and the reply (`replyId`).
2789
2848
  * `untrusted.name` is the name the person gave themselves, as an agent turn's: theirs to choose, so data, never
2790
2849
  * instructions, and under `untrusted` only. The engine marks a reply a press only while the buttons were open for
2791
- * that person.
2850
+ * that person. `message` (the reply, as `group.message` gives it) only on a group press learned after its reply's event.
2792
2851
  */
2793
- pressed(chat, group, message, json) {
2852
+ pressed(chat, group, message, json, withReply = false) {
2794
2853
  const press = message.press;
2795
2854
  const link = group ? void 0 : this.state?.links.find((l) => l.id === chat);
2796
2855
  const name = link ? chatJson(link).label : null;
@@ -2803,7 +2862,8 @@ var EventHub = class {
2803
2862
  name,
2804
2863
  replyId: message.id,
2805
2864
  ...press.inferred ? { inferred: true } : {},
2806
- untrusted: { name: json.nick ?? null }
2865
+ untrusted: { name: json.nick ?? null },
2866
+ ...withReply ? { message: json } : {}
2807
2867
  });
2808
2868
  }
2809
2869
  /**
@@ -3577,21 +3637,56 @@ function nodeHoldFetch(lookup = publicOnlyLookup) {
3577
3637
  /**
3578
3638
  * Whether the CLI's Iroh may dial a contact through the relay its descriptor names (irohWeb.ts `publicRelay`): at a
3579
3639
  * public address, or at a name whose every address is public now, as a held item's is (`publicOnlyLookup`). Asked again
3580
- * before each dial. The wasm resolves the name once more when it connects, so a name that changes its answer in
3581
- * between is not caught here.
3640
+ * before each dial. A name it takes is then opened only through that same lookup (`relaySockets`), each time the wasm
3641
+ * connects to it, so a name that answers this machine or its network after the check is not reached either.
3582
3642
  */
3583
3643
  function nodePublicRelay(lookup = publicOnlyLookup) {
3584
3644
  return (relay) => new Promise((resolve) => {
3585
- let host;
3645
+ let url;
3586
3646
  try {
3587
- host = new URL(relay).hostname.replace(/^\[(.*)\]$/, "$1");
3647
+ url = new URL(relay);
3588
3648
  } catch {
3589
3649
  return resolve(false);
3590
3650
  }
3651
+ const host = url.hostname.replace(/^\[(.*)\]$/, "$1");
3591
3652
  if (isIP(host)) return resolve(isPublicIp(host));
3592
- lookup(host, { all: true }, (error) => resolve(!error));
3653
+ lookup(host, { all: true }, (error) => {
3654
+ if (!error) relaySockets(globalThis).set(socketKey(url), lookup);
3655
+ resolve(!error);
3656
+ });
3593
3657
  });
3594
3658
  }
3659
+ /** A WebSocket URL's host and port, the same for a relay's https:// URL and the wss:// one the wasm opens. */
3660
+ function socketKey(url) {
3661
+ const port = url.port || (url.protocol === "https:" || url.protocol === "wss:" ? "443" : "80");
3662
+ return `${url.hostname.replace(/\.$/, "")}:${port}`;
3663
+ }
3664
+ var installed = /* @__PURE__ */ new WeakMap();
3665
+ /**
3666
+ * The wasm Iroh opens its relays with the global `WebSocket`, which resolves the name again by itself. From the first
3667
+ * contact's relay `nodePublicRelay` takes, the global one opens a socket to that relay's host and port with `ws` and
3668
+ * that check's lookup instead, so the address it dials is one the lookup took then; every other socket is the global
3669
+ * one as before. Answers the host and port → lookup table.
3670
+ */
3671
+ function relaySockets(scope) {
3672
+ let names = installed.get(scope);
3673
+ if (names) return names;
3674
+ const checked = names = /* @__PURE__ */ new Map();
3675
+ installed.set(scope, names);
3676
+ scope.WebSocket = new Proxy(scope.WebSocket, { construct(target, args, newTarget) {
3677
+ let lookup;
3678
+ try {
3679
+ lookup = checked.get(socketKey(new URL(args[0])));
3680
+ } catch {}
3681
+ if (!lookup) return Reflect.construct(target, args, newTarget);
3682
+ return new WebSocket(args[0], args[1], {
3683
+ lookup,
3684
+ followRedirects: false,
3685
+ perMessageDeflate: false
3686
+ });
3687
+ } });
3688
+ return names;
3689
+ }
3595
3690
  //#endregion
3596
3691
  //#region src/runtime/rows.ts
3597
3692
  /** The warning `node:sqlite` gives as it loads (experimental on Node 22 and 23): said once for every command, it is noise. */
@@ -3828,7 +3923,15 @@ var TreeFile = class {
3828
3923
  }
3829
3924
  /** Everything SQLite holds is on disk: before a snapshot takes the place of the journal that had it. */
3830
3925
  sync() {
3831
- this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
3926
+ const { busy } = this.db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
3927
+ if (!busy) return;
3928
+ const { file } = this.db.prepare("PRAGMA database_list").get();
3929
+ const fd = openSync(`${file}-wal`, "r");
3930
+ try {
3931
+ fsyncSync(fd);
3932
+ } finally {
3933
+ closeSync(fd);
3934
+ }
3832
3935
  }
3833
3936
  /** Trees whose store or index is gone from the schema (deleted, a database removed) go, with their entries. */
3834
3937
  sweep(keep) {
@@ -3931,7 +4034,7 @@ var TreeFile = class {
3931
4034
  }
3932
4035
  }
3933
4036
  };
3934
- var SqlTree = class {
4037
+ var SqlTree = class SqlTree {
3935
4038
  file;
3936
4039
  id;
3937
4040
  _keysAreUnique;
@@ -4113,6 +4216,15 @@ var SqlTree = class {
4113
4216
  }
4114
4217
  return out;
4115
4218
  }
4219
+ /**
4220
+ * This tree as it is now, its rows read from `file` (rows.db as it was at this turn, `openTreeReader`) under the
4221
+ * layers of the transactions finished so far: not the ones after, nor one still running.
4222
+ */
4223
+ at(file) {
4224
+ const tree = new SqlTree(file, this.id, this._keysAreUnique, this.index);
4225
+ tree.pending = [...this.pending];
4226
+ return tree;
4227
+ }
4116
4228
  /** @internal */
4117
4229
  complete(owner, seq) {
4118
4230
  if (!this.active || this.active.owner !== owner && this.active.owner !== null) return;
@@ -4160,6 +4272,22 @@ function openTreeFile(sqlite, path, constraintError) {
4160
4272
  db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA secure_delete = ON");
4161
4273
  return new TreeFile(db, constraintError);
4162
4274
  }
4275
+ /**
4276
+ * rows.db as it is at this call, for a long read that leaves the event loop turns between its pages (a backup's
4277
+ * export): a second connection, read-only, in one read transaction, which the writes after it do not change (WAL).
4278
+ * Closing its `db` ends it.
4279
+ */
4280
+ function openTreeReader(sqlite, path, constraintError) {
4281
+ const db = new sqlite.DatabaseSync(path, { readOnly: true });
4282
+ try {
4283
+ db.exec("BEGIN");
4284
+ db.prepare("SELECT 1 FROM entries LIMIT 1").get();
4285
+ return new TreeFile(db, constraintError);
4286
+ } catch (error) {
4287
+ db.close();
4288
+ throw error;
4289
+ }
4290
+ }
4163
4291
  /** A range's keys as bytes: from the first (in) up to the second (out), undefined where it is open. */
4164
4292
  function bounds(range) {
4165
4293
  return [range?.lower === void 0 ? void 0 : keyBytes(range.lower) + (range.lowerOpen ? "ÿ" : ""), range?.upper === void 0 ? void 0 : keyBytes(range.upper) + (range.upperOpen ? "" : "ÿ")];
@@ -4231,6 +4359,8 @@ var FOLLOWS = "__ghostly_journal__";
4231
4359
  var SEQ = "__ghostly_entry__";
4232
4360
  /** How long `close` waits for the transactions still running: one left open for good does not keep the process. */
4233
4361
  var CLOSE_WAIT_MS = 5e3;
4362
+ /** Records of rows.db an export reads in one turn of the event loop: a few milliseconds' worth. */
4363
+ var EXPORT_PAGE = 256;
4234
4364
  /** How long a relaxed transaction's entry may wait for a sync when no other transaction brings one. */
4235
4365
  var RELAXED_SYNC_MS = 1e3;
4236
4366
  var BLOB = "__ghostlyBlob";
@@ -4270,6 +4400,10 @@ async function openPersistentIndexedDb(dir, options = {}) {
4270
4400
  let unsaved = false;
4271
4401
  /** Set while the journal holds relaxed entries no sync has covered yet. */
4272
4402
  let relaxed = null;
4403
+ /** The `complete`s of transactions whose entries the running sync does not cover: the next one does. */
4404
+ let unsynced = [];
4405
+ /** The syncs running off the thread, one after another, until no `complete` waits for one. */
4406
+ let syncing = null;
4273
4407
  /** The journal holds a chat's ratchet state, and with the next one it holds a key already used. */
4274
4408
  let holdsRatchet = false;
4275
4409
  /** The journal holds a delete of a chat or a message (or a settings write), and what came before it with it. */
@@ -4410,6 +4544,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4410
4544
  const dispatch = txProto.dispatchEvent;
4411
4545
  txProto.dispatchEvent = function(event) {
4412
4546
  if (event.type === "complete" && writing) {
4547
+ let entry = 0, waits = false;
4413
4548
  if (this.mode === "versionchange") {
4414
4549
  schemaDirty = true;
4415
4550
  if (trees) {
@@ -4418,13 +4553,22 @@ async function openPersistentIndexedDb(dir, options = {}) {
4418
4553
  }
4419
4554
  } else {
4420
4555
  const ops = pending.get(this._rollbackLog);
4421
- if (ops?.length) {
4422
- const refused = append(ops, this.durability === "relaxed", ++seq, this._rollbackLog);
4423
- if (refused) return refuse(this, refused.error, event);
4424
- }
4556
+ if (!ops?.length) trees?.abort(this._rollbackLog);
4557
+ if (ops?.length) entry = ++seq;
4558
+ const appended = ops?.length ? append(ops, this.durability === "relaxed", entry, this._rollbackLog) : null;
4559
+ if (appended && appended !== "unsynced") return refuse(this, appended.error, event);
4560
+ waits = appended === "unsynced";
4425
4561
  }
4426
4562
  pending.delete(this._rollbackLog);
4427
4563
  if (schemaDirty) enqueue(writeSnapshot);
4564
+ if (waits) {
4565
+ shareSync(() => {
4566
+ written(entry);
4567
+ dispatch.call(this, event);
4568
+ });
4569
+ this.db._rawDatabase.processTransactions(event);
4570
+ return true;
4571
+ }
4428
4572
  } else if (event.type === "abort") {
4429
4573
  pending.delete(this._rollbackLog);
4430
4574
  trees?.abort(this._rollbackLog);
@@ -4445,7 +4589,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4445
4589
  /**
4446
4590
  * A committed transaction's entry, numbered `entry` (its first op says so, where there are trees), from the
4447
4591
  * transaction whose rollback log is `owner`. Written at once, it may fail (a full disk): the reason is given back,
4448
- * and the transaction is to be refused, not completed.
4592
+ * and the transaction is to be refused, not completed. "unsynced": written, and its `complete` waits for a sync.
4449
4593
  */
4450
4594
  function append(ops, lazy, entry, owner) {
4451
4595
  holdsDelete ||= ops.some(deletes);
@@ -4458,11 +4602,12 @@ async function openPersistentIndexedDb(dir, options = {}) {
4458
4602
  if (queued === 0 && !ops.some((op) => op.kind === "put" && hasBlob(op.value))) {
4459
4603
  let done;
4460
4604
  try {
4461
- done = writeEntry(serialize(ops), lazy);
4605
+ done = writeEntry(serialize(ops), lazy ? "lazy" : "shared");
4462
4606
  } catch (error) {
4463
4607
  return { error };
4464
4608
  }
4465
4609
  trees?.complete(owner, entry);
4610
+ if (done && !lazy) return "unsynced";
4466
4611
  if (done) written(entry);
4467
4612
  return null;
4468
4613
  }
@@ -4471,7 +4616,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4471
4616
  if (writeEntry(serialize(await Promise.all(ops.map(async (op) => op.kind === "put" ? {
4472
4617
  ...op,
4473
4618
  value: await blobsToDisk(op.value)
4474
- } : op))), lazy)) written(entry);
4619
+ } : op))), lazy ? "lazy" : "now")) written(entry);
4475
4620
  });
4476
4621
  return null;
4477
4622
  }
@@ -4564,11 +4709,13 @@ async function openPersistentIndexedDb(dir, options = {}) {
4564
4709
  process.stderr.write(`ghostly: storage write failed: ${error instanceof Error ? error.message : String(error)}\n`);
4565
4710
  }
4566
4711
  /**
4567
- * `lazy`: a relaxed transaction's entry. A sync blocks the whole process for milliseconds, and what such a
4568
- * transaction wrote can be made again (the event set's note of a message it already reported): written, it outlives
4569
- * the process; a power cut may take its last second.
4712
+ * `sync`: "now", synced before this returns; "shared", synced by the caller through `shareSync`; "lazy", a relaxed
4713
+ * transaction's entry. A sync blocks the whole process for milliseconds, and what such a transaction wrote can be
4714
+ * made again (the event set's note of a message it already reported): written, it outlives the process; a power cut
4715
+ * may take its last second.
4570
4716
  */
4571
- function writeEntry(entry, lazy = false) {
4717
+ function writeEntry(entry, sync = "now") {
4718
+ const lazy = sync === "lazy";
4572
4719
  if (!writing) return false;
4573
4720
  let whole = -1;
4574
4721
  try {
@@ -4582,7 +4729,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4582
4729
  }])));
4583
4730
  marked = false;
4584
4731
  writeAll(journalFd, framed(entry));
4585
- if (!lazy) sync();
4732
+ if (sync === "now") syncNow();
4586
4733
  } catch (error) {
4587
4734
  unsaved = true;
4588
4735
  if (journalFd !== null && whole >= 0) try {
@@ -4592,7 +4739,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4592
4739
  }
4593
4740
  if (lazy) relaxed ??= setTimeout(() => {
4594
4741
  try {
4595
- sync();
4742
+ syncNow();
4596
4743
  } catch (error) {
4597
4744
  failed(error);
4598
4745
  }
@@ -4601,13 +4748,50 @@ async function openPersistentIndexedDb(dir, options = {}) {
4601
4748
  if (statSync(journalPath).size > COMPACT_BYTES || ratchetDue() || deleteDue()) enqueue(writeSnapshot);
4602
4749
  return true;
4603
4750
  }
4604
- function sync() {
4751
+ function syncNow() {
4605
4752
  if (relaxed) {
4606
4753
  clearTimeout(relaxed);
4607
4754
  relaxed = null;
4608
4755
  }
4609
4756
  if (journalFd !== null) fsyncSync(journalFd);
4610
4757
  }
4758
+ /**
4759
+ * `done` (a transaction's `complete`) once a sync covers what the journal has now. A sync blocked the whole process
4760
+ * (5 ms on a Mac's SSD, where it flushes the drive's cache), one per transaction: 8 sends at once went no faster than
4761
+ * 1, and every other call waited behind them. It runs off the thread now, and every entry written while it runs
4762
+ * goes with the next one. One that fails leaves what the journal has unsure: the store is folded into a whole
4763
+ * snapshot before the `complete`s go (they go even if that fails, as a Blob's entry written late does).
4764
+ */
4765
+ function shareSync(done) {
4766
+ unsynced.push(done);
4767
+ syncing ??= (async () => {
4768
+ while (unsynced.length) {
4769
+ const batch = unsynced;
4770
+ unsynced = [];
4771
+ if (relaxed) {
4772
+ clearTimeout(relaxed);
4773
+ relaxed = null;
4774
+ }
4775
+ const fd = journalFd;
4776
+ try {
4777
+ if (fd !== null) await new Promise((resolve, reject) => fsync(fd, (error) => error ? reject(error) : resolve()));
4778
+ } catch (error) {
4779
+ failed(error);
4780
+ const folded = [...batch, ...unsynced.splice(0)];
4781
+ enqueue(writeSnapshot).then(() => {
4782
+ for (const complete of folded) complete();
4783
+ });
4784
+ continue;
4785
+ }
4786
+ for (const complete of batch) complete();
4787
+ }
4788
+ syncing = null;
4789
+ })();
4790
+ }
4791
+ /** Resolves once no sync runs: a snapshot or a close may take the journal's place. */
4792
+ async function synced() {
4793
+ while (syncing) await syncing;
4794
+ }
4611
4795
  async function writeSnapshot() {
4612
4796
  const dirty = schemaDirty;
4613
4797
  schemaDirty = false;
@@ -4628,50 +4812,66 @@ async function openPersistentIndexedDb(dir, options = {}) {
4628
4812
  ...journalName !== void 0 && { journal: journalName },
4629
4813
  databases: []
4630
4814
  };
4631
- for (const db of raw._databases.values()) {
4632
- if (db.name === PROBE) continue;
4633
- const stores = [];
4634
- for (const store of db.rawObjectStores.values()) {
4635
- if (store.deleted) continue;
4636
- const live = [...store.rawIndexes.values()].filter((index) => !index.deleted);
4637
- const meta = {
4638
- name: store.name,
4639
- keyPath: store.keyPath,
4640
- autoIncrement: store.autoIncrement,
4641
- keyGenerator: store.keyGenerator?.num ?? null,
4642
- indexes: live.map(({ name, keyPath, multiEntry, unique }) => ({
4643
- name,
4644
- keyPath,
4645
- multiEntry,
4646
- unique
4647
- }))
4648
- };
4649
- if (!inline && disk(store)) {
4650
- if (!onTrees(store)) toDisk(store);
4651
- stores.push({
4815
+ const held = [];
4816
+ const later = [];
4817
+ let reader = null;
4818
+ try {
4819
+ for (const db of raw._databases.values()) {
4820
+ if (db.name === PROBE) continue;
4821
+ const stores = [];
4822
+ for (const store of db.rawObjectStores.values()) {
4823
+ if (store.deleted) continue;
4824
+ const live = [...store.rawIndexes.values()].filter((index) => !index.deleted);
4825
+ const meta = {
4826
+ name: store.name,
4827
+ keyPath: store.keyPath,
4828
+ autoIncrement: store.autoIncrement,
4829
+ keyGenerator: store.keyGenerator?.num ?? null,
4830
+ indexes: live.map(({ name, keyPath, multiEntry, unique }) => ({
4831
+ name,
4832
+ keyPath,
4833
+ multiEntry,
4834
+ unique
4835
+ }))
4836
+ };
4837
+ if (!inline && disk(store)) {
4838
+ if (!onTrees(store)) toDisk(store);
4839
+ stores.push({
4840
+ ...meta,
4841
+ records: [],
4842
+ onDisk: true
4843
+ });
4844
+ snapshot.format = 3;
4845
+ continue;
4846
+ }
4847
+ const saved = {
4652
4848
  ...meta,
4653
- records: [],
4654
- onDisk: true
4655
- });
4656
- snapshot.format = 3;
4657
- continue;
4849
+ records: []
4850
+ };
4851
+ stores.push(saved);
4852
+ if (onTrees(store)) {
4853
+ reader ??= openTreeReader(sqlite, rowsPath, classes.constraintError);
4854
+ later.push([saved, store.records.records.at(reader)]);
4855
+ } else {
4856
+ for (const record of store.records.values()) saved.records.push([record.key, record.value]);
4857
+ held.push(saved);
4858
+ }
4658
4859
  }
4659
- const records = [];
4660
- for (const record of store.records.values()) records.push([record.key, await blobsToDisk(record.value)]);
4661
- stores.push({
4662
- ...meta,
4663
- records
4860
+ snapshot.databases.push({
4861
+ name: db.name,
4862
+ version: db.version,
4863
+ stores
4664
4864
  });
4665
4865
  }
4666
- snapshot.databases.push({
4667
- name: db.name,
4668
- version: db.version,
4669
- stores
4670
- });
4866
+ for (const store of held) for (const record of store.records) record[1] = await blobsToDisk(record[1]);
4867
+ for (const [saved, tree] of later) for (const record of tree.getAllRecords()) if (saved.records.push([record.key, record.value]) % EXPORT_PAGE === 0) await new Promise((resolve) => setImmediate(resolve));
4868
+ } finally {
4869
+ reader?.db.close();
4671
4870
  }
4672
4871
  return snapshot;
4673
4872
  }
4674
4873
  async function snapshotToDisk() {
4874
+ await synced();
4675
4875
  const name = randomBytes(8).toString("hex");
4676
4876
  const snapshot = await capture(name, false);
4677
4877
  if (trees) {
@@ -4709,6 +4909,7 @@ async function openPersistentIndexedDb(dir, options = {}) {
4709
4909
  }
4710
4910
  /** What `close` leaves: a short journal with the mark at its end, synced (its relaxed entries too), or a fresh snapshot. */
4711
4911
  async function leave() {
4912
+ await synced();
4712
4913
  if (schemaDirty || unsaved || journalBytes() > KEEP_BYTES || ratchetDue() || deleteDue()) return writeSnapshot();
4713
4914
  if (marked) return;
4714
4915
  writeEntry(serialize([{
@@ -4734,9 +4935,9 @@ async function openPersistentIndexedDb(dir, options = {}) {
4734
4935
  quiet = busy() ? 0 : quiet + 1;
4735
4936
  }
4736
4937
  }
4737
- /** Whether a transaction is running or waiting to. */
4938
+ /** Whether a transaction is running or waiting to, or for the sync that tells the engine it completed. */
4738
4939
  function busy() {
4739
- return [...raw._databases.values()].some((db) => db.transactions.some((transaction) => transaction._state !== "finished"));
4940
+ return syncing !== null || [...raw._databases.values()].some((db) => db.transactions.some((transaction) => transaction._state !== "finished"));
4740
4941
  }
4741
4942
  const installed = globalThis;
4742
4943
  installed.indexedDB = factory;
@@ -4777,12 +4978,12 @@ async function openPersistentIndexedDb(dir, options = {}) {
4777
4978
  return [key, link];
4778
4979
  });
4779
4980
  }
4780
- const fd = openSync(path, "w", 384);
4981
+ const file = await open(path, "w", 384);
4781
4982
  try {
4782
- writeAll(fd, serialize(snapshot));
4783
- fsyncSync(fd);
4983
+ await file.writeFile(serialize(snapshot));
4984
+ await file.sync();
4784
4985
  } finally {
4785
- closeSync(fd);
4986
+ await file.close();
4786
4987
  }
4787
4988
  }
4788
4989
  };
@@ -5627,6 +5828,14 @@ function refuseDataAnswers(scope) {
5627
5828
  }
5628
5829
  };
5629
5830
  }
5831
+ /**
5832
+ * For tests: `GHOSTLY_TEST_RELAY_REQUESTS_PER_MINUTE=<n>` gives the relays' budget n requests a minute (`Infinity`: no
5833
+ * bound), so a test on loopback relays need not wait out the minute its pairing spent (`REQUESTS_PER_MINUTE`).
5834
+ */
5835
+ function relayBudgetForTests() {
5836
+ const perMinute = Number(process.env.GHOSTLY_TEST_RELAY_REQUESTS_PER_MINUTE);
5837
+ return perMinute > 0 ? { requestsPerMinute: perMinute } : {};
5838
+ }
5630
5839
  /** `GHOSTLY_STUN=0`: every connection the engine makes leaves the apps' public STUN servers out of its configuration. */
5631
5840
  function leaveOutPublicStun(scope) {
5632
5841
  const Base = scope.RTCPeerConnection;
@@ -5713,12 +5922,16 @@ async function startRuntime(paths, options = {}) {
5713
5922
  const [{ registerFileBytes }, { NodeFileBytes }] = await Promise.all([import("./fileBytes-BtIyoDF2.js"), import("./fileBytes-B0z9A6Le.js")]);
5714
5923
  registerFileBytes("native", async () => new NodeFileBytes(paths.files), true);
5715
5924
  if (await (await import("./blobFiles-BmsrvZc3.js")).moveBlobFiles()) await store.compact();
5716
- const [{ EngineServer }, { createHyperEndpoint }] = await Promise.all([import("./server-DdtPxkqI.js"), import("./endpoint-DWHkXWVM.js")]);
5717
- const mainline = dht.off ? null : new (await (import("./mainline-p6HOW7sb.js"))).Mainline({
5925
+ const [{ EngineServer }, { createHyperEndpoint }] = await Promise.all([import("./server-B6PQ6iae.js"), import("./endpoint-DarqblYE.js")]);
5926
+ const mainline = dht.off ? null : new (await (import("./mainline-DYrjsS1t.js"))).Mainline({
5718
5927
  bootstrap: dht.bootstrap,
5719
5928
  host: dht.host
5720
5929
  });
5721
- const transport = mainline || pinned ? new (await (import("./mainline-p6HOW7sb.js"))).RelaysAndDht(mainline, pinned ? { relays: pinned } : {}, !!pinned) : null;
5930
+ const relayOptions = {
5931
+ ...pinned ? { relays: pinned } : {},
5932
+ ...relayBudgetForTests()
5933
+ };
5934
+ const transport = mainline || pinned ? new (await (import("./mainline-DYrjsS1t.js"))).RelaysAndDht(mainline, relayOptions, !!pinned) : null;
5722
5935
  const apps = servedApps(paths.dir).length > 0;
5723
5936
  const server = new EngineServer({
5724
5937
  ...transport ? { transport } : {},
@@ -5737,6 +5950,7 @@ async function startRuntime(paths, options = {}) {
5737
5950
  localFetch: nodeLocalFetch,
5738
5951
  pushSend: (request) => nodePushSend(request),
5739
5952
  holdFetch: nodeHoldFetch(),
5953
+ webrtcIgnoresRelayOnly: true,
5740
5954
  callsSupport: callsUnavailable === null,
5741
5955
  ...callsUnavailable ? { callsUnavailable } : {},
5742
5956
  ...options.autoJoins ? { autoJoins: options.autoJoins } : {},
@@ -5816,6 +6030,7 @@ async function openHost(paths, mode, version, options = {}) {
5816
6030
  }
5817
6031
  const hub = new EventHub(paths.events);
5818
6032
  let calls;
6033
+ let presence;
5819
6034
  try {
5820
6035
  await hub.open();
5821
6036
  const node = runtime.server.node;
@@ -5861,6 +6076,12 @@ async function openHost(paths, mode, version, options = {}) {
5861
6076
  ids: [...histories.keys(), ...newest.keys()]
5862
6077
  });
5863
6078
  joiner.check(node.getState());
6079
+ if (mode === "daemon") {
6080
+ const said = new DaemonPresence(node);
6081
+ presence = said;
6082
+ hub.onState((s) => said.check(s));
6083
+ said.check(node.getState());
6084
+ }
5864
6085
  } catch (error) {
5865
6086
  hub.release();
5866
6087
  await runtime.close().catch(() => {});
@@ -5881,6 +6102,7 @@ async function openHost(paths, mode, version, options = {}) {
5881
6102
  ctx,
5882
6103
  close: () => closing ??= (async () => {
5883
6104
  await Promise.all([calls.stopAll(), flushCardUpdates(ctx)]).catch(() => {});
6105
+ presence?.stop();
5884
6106
  runtime.server.detach(hub.sink);
5885
6107
  hub.release();
5886
6108
  await runtime.close().catch(() => {});
@@ -6125,4 +6347,4 @@ function connection(ctx, socket, secret, answering) {
6125
6347
  //#endregion
6126
6348
  export { BASELINE_NEWEST, MAX_UNREAD, STOP_ANSWERS_MS, keepServing, openHost, serve };
6127
6349
 
6128
- //# sourceMappingURL=host-BlUzZgQL.js.map
6350
+ //# sourceMappingURL=host-8RskzQgB.js.map