@ghostlytools/cli 1.10.2 → 1.10.4

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 (99) hide show
  1. package/README.md +4 -2
  2. package/dist/assets/{api-DcE4KylM.js → api-DgS7f5TT.js} +2 -2
  3. package/dist/assets/{api-EUGHGnRz.js → api-DkcMOWLX.js} +44 -19
  4. package/dist/assets/api-DkcMOWLX.js.map +1 -0
  5. package/dist/assets/{apiKit-CJVp_crp.js → apiKit-D6Oj-vFx.js} +27 -11
  6. package/dist/assets/apiKit-D6Oj-vFx.js.map +1 -0
  7. package/dist/assets/{apps-C54T_MOT.js → apps-B22SeD6T.js} +3 -3
  8. package/dist/assets/{apps-C54T_MOT.js.map → apps-B22SeD6T.js.map} +1 -1
  9. package/dist/assets/{apps-C-KbyLCa.js → apps-DgALLHzS.js} +1 -1
  10. package/dist/assets/{arkade-BmxJTa65.js → arkade-D5cPr_dV.js} +2 -2
  11. package/dist/assets/{arkade-BmxJTa65.js.map → arkade-D5cPr_dV.js.map} +1 -1
  12. package/dist/assets/{backup-C0Plp-DF.js → backup-DndsW2uX.js} +1 -1
  13. package/dist/assets/{backup-BxSH5BZG.js → backup-dzJLzg-k.js} +6 -6
  14. package/dist/assets/{backup-BxSH5BZG.js.map → backup-dzJLzg-k.js.map} +1 -1
  15. package/dist/assets/{blobFiles-BnjN_Vrz.js → blobFiles-XZ9PEXYy.js} +2 -2
  16. package/dist/assets/{blobFiles-BnjN_Vrz.js.map → blobFiles-XZ9PEXYy.js.map} +1 -1
  17. package/dist/assets/{buttons-B-ZJYdo0.js → buttons-ByKT_vP8.js} +4 -4
  18. package/dist/assets/{buttons-B-ZJYdo0.js.map → buttons-ByKT_vP8.js.map} +1 -1
  19. package/dist/assets/buttons-TVCNj280.js +2 -0
  20. package/dist/assets/{client-CDa87uYD.js → client-q7dVOtYb.js} +10 -4
  21. package/dist/assets/client-q7dVOtYb.js.map +1 -0
  22. package/dist/assets/{codec-D45W1L8n.js → codec-HD6iOn_D.js} +2 -2
  23. package/dist/assets/{codec-D45W1L8n.js.map → codec-HD6iOn_D.js.map} +1 -1
  24. package/dist/assets/{envelope-C3yFCQa-.js → envelope-C-0tfbOG.js} +2 -2
  25. package/dist/assets/{envelope-C3yFCQa-.js.map → envelope-C-0tfbOG.js.map} +1 -1
  26. package/dist/assets/{fileBytes-DjBYYyXT.js → fileBytes-BABGEF13.js} +2 -2
  27. package/dist/assets/{fileBytes-DjBYYyXT.js.map → fileBytes-BABGEF13.js.map} +1 -1
  28. package/dist/assets/{fileBytes-DMzrIdCu.js → fileBytes-CQQK2uOh.js} +1 -1
  29. package/dist/assets/{fileBytes-Douk1yOp.js → fileBytes-DqnfKIkj.js} +2 -2
  30. package/dist/assets/{fileBytes-Douk1yOp.js.map → fileBytes-DqnfKIkj.js.map} +1 -1
  31. package/dist/assets/fileBytesIdb-BtXATa7j.js +2 -0
  32. package/dist/assets/{fileBytesIdb-CkClu9YI.js → fileBytesIdb-DrXmDUSy.js} +2 -2
  33. package/dist/assets/{fileBytesIdb-CkClu9YI.js.map → fileBytesIdb-DrXmDUSy.js.map} +1 -1
  34. package/dist/assets/{fileBytesOpfs-WryQuOgK.js → fileBytesOpfs-udKCzcLe.js} +6 -9
  35. package/dist/assets/{fileBytesOpfs-WryQuOgK.js.map → fileBytesOpfs-udKCzcLe.js.map} +1 -1
  36. package/dist/assets/{fixedHosts-C6nCHjOa.js → fixedHosts-CN3CsslV.js} +7 -8
  37. package/dist/assets/fixedHosts-CN3CsslV.js.map +1 -0
  38. package/dist/assets/{groupFiles-DYopNE57.js → groupFiles-BFv9K_za.js} +256 -110
  39. package/dist/assets/groupFiles-BFv9K_za.js.map +1 -0
  40. package/dist/assets/{host-G5seUwaI.js → host-C-wwtVt2.js} +378 -60
  41. package/dist/assets/host-C-wwtVt2.js.map +1 -0
  42. package/dist/assets/{hyperdhtRelay-B_uHjg_r.js → hyperdhtRelay-B9EQTm_M.js} +2 -2
  43. package/dist/assets/{hyperdhtRelay-B_uHjg_r.js.map → hyperdhtRelay-B9EQTm_M.js.map} +1 -1
  44. package/dist/assets/{irohWeb-C-2oslSU.js → irohWeb-o0H_NlCF.js} +2 -2
  45. package/dist/assets/{irohWeb-C-2oslSU.js.map → irohWeb-o0H_NlCF.js.map} +1 -1
  46. package/dist/assets/{main-Dk--nD7X.js → main-CLUIPy4d.js} +49 -30
  47. package/dist/assets/main-CLUIPy4d.js.map +1 -0
  48. package/dist/assets/{mainline-HPlVrl8R.js → mainline-B2qmNsib.js} +155 -3
  49. package/dist/assets/mainline-B2qmNsib.js.map +1 -0
  50. package/dist/assets/{networkReason-CfpO9ayz.js → networkReason-BEl-DDWd.js} +4 -4
  51. package/dist/assets/{networkReason-CfpO9ayz.js.map → networkReason-BEl-DDWd.js.map} +1 -1
  52. package/dist/assets/{nwc-BY7BPttn.js → nwc-BNkhjJHN.js} +3 -3
  53. package/dist/assets/{nwc-BY7BPttn.js.map → nwc-BNkhjJHN.js.map} +1 -1
  54. package/dist/assets/{nwcProvider-CfpbNUf7.js → nwcProvider-CvaRJdHT.js} +2 -2
  55. package/dist/assets/{nwcProvider-CfpbNUf7.js.map → nwcProvider-CvaRJdHT.js.map} +1 -1
  56. package/dist/assets/{ownDid-DJFZM2cV.js → ownDid-D67KNdJq.js} +3 -2
  57. package/dist/assets/ownDid-D67KNdJq.js.map +1 -0
  58. package/dist/assets/{profiles-DKmZGXp6.js → profiles-QDB7V_Qt.js} +7 -5
  59. package/dist/assets/profiles-QDB7V_Qt.js.map +1 -0
  60. package/dist/assets/{registry-BUm4cAzV.js → registry-BKkSnpjL.js} +126 -19
  61. package/dist/assets/registry-BKkSnpjL.js.map +1 -0
  62. package/dist/assets/{registry-CAzrtV0_.js → registry-DN5a8Ul6.js} +1 -1
  63. package/dist/assets/{resolve-CDD4X68j.js → resolve-DhpAggDP.js} +24 -5
  64. package/dist/assets/resolve-DhpAggDP.js.map +1 -0
  65. package/dist/assets/{server-DcOsgYDU.js → server-7w2O5wsv.js} +956 -277
  66. package/dist/assets/server-7w2O5wsv.js.map +1 -0
  67. package/dist/assets/{src-D31D1_oY.js → src-BZkY6N3J.js} +909 -198
  68. package/dist/assets/src-BZkY6N3J.js.map +1 -0
  69. package/dist/assets/{sshForges-DerRwMf3.js → sshForges-Cxjt3c51.js} +2 -2
  70. package/dist/assets/{sshForges-DerRwMf3.js.map → sshForges-Cxjt3c51.js.map} +1 -1
  71. package/dist/assets/{translate-C-sj0VJe.js → translate-v8wF1GcF.js} +2 -2
  72. package/dist/assets/{translate-C-sj0VJe.js.map → translate-v8wF1GcF.js.map} +1 -1
  73. package/dist/assets/{usdt-DwHqp625.js → usdt-63gYjM5E.js} +7 -4
  74. package/dist/assets/usdt-63gYjM5E.js.map +1 -0
  75. package/dist/assets/{waitNotice-D52RWbV4.js → waitNotice-Ce3YCinu.js} +27 -5
  76. package/dist/assets/waitNotice-Ce3YCinu.js.map +1 -0
  77. package/dist/assets/{words-Db9WgatT.js → words-PUnyO4ph.js} +4 -4
  78. package/dist/assets/words-PUnyO4ph.js.map +1 -0
  79. package/dist/ghostly.mjs +1 -1
  80. package/package.json +1 -1
  81. package/dist/assets/api-EUGHGnRz.js.map +0 -1
  82. package/dist/assets/apiKit-CJVp_crp.js.map +0 -1
  83. package/dist/assets/buttons-DA3wZfG0.js +0 -2
  84. package/dist/assets/client-CDa87uYD.js.map +0 -1
  85. package/dist/assets/fileBytesIdb-CD5Uv490.js +0 -2
  86. package/dist/assets/fixedHosts-C6nCHjOa.js.map +0 -1
  87. package/dist/assets/groupFiles-DYopNE57.js.map +0 -1
  88. package/dist/assets/host-G5seUwaI.js.map +0 -1
  89. package/dist/assets/main-Dk--nD7X.js.map +0 -1
  90. package/dist/assets/mainline-HPlVrl8R.js.map +0 -1
  91. package/dist/assets/ownDid-DJFZM2cV.js.map +0 -1
  92. package/dist/assets/profiles-DKmZGXp6.js.map +0 -1
  93. package/dist/assets/registry-BUm4cAzV.js.map +0 -1
  94. package/dist/assets/resolve-CDD4X68j.js.map +0 -1
  95. package/dist/assets/server-DcOsgYDU.js.map +0 -1
  96. package/dist/assets/src-D31D1_oY.js.map +0 -1
  97. package/dist/assets/usdt-DwHqp625.js.map +0 -1
  98. package/dist/assets/waitNotice-D52RWbV4.js.map +0 -1
  99. package/dist/assets/words-Db9WgatT.js.map +0 -1
@@ -1,23 +1,23 @@
1
- import { Au as setLinkTraceSink, Qu as fromBase64Url, _s as parseCallSignal, cs as CALL_SIGNAL_MAX_AGE_MS, ds as answersOffer, fi as checkPushEndpoint, fs as buildSdpFromSignal, gs as extractParamsFromSdp, ms as callSignalHeardAt, ps as callRtcConfig, qo as DAEMON_WATCH_PEER_IDLE_MS, ua as isPublicAddress, us as RTC_CONFIG, vs as signalHasVideo } from "./src-D31D1_oY.js";
2
- import { o as fedimintSdkOn, r as irohRelayProblem } from "./irohWeb-C-2oslSU.js";
1
+ import { Nu as setLinkTraceSink, Xo as DAEMON_WATCH_PEER_IDLE_MS, _s as callSignalHeardAt, ba as ACTIVE_DHT_POLL_MS, bs as parseCallSignal, ds as CALL_SIGNAL_MAX_AGE_MS, fa as isPublicAddress, fi as checkPushEndpoint, gs as callRtcConfig, hs as buildSdpFromSignal, ms as answersOffer, nd as fromBase64Url, ps as RTC_CONFIG, xs as signalHasVideo, ys as extractParamsFromSdp } from "./src-BZkY6N3J.js";
2
+ import { o as fedimintSdkOn, r as irohRelayProblem } from "./irohWeb-o0H_NlCF.js";
3
3
  import { r as asCliError, t as CliError } from "./errors-Dt-ZnyOX.js";
4
- import { s as findChat, u as findOwnNamedChat } from "./apiKit-CJVp_crp.js";
5
- import { _ as flushCardUpdates, c as paymentJson, d as nodeLocalFetch, f as chatJson, g as resumeHolds, h as groupMessageJson, l as reportAppFrames, m as groupJson, p as chatMessageJson, r as callApi, u as servedApps } from "./api-EUGHGnRz.js";
6
- import { S as runtimePath, g as startingPath, n as RESTORED_MARK, r as acquireLock, v as ownFolder, x as privateFolder, y as ownProfile } from "./profiles-DKmZGXp6.js";
7
- import { c as proof, d as DEFAULT_RATE, f as PlaybackQueue, g as isCallRate, h as frameSamples, l as removeDaemonSecret, m as frameBytes, o as greeting, p as bytesToMs, s as newDaemonSecret } from "./client-CDa87uYD.js";
4
+ import { s as findChat, u as findOwnNamedChat } from "./apiKit-D6Oj-vFx.js";
5
+ import { _ as flushCardUpdates, c as paymentJson, d as nodeLocalFetch, f as chatJson, g as resumeHolds, h as groupMessageJson, l as reportAppFrames, m as groupJson, p as chatMessageJson, r as callApi, u as servedApps } from "./api-DkcMOWLX.js";
6
+ import { C as runtimePath, S as privateFolder, _ as startingPath, b as ownProfile, n as RESTORED_MARK, r as acquireLock, y as ownFolder } from "./profiles-QDB7V_Qt.js";
7
+ import { _ as monotonic, c as proof, d as DEFAULT_RATE, f as PlaybackQueue, g as isCallRate, h as frameSamples, l as removeDaemonSecret, m as frameBytes, o as greeting, p as bytesToMs, s as newDaemonSecret } from "./client-q7dVOtYb.js";
8
8
  import { createRequire } from "node:module";
9
9
  import { appendFileSync, chmodSync, closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, truncateSync, writeFileSync, writeSync } from "node:fs";
10
10
  import { readFile } from "node:fs/promises";
11
11
  import { dirname, join } from "node:path";
12
12
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
13
+ import { networkInterfaces } from "node:os";
13
14
  import { Readable } from "node:stream";
14
15
  import { createServer, isIP } from "node:net";
15
16
  import { createInterface } from "node:readline";
16
- import { lookup } from "node:dns/promises";
17
17
  import { fileURLToPath, pathToFileURL } from "node:url";
18
18
  import { Worker } from "node:worker_threads";
19
19
  import { request } from "node:https";
20
- import { lookup as lookup$1 } from "node:dns";
20
+ import { lookup } from "node:dns";
21
21
  import { deserialize, serialize } from "node:v8";
22
22
  import { IDBFactory, IDBKeyRange, IDBTransaction } from "fake-indexeddb";
23
23
  //#region src/announce.ts
@@ -341,17 +341,21 @@ var CallAudio = class {
341
341
  lastQuiet = null;
342
342
  same = 0;
343
343
  quiet = null;
344
+ /** The contact's last packet decoded, what it decoded to, and whether the one before was the same and gave the same (see `decoded`). */
345
+ lastIn = null;
346
+ lastPcm = null;
347
+ steady = false;
344
348
  /** Whether the encoder's FEC is on (`OpusCodec.fec`); unknown until the first frame. */
345
349
  fecOn;
346
350
  stopped = false;
347
351
  /** Frames sent and received, for `call list`. */
348
352
  sent = 0;
349
353
  received = 0;
350
- /** When the last packet, RTP or RTCP, came from the contact (Date.now(); 0: none yet), for the call's watch. */
354
+ /** When the last packet, RTP or RTCP, came from the contact (on `now`, `monotonic` by default; 0: none yet), for the call's watch. */
351
355
  heardAt = 0;
352
356
  constructor(options) {
353
357
  this.options = options;
354
- const now = options.now ?? Date.now;
358
+ const now = options.now ?? monotonic;
355
359
  this.queue = options.queue ?? new PlaybackQueue(options.rate, now);
356
360
  this.writer = new RtpWriter(options.ssrc, options.payloadType);
357
361
  this.frame = frameBytes(options.rate);
@@ -362,7 +366,7 @@ var CallAudio = class {
362
366
  /** Starts sending, a frame every 20 ms from now on. */
363
367
  start() {
364
368
  if (this.timer || this.stopped) return;
365
- this.startedAt = (this.options.now ?? Date.now)();
369
+ this.startedAt = (this.options.now ?? monotonic)();
366
370
  this.ticks = 0;
367
371
  this.schedule();
368
372
  }
@@ -423,25 +427,49 @@ var CallAudio = class {
423
427
  /** Handles one packet from the track. Exposed for tests. */
424
428
  receive(packet) {
425
429
  if (this.stopped) return;
426
- this.heardAt = (this.options.now ?? Date.now)();
430
+ this.heardAt = (this.options.now ?? monotonic)();
427
431
  if (isRtcp(packet)) return;
428
432
  const rtp = parseRtp(packet);
429
433
  if (!rtp || rtp.payloadType !== this.options.payloadType) return;
430
434
  for (const item of this.reorder.push(rtp)) {
431
435
  let pcm;
432
- if ("lost" in item) pcm = this.conceal();
433
- else {
436
+ if ("lost" in item) {
437
+ this.forgetSteady();
438
+ pcm = this.conceal();
439
+ } else {
434
440
  this.concealed = null;
435
- try {
436
- pcm = this.options.decoder.decode(item.payload);
437
- } catch {
438
- pcm = this.silence;
439
- }
441
+ pcm = this.decoded(item.payload);
440
442
  }
441
443
  this.emit(pcm);
442
444
  }
443
445
  }
444
446
  /**
447
+ * A packet of the contact's, decoded. Their silence settles into one packet sent again and again (the CLI's own,
448
+ * `settle`; an app's muted microphone), and the decoder settles with it: once the same packet gave the same audio
449
+ * twice in a row, it is not decoded again while it lasts, and the program gets that audio again. The audio after it
450
+ * decodes to the same bytes as with every packet decoded, and decoding it was half of a quiet call's work on the
451
+ * daemon's thread (libopus in WebAssembly, 50 times a second).
452
+ */
453
+ decoded(payload) {
454
+ if (this.steady && this.lastIn.equals(payload)) return this.lastPcm;
455
+ let pcm;
456
+ try {
457
+ pcm = this.options.decoder.decode(payload);
458
+ } catch {
459
+ this.forgetSteady();
460
+ return this.silence;
461
+ }
462
+ this.steady = !!this.lastIn?.equals(payload) && !!this.lastPcm?.equals(pcm);
463
+ this.lastIn = Buffer.from(payload);
464
+ this.lastPcm = Buffer.from(pcm);
465
+ return pcm;
466
+ }
467
+ /** A packet lost or unreadable: the decoder moved on without the packet (`decoded`) that came last. */
468
+ forgetSteady() {
469
+ this.lastIn = this.lastPcm = null;
470
+ this.steady = false;
471
+ }
472
+ /**
445
473
  * A frame for one that never came: the decoder's loss concealment (libopus PLC, what an empty packet decodes to), as
446
474
  * the apps' WebRTC stacks do, not a frame of silence (a click). opusscript conceals 60 ms at a time (its largest
447
475
  * frame), so one run of it serves the frames of a gap in turn (ReorderBuffer gives MAX_LOST_FRAMES at most).
@@ -468,7 +496,7 @@ var CallAudio = class {
468
496
  this.pending = Buffer.from(data);
469
497
  }
470
498
  schedule() {
471
- const now = this.options.now ?? Date.now;
499
+ const now = this.options.now ?? monotonic;
472
500
  const due = this.startedAt + (this.ticks + 1) * 20;
473
501
  this.timer = setTimeout(() => {
474
502
  if (this.stopped) return;
@@ -494,7 +522,7 @@ var CallAudio = class {
494
522
  * rest of the call.
495
523
  */
496
524
  catchUp(late) {
497
- const now = this.options.now ?? Date.now;
525
+ const now = this.options.now ?? monotonic;
498
526
  if (late > 1e3) {
499
527
  this.owed = late;
500
528
  this.kept = this.ahead;
@@ -517,7 +545,7 @@ var CallAudio = class {
517
545
  */
518
546
  drop() {
519
547
  if (this.owed <= 0) return;
520
- if ((this.options.now ?? Date.now)() > this.owedUntil) {
548
+ if ((this.options.now ?? monotonic)() > this.owedUntil) {
521
549
  this.owed = 0;
522
550
  return;
523
551
  }
@@ -910,13 +938,14 @@ var CallMedia = class CallMedia {
910
938
  /**
911
939
  * WebKit (Safari, the macOS app) hides its host addresses behind mDNS names, which other machines, and often this
912
940
  * one, cannot resolve: then the call can only connect when the contact's own checks reach this side. The log says so,
913
- * since that is what a call stuck on "connecting" needs to be understood.
941
+ * since that is what a call stuck on "connecting" needs to be understood. The names are not looked up for it: a name
942
+ * nobody answers holds one of the few threads every other lookup of the daemon waits on, for seconds.
914
943
  */
915
944
  function mdnsNote(signal, log) {
916
945
  for (const candidate of signal.c ?? []) {
917
946
  const host = candidate.split(" ")[4];
918
947
  if (!host?.endsWith(".local")) continue;
919
- lookup(host, { all: true }).then((found) => log(`${host} resolves here to ${found.map((a) => a.address).join(", ")}`), () => log(`${host} does not resolve here: the call connects only if the contact's checks reach this side`));
948
+ log(`${host}: an mDNS name, not resolved here: the call connects only if the contact's checks reach this side`);
920
949
  }
921
950
  }
922
951
  /** Whether a call's ICE servers (`callIceServers`) have a TURN server: its relay candidate is then the one waited for. */
@@ -984,6 +1013,11 @@ var CallManager = class {
984
1013
  missedAt = /* @__PURE__ */ new Map();
985
1014
  /** Per chat: the contact's last call held back (`QUICK_REDIAL_MS`) until its hang-up, and when it came. */
986
1015
  held = /* @__PURE__ */ new Map();
1016
+ /**
1017
+ * The chats whose contact's calls are being held back (`QUICK_REDIAL_MS`) since the last that rang: the log says so for
1018
+ * the first only. A detached daemon's log only grows, and a contact's loop would set its pace.
1019
+ */
1020
+ bursts = /* @__PURE__ */ new Set();
987
1021
  /** The early answers being made, those of ended calls too (MAX_EARLY_ANSWERS). */
988
1022
  makings = /* @__PURE__ */ new Set();
989
1023
  auto;
@@ -1019,7 +1053,8 @@ var CallManager = class {
1019
1053
  if (signal.t === "o" && !call) {
1020
1054
  this.lastSignal.set(chat, signal.ts);
1021
1055
  if (this.quickRedial(chat)) {
1022
- process.stderr.write(`ghostly: chat ${chat}: a call came right after a missed one that barely rang: kept as missed\n`);
1056
+ if (!this.bursts.has(chat)) process.stderr.write(`ghostly: chat ${chat}: a call came right after a missed one that barely rang: kept as missed, and the next ones that come as fast\n`);
1057
+ this.bursts.add(chat);
1023
1058
  this.missedAt.set(chat, this.now);
1024
1059
  this.held.set(chat, {
1025
1060
  offer: signal,
@@ -1036,7 +1071,10 @@ var CallManager = class {
1036
1071
  } else if (signal.t === "o" && call?.direction === "in" && call.state === "connecting" && call.media && signal.ts > (call.offer?.ts ?? 0)) {
1037
1072
  this.lastSignal.set(chat, signal.ts);
1038
1073
  if (call.reanswers < this.maxRedials) this.reanswer(call, signal);
1039
- else process.stderr.write(`ghostly: call ${call.id}: the contact offered again past the last start-over: ignored\n`);
1074
+ else if (!call.ignoring) {
1075
+ call.ignoring = true;
1076
+ process.stderr.write(`ghostly: call ${call.id}: the contact offered again past the last start-over: ignored, and its next offers on this call\n`);
1077
+ }
1040
1078
  } else if (signal.t === "v") this.lastSignal.set(chat, signal.ts);
1041
1079
  else if (signal.t === "h") {
1042
1080
  this.lastSignal.set(chat, signal.ts);
@@ -1060,6 +1098,7 @@ var CallManager = class {
1060
1098
  }
1061
1099
  incoming(chat, offer) {
1062
1100
  this.held.delete(chat);
1101
+ this.bursts.delete(chat);
1063
1102
  const link = this.link(chat);
1064
1103
  const call = this.add(chat, "in", this.auto.rate);
1065
1104
  call.offer = offer;
@@ -1079,7 +1118,7 @@ var CallManager = class {
1079
1118
  call.offering = false;
1080
1119
  call.state = "connecting";
1081
1120
  const attempt = call.answered = call.attempt;
1082
- call.answeredAt = Date.now();
1121
+ call.answeredAt = monotonic();
1083
1122
  try {
1084
1123
  call.media.applyAnswer(answer);
1085
1124
  } catch (error) {
@@ -1230,7 +1269,7 @@ var CallManager = class {
1230
1269
  const link = this.callable(chat);
1231
1270
  if (this.byChat(link.id)) throw new CliError("busy", "A call is already on in this chat");
1232
1271
  const held = this.held.get(link.id);
1233
- if (held && this.now - held.at < 6e4) {
1272
+ if (held && this.within(held.at, 6e4)) {
1234
1273
  this.incoming(link.id, held.offer);
1235
1274
  throw new CliError("busy", "The contact is calling: their call rings here");
1236
1275
  }
@@ -1387,6 +1426,7 @@ var CallManager = class {
1387
1426
  offering: false,
1388
1427
  redials: 0,
1389
1428
  reanswers: 0,
1429
+ ignoring: false,
1390
1430
  attempt: 0,
1391
1431
  answered: 0,
1392
1432
  answeredAt: 0,
@@ -1398,6 +1438,7 @@ var CallManager = class {
1398
1438
  queue: null,
1399
1439
  startedAt: this.now,
1400
1440
  connectedAt: null,
1441
+ connectedTick: null,
1401
1442
  timer: null,
1402
1443
  watcher: null,
1403
1444
  stalledFrom: null,
@@ -1445,7 +1486,7 @@ var CallManager = class {
1445
1486
  }
1446
1487
  if (state === "closed" && failed) return;
1447
1488
  failed ||= state === "failed";
1448
- if (state === "failed" && call.direction === "out" && call.answered === attempt && call.state !== "connected" && Date.now() - call.answeredAt < 2e3) {
1489
+ if (state === "failed" && call.direction === "out" && call.answered === attempt && call.state !== "connected" && monotonic() - call.answeredAt < 2e3) {
1449
1490
  this.refused(call, "the connection failed as the answer went in");
1450
1491
  return;
1451
1492
  }
@@ -1463,6 +1504,7 @@ var CallManager = class {
1463
1504
  if (call.state === "connected") return;
1464
1505
  call.state = "connected";
1465
1506
  call.connectedAt = this.now;
1507
+ call.connectedTick = monotonic();
1466
1508
  this.disarm(call);
1467
1509
  this.host.emit("call.connected", `call.connected:${call.id}`, {
1468
1510
  call: call.id,
@@ -1483,11 +1525,11 @@ var CallManager = class {
1483
1525
  afterMs: 5e3,
1484
1526
  endMs: 15e3
1485
1527
  };
1486
- const since = Date.now();
1528
+ const since = monotonic();
1487
1529
  call.watcher = setInterval(() => {
1488
1530
  if (call.ended) return;
1489
1531
  const heardAt = Math.max(since, call.media?.audio.heardAt ?? 0);
1490
- const silentMs = Date.now() - heardAt;
1532
+ const silentMs = monotonic() - heardAt;
1491
1533
  const fields = {
1492
1534
  call: call.id,
1493
1535
  chat: call.chat,
@@ -1525,7 +1567,7 @@ var CallManager = class {
1525
1567
  this.calls.delete(call.id);
1526
1568
  if (call.direction === "out" && call.connectedAt === null && call.state === "ringing" && (reason === "hangup" || reason === "unanswered")) this.unansweredAt.set(call.chat, this.now);
1527
1569
  if (call.direction === "in" && call.connectedAt === null && reason !== "hangup" && reason !== "stopped") {
1528
- if (this.now - call.startedAt < 1e3) this.missedAt.set(call.chat, this.now);
1570
+ if (this.within(call.startedAt, 1e3)) this.missedAt.set(call.chat, this.now);
1529
1571
  else this.missedAt.delete(call.chat);
1530
1572
  }
1531
1573
  if (report) process.stderr.write(`ghostly: call ${call.id}: ended (${reason})${call.media ? `, ice ${call.media.ice.state}` : ""}\n`);
@@ -1557,7 +1599,7 @@ var CallManager = class {
1557
1599
  chat: call.chat,
1558
1600
  direction: call.direction,
1559
1601
  reason,
1560
- ...call.connectedAt !== null ? { duration: this.now - call.connectedAt } : {}
1602
+ ...call.connectedTick !== null ? { duration: Math.round(monotonic() - call.connectedTick) } : {}
1561
1603
  });
1562
1604
  if (this.stopping) await closing;
1563
1605
  }
@@ -1565,17 +1607,25 @@ var CallManager = class {
1565
1607
  paced(chat) {
1566
1608
  const pace = this.host.callPaceMs ?? 2e3, last = this.unansweredAt.get(chat);
1567
1609
  if (!pace || last === void 0) return;
1568
- const left = last + pace - this.now;
1569
- if (left <= 0) {
1610
+ if (!this.within(last, pace)) {
1570
1611
  this.unansweredAt.delete(chat);
1571
1612
  return;
1572
1613
  }
1614
+ const left = last + pace - this.now;
1573
1615
  throw new CliError("busy", `Your last call in this chat ended unanswered a moment ago: call again in ${Math.ceil(left / 100) / 10} s`, { retryAfterMs: left });
1574
1616
  }
1575
1617
  /** Whether the contact's call coming now in the chat is held back: its last one was missed after it barely rang, or held, a moment ago. */
1576
1618
  quickRedial(chat) {
1577
1619
  const quick = this.host.quickRedialMs ?? 2e3, last = this.missedAt.get(chat);
1578
- return !!quick && last !== void 0 && this.now - last < quick;
1620
+ return !!quick && last !== void 0 && this.within(last, quick);
1621
+ }
1622
+ /**
1623
+ * Whether less than `ms` passed since `at`, on the device's clock (`now`, which the timestamps the contact sees are on).
1624
+ * An `at` later than now is the clock set back since: the wait is taken as over, not as lasting as long as the jump.
1625
+ */
1626
+ within(at, ms) {
1627
+ const passed = this.now - at;
1628
+ return passed >= 0 && passed < ms;
1579
1629
  }
1580
1630
  arm(call, ms, reason, tell) {
1581
1631
  this.disarm(call);
@@ -1712,8 +1762,9 @@ var FORGET_SEARCHED_IDS = 16;
1712
1762
  var SEEN_DB = "ghostly-cli";
1713
1763
  var SEEN = "seen";
1714
1764
  /**
1715
- * How long the seen set keeps the note of a settled message after its last activity (its arrival, its edit, a reaction):
1716
- * older notes are dropped, and a message that came here longer ago with no note is no news. A daemon kept a note per
1765
+ * How long the seen set keeps the note of a settled message after its last activity (its arrival, its edit, a reaction),
1766
+ * each as this device's clock has it: older notes are dropped, and a message that came here longer ago with no note is
1767
+ * no news. A daemon kept a note per
1717
1768
  * message of its whole history in memory, for as long as it ran.
1718
1769
  */
1719
1770
  var SEEN_KEEP_MS = 2592e6;
@@ -1745,10 +1796,27 @@ var EventHub = class {
1745
1796
  marked = false;
1746
1797
  /** Whether `dropped` is ahead of `<journal>.dropped` (a full disk refused it): the next event's write tries it again. */
1747
1798
  markOwed = false;
1799
+ /**
1800
+ * The highest seq `<journal>.reserved` holds: no event is told a seq past it before the mark says so, and a start
1801
+ * numbers on from it. A full disk can take an event and its `.dropped` mark both, after it was told; the next start
1802
+ * then never gives its seq again, and a replay across it says `events.gap`. A stop gives back what it did not use.
1803
+ */
1804
+ reserved = 0;
1748
1805
  /** Typing changes told this run: a change's id carries it, as it takes no seq of its own (`emitLive`). */
1749
1806
  typingChanges = 0;
1750
1807
  journalLines = 0;
1751
1808
  journalBytes = 0;
1809
+ /**
1810
+ * Where the journal first names each chat, group and message (`namedIn`), by the hash of the id as written
1811
+ * (`hashOfId`; two ids that share one only read more), so `forget` reads it from there on: each deletion read the
1812
+ * whole journal (up to 32 MiB) from disk and searched it, a contact's delete for everyone included. Built from the
1813
+ * journal at the first `forget`, kept by `emit`; null again once lines move (a trim, a rewrite).
1814
+ */
1815
+ firstNamed = null;
1816
+ /** The journal's size `firstNamed` covers: another size (a write it did not see) builds it again. */
1817
+ namedSize = 0;
1818
+ /** Where the first line that cannot be read is, which `forget` reads from too: it may name what is removed. */
1819
+ unreadableAt = Infinity;
1752
1820
  listeners = /* @__PURE__ */ new Set();
1753
1821
  stateListeners = /* @__PURE__ */ new Set();
1754
1822
  callListeners = /* @__PURE__ */ new Set();
@@ -1785,6 +1853,7 @@ var EventHub = class {
1785
1853
  }
1786
1854
  /** Loads the journal's last seq and the seen set; call before `sink` is attached. */
1787
1855
  async open() {
1856
+ const reserved = readDropped(this.journalPath + ".reserved") ?? 0;
1788
1857
  try {
1789
1858
  const dropped = readDropped(this.journalPath + ".dropped");
1790
1859
  if (existsSync(this.journalPath)) {
@@ -1821,6 +1890,11 @@ var EventHub = class {
1821
1890
  this.journalBytes = 0;
1822
1891
  this.markDropped(this.seq);
1823
1892
  }
1893
+ this.reserved = reserved;
1894
+ if (reserved > this.seq) {
1895
+ this.seq = reserved;
1896
+ this.markDropped(Math.max(this.dropped, reserved));
1897
+ }
1824
1898
  this.db = await new Promise((resolve, reject) => {
1825
1899
  const request = indexedDB.open(this.seenDb, 1);
1826
1900
  request.onupgradeneeded = () => {
@@ -1878,10 +1952,18 @@ var EventHub = class {
1878
1952
  }
1879
1953
  /**
1880
1954
  * Drops the notes of settled messages, and of reactions, whose last activity is older than `SEEN_KEEP_MS`: from memory
1881
- * and from the store. A message of mine still on its way (or failed, which a retry sends again) keeps its note.
1955
+ * and from the store. A message of mine still on its way (or failed, which a retry sends again) keeps its note. The
1956
+ * 30 days count back from the newest activity the set knows when the clock reads later than it: a clock run ahead (a
1957
+ * wrong RTC, a VM restored with a skewed clock) would otherwise drop the notes of the recent history, which the next
1958
+ * start with the clock right reports again.
1882
1959
  */
1883
1960
  sweep() {
1884
- const cutoff = this.now() - SEEN_KEEP_MS;
1961
+ let newest = 0;
1962
+ for (const [chat, known] of this.seen) {
1963
+ if (chat === FORMAT || chat.startsWith("said:")) continue;
1964
+ for (const note of known.values()) newest = Math.max(newest, timeIn(note) ?? 0);
1965
+ }
1966
+ const cutoff = Math.min(this.now(), newest) - SEEN_KEEP_MS;
1885
1967
  let dropped = 0;
1886
1968
  for (const [chat, known] of this.seen) {
1887
1969
  if (chat === FORMAT || chat.startsWith("said:")) continue;
@@ -1912,7 +1994,7 @@ var EventHub = class {
1912
1994
  const cutoff = this.now() - SEEN_KEEP_MS;
1913
1995
  return messages.every((message) => {
1914
1996
  const note = known?.get(message.id), before = note === void 0 ? void 0 : stateIn(note);
1915
- if (note === void 0 && message.timestamp < cutoff && activityOf(message) < cutoff) return true;
1997
+ if (note === void 0 && cameAt(message) < cutoff && activityOf(message) < cutoff) return true;
1916
1998
  let state = stateOf(message);
1917
1999
  if (before !== void 0 && mentionedIn(before) && !mentionedIn(state)) state = withFlag(state, MENTIONED);
1918
2000
  if (before !== state) return false;
@@ -1986,7 +2068,40 @@ var EventHub = class {
1986
2068
  this.marked = true;
1987
2069
  this.markOwed = false;
1988
2070
  } catch (error) {
1989
- this.markOwed = true;
2071
+ try {
2072
+ writeMark(this.journalPath + ".dropped", seq, false);
2073
+ this.marked = true;
2074
+ this.markOwed = false;
2075
+ } catch {
2076
+ this.markOwed = true;
2077
+ process.stderr.write(`ghostly: event journal error: ${error instanceof Error ? error.message : String(error)}\n`);
2078
+ }
2079
+ }
2080
+ }
2081
+ /**
2082
+ * Reserves seqs ahead of the one about to be told, in `<journal>.reserved`, rewritten where it is (no new block, so a
2083
+ * full disk takes it): written before the event goes anywhere, as `markDropped` is. Refused, the event still goes
2084
+ * (the reservation made before covers the next ones), and the next event tries again.
2085
+ */
2086
+ reserve() {
2087
+ if (this.reserved - this.seq >= 128) return;
2088
+ try {
2089
+ writeMark(this.journalPath + ".reserved", this.seq + 256, true);
2090
+ this.reserved = this.seq + 256;
2091
+ } catch (error) {
2092
+ process.stderr.write(`ghostly: event journal error: ${error instanceof Error ? error.message : String(error)}\n`);
2093
+ }
2094
+ }
2095
+ /**
2096
+ * At a stop: the seqs reserved past the last one told are given back, so the next start numbers on from it, with no
2097
+ * jump. Not written (a disk that takes no rewrite either), the next start numbers past the reservation instead.
2098
+ */
2099
+ release() {
2100
+ if (this.reserved <= this.seq) return;
2101
+ try {
2102
+ writeMark(this.journalPath + ".reserved", this.seq, true);
2103
+ this.reserved = this.seq;
2104
+ } catch (error) {
1990
2105
  process.stderr.write(`ghostly: event journal error: ${error instanceof Error ? error.message : String(error)}\n`);
1991
2106
  }
1992
2107
  }
@@ -2002,12 +2117,17 @@ var EventHub = class {
2002
2117
  at: this.now(),
2003
2118
  ...fields
2004
2119
  };
2120
+ this.reserve();
2005
2121
  let written = false;
2006
2122
  try {
2007
2123
  if (this.markOwed) this.markDropped(this.dropped);
2008
2124
  const line = Buffer.from(JSON.stringify(event) + "\n");
2009
- appendWhole(this.journalPath, line);
2125
+ const at = appendWhole(this.journalPath, line);
2010
2126
  written = true;
2127
+ if (this.firstNamed && at === this.namedSize) {
2128
+ for (const id of namedIn(event)) if (!this.firstNamed.has(hashOfId(id))) this.firstNamed.set(hashOfId(id), at);
2129
+ this.namedSize = at + line.length;
2130
+ } else this.firstNamed = null;
2011
2131
  this.journalBytes += line.length;
2012
2132
  if (++this.journalLines > 2e4 || this.journalBytes > 33554432) this.trimJournal();
2013
2133
  } catch (error) {
@@ -2047,6 +2167,7 @@ var EventHub = class {
2047
2167
  const kept = lines.slice(start);
2048
2168
  const first = firstSeq(kept);
2049
2169
  this.markDropped(Math.max(this.dropped, first === void 0 ? this.seq : first - 1));
2170
+ this.firstNamed = null;
2050
2171
  writeFileSync(this.journalPath + ".tmp", kept.length ? kept.join("\n") + "\n" : "", { mode: 384 });
2051
2172
  renameSync(this.journalPath + ".tmp", this.journalPath);
2052
2173
  this.journalLines = kept.length;
@@ -2064,7 +2185,9 @@ var EventHub = class {
2064
2185
  try {
2065
2186
  rmSync(this.journalPath + ".unreadable", { force: true });
2066
2187
  if (!existsSync(this.journalPath)) return;
2067
- const { bytes, start, at } = journalWindow(this.journalPath);
2188
+ const named = this.namedFrom(ids);
2189
+ if (named === void 0) return;
2190
+ let { bytes, start, at } = journalWindow(this.journalPath, named);
2068
2191
  const needles = ids.map((id) => JSON.stringify(id)), few = ids.length <= FORGET_SEARCHED_IDS;
2069
2192
  const names = (line) => needles.some((needle) => line.includes(needle));
2070
2193
  const edits = [];
@@ -2111,6 +2234,15 @@ var EventHub = class {
2111
2234
  }
2112
2235
  return;
2113
2236
  }
2237
+ this.firstNamed = null;
2238
+ if (start === 0 && at > 0) {
2239
+ const window = journalWindow(this.journalPath);
2240
+ for (const edit of edits) {
2241
+ edit.from += at - window.at;
2242
+ edit.to += at - window.at;
2243
+ }
2244
+ ({bytes, start, at} = window);
2245
+ }
2114
2246
  const parts = [];
2115
2247
  let from = start, removed = 0;
2116
2248
  for (const edit of edits) {
@@ -2126,9 +2258,42 @@ var EventHub = class {
2126
2258
  this.journalLines -= removed;
2127
2259
  this.journalBytes = written.length;
2128
2260
  } catch (error) {
2261
+ this.firstNamed = null;
2129
2262
  process.stderr.write(`ghostly: event journal error: ${error instanceof Error ? error.message : String(error)}\n`);
2130
2263
  }
2131
2264
  }
2265
+ /**
2266
+ * The first place in the journal a line may name one of these ids (`namedIn`), or undefined when none does. The
2267
+ * first call reads the journal for it once.
2268
+ */
2269
+ namedFrom(ids) {
2270
+ if (!this.firstNamed || statSync(this.journalPath).size !== this.namedSize) {
2271
+ const { bytes, start, at, size } = journalWindow(this.journalPath);
2272
+ const firstNamed = /* @__PURE__ */ new Map();
2273
+ for (const key of NAMING_KEYS) for (let found = bytes.indexOf(key, start); found !== -1; found = bytes.indexOf(key, found + key.length)) {
2274
+ const open = found + key.length;
2275
+ if (bytes[open] !== 34) continue;
2276
+ let close = open + 1;
2277
+ while (close < bytes.length && bytes[close] !== 34 && bytes[close] !== 10) close += bytes[close] === 92 ? 2 : 1;
2278
+ if (bytes[close] !== 34) continue;
2279
+ const hash = hashOf(bytes, open, close + 1), line = at + Math.max(start, bytes.lastIndexOf(10, found) + 1);
2280
+ if ((firstNamed.get(hash) ?? Infinity) > line) firstNamed.set(hash, line);
2281
+ }
2282
+ this.unreadableAt = Infinity;
2283
+ for (const [from, to] of linesOf(bytes, start)) {
2284
+ if (bytes[from] === 123 && bytes[to - 1] === 125) continue;
2285
+ if (bytes.subarray(from, to).some((byte) => byte !== 32)) {
2286
+ this.unreadableAt = at + from;
2287
+ break;
2288
+ }
2289
+ }
2290
+ this.firstNamed = firstNamed;
2291
+ this.namedSize = size;
2292
+ }
2293
+ let from = this.unreadableAt;
2294
+ for (const id of ids) from = Math.min(from, this.firstNamed.get(hashOfId(id)) ?? Infinity);
2295
+ return from === Infinity ? void 0 : from;
2296
+ }
2132
2297
  handle(message) {
2133
2298
  switch (message.kind) {
2134
2299
  case "state":
@@ -2429,13 +2594,13 @@ var EventHub = class {
2429
2594
  const note = known.get(message.id), before = note === void 0 ? void 0 : stateIn(note);
2430
2595
  const at = activityOf(message);
2431
2596
  const json = () => group ? groupMessageJson(message, this.state?.groups.find((g) => g.id === group)) : chatMessageJson(message, this.state?.links.find((l) => l.id === chat));
2432
- if (before === void 0 && message.timestamp < cutoff) {
2597
+ if (before === void 0 && cameAt(message) < cutoff) {
2433
2598
  if (at < cutoff) continue;
2434
2599
  const noted = noteOf(state, at);
2435
2600
  known.set(message.id, noted);
2436
2601
  changes.push([message.id, noted]);
2437
2602
  const edit = message.edit;
2438
- if (quiet || !edit || edit.at < cutoff || message.sender === "me" && edit.restore) continue;
2603
+ if (quiet || !edit || editedAt(edit) < cutoff || message.sender === "me" && edit.restore) continue;
2439
2604
  if (group) this.emit("group.message.edited", `group.message.edited:${group}:${message.id}:${edit.seq}`, {
2440
2605
  group,
2441
2606
  messageId: message.id,
@@ -2649,9 +2814,20 @@ function timeIn(note) {
2649
2814
  const at = note.lastIndexOf("@");
2650
2815
  return at === -1 ? void 0 : parseInt(note.slice(at + 1), 36);
2651
2816
  }
2817
+ /**
2818
+ * When a message came here: its place (a received row's is when it was stored here), or for a group's line, whose place
2819
+ * is its commit's moment, when this device stored it (`heardAt`; absent on lines stored before it).
2820
+ */
2821
+ function cameAt(message) {
2822
+ return Math.max(message.timestamp, message.heardAt ?? 0);
2823
+ }
2824
+ /** When an edit came here: a contact's or member's is dated by their clock (`at`), and taken here at `heardAt`. */
2825
+ function editedAt(edit) {
2826
+ return Math.max(edit.at, edit.heardAt ?? 0);
2827
+ }
2652
2828
  /** The last time a message changed here: it came, it was edited, someone reacted. */
2653
2829
  function activityOf(message) {
2654
- let at = Math.max(message.timestamp, message.edit?.at ?? 0);
2830
+ let at = Math.max(cameAt(message), message.edit ? editedAt(message.edit) : 0);
2655
2831
  for (const r of Object.values(message.reactions ?? {})) at = Math.max(at, r.at ?? 0);
2656
2832
  return at;
2657
2833
  }
@@ -2779,7 +2955,10 @@ function firstSeq(lines) {
2779
2955
  if (typeof seq === "number") return seq;
2780
2956
  } catch {}
2781
2957
  }
2782
- /** The journal's dropped mark (`EventHub.dropped`), or undefined when there is none (a journal from before it). */
2958
+ /**
2959
+ * The journal's dropped mark (`EventHub.dropped`) or its reserved one (`EventHub.reserved`), or undefined when there is
2960
+ * none (a journal from before it).
2961
+ */
2783
2962
  function readDropped(path) {
2784
2963
  try {
2785
2964
  const seq = Number(readFileSync(path, "utf8").trim());
@@ -2789,8 +2968,30 @@ function readDropped(path) {
2789
2968
  }
2790
2969
  }
2791
2970
  /**
2971
+ * Writes a mark over the one there, as a line of fixed width (`000…0042`, which `readDropped` reads, v1.10's too): a
2972
+ * rewrite never grows the file past its first block, so a full disk takes it, and one cut short leaves the new mark's
2973
+ * first digits before the old one's last, never a number below the old one when the mark grows. `create`: a file that
2974
+ * is not there is made (a first start).
2975
+ */
2976
+ function writeMark(path, seq, create) {
2977
+ const line = Buffer.from(String(seq).padStart(19, "0") + "\n");
2978
+ let fd;
2979
+ try {
2980
+ fd = openSync(path, "r+");
2981
+ } catch (error) {
2982
+ if (!create || error.code !== "ENOENT") throw error;
2983
+ fd = openSync(path, "wx", 384);
2984
+ }
2985
+ try {
2986
+ for (let at = 0; at < line.length;) at += writeSync(fd, line, at, line.length - at, at);
2987
+ } finally {
2988
+ closeSync(fd);
2989
+ }
2990
+ }
2991
+ /**
2792
2992
  * Appends a line whole or not at all: what a full disk took of it is cut back (as the store's journal does), so the
2793
- * next line, once there is room, starts a line of its own instead of making one no reader can parse with it.
2993
+ * next line, once there is room, starts a line of its own instead of making one no reader can parse with it. Returns
2994
+ * where the line begins in the file.
2794
2995
  */
2795
2996
  function appendWhole(path, line) {
2796
2997
  const fd = openSync(path, "a", 384);
@@ -2806,7 +3007,39 @@ function appendWhole(path, line) {
2806
3007
  } finally {
2807
3008
  closeSync(fd);
2808
3009
  }
3010
+ return whole;
2809
3011
  }
3012
+ /**
3013
+ * The ids an event is of, as `forget`'s callers tell what is removed: its chat, its group, its message (`messageId`,
3014
+ * `message.id`), the reply that pressed it (`replyId`) and the message it quotes (`message.replyTo.id`).
3015
+ */
3016
+ function namedIn(event) {
3017
+ const message = event.message;
3018
+ return [
3019
+ event.chat,
3020
+ event.group,
3021
+ event.messageId,
3022
+ event.replyId,
3023
+ message?.id,
3024
+ message?.replyTo?.id
3025
+ ].filter((id) => typeof id === "string");
3026
+ }
3027
+ /** The keys whose values `namedIn` reads, as a journal line has them: `id` stands for `message.id` and its quote's. */
3028
+ var NAMING_KEYS = [
3029
+ "\"chat\":",
3030
+ "\"group\":",
3031
+ "\"messageId\":",
3032
+ "\"replyId\":",
3033
+ "\"id\":"
3034
+ ].map((key) => Buffer.from(key));
3035
+ /** FNV-1a of these bytes. */
3036
+ function hashOf(bytes, from = 0, to = bytes.length) {
3037
+ let hash = 2166136261;
3038
+ for (let i = from; i < to; i++) hash = Math.imul(hash ^ bytes[i], 16777619);
3039
+ return hash >>> 0;
3040
+ }
3041
+ /** The hash of an id as a journal line writes it (quoted, escaped). */
3042
+ var hashOfId = (id) => hashOf(Buffer.from(JSON.stringify(id)));
2810
3043
  /** The bounds in `bytes` of each line from `start` on, its newline left out. */
2811
3044
  function linesOf(bytes, start) {
2812
3045
  const lines = [];
@@ -2829,13 +3062,13 @@ function linesNaming(bytes, start, needles) {
2829
3062
  }
2830
3063
  /**
2831
3064
  * The bytes of the journal's last `JOURNAL_MAX_BYTES`, `start` where its first whole line begins in them, `at` where
2832
- * they begin in the file, and its size.
3065
+ * they begin in the file, and its size. `lineAt`: where a line begins, read from there on when it is within them.
2833
3066
  */
2834
- function journalWindow(path) {
3067
+ function journalWindow(path, lineAt = 0) {
2835
3068
  const fd = openSync(path, "r");
2836
3069
  try {
2837
3070
  const size = fstatSync(fd).size;
2838
- const from = Math.max(0, size - JOURNAL_MAX_BYTES - 1);
3071
+ const cut = Math.max(0, size - JOURNAL_MAX_BYTES - 1), from = Math.max(cut, lineAt);
2839
3072
  const buffer = Buffer.alloc(size - from);
2840
3073
  let read = 0;
2841
3074
  while (read < buffer.length) {
@@ -2846,7 +3079,7 @@ function journalWindow(path) {
2846
3079
  const bytes = buffer.subarray(0, read);
2847
3080
  return {
2848
3081
  bytes,
2849
- start: from > 0 ? bytes.indexOf(10) + 1 || bytes.length : 0,
3082
+ start: from > cut || from === 0 ? 0 : bytes.indexOf(10) + 1 || bytes.length,
2850
3083
  at: from,
2851
3084
  size
2852
3085
  };
@@ -3073,7 +3306,7 @@ var publicOnly = (resolve) => (hostname, options, callback) => {
3073
3306
  callback(null, addresses[0].address, addresses[0].family);
3074
3307
  });
3075
3308
  };
3076
- var publicOnlyLookup = publicOnly(lookup$1);
3309
+ var publicOnlyLookup = publicOnly(lookup);
3077
3310
  /**
3078
3311
  * Posts a wake-up (WISP 401 § Wake-up push) the way the Desktop does from Rust: only to a push service's endpoint
3079
3312
  * (`checkPushEndpoint`), whose name must resolve to public addresses only, no redirect followed, no proxy, 10 s at most.
@@ -4944,6 +5177,84 @@ function blobsFromDisk(value, depth = 0) {
4944
5177
  for (const [k, v] of Object.entries(value)) out[k] = blobsFromDisk(v, depth + 1);
4945
5178
  return out;
4946
5179
  }
5180
+ /**
5181
+ * A wake republishes every chat with nothing published in the last seconds (on the CLI the DHT copy goes whatever the
5182
+ * relays' budgets say: 200 chats are 200 DHT puts and a ~76 ms turn). A network that flaps (Wi-Fi at the edge of range,
5183
+ * a VPN in a reconnect loop) changed the addresses every tick and woke the engine every 10 s for nothing new. A network
5184
+ * wake within this long of the previous wake is held and runs once when the gap is over, the latest change included; each
5185
+ * held one run doubles the gap, up to `WAKE_GAP_MAX_MS`, and a whole gap with no change brings it back. A network change
5186
+ * after a quiet spell, and a sleep, still wake at once.
5187
+ */
5188
+ var WAKE_GAP_MS = 6e4;
5189
+ var WAKE_GAP_MAX_MS = 6e5;
5190
+ /**
5191
+ * The machine's own virtual bridges, for containers and VMs on it: Docker's (`docker0`, a compose network's `br-<id>`,
5192
+ * `veth*`), libvirt's, CNI's, LXD's, VirtualBox's and VMware's host networks, macOS's `bridge100` (sharing, a VM), and
5193
+ * Windows's WSL and Default Switch. A container network made or removed changes them with nothing changed for the
5194
+ * internet, and a network wake makes every chat read and publish at once. A Hyper-V switch bound to the network card (`vEthernet
5195
+ * (External)`) holds the machine's real address and stays.
5196
+ */
5197
+ var LOCAL_BRIDGE = /^(docker\d*|br-[0-9a-f]+|veth.*|virbr\d+|cni\d+|flannel.*|cali.*|lxcbr\d+|lxdbr\d+|incusbr\d+|podman\d+|vboxnet\d+|vmnet\d+|bridge\d+|vEthernet \((WSL.*|Default Switch)\))$/;
5198
+ /** The machine's own non-internal addresses, sorted: a change means another network (Wi-Fi to cable, a new DHCP lease). */
5199
+ function addressesKey(nets = networkInterfaces()) {
5200
+ const out = [];
5201
+ for (const [name, list] of Object.entries(nets)) {
5202
+ if (LOCAL_BRIDGE.test(name)) continue;
5203
+ for (const entry of list ?? []) {
5204
+ if (entry.internal || entry.family === "IPv6" && entry.address.toLowerCase().startsWith("fe80")) continue;
5205
+ out.push(`${name}/${entry.address}`);
5206
+ }
5207
+ }
5208
+ return out.sort().join(",");
5209
+ }
5210
+ /** Starts the watch; the returned function stops it. The timer never keeps the process alive. */
5211
+ function watchWake(onWake, options = {}) {
5212
+ const tickMs = options.tickMs ?? 1e4;
5213
+ const lateMs = options.lateMs ?? 3e4;
5214
+ const now = options.now ?? Date.now;
5215
+ const addresses = options.addresses ?? (() => addressesKey());
5216
+ let last = now();
5217
+ let key = safe(addresses);
5218
+ let wokeAt = -Infinity;
5219
+ let gap = WAKE_GAP_MS;
5220
+ /** A network change seen within the gap, not woken for yet. */
5221
+ let held = false;
5222
+ const wake = (why, at) => {
5223
+ wokeAt = at;
5224
+ held = false;
5225
+ try {
5226
+ onWake(why);
5227
+ } catch {}
5228
+ };
5229
+ const timer = setInterval(() => {
5230
+ const at = now();
5231
+ const slept = at - last > tickMs + lateMs;
5232
+ last = at;
5233
+ const next = safe(addresses);
5234
+ const moved = next !== "" && next !== key;
5235
+ key = next;
5236
+ if (slept) return wake("sleep", at);
5237
+ if (!(at - wokeAt >= gap)) {
5238
+ held ||= moved;
5239
+ return;
5240
+ }
5241
+ if (held) {
5242
+ gap = Math.min(gap * 2, WAKE_GAP_MAX_MS);
5243
+ return wake("network", at);
5244
+ }
5245
+ gap = WAKE_GAP_MS;
5246
+ if (moved) wake("network", at);
5247
+ }, tickMs);
5248
+ timer.unref?.();
5249
+ return () => clearInterval(timer);
5250
+ }
5251
+ function safe(read) {
5252
+ try {
5253
+ return read();
5254
+ } catch {
5255
+ return "";
5256
+ }
5257
+ }
4947
5258
  //#endregion
4948
5259
  //#region src/runtime/engine.ts
4949
5260
  /**
@@ -5166,15 +5477,15 @@ async function startRuntime(paths, options = {}) {
5166
5477
  await installEventSource();
5167
5478
  await preloadWalletModules();
5168
5479
  (await import("./ghostly_iroh_web-BzAXJUYH.js")).initSync({ module: irohWasmBytes() });
5169
- const [{ registerFileBytes }, { NodeFileBytes }] = await Promise.all([import("./fileBytes-DMzrIdCu.js"), import("./fileBytes-Douk1yOp.js")]);
5480
+ const [{ registerFileBytes }, { NodeFileBytes }] = await Promise.all([import("./fileBytes-CQQK2uOh.js"), import("./fileBytes-DqnfKIkj.js")]);
5170
5481
  registerFileBytes("native", async () => new NodeFileBytes(paths.files), true);
5171
- if (await (await import("./blobFiles-BnjN_Vrz.js")).moveBlobFiles()) await store.compact();
5172
- const [{ EngineServer }, { createHyperEndpoint }] = await Promise.all([import("./server-DcOsgYDU.js"), import("./endpoint-DWHkXWVM.js")]);
5173
- const mainline = dht.off ? null : new (await (import("./mainline-HPlVrl8R.js"))).Mainline({
5482
+ if (await (await import("./blobFiles-XZ9PEXYy.js")).moveBlobFiles()) await store.compact();
5483
+ const [{ EngineServer }, { createHyperEndpoint }] = await Promise.all([import("./server-7w2O5wsv.js"), import("./endpoint-DWHkXWVM.js")]);
5484
+ const mainline = dht.off ? null : new (await (import("./mainline-B2qmNsib.js"))).Mainline({
5174
5485
  bootstrap: dht.bootstrap,
5175
5486
  host: dht.host
5176
5487
  });
5177
- const transport = mainline || pinned ? new (await (import("./mainline-HPlVrl8R.js"))).RelaysAndDht(mainline, pinned ? { relays: pinned } : {}, !!pinned) : null;
5488
+ const transport = mainline || pinned ? new (await (import("./mainline-B2qmNsib.js"))).RelaysAndDht(mainline, pinned ? { relays: pinned } : {}, !!pinned) : null;
5178
5489
  const apps = servedApps(paths.dir).length > 0;
5179
5490
  const server = new EngineServer({
5180
5491
  ...transport ? { transport } : {},
@@ -5188,6 +5499,7 @@ async function startRuntime(paths, options = {}) {
5188
5499
  apps: apps ? "wire" : false,
5189
5500
  staysOnline: envSwitch("GHOSTLY_HUB", true),
5190
5501
  watchPeerIdleMs: DAEMON_WATCH_PEER_IDLE_MS,
5502
+ peerDhtPollMs: ACTIVE_DHT_POLL_MS,
5191
5503
  localFetch: nodeLocalFetch,
5192
5504
  pushSend: (request) => nodePushSend(request),
5193
5505
  holdFetch: nodeHoldFetch(),
@@ -5205,6 +5517,9 @@ async function startRuntime(paths, options = {}) {
5205
5517
  await store.close().catch(() => {});
5206
5518
  throw error;
5207
5519
  }
5520
+ const stopWake = options.offline ? () => {} : watchWake(() => {
5521
+ server.node.wake({ network: true });
5522
+ });
5208
5523
  let closing = null;
5209
5524
  return {
5210
5525
  paths,
@@ -5214,6 +5529,7 @@ async function startRuntime(paths, options = {}) {
5214
5529
  callsUnavailable,
5215
5530
  apps,
5216
5531
  close: () => closing ??= (async () => {
5532
+ stopWake();
5217
5533
  await server.node.shutdown({ quitting: true }).catch(() => {});
5218
5534
  await mainline?.destroy().catch(() => {});
5219
5535
  await store.close();
@@ -5296,6 +5612,7 @@ async function openHost(paths, mode, version, options = {}) {
5296
5612
  ids: [...histories.keys(), ...newest.keys()]
5297
5613
  });
5298
5614
  } catch (error) {
5615
+ hub.release();
5299
5616
  await runtime.close().catch(() => {});
5300
5617
  release();
5301
5618
  throw error;
@@ -5314,6 +5631,7 @@ async function openHost(paths, mode, version, options = {}) {
5314
5631
  close: () => closing ??= (async () => {
5315
5632
  await Promise.all([calls.stopAll(), flushCardUpdates(ctx)]).catch(() => {});
5316
5633
  runtime.server.detach(hub.sink);
5634
+ hub.release();
5317
5635
  await runtime.close().catch(() => {});
5318
5636
  release();
5319
5637
  })()
@@ -5534,4 +5852,4 @@ function connection(ctx, socket, secret) {
5534
5852
  //#endregion
5535
5853
  export { BASELINE_NEWEST, MAX_UNREAD, keepServing, openHost, serve };
5536
5854
 
5537
- //# sourceMappingURL=host-G5seUwaI.js.map
5855
+ //# sourceMappingURL=host-C-wwtVt2.js.map