@ghostlytools/cli 1.11.2 → 1.11.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 (97) hide show
  1. package/README.md +34 -28
  2. package/SKILL.md +4 -2
  3. package/dist/assets/{api-CtXgscmK.js → api-BwyFq4lA.js} +2 -2
  4. package/dist/assets/{api-BM3PsXbB.js → api-MYc6QNRs.js} +306 -114
  5. package/dist/assets/api-MYc6QNRs.js.map +1 -0
  6. package/dist/assets/{apiKit-lCTQ0EBG.js → apiKit-CfsNx9ZR.js} +62 -16
  7. package/dist/assets/apiKit-CfsNx9ZR.js.map +1 -0
  8. package/dist/assets/{appFetch-BKHy5H8J.js → appFetch-DVYZOZFw.js} +3 -3
  9. package/dist/assets/{appFetch-BKHy5H8J.js.map → appFetch-DVYZOZFw.js.map} +1 -1
  10. package/dist/assets/{apps-DO_gAZgm.js → apps-Dbw2Hcko.js} +1 -1
  11. package/dist/assets/{apps-Do26w3c7.js → apps-h12II1us.js} +150 -57
  12. package/dist/assets/apps-h12II1us.js.map +1 -0
  13. package/dist/assets/{arkade-CZrLbz-M.js → arkade-Bw_4PZRG.js} +2 -2
  14. package/dist/assets/{arkade-CZrLbz-M.js.map → arkade-Bw_4PZRG.js.map} +1 -1
  15. package/dist/assets/{backup-D21x1f5P.js → backup-CdEzTq5C.js} +1 -1
  16. package/dist/assets/{backup-j47AzDvG.js → backup-Chvy79SN.js} +60 -55
  17. package/dist/assets/backup-Chvy79SN.js.map +1 -0
  18. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  19. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  20. package/dist/assets/{buttons-CiGlBVBT.js → buttons-BgoExb4E.js} +37 -7
  21. package/dist/assets/buttons-BgoExb4E.js.map +1 -0
  22. package/dist/assets/buttons-DK2aAGat.js +2 -0
  23. package/dist/assets/{client-raIncVtF.js → client-DY8tZZWi.js} +28 -8
  24. package/dist/assets/client-DY8tZZWi.js.map +1 -0
  25. package/dist/assets/{codec-DcG2AeyE.js → codec-BnMg-Grj.js} +2 -2
  26. package/dist/assets/{codec-DcG2AeyE.js.map → codec-BnMg-Grj.js.map} +1 -1
  27. package/dist/assets/{envelope-Dud6lntA.js → envelope-CdV7vHVZ.js} +2 -2
  28. package/dist/assets/{envelope-Dud6lntA.js.map → envelope-CdV7vHVZ.js.map} +1 -1
  29. package/dist/assets/{errors-Dt-ZnyOX.js → errors-CAh6GLJZ.js} +27 -2
  30. package/dist/assets/errors-CAh6GLJZ.js.map +1 -0
  31. package/dist/assets/{fedimintSdk-DRKRSw14.js → fedimintSdk-CPFfVK-G.js} +2 -2
  32. package/dist/assets/{fedimintSdk-DRKRSw14.js.map → fedimintSdk-CPFfVK-G.js.map} +1 -1
  33. package/dist/assets/{fixedHosts-CNX7QiUD.js → fixedHosts-CbgqrIKs.js} +3 -3
  34. package/dist/assets/{fixedHosts-CNX7QiUD.js.map → fixedHosts-CbgqrIKs.js.map} +1 -1
  35. package/dist/assets/{host-8RskzQgB.js → host-C0NMNQLl.js} +702 -143
  36. package/dist/assets/host-C0NMNQLl.js.map +1 -0
  37. package/dist/assets/{hyperdhtRelay-uAThbFub.js → hyperdhtRelay-Dz7pvcBA.js} +2 -2
  38. package/dist/assets/{hyperdhtRelay-uAThbFub.js.map → hyperdhtRelay-Dz7pvcBA.js.map} +1 -1
  39. package/dist/assets/{irohWeb-DGelfgDJ.js → irohWeb-caAj4Dms.js} +19 -12
  40. package/dist/assets/irohWeb-caAj4Dms.js.map +1 -0
  41. package/dist/assets/{main-BC33ooYg.js → main-C6t5zrD5.js} +383 -110
  42. package/dist/assets/main-C6t5zrD5.js.map +1 -0
  43. package/dist/assets/{mainline-DYrjsS1t.js → mainline-DCuGUSZF.js} +35 -18
  44. package/dist/assets/mainline-DCuGUSZF.js.map +1 -0
  45. package/dist/assets/{networkReason-n2oBs4by.js → networkReason-BbQW1Xpc.js} +3 -3
  46. package/dist/assets/{networkReason-n2oBs4by.js.map → networkReason-BbQW1Xpc.js.map} +1 -1
  47. package/dist/assets/{nwc-Do3VSlIS.js → nwc-CSDRMZ0e.js} +3 -3
  48. package/dist/assets/{nwc-Do3VSlIS.js.map → nwc-CSDRMZ0e.js.map} +1 -1
  49. package/dist/assets/{nwcProvider-Du5aWNIn.js → nwcProvider-PE0wli8n.js} +2 -2
  50. package/dist/assets/{nwcProvider-Du5aWNIn.js.map → nwcProvider-PE0wli8n.js.map} +1 -1
  51. package/dist/assets/{ownDid-CwwYu8s2.js → ownDid-C1R5Kd8q.js} +2 -2
  52. package/dist/assets/{ownDid-CwwYu8s2.js.map → ownDid-C1R5Kd8q.js.map} +1 -1
  53. package/dist/assets/{ownStatus-D7dB4zJB.js → ownStatus-BoTf5WqQ.js} +27 -9
  54. package/dist/assets/ownStatus-BoTf5WqQ.js.map +1 -0
  55. package/dist/assets/{profiles-NyF5FnYF.js → profiles-DszHjEJi.js} +25 -10
  56. package/dist/assets/profiles-DszHjEJi.js.map +1 -0
  57. package/dist/assets/{registry-DKDInr0A.js → registry-Da-r6eC3.js} +30 -12
  58. package/dist/assets/registry-Da-r6eC3.js.map +1 -0
  59. package/dist/assets/{registry-C734VrO9.js → registry-zUZBSHYv.js} +1 -1
  60. package/dist/assets/{resolve-3Tqh9AWQ.js → resolve-tUzh4lHh.js} +2 -2
  61. package/dist/assets/{resolve-3Tqh9AWQ.js.map → resolve-tUzh4lHh.js.map} +1 -1
  62. package/dist/assets/{secretGuard-B7Hj0Kvz.js → secretGuard-CsVHDdYk.js} +68 -6
  63. package/dist/assets/{secretGuard-B7Hj0Kvz.js.map → secretGuard-CsVHDdYk.js.map} +1 -1
  64. package/dist/assets/secretGuard-DCb1I0_B.js +2 -0
  65. package/dist/assets/{server-B6PQ6iae.js → server-C1jZZ61O.js} +896 -277
  66. package/dist/assets/server-C1jZZ61O.js.map +1 -0
  67. package/dist/assets/{src-ChJijTlM.js → src-DJe-OYxd.js} +1010 -236
  68. package/dist/assets/src-DJe-OYxd.js.map +1 -0
  69. package/dist/assets/{sshForges-Brf0fslM.js → sshForges-C9zTO72R.js} +4 -3
  70. package/dist/assets/sshForges-C9zTO72R.js.map +1 -0
  71. package/dist/assets/{translate-xLme9Rdh.js → translate-CUuC5szR.js} +36 -15
  72. package/dist/assets/translate-CUuC5szR.js.map +1 -0
  73. package/dist/assets/{usdt-CSU5KzTV.js → usdt-DI51znt-.js} +3 -3
  74. package/dist/assets/{usdt-CSU5KzTV.js.map → usdt-DI51znt-.js.map} +1 -1
  75. package/dist/ghostly.mjs +1 -1
  76. package/npm-shrinkwrap.json +2 -2
  77. package/package.json +1 -1
  78. package/dist/assets/api-BM3PsXbB.js.map +0 -1
  79. package/dist/assets/apiKit-lCTQ0EBG.js.map +0 -1
  80. package/dist/assets/apps-Do26w3c7.js.map +0 -1
  81. package/dist/assets/backup-j47AzDvG.js.map +0 -1
  82. package/dist/assets/buttons-CiGlBVBT.js.map +0 -1
  83. package/dist/assets/buttons-D2l2bVCG.js +0 -2
  84. package/dist/assets/client-raIncVtF.js.map +0 -1
  85. package/dist/assets/errors-Dt-ZnyOX.js.map +0 -1
  86. package/dist/assets/host-8RskzQgB.js.map +0 -1
  87. package/dist/assets/irohWeb-DGelfgDJ.js.map +0 -1
  88. package/dist/assets/main-BC33ooYg.js.map +0 -1
  89. package/dist/assets/mainline-DYrjsS1t.js.map +0 -1
  90. package/dist/assets/ownStatus-D7dB4zJB.js.map +0 -1
  91. package/dist/assets/profiles-NyF5FnYF.js.map +0 -1
  92. package/dist/assets/registry-DKDInr0A.js.map +0 -1
  93. package/dist/assets/secretGuard-DUr6bgKc.js +0 -2
  94. package/dist/assets/server-B6PQ6iae.js.map +0 -1
  95. package/dist/assets/src-ChJijTlM.js.map +0 -1
  96. package/dist/assets/sshForges-Brf0fslM.js.map +0 -1
  97. package/dist/assets/translate-xLme9Rdh.js.map +0 -1
@@ -1,18 +1,19 @@
1
- import { Ao as STATUS_CARD_LIMITS, Ba as sanitizeMime, Bn as withoutAudioMetadata, Fo as cardLine, Ga as downsamplePeaks, Gu as normalizeRelayUrl, Ha as VOICE_LIMITS, Ja as voiceDownloadName, Jn as withoutPictureMetadata, Ku as relayUrlProblem, Lo as checkStatusCard, Mo as appCardId, Nl as appRef, No as appCardUrl, Oi as APP_DATA_MAX_BYTES, Tl as isAppUrl, Ua as VOICE_METER, Un as withoutVideoMetadata, Uo as claimedTime, Va as PLAYABLE_AUDIO, Vo as MESSAGE_CLOCK_SKEW_MS, Wa as baseMime, Wn as NO_PICTURE_METADATA, Xi as identityStatement, Ya as voiceLevel, ai as sanitizeTypingStatus, bd as toBase64Url, bl as APP_PERMISSIONS, bs as LIMITS, cs as AWAITING_PEER_MS, dd as sanitizeAvatar, gs as GhostlyHttpError, lu as ownInviteRefusal, ni as TYPING_KINDS, or as GROUP_FILE_LIMITS, qa as parseVoiceMeta, ql as readImageMeta, qn as stripPictureMetadata, ri as TYPING_REFRESH_MS, su as inviteLink, ud as MAX_AVATAR_LENGTH, vs as parseLocalTarget, xo as replySnippet, yd as randomBytes$1, za as sanitizeFileName, zl as isAppRef, zo as statusCardBytes } from "./src-ChJijTlM.js";
1
+ import { $i as identityStatement, Cd as randomBytes$1, Ga as VOICE_LIMITS, Go as MESSAGE_CLOCK_SKEW_MS, Ha as sanitizeFileName, Hl as isAppRef, Il as appRef, Io as appCardId, Ja as downsamplePeaks, Ju as normalizeRelayUrl, Ka as VOICE_METER, Kn as withoutVideoMetadata, Lo as appCardUrl, Ol as isAppUrl, Po as STATUS_CARD_LIMITS, Qa as voiceLevel, Ss as parseLocalTarget, To as replySnippet, Ua as sanitizeMime, Un as withoutAudioMetadata, Uo as statusCardBytes, Vo as checkStatusCard, Wa as PLAYABLE_AUDIO, Xa as parseVoiceMeta, Xl as readImageMeta, Xn as stripPictureMetadata, Yu as relayUrlProblem, Za as voiceDownloadName, Zn as withoutPictureMetadata, ai as TYPING_KINDS, bs as GhostlyHttpError, ci as sanitizeTypingStatus, fs as AWAITING_PEER_MS, fu as ownInviteRefusal, hd as sanitizeAvatar, ji as APP_DATA_MAX_BYTES, lr as GROUP_FILE_LIMITS, md as MAX_AVATAR_LENGTH, oi as TYPING_REFRESH_MS, pn as parsePaymentAmount, qa as baseMime, qn as NO_PICTURE_METADATA, qo as claimedTime, uu as inviteLink, wd as toBase64Url, ws as LIMITS, zo as cardLine } from "./src-DJe-OYxd.js";
2
2
  import { p as fileStore } from "./idb-CEuoNsTv.js";
3
3
  import { f as FILE_BYTES_STEP, o as fileBytes, s as fileBytesOf } from "./fileBytes-BLPZq9YU.js";
4
- import { B as removeStored, U as waitingGroupFile, W as IDENTITY_DRAFT_TTL_MS, a as groupMemberOfLink, b as replyRef, c as groupPayTwin, ft as iceServerProblem, h as groupOfFile, k as paymentNetwork, o as groupPayLineId, p as groupFileId, pt as iceServerSetting, s as groupPayNoteId, t as DEFAULT_IROH_RELAYS } from "./irohWeb-DGelfgDJ.js";
5
- import { t as IDENTITY_PROVIDERS } from "./registry-DKDInr0A.js";
6
- import { n as secretWords, r as findSecret, t as guardText } from "./secretGuard-B7Hj0Kvz.js";
7
- import { i as localFileError, r as asCliError, t as CliError } from "./errors-Dt-ZnyOX.js";
8
- import { a as PAY_METHODS, d as ENGINE_METHODS, f as ENGINE_PARAMS, g as engineParamsProblem, i as CHAT_METHODS, l as withStoredIds, m as READ_PARAMS, n as statusJson, o as TRANSPORT_NAMES, p as ENGINE_READS, r as ADDRESS_TYPES, s as WALLET_TYPES, t as checkOwnStatus, u as DESTRUCTIVE_CALLS } from "./ownStatus-D7dB4zJB.js";
9
- import { A as sinceSeq, D as oneShotWaits, E as oneOf, F as transportOffered, I as waitForState, N as state, O as sentAt, P as str, S as nobodyJoined, T as num, _ as messageOf, a as contactKeyOf, b as noFile, c as findChatOrGroup, d as groupNameOf, f as groupOf, g as list, h as keptForJoin, j as somebodyJoined, k as shownName, l as findGroup, m as inviteTaken, n as chatOf, o as dhtOnly, p as groupPrefixed, r as chatOrGroup, s as findChat, t as bool, u as findOwnNamedChat, w as node, x as noMessage } from "./apiKit-lCTQ0EBG.js";
4
+ import { B as removeStored, U as waitingGroupFile, W as IDENTITY_DRAFT_TTL_MS, a as groupMemberOfLink, b as replyRef, c as groupPayTwin, ft as iceServerProblem, h as groupOfFile, k as paymentNetwork, o as groupPayLineId, p as groupFileId, pt as iceServerSetting, s as groupPayNoteId, t as DEFAULT_IROH_RELAYS } from "./irohWeb-caAj4Dms.js";
5
+ import { s as isAppFetchUrl } from "./appFetch-DVYZOZFw.js";
6
+ import { i as parseProofBunker, t as IDENTITY_PROVIDERS } from "./registry-Da-r6eC3.js";
7
+ import { n as secretWords, r as findSecret, t as guardText } from "./secretGuard-CsVHDdYk.js";
8
+ import { i as localFileError, r as asCliError, t as CliError } from "./errors-CAh6GLJZ.js";
9
+ import { a as PAY_METHODS, d as ENGINE_METHODS, f as ENGINE_PARAMS, g as engineParamsProblem, i as CHAT_METHODS, l as withStoredIds, m as READ_PARAMS, n as statusJson, o as TRANSPORT_NAMES, p as ENGINE_READS, r as ADDRESS_TYPES, s as WALLET_TYPES, t as checkOwnStatus, u as DESTRUCTIVE_CALLS } from "./ownStatus-BoTf5WqQ.js";
10
+ import { A as settingsOf, D as oneShotWaits, E as oneOf, F as state, I as str, L as transportOffered, M as sinceSeq, N as somebodyJoined, O as ownChatOf, R as waitForState, S as nobodyJoined, T as num, _ as messageOf, a as contactKeyOf, b as noFile, c as findChatOrGroup, d as groupNameOf, f as groupOf, g as list, h as keptForJoin, j as shownName, k as sentAt, l as findGroup, m as inviteTaken, n as chatOf, o as dhtOnly, p as groupPrefixed, r as chatOrGroup, s as findChat, t as bool, w as node, x as noMessage } from "./apiKit-CfsNx9ZR.js";
10
11
  import { t as childEnv } from "./childEnv-K_IzUqQx.js";
11
12
  import { t as chatState } from "./waitNotice-Cn0WJ-He.js";
12
- import { a as goesOn, c as waitForEdit, d as waitForRemoval, i as pressable, l as waitForGroupFrame, n as buttonsCard, o as nobodyElseIn, s as waitForConfirmed, t as BUTTON_METHODS, u as waitForMessage } from "./buttons-CiGlBVBT.js";
13
- import { a as checkShownName } from "./profiles-NyF5FnYF.js";
14
- import { t as BACKUP_METHODS } from "./backup-j47AzDvG.js";
15
- import { o as checkedBundle } from "./apps-Do26w3c7.js";
13
+ import { a as checkTextSize$1, c as waitForConfirmed, d as waitForMessage, f as waitForRemoval, i as pressable, l as waitForEdit, n as buttonsCard, o as goesOn, s as nobodyElseIn, t as BUTTON_METHODS, u as waitForGroupFrame } from "./buttons-BgoExb4E.js";
14
+ import { a as checkShownName } from "./profiles-DszHjEJi.js";
15
+ import { t as BACKUP_METHODS } from "./backup-Chvy79SN.js";
16
+ import { o as checkedBundle } from "./apps-h12II1us.js";
16
17
  import { generateMnemonic } from "@scure/bip39";
17
18
  import { wordlist } from "@scure/bip39/wordlists/english.js";
18
19
  import { execFile, spawn } from "node:child_process";
@@ -292,6 +293,10 @@ async function* piecesOf(file, size, piece) {
292
293
  function ascii(bytes, at, length) {
293
294
  return String.fromCharCode(...bytes.subarray(at, at + length));
294
295
  }
296
+ /** The channels and rates a WAV's sound may have (ffmpeg's DSD at 705.6 kHz among them). */
297
+ var WAV_MAX_CHANNELS = 255;
298
+ var WAV_MIN_RATE = 1e3;
299
+ var WAV_MAX_RATE = 768e3;
295
300
  /** The format of a WAV and where its samples are; null while its header is not all there. */
296
301
  function wavHeader(bytes) {
297
302
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -313,6 +318,7 @@ function wavHeader(bytes) {
313
318
  }
314
319
  } else if (id === "data") {
315
320
  if (!channels || !sampleRate || !bits) throw new NotSound("a WAV without its format");
321
+ if (channels > WAV_MAX_CHANNELS || sampleRate < WAV_MIN_RATE || sampleRate > WAV_MAX_RATE) throw new NotSound(`a WAV with ${channels} channel${channels === 1 ? "" : "s"} at ${sampleRate} Hz, which no sound has`);
316
322
  const to = size === 0 || size === 4294967295 ? Infinity : body + size;
317
323
  return {
318
324
  format,
@@ -729,19 +735,22 @@ function mimeOf(path, given) {
729
735
  * a date can hold it; else when it was stored here.
730
736
  */
731
737
  async function voiceTime(ctx, stored) {
732
- return (await findMessage(ctx, stored.linkId, (m) => m.file?.id === stored.id))?.timestamp ?? claimedTime(stored.metadata?.timestamp) ?? stored.createdAt;
738
+ const older = (linkId) => node(ctx).fileMessages(linkId);
739
+ return (await findMessage(ctx, stored.linkId, (m) => m.file?.id === stored.id, older))?.timestamp ?? claimedTime(stored.metadata?.timestamp) ?? stored.createdAt;
733
740
  }
734
741
  /**
735
742
  * The message of a chat or a group (`group:<id>`) that `test` picks: looked for among its newest first, where the one a
736
- * command names almost always is, then in all of them only when there are more. A whole history costs a read of every row.
743
+ * command names almost always is, then in all of them only when there are more. A whole history costs a read of every row;
744
+ * `older` reads fewer, where the message is known to be among them.
737
745
  */
738
- async function findMessage(ctx, linkId, test) {
746
+ async function findMessage(ctx, linkId, test, older) {
739
747
  const page = await node(ctx).messagePage({
740
748
  linkId,
741
749
  limit: 200
742
750
  });
743
751
  const newest = page.messages.find(test);
744
752
  if (newest || !page.more) return newest;
753
+ if (older) return (await older(linkId)).find(test);
745
754
  const group = linkId.startsWith("group:") ? linkId.slice(6) : void 0;
746
755
  return (group ? await node(ctx).groupMessages({ groupId: group }) : await node(ctx).getMessages(linkId)).find(test);
747
756
  }
@@ -791,15 +800,16 @@ function withWaitingFor(transfer) {
791
800
  };
792
801
  }
793
802
  /** The chat or the group a file command names (`findChatOrGroup`). */
794
- var chatOrGroupOf = (ctx, params) => findChatOrGroup(state(ctx).links, state(ctx).groups, str(params, "chat", true));
803
+ var chatOrGroupOf = (ctx, params, { links, groups } = state(ctx)) => findChatOrGroup(links, groups, str(params, "chat", true));
795
804
  /**
796
805
  * The chat or group a file belongs to: a file id starts with its chat's id (a group's file with `group-<id>-`), so it
797
806
  * may be left out; given, it must be the file's own. `where` is what the answer names it by.
798
807
  */
799
808
  function fileChat(ctx, params, fileId) {
800
- const groupId = groupOfFile(fileId, state(ctx).groups.map((g) => g.id));
809
+ const s = state(ctx);
810
+ const groupId = groupOfFile(fileId, s.groups.map((g) => g.id));
801
811
  if (groupId) {
802
- const named = params.chat === void 0 ? void 0 : chatOrGroupOf(ctx, params);
812
+ const named = params.chat === void 0 ? void 0 : chatOrGroupOf(ctx, params, s);
803
813
  if (named && !("group" in named && named.group.id === groupId)) throw noFile(fileId, {
804
814
  group: "group" in named,
805
815
  ref: str(params, "chat", true)
@@ -809,7 +819,7 @@ function fileChat(ctx, params, fileId) {
809
819
  where: { group: groupId }
810
820
  };
811
821
  }
812
- const link = params.chat === void 0 ? state(ctx).links.find((l) => fileId.startsWith(`${l.id}-in-`) || fileId.startsWith(`${l.id}-out-`)) : chatOf(ctx, params);
822
+ const link = params.chat === void 0 ? s.links.find((l) => fileId.startsWith(`${l.id}-in-`) || fileId.startsWith(`${l.id}-out-`)) : chatOf(ctx, params, s);
813
823
  if (!link) throw noFile(fileId);
814
824
  if (!fileId.startsWith(`${link.id}-`)) throw noFile(fileId, {
815
825
  group: false,
@@ -894,7 +904,7 @@ async function whileUnchanged(path, read) {
894
904
  * A file announced in a group (WISP 503): its bytes staged under a group file id with their digest, as a chat's are, then
895
905
  * the announcement. This device is its first holder and serves the members who ask.
896
906
  */
897
- async function sendToGroup(ctx, params, group, path, picked) {
907
+ async function sendToGroup(ctx, params, group, path, name, picked) {
898
908
  if (picked > GROUP_FILE_LIMITS.maxBytes) throw new CliError("refused", `Too large for a group (at most ${GROUP_FILE_LIMITS.maxBytes} bytes)`);
899
909
  if (!picked) throw new CliError("refused", "An empty file cannot go to a group");
900
910
  const mime = mimeOf(path, str(params, "mime"));
@@ -914,7 +924,7 @@ async function sendToGroup(ctx, params, group, path, picked) {
914
924
  const fileId = groupFileId(group.id, "out");
915
925
  const file = {
916
926
  id: fileId,
917
- name: sanitizeFileName(str(params, "name") ?? basename(path)),
927
+ name,
918
928
  size,
919
929
  mime,
920
930
  ...voice ? { voice } : {},
@@ -1072,15 +1082,7 @@ async function waitForFile(ctx, params, stopping) {
1072
1082
  ...where,
1073
1083
  retry: !!transfer.retry
1074
1084
  });
1075
- if (transfer.state !== "done") {
1076
- const name = (stored ?? await fileStore.get(fileId).catch(() => void 0))?.metadata?.name ?? "The file";
1077
- throw new CliError("confirm", `${name} (${megabytes(transfer.size)}) waits for you to take it: ghostly file accept ${fileId} (or file decline)`, {
1078
- file: fileId,
1079
- ...where,
1080
- size: transfer.size,
1081
- stage: "asking"
1082
- });
1083
- }
1085
+ if (transfer.state !== "done") throw waitsForYou((stored ?? await fileStore.get(fileId).catch(() => void 0))?.metadata?.name, fileId, where, transfer.size);
1084
1086
  return {
1085
1087
  ...where,
1086
1088
  file: fileId,
@@ -1088,11 +1090,21 @@ async function waitForFile(ctx, params, stopping) {
1088
1090
  size: transfer.size
1089
1091
  };
1090
1092
  }
1093
+ /** A received file that waits for this person's `file accept` (`file wait`, `file save`): said naming the command. */
1094
+ function waitsForYou(name, fileId, where, size) {
1095
+ return new CliError("confirm", `${name ?? "The file"} (${megabytes(size)}) waits for you to take it: ghostly file accept ${fileId} (or file decline)`, {
1096
+ file: fileId,
1097
+ ...where,
1098
+ size,
1099
+ stage: "asking"
1100
+ });
1101
+ }
1091
1102
  var FILE_METHODS = {
1092
1103
  async "file.send"(ctx, params) {
1093
- guardText(str(params, "name"), bool(params, "force"), "file's name", "send it");
1094
- const target = chatOrGroupOf(ctx, params);
1095
1104
  const path = resolve(str(params, "path", true));
1105
+ const name = sanitizeFileName(str(params, "name") ?? basename(path));
1106
+ guardText(name, bool(params, "force"), "file's name", "send it");
1107
+ const target = chatOrGroupOf(ctx, params);
1096
1108
  let info;
1097
1109
  try {
1098
1110
  info = await stat(path);
@@ -1106,10 +1118,10 @@ var FILE_METHODS = {
1106
1118
  min: 1,
1107
1119
  max: 86400
1108
1120
  });
1109
- if ("group" in target) return sendToGroup(ctx, params, target.group, path, info.size);
1121
+ if ("group" in target) return sendToGroup(ctx, params, target.group, path, name, info.size);
1110
1122
  const { link } = target;
1111
1123
  if (link.profile && link.dataLink === "open" && !link.capabilities?.files) throw new CliError("unavailable", "The contact's app takes no files");
1112
- if (!link.capabilities?.largeFiles && info.size > LIMITS.maxFileBytes) throw new CliError("refused", `Too large for the contact's app (at most ${LIMITS.maxFileBytes} bytes)`);
1124
+ if (link.dataLink === "open" && !link.capabilities?.largeFiles && info.size > LIMITS.maxFileBytes) throw new CliError("refused", `Too large for the contact's app (at most ${LIMITS.maxFileBytes} bytes)`);
1113
1125
  if (typeof link.peerFileRoom === "number" && info.size > link.peerFileRoom) throw new CliError("refused", `Not enough space on the contact's device (${link.peerFileRoom} bytes free)`);
1114
1126
  const mime = mimeOf(path, str(params, "mime"));
1115
1127
  const replyTo = str(params, "reply");
@@ -1125,7 +1137,7 @@ var FILE_METHODS = {
1125
1137
  const wireId = toBase64Url(randomBytes$1(12));
1126
1138
  const file = {
1127
1139
  id: `${link.id}-out-${wireId}`,
1128
- name: sanitizeFileName(str(params, "name") ?? basename(path)),
1140
+ name,
1129
1141
  size: source.size,
1130
1142
  mime,
1131
1143
  ...voice ? { voice } : {},
@@ -1272,6 +1284,9 @@ var FILE_METHODS = {
1272
1284
  if (whole && action === "cancel") throw new CliError("refused", "Too late to cancel: it arrived whole, and the contact keeps it");
1273
1285
  if (whole && action === "pause") throw new CliError("refused", "Too late to pause: it arrived whole, and the contact keeps it");
1274
1286
  }
1287
+ const view = state(ctx).transfers[fileId];
1288
+ if ((action === "resume" || action === "request" || action === "resend") && view?.stage === "paused" && view.pausedBy === "peer") throw new CliError("refused", "Paused by the contact: it goes on when they resume it");
1289
+ if ((action === "pause" || action === "resume" || action === "request") && view?.stage === "asking" && view.direction === "in") throw new CliError("refused", "Not taken yet: it waits for you to take it (file accept, or file decline)");
1275
1290
  await node(ctx).fileAction({
1276
1291
  linkId,
1277
1292
  fileId,
@@ -1295,15 +1310,22 @@ var FILE_METHODS = {
1295
1310
  async "file.save"(ctx, params) {
1296
1311
  const fileId = str(params, "file", true);
1297
1312
  if (params.chat !== void 0) fileChat(ctx, params, fileId);
1298
- if (bool(params, "wait")) await FILE_METHODS["file.wait"](ctx, {
1313
+ if (bool(params, "wait") && (await fileStore.get(fileId))?.direction !== "out") await FILE_METHODS["file.wait"](ctx, {
1299
1314
  file: fileId,
1300
1315
  timeout: params.timeout
1301
1316
  });
1302
1317
  const stored = await fileStore.get(fileId);
1303
1318
  if (!stored?.metadata) throw noFile(fileId);
1304
1319
  if (stored.leftOut) throw new CliError("not_found", "Not in this backup: the light backup this profile was restored from left the file out");
1305
- const transfer = stored.direction === "out" ? void 0 : state(ctx).transfers[fileId] ?? stored.transfer;
1320
+ const transfer = stored.direction === "out" ? void 0 : state(ctx).transfers[fileId] ?? waitingGroupFile(stored) ?? stored.transfer;
1306
1321
  if (transfer?.state === "failed") throw new CliError("refused", `It ended: ${transfer.error ?? "failed"}`);
1322
+ if (transfer?.state === "transferring" && transfer.stage === "asking" && transfer.direction === "in") {
1323
+ let where;
1324
+ try {
1325
+ where = fileChat(ctx, params, fileId).where;
1326
+ } catch {}
1327
+ throw waitsForYou(stored.metadata.name, fileId, where, transfer.size);
1328
+ }
1307
1329
  if (transfer && transfer.state !== "done") throw new CliError("unavailable", `The file is not all here yet (${transfer.transferred} of ${transfer.size} bytes)`);
1308
1330
  const named = str(params, "path") ? resolve(str(params, "path", true)) : join(resolve(str(params, "dir") ?? "."), saveName(stored.metadata.voice ? voiceDownloadName(stored.metadata.mime, await voiceTime(ctx, stored)) : stored.metadata.name));
1309
1331
  const force = bool(params, "force");
@@ -1314,7 +1336,12 @@ var FILE_METHODS = {
1314
1336
  const taken = async (target, code) => {
1315
1337
  const there = await stat(target).catch(() => void 0);
1316
1338
  if (there?.isDirectory()) return new CliError("bad_request", `${target} is a folder: name a file, or use --dir ${target} (dir over the socket)`);
1317
- if (there && !force || code === "EEXIST") return new CliError("confirm", `${target} exists: pass --force (force: true over the socket) to replace it`);
1339
+ if (!(there && !force || code === "EEXIST")) return;
1340
+ const replace = `${target} exists: pass --force (force: true over the socket) to replace it`;
1341
+ if (path) return new CliError("confirm", replace);
1342
+ let n = 2;
1343
+ while (n <= 1e3 && await stat(`${stem} (${n})${ext}`).catch(() => void 0)) n += 1;
1344
+ return new CliError("confirm", `${replace}, or --path ${stem} (${n})${ext} (path over the socket) to keep both`);
1318
1345
  };
1319
1346
  let target = named;
1320
1347
  for (let n = 2, refused = await taken(target); refused; n += 1, refused = await taken(target)) {
@@ -1497,9 +1524,11 @@ function secretIn(value) {
1497
1524
  * The secret guard `send` has (docs/CLI.md § Safety): a card whose text looks like a seed, a private key or a Cashu
1498
1525
  * token goes only with `--force`. `fields` are what this command gives (an update's own, not the card it merges over).
1499
1526
  * A card's text is read as given and as the card carries it (`cardLine`): a line loses its invisible characters on the
1500
- * way, so a key one of them broke in two is whole again on the card. The fallback text goes as it is, as `send`'s.
1527
+ * way, so a key one of them broke in two is whole again on the card. The fallback text goes as it is, as `send`'s, and
1528
+ * one past 16 KiB is refused first, with its size, `--force` or not (`checkTextSize`).
1501
1529
  */
1502
1530
  function guardSecrets(fields, params, verb) {
1531
+ if (typeof params.text === "string") checkTextSize$1(params.text);
1503
1532
  if (bool(params, "force")) return;
1504
1533
  const check = (text) => {
1505
1534
  const secret = findSecret(text);
@@ -1695,16 +1724,18 @@ async function updateCard(ctx, params, kind) {
1695
1724
  let queued = false;
1696
1725
  if (due > 0 && ctx.mode === "daemon") {
1697
1726
  pace.next = card;
1727
+ pace.text = text;
1698
1728
  queued = true;
1699
1729
  if (!pace.timer) pace.flushed = new Promise((resolve) => {
1700
1730
  const send = () => {
1701
- const next = pace.next;
1731
+ const next = pace.next, nextText = pace.text ?? "";
1702
1732
  clearTimeout(pace.timer);
1703
1733
  pace.timer = void 0;
1704
1734
  pace.next = void 0;
1735
+ pace.text = void 0;
1705
1736
  pace.flush = void 0;
1706
1737
  pace.last = Date.now();
1707
- (next ? editCard(ctx, target, message.id, next, text) : Promise.resolve()).catch(() => {}).finally(resolve);
1738
+ (next ? editCard(ctx, target, message.id, next, nextText) : Promise.resolve()).catch(() => {}).finally(resolve);
1708
1739
  };
1709
1740
  pace.flush = send;
1710
1741
  pace.timer = setTimeout(send, due);
@@ -1805,6 +1836,7 @@ async function sendUsage(ctx, params) {
1805
1836
  kind: "usage",
1806
1837
  id: typeof fields.id === "string" && fields.id ? fields.id : USAGE_CARD_ID
1807
1838
  });
1839
+ if (typeof params.text === "string") checkTextSize$1(params.text);
1808
1840
  oneOf(params, "wait", ["none", "sent"], "none");
1809
1841
  num(params, "timeout", 30, {
1810
1842
  min: 1,
@@ -1911,12 +1943,19 @@ function stopWait(ctx, linkId) {
1911
1943
  timersOf(ctx).get(linkId)?.();
1912
1944
  timersOf(ctx).delete(linkId);
1913
1945
  }
1946
+ /**
1947
+ * The longest a hold's timer waits before it reads the wall clock again. Timers run on a clock that stops while the
1948
+ * machine sleeps: one timer for the whole hold, after a sleep past its end, kept the chat on DHT only for as long again
1949
+ * as the hold had left when the machine went to sleep, while `holdOf` no longer reported it.
1950
+ */
1951
+ var HOLD_CHECK_MS = 6e4;
1914
1952
  function schedule(ctx, linkId, until) {
1915
1953
  stopWait(ctx, linkId);
1916
1954
  const timer = setTimeout(() => {
1917
1955
  timersOf(ctx).delete(linkId);
1918
- expire(ctx, linkId);
1919
- }, Math.max(0, until - Date.now()));
1956
+ if (until > Date.now()) schedule(ctx, linkId, until);
1957
+ else expire(ctx, linkId);
1958
+ }, Math.min(HOLD_CHECK_MS, Math.max(0, until - Date.now())));
1920
1959
  timer.unref?.();
1921
1960
  timersOf(ctx).set(linkId, () => clearTimeout(timer));
1922
1961
  }
@@ -2292,7 +2331,9 @@ function groupJson(group, showSecret = false) {
2292
2331
  chat: group.invitation.linkId,
2293
2332
  accepted: group.invitation.accepted,
2294
2333
  viaLink: !!group.invitation.viaLink,
2295
- stage: group.invitation.stage ?? null
2334
+ stage: group.invitation.stage ?? null,
2335
+ ...group.invitation.unanswered ? { unanswered: true } : {},
2336
+ ...group.invitation.takenBack ? { takenBack: true } : {}
2296
2337
  } : null,
2297
2338
  ...group.others?.length ? { others: group.others.map((o) => "link" in o ? { link: showSecret ? o.link : "<hidden>" } : {
2298
2339
  chat: o.linkId,
@@ -2388,12 +2429,12 @@ function joined(ctx, params, twin) {
2388
2429
  throw new CliError("refused", group.invitation.accepted ? `You are not in ${group.name} yet: you accepted its invitation, and its admin has not let you in` : `You are not in ${group.name} yet: ghostly group accept ${shown} joins it`);
2389
2430
  }
2390
2431
  /** The member `params.member` names in `group`, this profile's own name said to be it; by its key only for a grant. */
2391
- var member = (ctx, group, params, grant = false) => findMember(group, str(params, "member", true), state(ctx).settings.nick, grant);
2432
+ var member = (ctx, group, params, grant = false) => findMember(group, str(params, "member", true), settingsOf(ctx).nick, grant);
2392
2433
  var view = (ctx, id, params) => groupJson(state(ctx).groups.find((g) => g.id === id) ?? groupOf(ctx, { group: id }), bool(params, "showSecret"));
2393
2434
  var GROUP_ADMIN_METHODS = {
2394
2435
  async "group.invite"(ctx, params) {
2395
2436
  const group = joined(ctx, params);
2396
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2437
+ const link = ownChatOf(ctx, params);
2397
2438
  await node(ctx).inviteToGroup({
2398
2439
  groupId: group.id,
2399
2440
  linkId: link.id
@@ -2453,7 +2494,9 @@ var GROUP_ADMIN_METHODS = {
2453
2494
  },
2454
2495
  async "group.link"(ctx, params) {
2455
2496
  const group = joined(ctx, params);
2456
- if (params.on === false) {
2497
+ const on = params.on === void 0 || bool(params, "on"), reset = bool(params, "reset");
2498
+ if (!on && reset) throw new CliError("bad_request", "on: false turns the link off: not with reset");
2499
+ if (!on) {
2457
2500
  await node(ctx).disableGroupLink({ groupId: group.id });
2458
2501
  return {
2459
2502
  group: group.id,
@@ -2462,7 +2505,7 @@ var GROUP_ADMIN_METHODS = {
2462
2505
  }
2463
2506
  const { link } = await node(ctx).enableGroupLink({
2464
2507
  groupId: group.id,
2465
- ...bool(params, "reset") ? { reset: true } : {}
2508
+ ...reset ? { reset: true } : {}
2466
2509
  });
2467
2510
  return {
2468
2511
  group: group.id,
@@ -2514,7 +2557,7 @@ function headless(s) {
2514
2557
  function signerOf(p, id) {
2515
2558
  const usable = p.signers.filter(headless);
2516
2559
  const found = id ? p.signers.find((s) => s.id === id) : usable[0];
2517
- if (!found) throw new CliError(id ? "not_found" : "unavailable", id ? `${p.label} has no signer ${id}` : `${p.label} proofs need a browser window: make them in the app`);
2560
+ if (!found) throw new CliError(id ? "not_found" : "unavailable", id ? `${p.label} has no signer ${id}` : `${p.label}: this kind of proof needs a browser window, make it in the app`);
2518
2561
  if (!headless(found)) {
2519
2562
  const instead = usable.length ? ` (here: --signer ${usable.map((s) => s.id).join(" or ")})` : "";
2520
2563
  throw new CliError("unavailable", `${found.label} needs a browser window: make this proof in the app${instead}`);
@@ -2625,6 +2668,12 @@ var IDENTITY_METHODS = {
2625
2668
  const values = params.fields ?? {};
2626
2669
  if (typeof values !== "object" || Array.isArray(values) || Object.values(values).some((v) => typeof v !== "string")) throw new CliError("bad_request", "fields must be an object of strings");
2627
2670
  for (const field of signer.fields ?? []) if (!field.optional && !values[field.name]) throw new CliError("usage", `${signer.label} needs ${field.name} (${field.label}): ${howToGive(field)}`);
2671
+ const bunker = signer.fields?.find((f) => f.name === "bunker");
2672
+ if (bunker && values.bunker) try {
2673
+ parseProofBunker(values.bunker);
2674
+ } catch (error) {
2675
+ throw new CliError("bad_request", `${bunker.name} (${bunker.label}): ${error instanceof Error ? error.message : String(error)}`);
2676
+ }
2628
2677
  const seconds = num(params, "timeout", 300, {
2629
2678
  min: 5,
2630
2679
  max: 3600
@@ -2744,9 +2793,10 @@ var IDENTITY_METHODS = {
2744
2793
  return { removed: id };
2745
2794
  },
2746
2795
  async "identity.share"(ctx, params) {
2747
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2796
+ const s = state(ctx);
2797
+ const link = ownChatOf(ctx, params, s);
2748
2798
  const id = str(params, "id", true);
2749
- if (!state(ctx).identityProofs.some((p) => p.id === id)) throw new CliError("not_found", `No identity proof ${JSON.stringify(id)} (ghostly identity list)`);
2799
+ if (!s.identityProofs.some((p) => p.id === id)) throw new CliError("not_found", `No identity proof ${JSON.stringify(id)} (ghostly identity list)`);
2750
2800
  await node(ctx).shareIdentityProof({
2751
2801
  linkId: link.id,
2752
2802
  id
@@ -2757,7 +2807,7 @@ var IDENTITY_METHODS = {
2757
2807
  };
2758
2808
  },
2759
2809
  async "identity.withdraw"(ctx, params) {
2760
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2810
+ const link = ownChatOf(ctx, params);
2761
2811
  const id = str(params, "id", true);
2762
2812
  if (!link.identities?.shared.some((s) => s.id === id)) throw new CliError("not_found", `No identity proof ${JSON.stringify(id)} shared in this chat (ghostly identity contact ${link.id})`);
2763
2813
  await node(ctx).withdrawIdentityProof({
@@ -2977,6 +3027,8 @@ function withoutReports(value) {
2977
3027
  }
2978
3028
  /** `service open` while Hide my IP from contacts is on (as the browser extension refuses to open one). */
2979
3029
  var SERVICE_OPEN_OFF_RELAY_ONLY = "A contact's app does not open here while Hide my IP from contacts is on: a browser tab cannot keep its page off WebRTC";
3030
+ /** `service open` or `service close` in a one-shot: only the daemon keeps a contact's app open on a port. */
3031
+ var SERVICE_NEEDS_DAEMON = "An opened service lives in the daemon: start `ghostly daemon --detach` first";
2980
3032
  function plain(response, status, text, headers = {}) {
2981
3033
  response.writeHead(status, {
2982
3034
  "content-type": "text/plain; charset=utf-8",
@@ -2997,9 +3049,10 @@ async function openServiceServer(send, port = 0, { relayOnly = false } = {}) {
2997
3049
  const name = `${randomBytes(16).toString("hex")}.localhost`;
2998
3050
  const token = randomBytes(32).toString("hex");
2999
3051
  const cookies = /* @__PURE__ */ new Set();
3000
- let host = "";
3052
+ let host = "", portless = "";
3001
3053
  const server = createServer((request, response) => {
3002
- if (request.headers.host?.toLowerCase() !== host) return plain(response, 404, "Not found");
3054
+ const asked = request.headers.host?.toLowerCase();
3055
+ if (!asked || asked !== host && asked !== portless) return plain(response, 404, "Not found");
3003
3056
  const path = request.url ?? "/";
3004
3057
  if (path.startsWith(OPEN_PATH)) {
3005
3058
  if (!sameSecret(path.slice(15), token)) return plain(response, 404, "Not found");
@@ -3034,7 +3087,9 @@ async function openServiceServer(send, port = 0, { relayOnly = false } = {}) {
3034
3087
  resolve();
3035
3088
  });
3036
3089
  });
3037
- host = `${name}:${server.address().port}`;
3090
+ const on = server.address().port;
3091
+ host = `${name}:${on}`;
3092
+ if (on === 80) portless = name;
3038
3093
  return {
3039
3094
  server,
3040
3095
  host,
@@ -3104,6 +3159,20 @@ function serviceOf(ctx, params) {
3104
3159
  * A port the person chose that could not be taken, in words that name it. Before, one in use was Node's EADDRINUSE as
3105
3160
  * `engine`, and one not allowed read as a file (`localFileError`): "Not allowed to write or read the path".
3106
3161
  */
3162
+ /** As long as the engine keeps a service's name (node.ts addService) and the Desktop's form takes it (Services.tsx). */
3163
+ var MAX_SERVICE_NAME_LENGTH = 48;
3164
+ /**
3165
+ * The `name` of `service add`, refused as a chat's or the profile's name is (`shownName`), before anything is made.
3166
+ * Before, one of spaces was the engine's plain error as `engine` (exit 1), and a longer one was cut with exit 0.
3167
+ */
3168
+ function serviceNameOf(params) {
3169
+ const name = shownName(str(params, "name", true), MAX_SERVICE_NAME_LENGTH, "A service's name");
3170
+ if (name.length > MAX_SERVICE_NAME_LENGTH) throw new CliError("bad_request", `A service's name is up to ${MAX_SERVICE_NAME_LENGTH} characters as stored, an emoji counting as 2 (this one is ${name.length})`, {
3171
+ length: name.length,
3172
+ max: MAX_SERVICE_NAME_LENGTH
3173
+ });
3174
+ return name;
3175
+ }
3107
3176
  function portError(error, port) {
3108
3177
  const { code } = error ?? {};
3109
3178
  if (port && code === "EADDRINUSE") return new CliError("busy", `Port ${port} is in use on this machine: choose another, or leave out --port`);
@@ -3122,23 +3191,22 @@ var SERVICE_METHODS = {
3122
3191
  })) };
3123
3192
  },
3124
3193
  async "service.add"(ctx, params) {
3194
+ const name = serviceNameOf(params);
3125
3195
  const target = str(params, "target", true);
3126
- let url;
3127
- try {
3128
- url = new URL(target);
3129
- } catch {
3130
- throw new CliError("bad_request", `Not a URL: ${target}`);
3131
- }
3132
- if (!(LOOPBACK.has(url.hostname) || /^127\.\d+\.\d+\.\d+$/.test(url.hostname))) throw new CliError("refused", "Only a web app on this machine (127.0.0.1, localhost) can be shared");
3133
3196
  try {
3134
3197
  parseLocalTarget(target);
3135
3198
  } catch (error) {
3136
3199
  const said = error instanceof Error ? error.message : String(error);
3137
- const shown = `${url.protocol}//${url.host}${url.pathname}`;
3200
+ const text = target.trim();
3201
+ let shown = text;
3202
+ try {
3203
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text}`);
3204
+ shown = `${url.protocol}//${url.host}${url.pathname}`;
3205
+ } catch {}
3138
3206
  throw new CliError(/^Only services on this machine/.test(said) ? "refused" : "bad_request", `${said}: ${shown}`);
3139
3207
  }
3140
3208
  const { serviceId } = node(ctx).addService({
3141
- name: str(params, "name", true),
3209
+ name,
3142
3210
  target
3143
3211
  });
3144
3212
  return {
@@ -3163,7 +3231,7 @@ var SERVICE_METHODS = {
3163
3231
  };
3164
3232
  },
3165
3233
  async "service.share"(ctx, params) {
3166
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
3234
+ const link = ownChatOf(ctx, params);
3167
3235
  const shared = !bool(params, "off");
3168
3236
  const serviceId = serviceOf(ctx, params);
3169
3237
  await node(ctx).setServiceShared({
@@ -3188,8 +3256,8 @@ var SERVICE_METHODS = {
3188
3256
  },
3189
3257
  /** A contact's shared app on a loopback port of this machine, as the Desktop opens it in a window. */
3190
3258
  async "service.open"(ctx, params) {
3191
- if (ctx.mode !== "daemon") throw new CliError("unavailable", "An opened service lives in the daemon: start `ghostly daemon --detach` first");
3192
- if (state(ctx).settings?.relayOnly === true) throw new CliError("unavailable", SERVICE_OPEN_OFF_RELAY_ONLY);
3259
+ if (ctx.mode !== "daemon") throw new CliError("unavailable", SERVICE_NEEDS_DAEMON);
3260
+ if (settingsOf(ctx).relayOnly === true) throw new CliError("unavailable", SERVICE_OPEN_OFF_RELAY_ONLY);
3193
3261
  const link = chatOf(ctx, params);
3194
3262
  const service = str(params, "service", true);
3195
3263
  const key = `${link.peerPubKeyZ32}/${service}`;
@@ -3224,18 +3292,40 @@ var SERVICE_METHODS = {
3224
3292
  };
3225
3293
  },
3226
3294
  async "service.close"(ctx, params) {
3295
+ if (ctx.mode !== "daemon") throw new CliError("unavailable", SERVICE_NEEDS_DAEMON);
3227
3296
  const key = `${chatOf(ctx, params).peerPubKeyZ32}/${str(params, "service", true)}`;
3228
3297
  const pending = open$1.get(key);
3229
3298
  open$1.delete(key);
3230
3299
  const entry = await pending?.catch(() => void 0);
3231
3300
  if (!entry) throw new CliError("not_found", "That service is not open here");
3232
- await new Promise((resolve) => {
3233
- entry.server.close(() => resolve());
3234
- entry.server.closeAllConnections();
3235
- });
3301
+ await closeOpened(entry);
3236
3302
  return { closed: key };
3237
3303
  }
3238
3304
  };
3305
+ /**
3306
+ * Closed means closed: an answer still streaming (a page's EventSource) kept `close` waiting for good, and kept coming.
3307
+ * Each connection's end stops the contact's answer too (`proxy`).
3308
+ */
3309
+ function closeOpened(entry) {
3310
+ return new Promise((resolve) => {
3311
+ entry.server.close(() => resolve());
3312
+ entry.server.closeAllConnections();
3313
+ });
3314
+ }
3315
+ /**
3316
+ * `chat remove`: the services opened from a contact no chat here has any more. Before, they stayed on their ports, each
3317
+ * request a 503, and `service close` answered `No chat` for good.
3318
+ */
3319
+ async function closeServicesOf(ctx, peer) {
3320
+ if (state(ctx).links.some((link) => link.peerPubKeyZ32 === peer)) return;
3321
+ const keys = [...open$1.keys()].filter((key) => key.startsWith(`${peer}/`));
3322
+ await Promise.all(keys.map(async (key) => {
3323
+ const pending = open$1.get(key);
3324
+ open$1.delete(key);
3325
+ const entry = await pending?.catch(() => void 0);
3326
+ if (entry) await closeOpened(entry);
3327
+ }));
3328
+ }
3239
3329
  //#endregion
3240
3330
  //#region src/calls/api.ts
3241
3331
  /** Voice calls (WISP 1100 § Calls): the API methods. The audio itself goes over each call's own socket. */
@@ -3274,7 +3364,7 @@ var CALL_METHODS = {
3274
3364
  };
3275
3365
  //#endregion
3276
3366
  //#region src/appServe.ts
3277
- /** The permissions a bot can be granted: `internet` is a page's, and no page runs here. */
3367
+ /** The permissions a bot can be granted: `internet` and `files` are a page's, and no page runs here. */
3278
3368
  var GRANTABLE = ["chat", "name"];
3279
3369
  var servedFile = (dir) => join(dir, "apps.json");
3280
3370
  /** The apps a profile serves, by its folder: none when the file is missing or not a list of them. */
@@ -3313,6 +3403,8 @@ function servedApp(apps, ref) {
3313
3403
  if (matches.length !== 1) throw new CliError(matches.length ? "bad_request" : "not_found", matches.length ? `${JSON.stringify(ref)} names more than one served app: give its whole reference` : `No served app ${JSON.stringify(ref)}: app serve its bundle first`);
3314
3404
  return matches[0];
3315
3405
  }
3406
+ /** A link a contact's app reads a card's bundle from. */
3407
+ var readable = (url) => isAppFetchUrl(url) && appCardUrl(url) !== void 0;
3316
3408
  /** Whether this engine offers apps/1 now: it read the list when it started, so the first app served waits for a restart. */
3317
3409
  var offered = (ctx, apps) => ({
3318
3410
  offered: ctx.runtime.apps,
@@ -3322,12 +3414,14 @@ var APP_SERVE_METHODS = {
3322
3414
  async "app.serve"(ctx, params) {
3323
3415
  const source = str(params, "bundle", true);
3324
3416
  const grant = list(params, "grant");
3325
- const unknown = grant.filter((p) => !APP_PERMISSIONS.includes(p));
3326
- if (unknown.length) throw new CliError("bad_request", `grant takes ${GRANTABLE.join(" or ")}, not ${unknown.map((p) => JSON.stringify(p)).join(", ")}`);
3327
3417
  if (grant.includes("internet")) throw new CliError("refused", "internet cannot be granted here: no app's page runs on the CLI, and a bot reaches the network as its own program");
3418
+ if (grant.includes("files")) throw new CliError("refused", "files cannot be granted here: no app's page runs on the CLI to ask a person for a file, and a bot reads files as its own program");
3419
+ const ungrantable = grant.filter((p) => !GRANTABLE.includes(p));
3420
+ if (ungrantable.length) throw new CliError("bad_request", `grant takes ${GRANTABLE.join(" or ")}, not ${ungrantable.map((p) => JSON.stringify(p)).join(", ")}`);
3328
3421
  const given = str(params, "url");
3329
3422
  if (given !== void 0 && !isAppUrl(given)) throw new CliError("bad_request", "url is where a contact's app reads the bundle: https only, no user or password, jsDelivr only at a full commit");
3330
3423
  if (given !== void 0 && /[?#]/.test(given)) throw new CliError("bad_request", "url goes to contacts on the app's card: no query or fragment (a private repository's token rides there); publish the app in a public repository");
3424
+ if (given !== void 0 && !readable(given)) throw new CliError("bad_request", "url is where a contact's app reads the bundle: raw.githubusercontent.com, or cdn.jsdelivr.net at a full commit, with no port and no space");
3331
3425
  const { bundle, url } = await checkedBundle(source);
3332
3426
  const m = bundle.manifest;
3333
3427
  if (!m.permissions.includes("chat")) throw new CliError("refused", `${m.title} does not ask for chat: it talks to no contact, so a bot has nothing to speak for it`);
@@ -3339,7 +3433,7 @@ var APP_SERVE_METHODS = {
3339
3433
  missing
3340
3434
  });
3341
3435
  const ref = appRef(m.publisher, m.name);
3342
- const cardUrl = appCardUrl(given ?? url ?? m.sources?.[0]);
3436
+ const cardUrl = appCardUrl(given ?? [url, ...m.sources ?? []].find(readable));
3343
3437
  const app = {
3344
3438
  ref,
3345
3439
  title: m.title,
@@ -3612,8 +3706,7 @@ function createChecked(type, n, offer, provider, values, params) {
3612
3706
  if (!provider) throw new CliError("bad_request", `${type} needs --provider: one of ${sources.map((p) => p.id).join(", ")} (ghostly wallet list)`);
3613
3707
  const source = sources.find((p) => p.id === provider);
3614
3708
  if (!source) throw new CliError("bad_request", `No ${type} source ${JSON.stringify(provider)} on ${n} (ghostly wallet list)`);
3615
- const unknown = Object.keys(values).find((name) => !source.fields.some((f) => f.name === name));
3616
- if (unknown) throw new CliError("bad_request", `${provider} takes no --value ${unknown}: ${source.fields.length ? `its fields are ${source.fields.map((f) => f.name).join(", ")}` : "it has no fields"}`);
3709
+ if (Object.keys(values).find((name) => !source.fields.some((f) => f.name === name))) throw new CliError("bad_request", `one --value names no field of ${provider}: ${source.fields.length ? `its fields are ${source.fields.map((f) => f.name).join(", ")}` : "it has no fields"}`);
3617
3710
  const missing = source.fields.find((f) => !f.optional && !f.defaults?.[n] && !values[f.name]?.trim());
3618
3711
  if (missing) throw new CliError("bad_request", `${provider} needs --value ${missing.name}=<${missing.options?.map((o) => o.value).join("|") ?? missing.placeholder ?? missing.label.toLowerCase()}>`);
3619
3712
  }
@@ -3741,6 +3834,18 @@ function walletJson(instance, s) {
3741
3834
  config: instance.config
3742
3835
  };
3743
3836
  }
3837
+ /** A token amount (USDT) is in base units: its `decimals` say how many make one. Sats carry none. */
3838
+ var tokenDecimals = (p) => p.target?.method === "usdt" ? { decimals: p.target.decimals ?? 6 } : {};
3839
+ /** USDT typed as the app's composer takes it ("5", "0.25") in base units: more decimals than the token has is refused. */
3840
+ function tokenUnits(text, decimals) {
3841
+ try {
3842
+ const units = parsePaymentAmount(text.trim(), decimals);
3843
+ if (units > 0) return units;
3844
+ } catch (error) {
3845
+ throw new CliError("bad_request", `amount: ${error.message}`);
3846
+ }
3847
+ throw new CliError("bad_request", "amount must be above 0");
3848
+ }
3744
3849
  function paymentJson(p) {
3745
3850
  return {
3746
3851
  id: p.id,
@@ -3749,6 +3854,7 @@ function paymentJson(p) {
3749
3854
  direction: p.direction,
3750
3855
  amount: p.amount,
3751
3856
  unit: p.unit,
3857
+ ...tokenDecimals(p),
3752
3858
  memo: p.memo ?? null,
3753
3859
  state: p.state,
3754
3860
  error: p.error ?? null,
@@ -4015,7 +4121,7 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4015
4121
  let n;
4016
4122
  let note;
4017
4123
  if (params.chat !== void 0 && !isInvoice(text)) throw new CliError("usage", "--chat names the chat an invoice came from: an address's or LNURL's invoice is its server's");
4018
- const chat = params.chat === void 0 ? void 0 : findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
4124
+ const chat = params.chat === void 0 ? void 0 : ownChatOf(ctx, params);
4019
4125
  if (chat) inviteTaken(chat);
4020
4126
  if (isInvoice(text)) n = network(params);
4021
4127
  else if (isLnurl(text)) {
@@ -4069,7 +4175,7 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4069
4175
  /** Ecash to a contact in a chat (the payment sheet's Pay). */
4070
4176
  async "chat.pay"(ctx, params) {
4071
4177
  const memo = memoOf(params, "pay");
4072
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
4178
+ const link = ownChatOf(ctx, params);
4073
4179
  inviteTaken(link);
4074
4180
  const amount = num(params, "amount", 0, { min: 1 });
4075
4181
  if (!amount) throw new CliError("bad_request", "amount is required");
@@ -4091,16 +4197,20 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4091
4197
  paymentId
4092
4198
  };
4093
4199
  },
4094
- /** A request in a chat (the payment sheet's Request): the contact's app pays it. */
4200
+ /**
4201
+ * A request in a chat (the payment sheet's Request): the contact's app pays it. A USDT amount given as text ("5",
4202
+ * "0.25") is USDT, turned into base units with the wallet's decimals as the app's composer does; a number is base units.
4203
+ * The answer says the amount asked: USDT's carries the engine's tag of a few base units, and its decimals.
4204
+ */
4095
4205
  async "chat.request"(ctx, params) {
4096
4206
  const memo = memoOf(params, "request");
4097
4207
  const link = chatOf(ctx, params);
4098
- const amount = num(params, "amount", 0, { min: 1 });
4099
- if (!amount) throw new CliError("bad_request", "amount is required");
4100
4208
  const method = params.method === void 0 ? void 0 : oneOf(params, "method", PAY_METHODS, "cashu");
4209
+ const n = network(params);
4210
+ const amount = method === "usdt" && typeof params.amount === "string" ? tokenUnits(params.amount, netView(state(ctx), n)?.usdt?.decimals ?? 6) : num(params, "amount", 0, { min: 1 });
4211
+ if (!amount) throw new CliError("bad_request", "amount is required");
4101
4212
  const rail = params.rail === void 0 ? void 0 : oneOf(params, "rail", ["cashu", "lightning"], "cashu");
4102
4213
  await federationsOpen(ctx);
4103
- const n = network(params);
4104
4214
  const { paymentId } = await node(ctx).requestPayment({
4105
4215
  linkId: link.id,
4106
4216
  amount,
@@ -4113,16 +4223,23 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4113
4223
  }).catch((error) => {
4114
4224
  throw (!method || method === "cashu") && error instanceof Error && NO_MINT.test(error.message) ? noWalletOf(ctx, n, error) : error;
4115
4225
  });
4226
+ const asked = state(ctx).payments[paymentId];
4116
4227
  return {
4117
4228
  chat: link.id,
4118
- paymentId
4229
+ paymentId,
4230
+ ...asked ? {
4231
+ amount: asked.amount,
4232
+ unit: asked.unit,
4233
+ ...tokenDecimals(asked)
4234
+ } : {}
4119
4235
  };
4120
4236
  },
4121
4237
  /** Pays a request the contact made in a chat. */
4122
4238
  async "chat.payRequest"(ctx, params) {
4123
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
4239
+ const s = state(ctx);
4240
+ const link = ownChatOf(ctx, params, s);
4124
4241
  const paymentId = str(params, "payment", true);
4125
- const request = state(ctx).payments[paymentId];
4242
+ const request = s.payments[paymentId];
4126
4243
  if (!request || request.linkId !== link.id || request.kind !== "request") throw new CliError("not_found", `No request ${paymentId} in this chat`);
4127
4244
  const n = paymentNetwork(request);
4128
4245
  if (n === "mainnet" && !bool(params, "confirmReal")) throw new CliError("confirm", "This request is for real money (Mainnet): pass --confirm-real to confirm this payment", { network: n });
@@ -4171,12 +4288,14 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4171
4288
  };
4172
4289
  },
4173
4290
  async "payment.list"(ctx, params) {
4174
- const chat = params.chat === void 0 ? null : chatOf(ctx, params).id;
4175
- return { payments: Object.values(state(ctx).payments).filter((p) => !chat || p.linkId === chat).sort((a, b) => b.createdAt - a.createdAt).map(paymentJson) };
4291
+ const s = state(ctx);
4292
+ const chat = params.chat === void 0 ? null : chatOf(ctx, params, s).id;
4293
+ return { payments: Object.values(s.payments).filter((p) => !chat || p.linkId === chat).sort((a, b) => b.createdAt - a.createdAt).map(paymentJson) };
4176
4294
  },
4177
4295
  async "payment.check"(ctx, params) {
4178
- const link = chatOf(ctx, params);
4179
- const p = state(ctx).payments[str(params, "payment", true)];
4296
+ const s = state(ctx);
4297
+ const link = chatOf(ctx, params, s);
4298
+ const p = s.payments[str(params, "payment", true)];
4180
4299
  if (p?.linkId !== link.id) throw new CliError("not_found", `No payment ${JSON.stringify(str(params, "payment", true))} in this chat (ghostly payment list --chat ${link.id})`);
4181
4300
  if (p.kind !== "request" || p.direction !== "in") throw new CliError("bad_request", `${JSON.stringify(p.id)} is ${p.kind === "request" ? "your own request" : p.direction === "out" ? "a payment you sent" : "a payment you received"}: payment check is for a request the contact made of you`);
4182
4301
  await node(ctx).checkPayment({
@@ -4420,6 +4539,27 @@ function inviteNotOut(detail) {
4420
4539
  var BAD_VALUE = /^Cannot (destructure|read properties of (undefined|null))|is not (a function|iterable)/;
4421
4540
  /** A one-shot's typing without `--for` (it opens the profile offline, `offlineCall`): said on no live session. */
4422
4541
  var ONE_SHOT_TYPING = "Typing is said on a live session only, and a one-shot has none: it reached nobody. Keep the profile online (`ghostly daemon --detach`), or give --for to wait until it is live";
4542
+ var ONE_SHOT_TYPING_STOP = "A stop is said on a live session only, and a one-shot has none: it reached nobody. Keep the profile online (`ghostly daemon --detach`)";
4543
+ /**
4544
+ * A removal on its way goes with the chat's row, and the contact kept the message for good, though `message delete
4545
+ * --everyone` had said its removal goes on: `chat remove`, the engine's `removeLink` and `clearProfileData` (every
4546
+ * chat's row at once) are refused until `--force`.
4547
+ */
4548
+ function noRemovalOnItsWay(ctx, linkIds, clearing = false) {
4549
+ const pending = linkIds.flatMap((linkId) => node(ctx).removalsPending({ linkId }));
4550
+ if (!pending.length) return;
4551
+ const n = pending.length, one = n === 1;
4552
+ const [now, then, go] = clearing ? [
4553
+ "clearing the profile",
4554
+ "clear it then",
4555
+ "clear it"
4556
+ ] : [
4557
+ "removing the chat",
4558
+ "remove the chat then",
4559
+ "remove it"
4560
+ ];
4561
+ throw new CliError("confirm", `${one ? "A message you deleted for everyone has" : `${n} messages you deleted for everyone have`} not reached the contact yet: ${now} now leaves ${one ? "it" : "them"} on their device. Keep this profile online until the contact is reachable (ghostly daemon --detach) and ${then}, or pass --force (force: true over the socket) to ${go} now`, { messages: pending });
4562
+ }
4423
4563
  var METHODS = {
4424
4564
  ...WALLET_METHODS,
4425
4565
  ...FILE_METHODS,
@@ -4482,7 +4622,7 @@ var METHODS = {
4482
4622
  return statusJson(node(ctx).getOwnStatus().status);
4483
4623
  },
4484
4624
  async "profile.get"(ctx) {
4485
- const { settings } = state(ctx);
4625
+ const settings = settingsOf(ctx);
4486
4626
  return {
4487
4627
  profile: ctx.runtime.paths.name,
4488
4628
  name: settings.nick || null,
@@ -4500,7 +4640,7 @@ var METHODS = {
4500
4640
  return METHODS["profile.get"](ctx, {});
4501
4641
  },
4502
4642
  async "settings.get"(ctx, params) {
4503
- return redactSettings(settingsInEffect(state(ctx).settings), bool(params, "showSecret"));
4643
+ return redactSettings(settingsInEffect(settingsOf(ctx)), bool(params, "showSecret"));
4504
4644
  },
4505
4645
  async "settings.set"(ctx, params) {
4506
4646
  const patch = {};
@@ -4537,7 +4677,7 @@ var METHODS = {
4537
4677
  throw relayRefused(error, patch);
4538
4678
  });
4539
4679
  return {
4540
- ...redactSettings(settingsInEffect(state(ctx).settings)),
4680
+ ...redactSettings(settingsInEffect(settingsOf(ctx))),
4541
4681
  ...warning ? { warning } : {}
4542
4682
  };
4543
4683
  },
@@ -4718,15 +4858,16 @@ var METHODS = {
4718
4858
  const kept = seconds ? keepTyping(ctx, { linkId: link.id }, seconds * 1e3, word) : null;
4719
4859
  const open = (s) => s.links.find((l) => l.id === link.id)?.dataLink === "open";
4720
4860
  if (kept && ctx.mode === "one-shot") await keepOneShot(ctx, { linkId: link.id }, kept, open);
4861
+ const now = state(ctx);
4721
4862
  return {
4722
4863
  chat: link.id,
4723
4864
  typing,
4724
4865
  ...typing ? { kind } : {},
4725
4866
  ...status ? { status } : {},
4726
- live: open(state(ctx)),
4727
- sendTyping: state(ctx).settings.sendTyping !== false,
4867
+ live: open(now),
4868
+ sendTyping: now.settings.sendTyping !== false,
4728
4869
  ...until ? { until } : {},
4729
- ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
4870
+ ...!kept && ctx.mode === "one-shot" && { note: typing ? ONE_SHOT_TYPING : ONE_SHOT_TYPING_STOP }
4730
4871
  };
4731
4872
  },
4732
4873
  /**
@@ -4843,13 +4984,14 @@ var METHODS = {
4843
4984
  * took it), each file until its transfer is done. What a chat refused comes back per chat; any refusal fails the call.
4844
4985
  */
4845
4986
  async "chat.forward"(ctx, params) {
4846
- const from = chatOrGroup(ctx, str(params, "chat", true));
4987
+ const s = state(ctx);
4988
+ const from = chatOrGroup(ctx, str(params, "chat", true), s);
4847
4989
  const messageIds = [...new Set(list(params, "messages"))];
4848
4990
  if (!messageIds.length) throw new CliError("bad_request", "Name the messages to forward (their ids, from history or an event)");
4849
4991
  if (messageIds.length > 30) throw new CliError("bad_request", `Forward at most 30 messages at once, not ${messageIds.length}`);
4850
4992
  const to = [];
4851
4993
  for (const ref of new Set(list(params, "to"))) {
4852
- const target = chatOrGroup(ctx, ref);
4994
+ const target = chatOrGroup(ctx, ref, s);
4853
4995
  if (to.some((t) => t.linkId === target.linkId)) continue;
4854
4996
  if (to.length === 5) throw new CliError("bad_request", `Forward to at most 5 chats and groups at once`);
4855
4997
  to.push(target);
@@ -4894,32 +5036,50 @@ var METHODS = {
4894
5036
  sent: result.sent,
4895
5037
  error: result.error
4896
5038
  }));
5039
+ let short;
5040
+ const waited = async (wait, now) => {
5041
+ if (short) return now();
5042
+ try {
5043
+ return await wait();
5044
+ } catch (error) {
5045
+ short = asCliError(error);
5046
+ return now();
5047
+ }
5048
+ };
4897
5049
  for (const [i, result] of out.entries()) if (to[i].group) {
4898
5050
  let edges;
4899
5051
  for (const messageId of result.messageIds) {
4900
- const took = groupWait === "sent" ? await waitForGroupFrame(ctx, to[i].id, messageId, void 0, ms) : node(ctx).groupTaken({
5052
+ const taken = () => node(ctx).groupTaken({
4901
5053
  groupId: to[i].id,
4902
5054
  messageId
4903
5055
  });
5056
+ const took = groupWait === "sent" ? await waited(() => waitForGroupFrame(ctx, to[i].id, messageId, void 0, ms), taken) : taken();
4904
5057
  edges = Math.min(edges ?? took, took);
4905
5058
  }
4906
5059
  result.edges = edges ?? 0;
4907
5060
  }
4908
5061
  if (wait === "sent") for (const [i, result] of out.entries()) for (const messageId of result.messageIds) {
4909
5062
  if (to[i].group) continue;
4910
- const sent = await node(ctx).getMessage(to[i].id, messageId);
4911
- if (sent?.file) await FILE_METHODS["file.wait"](ctx, {
4912
- chat: to[i].id,
4913
- file: sent.file.id,
4914
- timeout: ms / 1e3
4915
- });
4916
- else await waitForMessage(ctx, to[i].id, messageId, "sent", ms);
5063
+ await waited(async () => {
5064
+ const sent = await node(ctx).getMessage(to[i].id, messageId);
5065
+ if (sent?.file) await FILE_METHODS["file.wait"](ctx, {
5066
+ chat: to[i].id,
5067
+ file: sent.file.id,
5068
+ timeout: ms / 1e3
5069
+ });
5070
+ else await waitForMessage(ctx, to[i].id, messageId, "sent", ms);
5071
+ }, () => void 0);
4917
5072
  }
4918
5073
  const failed = out.filter((r) => r.error);
4919
5074
  if (failed.length) throw new CliError(failed.length === out.length ? "refused" : "engine", failed.map((r) => `${r.to}: ${r.error}`).join("; "), {
4920
5075
  from: from.id,
4921
5076
  results: out
4922
5077
  });
5078
+ if (short) throw new CliError(short.code, short.message, {
5079
+ ...short.details,
5080
+ from: from.id,
5081
+ results: out
5082
+ });
4923
5083
  return {
4924
5084
  from: from.id,
4925
5085
  results: out
@@ -5048,10 +5208,12 @@ var METHODS = {
5048
5208
  const link = chatNotGroup(ctx, params, "group forget", "--yes");
5049
5209
  if (!bool(params, "yes")) throw new CliError("confirm", "Removing a chat deletes its keys and history on this device; pass --yes (yes: true over the socket) to go on");
5050
5210
  noCallOn(ctx, link.id, "remove the chat");
5211
+ if (!bool(params, "force")) noRemovalOnItsWay(ctx, [link.id]);
5051
5212
  await node(ctx).removeLink({ linkId: link.id });
5052
5213
  ctx.calls.forgetChat(link.id);
5053
5214
  ctx.groupAuto.forgetChat(link.id);
5054
5215
  await forgetHold(ctx, link.id);
5216
+ await closeServicesOf(ctx, link.peerPubKeyZ32);
5055
5217
  return { removed: link.id };
5056
5218
  },
5057
5219
  async "chat.transport"(ctx, params) {
@@ -5334,15 +5496,16 @@ var METHODS = {
5334
5496
  const kept = seconds ? keepTyping(ctx, target, seconds * 1e3, word) : null;
5335
5497
  const reached = (s) => (s.groups.find((g) => g.id === group.id) ?? group).members.filter((m) => !m.me && m.online && !m.viaHub).length;
5336
5498
  if (kept && ctx.mode === "one-shot") await keepOneShot(ctx, target, kept, (s) => reached(s) > 0);
5499
+ const now = state(ctx);
5337
5500
  return {
5338
5501
  group: group.id,
5339
5502
  typing,
5340
5503
  ...typing ? { kind } : {},
5341
5504
  ...status ? { status } : {},
5342
- reached: reached(state(ctx)),
5343
- sendTyping: state(ctx).settings.sendTyping !== false,
5505
+ reached: reached(now),
5506
+ sendTyping: now.settings.sendTyping !== false,
5344
5507
  ...until ? { until } : {},
5345
- ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
5508
+ ...!kept && ctx.mode === "one-shot" && { note: typing ? ONE_SHOT_TYPING : ONE_SHOT_TYPING_STOP }
5346
5509
  };
5347
5510
  },
5348
5511
  async "group.leave"(ctx, params) {
@@ -5399,7 +5562,7 @@ var METHODS = {
5399
5562
  if (args && "confirmedReal" in args && !bool(params, "confirmReal")) throw new CliError("confirm", `${method} spends real money: pass --confirm-real (confirmReal: true over the socket) to confirm it`);
5400
5563
  const deletes = DESTRUCTIVE_CALLS.get(method);
5401
5564
  if (deletes && !bool(params, "yes")) throw new CliError("confirm", `${method} ${deletes}; pass --yes (yes: true over the socket) to go on`);
5402
- if (method === "clearProfileData") return clearProfile(ctx);
5565
+ if (method === "clearProfileData") return clearProfile(ctx, bool(params, "force"));
5403
5566
  const takes = ENGINE_PARAMS[method] ?? READ_PARAMS[method];
5404
5567
  const wrong = (why, rawError) => new CliError("bad_request", `${method} takes ${takes || "no parameters"}: ${why} (ghostly engine --list --verbose)`, {
5405
5568
  takes,
@@ -5408,8 +5571,10 @@ var METHODS = {
5408
5571
  const problem = engineParamsProblem(method, args);
5409
5572
  if (problem) throw wrong(problem);
5410
5573
  if (typeof args?.linkId === "string") {
5411
- if (method === "removeLink") noCallOn(ctx, args.linkId, "remove the chat");
5412
- else if (method === "setChatTransport" && args.transport === "dht" || method === "setDeliveryMode" && args.mode === "dht") noCallOn(ctx, args.linkId, "put the chat on DHT only");
5574
+ if (method === "removeLink") {
5575
+ noCallOn(ctx, args.linkId, "remove the chat");
5576
+ if (!bool(params, "force")) noRemovalOnItsWay(ctx, [args.linkId]);
5577
+ } else if (method === "setChatTransport" && args.transport === "dht" || method === "setDeliveryMode" && args.mode === "dht") noCallOn(ctx, args.linkId, "put the chat on DHT only");
5413
5578
  }
5414
5579
  if (args && ENGINE_SENDS.has(method) && !bool(params, "force")) await guardEngineSend(ctx, method, args);
5415
5580
  if (method === "getMessages") return node(ctx).getMessages(str(args ?? {}, "linkId", true));
@@ -5417,12 +5582,16 @@ var METHODS = {
5417
5582
  if (method === "setActiveLink") inviteShown.get(ctx)?.();
5418
5583
  const target = node(ctx)[method];
5419
5584
  if (typeof target !== "function") throw new CliError("not_found", `The engine has no call ${method}`);
5585
+ const removedPeer = method === "removeLink" ? state(ctx).links.find((link) => link.id === args?.linkId)?.peerPubKeyZ32 : void 0;
5420
5586
  try {
5421
5587
  const result = await target.call(node(ctx), args) ?? null;
5422
5588
  if (method === "removeLink") {
5423
5589
  ctx.calls.forgetChat(str(args ?? {}, "linkId", true));
5424
5590
  ctx.groupAuto.forgetChat(str(args ?? {}, "linkId", true));
5591
+ await forgetHold(ctx, str(args ?? {}, "linkId", true));
5592
+ if (removedPeer) await closeServicesOf(ctx, removedPeer);
5425
5593
  }
5594
+ if ((method === "setChatTransport" || method === "setDeliveryMode") && typeof args?.linkId === "string") await releaseHold(ctx, args.linkId, "lifted", true);
5426
5595
  return result;
5427
5596
  } catch (error) {
5428
5597
  if (error instanceof TypeError && BAD_VALUE.test(error.message)) throw wrong("a parameter of the wrong kind", error.message);
@@ -5435,10 +5604,11 @@ var METHODS = {
5435
5604
  * A daemon would go on serving the stopped engine's memory (chats and groups that are gone, new ones that are not
5436
5605
  * kept): it stops once it has answered, and the next command starts on the emptied profile.
5437
5606
  */
5438
- async function clearProfile(ctx) {
5607
+ async function clearProfile(ctx, force) {
5439
5608
  const call = ctx.calls.list()[0];
5440
5609
  if (call) throw new CliError("busy", `A call is on in a chat: hang it up first (ghostly call hangup ${call.chat}), then clear the profile`, { call: call.call });
5441
5610
  const { links, groups } = state(ctx);
5611
+ if (!force) noRemovalOnItsWay(ctx, links.map((link) => link.id), true);
5442
5612
  await node(ctx).clearProfileData();
5443
5613
  const cleared = {
5444
5614
  chats: links.length,
@@ -5629,13 +5799,35 @@ async function connectWithin(ctx, link, ms) {
5629
5799
  } catch (error) {
5630
5800
  if (asCliError(error).code !== "timeout") {
5631
5801
  dhtOnly(findChat(state(ctx).links, link.id));
5802
+ const away = contactAway(error);
5803
+ if (away) throw new CliError("unavailable", `${away}. ${connectNext(ctx, link)}`, {
5804
+ chat: link.id,
5805
+ reason: error.message
5806
+ });
5632
5807
  throw error;
5633
5808
  }
5634
5809
  } finally {
5635
5810
  clearTimeout(timer);
5636
5811
  }
5812
+ throw new CliError("timeout", `Timed out after ${Math.round(ms / 1e3)} s: the contact did not answer. ${connectNext(ctx, link)}`, { chat: link.id });
5813
+ }
5814
+ /** What happens after a `chat connect` the contact did not answer: the daemon dials again by itself, a one-shot does not. */
5815
+ function connectNext(ctx, link) {
5637
5816
  const shown = /^[\w.:-]+$/.test(link.label ?? "") ? link.label : link.id;
5638
- throw new CliError("timeout", `Timed out after ${Math.round(ms / 1e3)} s: the contact did not answer. ${ctx.mode === "one-shot" ? "Try again later, or keep this profile online with `ghostly daemon --detach`: it reconnects by itself" : `It reconnects by itself while this profile is online; ghostly chat wait ${shown} --until live waits for it`}`, { chat: link.id });
5817
+ return ctx.mode === "one-shot" ? "Try again later, or keep this profile online with `ghostly daemon --detach`: it reconnects by itself" : `It reconnects by itself while this profile is online; ghostly chat wait ${shown} --until live waits for it`;
5818
+ }
5819
+ /**
5820
+ * A dial that ended because the contact's app is not there: the link's own "Could not connect to the peer", or
5821
+ * HyperDHT's errors as the app's errorText says them (closed, or asleep or frozen). They answered as they came, without
5822
+ * the next step; HyperDHT's as `engine`, "PEER_NOT_FOUND: Peer not found", as if this side had failed.
5823
+ */
5824
+ function contactAway(error) {
5825
+ const message = error instanceof Error ? error.message : "";
5826
+ const reason = /^Could not connect to the peer(?:: ([\s\S]*))?$/.exec(message);
5827
+ const native = reason ? reason[1] ?? "" : message;
5828
+ if (/^PEER_NOT_FOUND: /.test(native)) return "Your contact's app isn't reachable on HyperDHT: it may be closed";
5829
+ if (/^(?:PEER_CONNECTION_FAILED|BAD_HOLEPUNCH_REPLY|HOLEPUNCH_[A-Z_]+): /.test(native)) return "Your contact's app isn't answering on HyperDHT: it may be asleep or frozen";
5830
+ return reason ? "The contact did not answer" : void 0;
5639
5831
  }
5640
5832
  async function saveMark(ctx, params, remove) {
5641
5833
  const target = chatOrGroup(ctx, str(params, "chat", true)), messageId = str(params, "message", true);
@@ -5760,4 +5952,4 @@ async function callApi(ctx, method, params = {}) {
5760
5952
  //#endregion
5761
5953
  export { groupPayTwins as _, hideStateSecrets as a, settingsInEffect as c, servedApps as d, nodeLocalFetch as f, groupMessageJson as g, groupJson as h, groupSendRefused as i, paymentJson as l, chatMessageJson as m, SETTABLE as n, mentionsFor as o, chatJson as p, callApi as r, redactSettings as s, API_METHODS as t, reportAppFrames as u, resumeHolds as v, flushCardUpdates as y };
5762
5954
 
5763
- //# sourceMappingURL=api-BM3PsXbB.js.map
5955
+ //# sourceMappingURL=api-MYc6QNRs.js.map