@ghostlytools/cli 1.11.3 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +52 -30
  2. package/SKILL.md +4 -2
  3. package/dist/assets/{api-DBlaoz8i.js → api-DLzCtePC.js} +533 -195
  4. package/dist/assets/api-DLzCtePC.js.map +1 -0
  5. package/dist/assets/{api-DgU4MZPD.js → api-DYMKyb1k.js} +2 -2
  6. package/dist/assets/{apiKit-DesObIDf.js → apiKit-CVaEzKWQ.js} +104 -21
  7. package/dist/assets/apiKit-CVaEzKWQ.js.map +1 -0
  8. package/dist/assets/appFetch-D56GsYuq.js +602 -0
  9. package/dist/assets/appFetch-D56GsYuq.js.map +1 -0
  10. package/dist/assets/apps-BPFW19Wc.js +1 -0
  11. package/dist/assets/{apps-DkMjDHML.js → apps-XnZ8VEuj.js} +66 -38
  12. package/dist/assets/apps-XnZ8VEuj.js.map +1 -0
  13. package/dist/assets/{argon2id-088uQfnH.js → argon2id-B9wFdSj6.js} +2 -3
  14. package/dist/assets/{argon2id-088uQfnH.js.map → argon2id-B9wFdSj6.js.map} +1 -1
  15. package/dist/assets/{arkade-CarKONmH.js → arkade-DryM-q5n.js} +6 -7
  16. package/dist/assets/arkade-DryM-q5n.js.map +1 -0
  17. package/dist/assets/backup-COX6j1_W.js +1 -0
  18. package/dist/assets/{backup-C0OJCJlM.js → backup-DpyvT9Z6.js} +108 -50
  19. package/dist/assets/backup-DpyvT9Z6.js.map +1 -0
  20. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js +5 -0
  21. package/dist/assets/{bark_ffi_wasm_bg-EY2uc0Bx.js.map → bark_ffi_wasm_bg-CcafsJla.js.map} +1 -1
  22. package/dist/assets/{bark_ffi_wasm_bg-Bxru_BVW.wasm → bark_ffi_wasm_bg-VNmaJsc9.wasm} +0 -0
  23. package/dist/assets/{bitcoind-CdSmvy2y.js → bitcoind-DTsrd7TF.js} +4 -5
  24. package/dist/assets/{bitcoind-CdSmvy2y.js.map → bitcoind-DTsrd7TF.js.map} +1 -1
  25. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js +5 -0
  26. package/dist/assets/{bitcoindevkit_bg-B-iLWrmX.js.map → bitcoindevkit_bg-BWQHx7vd.js.map} +1 -1
  27. package/dist/assets/bitcoindevkit_bg-DXil67yS.wasm +0 -0
  28. package/dist/assets/{blobFiles-BmsrvZc3.js → blobFiles-DDs34n0r.js} +4 -5
  29. package/dist/assets/{blobFiles-BmsrvZc3.js.map → blobFiles-DDs34n0r.js.map} +1 -1
  30. package/dist/assets/breez_sdk_spark_wasm_bg.wasm +0 -0
  31. package/dist/assets/buttons-Bq7pTXqF.js +1 -0
  32. package/dist/assets/{buttons-fZTEa_2i.js → buttons-BvWqHJeh.js} +46 -23
  33. package/dist/assets/buttons-BvWqHJeh.js.map +1 -0
  34. package/dist/assets/bytes-C1DNGY18.js +132 -0
  35. package/dist/assets/bytes-C1DNGY18.js.map +1 -0
  36. package/dist/assets/{childEnv-K_IzUqQx.js → childEnv-C-99hdbL.js} +2 -3
  37. package/dist/assets/{childEnv-K_IzUqQx.js.map → childEnv-C-99hdbL.js.map} +1 -1
  38. package/dist/assets/{client-Ibk3-e60.js → client-kGZ3ZdUW.js} +30 -13
  39. package/dist/assets/client-kGZ3ZdUW.js.map +1 -0
  40. package/dist/assets/{codec-DMpQqVSt.js → codec-B2rH1mfx.js} +2 -4
  41. package/dist/assets/{codec-DMpQqVSt.js.map → codec-B2rH1mfx.js.map} +1 -1
  42. package/dist/assets/domainProofs-BDNP1dIy.js +280 -0
  43. package/dist/assets/domainProofs-BDNP1dIy.js.map +1 -0
  44. package/dist/assets/{endpoint-DarqblYE.js → endpoint-B0vE5ojY.js} +421 -420
  45. package/dist/assets/endpoint-B0vE5ojY.js.map +1 -0
  46. package/dist/assets/engineErrors--9hfgKlK.js +150 -0
  47. package/dist/assets/engineErrors--9hfgKlK.js.map +1 -0
  48. package/dist/assets/{envelope-CvQVCGdf.js → envelope-Bi2kMqbp.js} +3 -4
  49. package/dist/assets/{envelope-CvQVCGdf.js.map → envelope-Bi2kMqbp.js.map} +1 -1
  50. package/dist/assets/{errors-Dt-ZnyOX.js → errors-DDLFO4Gf.js} +31 -5
  51. package/dist/assets/errors-DDLFO4Gf.js.map +1 -0
  52. package/dist/assets/{fedimintSdk-zV_5Qdqz.js → fedimintSdk-D-6H9Pe7.js} +4 -5
  53. package/dist/assets/{fedimintSdk-zV_5Qdqz.js.map → fedimintSdk-D-6H9Pe7.js.map} +1 -1
  54. package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +5 -0
  55. package/dist/assets/{fedimint_client_wasm_bg-BtHHlFpp.js.map → fedimint_client_wasm_bg-Cr5xGD-w.js.map} +1 -1
  56. package/dist/assets/fileBytes-CCKbwqG_.js +1 -0
  57. package/dist/assets/{fileBytes-BLPZq9YU.js → fileBytes-CfvUXdSy.js} +5 -7
  58. package/dist/assets/fileBytes-CfvUXdSy.js.map +1 -0
  59. package/dist/assets/{fileBytes-B0z9A6Le.js → fileBytes-tj6-VZcB.js} +3 -4
  60. package/dist/assets/{fileBytes-B0z9A6Le.js.map → fileBytes-tj6-VZcB.js.map} +1 -1
  61. package/dist/assets/fileBytesIdb-B0zzJ6p7.js +1 -0
  62. package/dist/assets/{fileBytesIdb-Bmlrl9EO.js → fileBytesIdb-BJirUAjI.js} +4 -5
  63. package/dist/assets/{fileBytesIdb-Bmlrl9EO.js.map → fileBytesIdb-BJirUAjI.js.map} +1 -1
  64. package/dist/assets/{fileBytesOpfs-DBS0kbPT.js → fileBytesOpfs-DRUYLER4.js} +4 -5
  65. package/dist/assets/{fileBytesOpfs-DBS0kbPT.js.map → fileBytesOpfs-DRUYLER4.js.map} +1 -1
  66. package/dist/assets/{fixedHosts-6gKn8dp2.js → fixedHosts-CPSsGOI2.js} +4 -5
  67. package/dist/assets/{fixedHosts-6gKn8dp2.js.map → fixedHosts-CPSsGOI2.js.map} +1 -1
  68. package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js → ghostly_iroh_web-DIj5xGmR.js} +2 -3
  69. package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js.map → ghostly_iroh_web-DIj5xGmR.js.map} +1 -1
  70. package/dist/assets/{src-DjVj2ynY.js → groupMeta-DTQAJG50.js} +4879 -23799
  71. package/dist/assets/groupMeta-DTQAJG50.js.map +1 -0
  72. package/dist/assets/{host-CYlIiY3r.js → host-z0FAHP9Z.js} +750 -245
  73. package/dist/assets/host-z0FAHP9Z.js.map +1 -0
  74. package/dist/assets/{hyperdhtRelay-CdsLcAhY.js → hyperdhtRelay-CvsAfQRQ.js} +5 -6
  75. package/dist/assets/hyperdhtRelay-CvsAfQRQ.js.map +1 -0
  76. package/dist/assets/hyperdhtRelay-bjNGacf5.js +32 -0
  77. package/dist/assets/hyperdhtRelay-bjNGacf5.js.map +1 -0
  78. package/dist/assets/{idb-CEuoNsTv.js → idb-ewvbqyDI.js} +2 -3
  79. package/dist/assets/{idb-CEuoNsTv.js.map → idb-ewvbqyDI.js.map} +1 -1
  80. package/dist/assets/identityProofs-Cksc_K7_.js +940 -0
  81. package/dist/assets/identityProofs-Cksc_K7_.js.map +1 -0
  82. package/dist/assets/{irohWeb-D2IuloLL.js → irohWeb-CLBx5MIv.js} +3061 -86
  83. package/dist/assets/irohWeb-CLBx5MIv.js.map +1 -0
  84. package/dist/assets/joinTrace-CBr1jbch.js +1 -0
  85. package/dist/assets/{joinTrace-CjRDFy85.js → joinTrace-xKBe73j9.js} +2 -3
  86. package/dist/assets/{joinTrace-CjRDFy85.js.map → joinTrace-xKBe73j9.js.map} +1 -1
  87. package/dist/assets/{legacy_ciphers-JJOu0JXL.js → legacy_ciphers-BnYATjxo.js} +2 -3
  88. package/dist/assets/{legacy_ciphers-JJOu0JXL.js.map → legacy_ciphers-BnYATjxo.js.map} +1 -1
  89. package/dist/assets/linkPreview-DdMf-YAc.js +252 -0
  90. package/dist/assets/linkPreview-DdMf-YAc.js.map +1 -0
  91. package/dist/assets/{main-C0PfjKTe.js → main-CVqkvuIo.js} +536 -173
  92. package/dist/assets/main-CVqkvuIo.js.map +1 -0
  93. package/dist/assets/{mainline-Cu61qcPS.js → mainline-CVrd0C1n.js} +72 -18
  94. package/dist/assets/mainline-CVrd0C1n.js.map +1 -0
  95. package/dist/assets/mints-BcBODVVW.js +1 -0
  96. package/dist/assets/{mints-j5XAOk4f.js → mints-CMDLbMeH.js} +8 -6
  97. package/dist/assets/mints-CMDLbMeH.js.map +1 -0
  98. package/dist/assets/{nacl-fast-CDhNCYHs.js → nacl-fast-B1ThWvuM.js} +2 -3
  99. package/dist/assets/{nacl-fast-CDhNCYHs.js.map → nacl-fast-B1ThWvuM.js.map} +1 -1
  100. package/dist/assets/{networkReason-Dt7Yx_n4.js → networkReason-Be-hMghr.js} +10 -14
  101. package/dist/assets/{networkReason-Dt7Yx_n4.js.map → networkReason-Be-hMghr.js.map} +1 -1
  102. package/dist/assets/{noble_curves-DDWn5AH0.js → noble_curves-DqpNlhAU.js} +3 -4
  103. package/dist/assets/{noble_curves-DDWn5AH0.js.map → noble_curves-DqpNlhAU.js.map} +1 -1
  104. package/dist/assets/{noble_hashes-B7AZyFyS.js → noble_hashes-LFe1N2xt.js} +3 -4
  105. package/dist/assets/{noble_hashes-B7AZyFyS.js.map → noble_hashes-LFe1N2xt.js.map} +1 -1
  106. package/dist/assets/{nwc-CtZypDcv.js → nwc-DKE2FXr6.js} +5 -6
  107. package/dist/assets/{nwc-CtZypDcv.js.map → nwc-DKE2FXr6.js.map} +1 -1
  108. package/dist/assets/nwcProvider-pL2XqSbW.js +208 -0
  109. package/dist/assets/nwcProvider-pL2XqSbW.js.map +1 -0
  110. package/dist/assets/{openpgp-BBFr-zHQ.js → openpgp-LkR_Zof0.js} +14 -15
  111. package/dist/assets/{openpgp-BBFr-zHQ.js.map → openpgp-LkR_Zof0.js.map} +1 -1
  112. package/dist/assets/ownDid-DY3rYqDI.js +862 -0
  113. package/dist/assets/ownDid-DY3rYqDI.js.map +1 -0
  114. package/dist/assets/{ownStatus-D4HC6tNR.js → ownStatus-DMEhrpkd.js} +81 -19
  115. package/dist/assets/ownStatus-DMEhrpkd.js.map +1 -0
  116. package/dist/assets/pairedTransports-BKmvlKz1.js +581 -0
  117. package/dist/assets/pairedTransports-BKmvlKz1.js.map +1 -0
  118. package/dist/assets/paymentIntent-DySU3Ajm.js +349 -0
  119. package/dist/assets/paymentIntent-DySU3Ajm.js.map +1 -0
  120. package/dist/assets/pkarr-BQo4PcCg.js +367 -0
  121. package/dist/assets/pkarr-BQo4PcCg.js.map +1 -0
  122. package/dist/assets/{profiles-Ccdq6Xf6.js → profiles-BFSGqDFC.js} +30 -16
  123. package/dist/assets/profiles-BFSGqDFC.js.map +1 -0
  124. package/dist/assets/registry-B15Yg_1C.js +1 -0
  125. package/dist/assets/{registry-LvxsLJ5S.js → registry-rXgaZeNn.js} +1273 -58
  126. package/dist/assets/registry-rXgaZeNn.js.map +1 -0
  127. package/dist/assets/relay-Cjfmdec0.js +2219 -0
  128. package/dist/assets/relay-Cjfmdec0.js.map +1 -0
  129. package/dist/assets/resolve-CIc3KZMV.js +970 -0
  130. package/dist/assets/resolve-CIc3KZMV.js.map +1 -0
  131. package/dist/assets/{restoredRows-C3LcxmOw.js → restoredRows-D_WSHE7H.js} +3 -4
  132. package/dist/assets/{restoredRows-C3LcxmOw.js.map → restoredRows-D_WSHE7H.js.map} +1 -1
  133. package/dist/assets/{secretGuard-B7Hj0Kvz.js → secretGuard-B4-LlMjv.js} +75 -16
  134. package/dist/assets/{secretGuard-B7Hj0Kvz.js.map → secretGuard-B4-LlMjv.js.map} +1 -1
  135. package/dist/assets/secretGuard-BmmnEbYf.js +1 -0
  136. package/dist/assets/{server-Q3VcNqGt.js → server-CQR7NLCz.js} +10200 -625
  137. package/dist/assets/server-CQR7NLCz.js.map +1 -0
  138. package/dist/assets/{sha512-BYId-G-T.js → sha512-DST9fbWH.js} +2 -3
  139. package/dist/assets/{sha512-BYId-G-T.js.map → sha512-DST9fbWH.js.map} +1 -1
  140. package/dist/assets/sshForges-BnvwmNj-.js +539 -0
  141. package/dist/assets/sshForges-BnvwmNj-.js.map +1 -0
  142. package/dist/assets/{storage-Bya5b2Xt.js → storage-BpjdxvO2.js} +243 -34
  143. package/dist/assets/storage-BpjdxvO2.js.map +1 -0
  144. package/dist/assets/text-li76pThX.js +106 -0
  145. package/dist/assets/text-li76pThX.js.map +1 -0
  146. package/dist/assets/{translate-iQZq4TnY.js → translate-BcbSWkuq.js} +21 -26
  147. package/dist/assets/{translate-iQZq4TnY.js.map → translate-BcbSWkuq.js.map} +1 -1
  148. package/dist/assets/{tree-store-N362nuzZ.js → tree-store-CAchkO_l.js} +22 -6
  149. package/dist/assets/tree-store-CAchkO_l.js.map +1 -0
  150. package/dist/assets/{types-Clyb52K2.js → types-CdWwgvyt.js} +2 -3
  151. package/dist/assets/{types-Clyb52K2.js.map → types-CdWwgvyt.js.map} +1 -1
  152. package/dist/assets/{unbzip2-stream-B1C-JX9L.js → unbzip2-stream-BtkYGpC5.js} +2 -3
  153. package/dist/assets/{unbzip2-stream-B1C-JX9L.js.map → unbzip2-stream-BtkYGpC5.js.map} +1 -1
  154. package/dist/assets/{usdt-DnyTGdTX.js → usdt-CBJ4Q5Ji.js} +7 -7
  155. package/dist/assets/usdt-CBJ4Q5Ji.js.map +1 -0
  156. package/dist/assets/{waitNotice-Cn0WJ-He.js → waitNotice-BGM0QOS2.js} +27 -4
  157. package/dist/assets/waitNotice-BGM0QOS2.js.map +1 -0
  158. package/dist/assets/{web-DwgdhfcY.js → web-68CYFCl9.js} +314 -91
  159. package/dist/assets/web-68CYFCl9.js.map +1 -0
  160. package/dist/ghostly.mjs +3 -5
  161. package/dist/ghostly.mjs.map +1 -1
  162. package/npm-shrinkwrap.json +225 -200
  163. package/package.json +16 -16
  164. package/dist/assets/api-DBlaoz8i.js.map +0 -1
  165. package/dist/assets/apiKit-DesObIDf.js.map +0 -1
  166. package/dist/assets/appFetch-C8yZIq1e.js +0 -194
  167. package/dist/assets/appFetch-C8yZIq1e.js.map +0 -1
  168. package/dist/assets/apps-DkMjDHML.js.map +0 -1
  169. package/dist/assets/apps-rzxsjfBV.js +0 -2
  170. package/dist/assets/arkade-CarKONmH.js.map +0 -1
  171. package/dist/assets/backup-C0OJCJlM.js.map +0 -1
  172. package/dist/assets/backup-CgWU7x0T.js +0 -2
  173. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js +0 -6
  174. package/dist/assets/bitcoindProvider-BvoRh0D5.js +0 -97
  175. package/dist/assets/bitcoindProvider-BvoRh0D5.js.map +0 -1
  176. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js +0 -6
  177. package/dist/assets/bitcoindevkit_bg-CRkZTSbO.wasm +0 -0
  178. package/dist/assets/buttons-Cco0Agfa.js +0 -2
  179. package/dist/assets/buttons-fZTEa_2i.js.map +0 -1
  180. package/dist/assets/client-Ibk3-e60.js.map +0 -1
  181. package/dist/assets/endpoint-DarqblYE.js.map +0 -1
  182. package/dist/assets/errors-Dt-ZnyOX.js.map +0 -1
  183. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js +0 -6
  184. package/dist/assets/fileBytes-BLPZq9YU.js.map +0 -1
  185. package/dist/assets/fileBytes-BtIyoDF2.js +0 -2
  186. package/dist/assets/fileBytesIdb-D8mAK4pF.js +0 -2
  187. package/dist/assets/host-CYlIiY3r.js.map +0 -1
  188. package/dist/assets/hyperdhtRelay-1wzya_0L.js +0 -25
  189. package/dist/assets/hyperdhtRelay-1wzya_0L.js.map +0 -1
  190. package/dist/assets/hyperdhtRelay-CdsLcAhY.js.map +0 -1
  191. package/dist/assets/irohWeb-D2IuloLL.js.map +0 -1
  192. package/dist/assets/joinTrace-D-fnt2p3.js +0 -2
  193. package/dist/assets/jsonOut-POtMBS_V.js +0 -16
  194. package/dist/assets/jsonOut-POtMBS_V.js.map +0 -1
  195. package/dist/assets/main-C0PfjKTe.js.map +0 -1
  196. package/dist/assets/mainline-Cu61qcPS.js.map +0 -1
  197. package/dist/assets/mints-BaOmx517.js +0 -2
  198. package/dist/assets/mints-j5XAOk4f.js.map +0 -1
  199. package/dist/assets/nwcProvider-DYHkd0iu.js +0 -88
  200. package/dist/assets/nwcProvider-DYHkd0iu.js.map +0 -1
  201. package/dist/assets/ownDid-CJ0ta8CL.js +0 -282
  202. package/dist/assets/ownDid-CJ0ta8CL.js.map +0 -1
  203. package/dist/assets/ownStatus-D4HC6tNR.js.map +0 -1
  204. package/dist/assets/profiles-Ccdq6Xf6.js.map +0 -1
  205. package/dist/assets/registry-CE0PpQAE.js +0 -2
  206. package/dist/assets/registry-LvxsLJ5S.js.map +0 -1
  207. package/dist/assets/resolve-6kVu2DE5.js +0 -400
  208. package/dist/assets/resolve-6kVu2DE5.js.map +0 -1
  209. package/dist/assets/secretGuard-DUr6bgKc.js +0 -2
  210. package/dist/assets/server-Q3VcNqGt.js.map +0 -1
  211. package/dist/assets/src-DjVj2ynY.js.map +0 -1
  212. package/dist/assets/sshForges-DeZ9cN9Q.js +0 -261
  213. package/dist/assets/sshForges-DeZ9cN9Q.js.map +0 -1
  214. package/dist/assets/storage-Bya5b2Xt.js.map +0 -1
  215. package/dist/assets/tree-store-N362nuzZ.js.map +0 -1
  216. package/dist/assets/usdt-DnyTGdTX.js.map +0 -1
  217. package/dist/assets/waitNotice-Cn0WJ-He.js.map +0 -1
  218. package/dist/assets/web-DwgdhfcY.js.map +0 -1
@@ -1,18 +1,24 @@
1
- import { Ba as sanitizeFileName, Cd as toBase64Url, Co as replySnippet, Dl as isAppUrl, Fl as appRef, Fo as appCardUrl, Ga as baseMime, Gn as NO_PICTURE_METADATA, Go as claimedTime, Ha as PLAYABLE_AUDIO, Ja as parseVoiceMeta, Jn as stripPictureMetadata, Ju as relayUrlProblem, Ka as downsamplePeaks, Lo as cardLine, Mo as STATUS_CARD_LIMITS, Po as appCardId, Sd as randomBytes$1, Sl as APP_PERMISSIONS, Ss as LIMITS, Ua as VOICE_LIMITS, Uo as MESSAGE_CLOCK_SKEW_MS, Va as sanitizeMime, Vl as isAppRef, Vn as withoutAudioMetadata, Vo as statusCardBytes, Wa as VOICE_METER, Wn as withoutVideoMetadata, Xa as voiceLevel, Ya as voiceDownloadName, Yl as readImageMeta, Yn as withoutPictureMetadata, Zi as identityStatement, bs as parseLocalTarget, du as ownInviteRefusal, ii as TYPING_REFRESH_MS, ki as APP_DATA_MAX_BYTES, lu as inviteLink, md as sanitizeAvatar, oi as sanitizeTypingStatus, pd as MAX_AVATAR_LENGTH, qu as normalizeRelayUrl, ri as TYPING_KINDS, sr as GROUP_FILE_LIMITS, us as AWAITING_PEER_MS, vs as GhostlyHttpError, zo as checkStatusCard } from "./src-DjVj2ynY.js";
2
- import { p as fileStore } from "./idb-CEuoNsTv.js";
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-D2IuloLL.js";
5
- import { t as IDENTITY_PROVIDERS } from "./registry-LvxsLJ5S.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-D4HC6tNR.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-DesObIDf.js";
10
- import { t as childEnv } from "./childEnv-K_IzUqQx.js";
11
- import { t as chatState } from "./waitNotice-Cn0WJ-He.js";
12
- 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-fZTEa_2i.js";
13
- import { a as checkShownName } from "./profiles-Ccdq6Xf6.js";
14
- import { t as BACKUP_METHODS } from "./backup-C0OJCJlM.js";
15
- import { o as checkedBundle } from "./apps-DkMjDHML.js";
1
+ import { Aa as appRef, At as sanitizeTypingStatus, Cn as sanitizeFileName, D as GROUP_FILE_LIMITS, Di as GhostlyHttpError, Dn as VOICE_METER, Dr as statusCardBytes, Dt as TYPING_REFRESH_MS, En as VOICE_LIMITS, Et as TYPING_KINDS, Ia as isAppRef, Ja as readImageMeta, Mn as voiceDownloadName, Nn as voiceLevel, On as baseMime, Sa as isAppUrl, Sr as cardLine, Tn as PLAYABLE_AUDIO, gr as STATUS_CARD_LIMITS, io as inviteLink, ji as LIMITS, jn as parseVoiceMeta, jr as claimedTime, ki as parseLocalTarget, kn as downsamplePeaks, kr as MESSAGE_CLOCK_SKEW_MS, n as groupCallSfu, oo as ownInviteRefusal, or as replySnippet, tn as APP_DATA_MAX_BYTES, vr as appCardId, wn as sanitizeMime, wr as checkStatusCard, yi as AWAITING_PEER_MS, yr as appCardUrl } from "./groupMeta-DTQAJG50.js";
2
+ import { B as removeStored, Qt as withoutPictureMetadata, Tt as decodeGroupEntryLink, U as waitingGroupFile, W as IDENTITY_DRAFT_TTL_MS, Xt as NO_PICTURE_METADATA, Yt as withoutVideoMetadata, Zt as stripPictureMetadata, 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, qt as withoutAudioMetadata, s as groupPayNoteId, t as DEFAULT_IROH_RELAYS } from "./irohWeb-CLBx5MIv.js";
3
+ import { c as normalizeRelayUrl, l as relayUrlProblem } from "./relay-Cjfmdec0.js";
4
+ import { n as secretWords, r as findSecret, t as guardText } from "./secretGuard-B4-LlMjv.js";
5
+ 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-DMEhrpkd.js";
6
+ import { i as localFileError, r as asCliError, t as CliError } from "./errors-DDLFO4Gf.js";
7
+ import { A as sentAt, B as shellWord, C as nobodyJoined, D as oneOf, E as num, I as state, L as str, M as shownName, N as sinceSeq, O as oneShotWaits, P as somebodyJoined, R as transportOffered, S as noMessage, T as node, _ as list, a as contactKeyOf, c as findChatOrGroup, d as groupById, f as groupNameOf, g as keptForJoin, h as inviteTaken, j as settingsOf, k as ownChatOf, l as findGroup, m as groupPrefixed, n as chatOf, o as dhtOnly, p as groupOf, r as chatOrGroup, s as findChat, t as bool, v as messageOf, x as noFile, z as waitForState } from "./apiKit-CVaEzKWQ.js";
8
+ import { l as toBase64Url, s as randomBytes$1 } from "./bytes-C1DNGY18.js";
9
+ import { f as FILE_BYTES_STEP, o as fileBytes, s as fileBytesOf } from "./fileBytes-CfvUXdSy.js";
10
+ import { p as fileStore } from "./idb-ewvbqyDI.js";
11
+ import { t as childEnv } from "./childEnv-C-99hdbL.js";
12
+ import { a as checkTextSize$1, c as outOf, d as waitForEdit, f as waitForGroupFrame, i as pressable, l as purgeMessage, m as waitForRemoval, n as buttonsCard, o as goesOn, p as waitForMessage, s as nobodyElseIn, t as BUTTON_METHODS, u as waitForConfirmed } from "./buttons-BvWqHJeh.js";
13
+ import { a as checkShownName } from "./profiles-BFSGqDFC.js";
14
+ import { a as MAX_AVATAR_LENGTH, o as sanitizeAvatar } from "./linkPreview-DdMf-YAc.js";
15
+ import { m as identityStatement } from "./identityProofs-Cksc_K7_.js";
16
+ import { i as parseProofBunker, t as IDENTITY_PROVIDERS } from "./registry-rXgaZeNn.js";
17
+ import { t as BACKUP_METHODS } from "./backup-DpyvT9Z6.js";
18
+ import { s as isAppFetchUrl } from "./appFetch-D56GsYuq.js";
19
+ import { o as checkedBundle } from "./apps-XnZ8VEuj.js";
20
+ import { m as parsePaymentAmount } from "./paymentIntent-DySU3Ajm.js";
21
+ import { t as chatState } from "./waitNotice-BGM0QOS2.js";
16
22
  import { generateMnemonic } from "@scure/bip39";
17
23
  import { wordlist } from "@scure/bip39/wordlists/english.js";
18
24
  import { execFile, spawn } from "node:child_process";
@@ -23,7 +29,7 @@ import { randomBytes, timingSafeEqual } from "node:crypto";
23
29
  import { createServer } from "node:http";
24
30
  import { Readable } from "node:stream";
25
31
  import { pipeline } from "node:stream/promises";
26
- //#region src/typing.ts
32
+ // src/typing.ts
27
33
  /**
28
34
  * `typing --for` and `group typing --for`: a `start` holds 6 s on the other side (WISP 401 § Typing, WISP 902 · Group
29
35
  * Mesh § Typing), so the daemon says it again until the time is up, a message goes to that chat or group, or a
@@ -123,8 +129,7 @@ function endTyping(ctx, target, tell) {
123
129
  if (tell) sayTyping(ctx, target, false);
124
130
  return true;
125
131
  }
126
- //#endregion
127
- //#region src/voicePeaks.ts
132
+ // src/voicePeaks.ts
128
133
  /** Longer than any voice note (15 minutes) with room: a WebM or Ogg past it is not read (their demuxers hold it all). */
129
134
  var MAX_BYTES = 268435456;
130
135
  /** Read first to tell a file's kind; a WAV's header is looked for in up to `WAV_HEAD_MAX` (as in ffmpeg's output). */
@@ -243,7 +248,10 @@ function kindOf(head) {
243
248
  if (ascii(head, 0, 3) === "ID3" || head[0] === 255 && (head[1] & 224) === 224) return "mp3";
244
249
  return null;
245
250
  }
246
- /** As `streamBytes`, reading the file only as far as its decoder goes; a kind left to ffmpeg is not read past its head. */
251
+ /**
252
+ * Feeds `sink` the sound of a kind this module decodes itself, reading the file only as far as its decoder goes; false
253
+ * for a kind it leaves to ffmpeg, not read past its head.
254
+ */
247
255
  async function streamFile(path, sink) {
248
256
  const file = await open(path);
249
257
  try {
@@ -292,6 +300,10 @@ async function* piecesOf(file, size, piece) {
292
300
  function ascii(bytes, at, length) {
293
301
  return String.fromCharCode(...bytes.subarray(at, at + length));
294
302
  }
303
+ /** The channels and rates a WAV's sound may have (ffmpeg's DSD at 705.6 kHz among them). */
304
+ var WAV_MAX_CHANNELS = 255;
305
+ var WAV_MIN_RATE = 1e3;
306
+ var WAV_MAX_RATE = 768e3;
295
307
  /** The format of a WAV and where its samples are; null while its header is not all there. */
296
308
  function wavHeader(bytes) {
297
309
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -313,6 +325,7 @@ function wavHeader(bytes) {
313
325
  }
314
326
  } else if (id === "data") {
315
327
  if (!channels || !sampleRate || !bits) throw new NotSound("a WAV without its format");
328
+ 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
329
  const to = size === 0 || size === 4294967295 ? Infinity : body + size;
317
330
  return {
318
331
  format,
@@ -333,7 +346,10 @@ function sampleReader(view, format, bits) {
333
346
  }
334
347
  /** Frames of a channel each pushed at a time: few enough to keep nothing large, many enough for few calls. */
335
348
  var PIECE_FRAMES = 4096;
336
- /** As `streamWav`, reading the file a piece of frames at a time until the sink wants no more. */
349
+ /**
350
+ * PCM (8, 16, 24 or 32 bit) or float (32 or 64 bit) WAV, read a piece of frames at a time until the sink wants no
351
+ * more. A data chunk whose size is unknown (a pipe) runs to the end.
352
+ */
337
353
  async function streamWavFile(file, size, sink) {
338
354
  let header = null;
339
355
  for (let length = HEAD_BYTES; !header; length *= 2) {
@@ -660,7 +676,9 @@ function streamFfmpeg(path, sink, command = process.env.GHOSTLY_FFMPEG || "ffmpe
660
676
  });
661
677
  child.on("error", (error) => {
662
678
  clearTimeout(timer);
663
- reject(/* @__PURE__ */ new Error(error.code === "ENOENT" ? "no decoder here for this kind of audio (install ffmpeg to read it)" : `ffmpeg: ${error.message}`));
679
+ const setting = process.env.GHOSTLY_FFMPEG;
680
+ const missing = setting && command === setting ? `GHOSTLY_FFMPEG (${setting}) is not there: set it to ffmpeg's path, or unset it to use the one on the PATH` : "no decoder here for this kind of audio (install ffmpeg to read it)";
681
+ reject(new Error(error.code === "ENOENT" ? missing : `ffmpeg: ${error.message}`));
664
682
  });
665
683
  child.on("close", (code) => {
666
684
  clearTimeout(timer);
@@ -689,8 +707,7 @@ function streamFfmpeg(path, sink, command = process.env.GHOSTLY_FFMPEG || "ffmpe
689
707
  });
690
708
  });
691
709
  }
692
- //#endregion
693
- //#region src/files.ts
710
+ // src/files.ts
694
711
  /**
695
712
  * Files and voice notes in a chat (WISP 1100, phase 3), as the app's composer sends them (packages/browser
696
713
  * platform/services.ts `sendFile`): the bytes go into the profile's file store first, then the engine offers them.
@@ -716,12 +733,18 @@ var TYPES = {
716
733
  ".ogg": "audio/ogg",
717
734
  ".opus": "audio/ogg",
718
735
  ".wav": "audio/wav",
736
+ ".aac": "audio/aac",
737
+ ".flac": "audio/flac",
738
+ ".oga": "audio/ogg",
739
+ ".weba": "audio/webm",
719
740
  ".webm": "audio/webm",
720
741
  ".mp4": "video/mp4",
721
742
  ".mov": "video/quicktime"
722
743
  };
723
- function mimeOf(path, given) {
724
- return sanitizeMime(given ?? TYPES[extname(path).toLowerCase()] ?? "application/octet-stream");
744
+ /** A voice note in an .mp4 is its sound in an MP4 box, as an .m4a: sent as audio/mp4, not as a video. */
745
+ function mimeOf(path, given, voice = false) {
746
+ const known = TYPES[extname(path).toLowerCase()];
747
+ return sanitizeMime(given ?? (voice && known === "video/mp4" ? "audio/mp4" : known) ?? "application/octet-stream");
725
748
  }
726
749
  /**
727
750
  * The time a saved voice message is named from: its message's in the chat, as the apps' Download names it. The file's
@@ -794,15 +817,16 @@ function withWaitingFor(transfer) {
794
817
  };
795
818
  }
796
819
  /** The chat or the group a file command names (`findChatOrGroup`). */
797
- var chatOrGroupOf = (ctx, params) => findChatOrGroup(state(ctx).links, state(ctx).groups, str(params, "chat", true));
820
+ var chatOrGroupOf = (ctx, params, { links, groups } = state(ctx)) => findChatOrGroup(links, groups, str(params, "chat", true));
798
821
  /**
799
822
  * 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
800
823
  * may be left out; given, it must be the file's own. `where` is what the answer names it by.
801
824
  */
802
825
  function fileChat(ctx, params, fileId) {
803
- const groupId = groupOfFile(fileId, state(ctx).groups.map((g) => g.id));
826
+ const s = state(ctx);
827
+ const groupId = groupOfFile(fileId, s.groups.map((g) => g.id));
804
828
  if (groupId) {
805
- const named = params.chat === void 0 ? void 0 : chatOrGroupOf(ctx, params);
829
+ const named = params.chat === void 0 ? void 0 : chatOrGroupOf(ctx, params, s);
806
830
  if (named && !("group" in named && named.group.id === groupId)) throw noFile(fileId, {
807
831
  group: "group" in named,
808
832
  ref: str(params, "chat", true)
@@ -812,7 +836,7 @@ function fileChat(ctx, params, fileId) {
812
836
  where: { group: groupId }
813
837
  };
814
838
  }
815
- const link = params.chat === void 0 ? state(ctx).links.find((l) => fileId.startsWith(`${l.id}-in-`) || fileId.startsWith(`${l.id}-out-`)) : chatOf(ctx, params);
839
+ const link = params.chat === void 0 ? s.links.find((l) => fileId.startsWith(`${l.id}-in-`) || fileId.startsWith(`${l.id}-out-`)) : chatOf(ctx, params, s);
816
840
  if (!link) throw noFile(fileId);
817
841
  if (!fileId.startsWith(`${link.id}-`)) throw noFile(fileId, {
818
842
  group: false,
@@ -832,7 +856,7 @@ async function voiceOf(params, path, mime, size) {
832
856
  if (params.voice === void 0) return {};
833
857
  const name = basename(path);
834
858
  if (!size) throw new CliError("bad_request", `${name} is empty: a voice note is audio`);
835
- if (!PLAYABLE_AUDIO.test(baseMime(mime))) throw new CliError("bad_request", `${name} is ${mime}, not audio (webm, ogg, mp4, mpeg, aac, m4a or wav)`);
859
+ if (!PLAYABLE_AUDIO.test(baseMime(mime))) throw new CliError("bad_request", `${name} is ${mime}, not audio (webm, ogg, opus, mp4, m4a, mpeg, aac, wav or flac)`);
836
860
  const given = params.voice === true ? void 0 : num(params, "voice", 0, { min: 1 });
837
861
  let duration = given;
838
862
  let peaks = list(params, "peaks").map(Number);
@@ -894,13 +918,28 @@ async function whileUnchanged(path, read) {
894
918
  }
895
919
  }
896
920
  /**
921
+ * The file copied into the profile (`stage`) for a send whose client is still there to hear of it (`CallScope.gone`).
922
+ * Ctrl-C on `file send` through a daemon, while a large file was copied in (seconds per GiB), said "stopped before the
923
+ * command answered"; the daemon went on, and the file went to the contact a moment later. Sent again, it went twice.
924
+ * The copy stops at its next step, and what was copied is removed: nothing is in the chat, nothing goes.
925
+ */
926
+ async function stageWhileAsked(bytes, id, path, source, gone) {
927
+ const stillAsked = () => {
928
+ if (gone?.aborted) throw new CliError("interrupted", "The file was not sent: the command that sent it went away before it was copied in");
929
+ };
930
+ const digest = await whileUnchanged(path, () => bytes.stage(id, source, stillAsked));
931
+ if (gone?.aborted) await bytes.remove(id).catch(() => {});
932
+ stillAsked();
933
+ return digest;
934
+ }
935
+ /**
897
936
  * 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
898
937
  * the announcement. This device is its first holder and serves the members who ask.
899
938
  */
900
- async function sendToGroup(ctx, params, group, path, name, picked) {
939
+ async function sendToGroup(ctx, params, group, path, name, picked, gone) {
901
940
  if (picked > GROUP_FILE_LIMITS.maxBytes) throw new CliError("refused", `Too large for a group (at most ${GROUP_FILE_LIMITS.maxBytes} bytes)`);
902
941
  if (!picked) throw new CliError("refused", "An empty file cannot go to a group");
903
- const mime = mimeOf(path, str(params, "mime"));
942
+ const mime = mimeOf(path, str(params, "mime"), params.voice !== void 0);
904
943
  const replyTo = str(params, "reply");
905
944
  if (replyTo) {
906
945
  if (!await findMessage(ctx, `group:${group.id}`, (m) => m.id === replyTo || replyRef(m) === replyTo)) throw noMessage(replyTo, {
@@ -925,7 +964,7 @@ async function sendToGroup(ctx, params, group, path, name, picked) {
925
964
  };
926
965
  const timestamp = Date.now();
927
966
  const bytes = await fileBytes();
928
- const digest = await whileUnchanged(path, () => bytes.stage(fileId, source));
967
+ const digest = await stageWhileAsked(bytes, fileId, path, source, gone);
929
968
  await fileStore.put({
930
969
  id: fileId,
931
970
  linkId: `group:${group.id}`,
@@ -1075,15 +1114,7 @@ async function waitForFile(ctx, params, stopping) {
1075
1114
  ...where,
1076
1115
  retry: !!transfer.retry
1077
1116
  });
1078
- if (transfer.state !== "done") {
1079
- const name = (stored ?? await fileStore.get(fileId).catch(() => void 0))?.metadata?.name ?? "The file";
1080
- throw new CliError("confirm", `${name} (${megabytes(transfer.size)}) waits for you to take it: ghostly file accept ${fileId} (or file decline)`, {
1081
- file: fileId,
1082
- ...where,
1083
- size: transfer.size,
1084
- stage: "asking"
1085
- });
1086
- }
1117
+ if (transfer.state !== "done") throw waitsForYou((stored ?? await fileStore.get(fileId).catch(() => void 0))?.metadata?.name, fileId, where, transfer.size);
1087
1118
  return {
1088
1119
  ...where,
1089
1120
  file: fileId,
@@ -1091,8 +1122,17 @@ async function waitForFile(ctx, params, stopping) {
1091
1122
  size: transfer.size
1092
1123
  };
1093
1124
  }
1125
+ /** A received file that waits for this person's `file accept` (`file wait`, `file save`): said naming the command. */
1126
+ function waitsForYou(name, fileId, where, size) {
1127
+ return new CliError("confirm", `${name ?? "The file"} (${megabytes(size)}) waits for you to take it: ghostly file accept ${fileId} (or file decline)`, {
1128
+ file: fileId,
1129
+ ...where,
1130
+ size,
1131
+ stage: "asking"
1132
+ });
1133
+ }
1094
1134
  var FILE_METHODS = {
1095
- async "file.send"(ctx, params) {
1135
+ async "file.send"(ctx, params, call) {
1096
1136
  const path = resolve(str(params, "path", true));
1097
1137
  const name = sanitizeFileName(str(params, "name") ?? basename(path));
1098
1138
  guardText(name, bool(params, "force"), "file's name", "send it");
@@ -1110,12 +1150,12 @@ var FILE_METHODS = {
1110
1150
  min: 1,
1111
1151
  max: 86400
1112
1152
  });
1113
- if ("group" in target) return sendToGroup(ctx, params, target.group, path, name, info.size);
1153
+ if ("group" in target) return sendToGroup(ctx, params, target.group, path, name, info.size, call?.gone);
1114
1154
  const { link } = target;
1115
1155
  if (link.profile && link.dataLink === "open" && !link.capabilities?.files) throw new CliError("unavailable", "The contact's app takes no files");
1116
1156
  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)`);
1117
1157
  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)`);
1118
- const mime = mimeOf(path, str(params, "mime"));
1158
+ const mime = mimeOf(path, str(params, "mime"), params.voice !== void 0);
1119
1159
  const replyTo = str(params, "reply");
1120
1160
  if (replyTo) {
1121
1161
  if (!await findMessage(ctx, link.id, (m) => m.id === replyTo || replyRef(m) === replyTo)) throw noMessage(replyTo, {
@@ -1137,7 +1177,7 @@ var FILE_METHODS = {
1137
1177
  };
1138
1178
  const timestamp = sentAt();
1139
1179
  const bytes = await fileBytes();
1140
- const digest = await whileUnchanged(path, () => bytes.stage(file.id, source));
1180
+ const digest = await stageWhileAsked(bytes, file.id, path, source, call?.gone);
1141
1181
  await fileStore.put({
1142
1182
  id: file.id,
1143
1183
  linkId: link.id,
@@ -1278,6 +1318,7 @@ var FILE_METHODS = {
1278
1318
  }
1279
1319
  const view = state(ctx).transfers[fileId];
1280
1320
  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");
1321
+ 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)");
1281
1322
  await node(ctx).fileAction({
1282
1323
  linkId,
1283
1324
  fileId,
@@ -1308,24 +1349,45 @@ var FILE_METHODS = {
1308
1349
  const stored = await fileStore.get(fileId);
1309
1350
  if (!stored?.metadata) throw noFile(fileId);
1310
1351
  if (stored.leftOut) throw new CliError("not_found", "Not in this backup: the light backup this profile was restored from left the file out");
1311
- const transfer = stored.direction === "out" ? void 0 : state(ctx).transfers[fileId] ?? stored.transfer;
1352
+ const transfer = stored.direction === "out" ? void 0 : state(ctx).transfers[fileId] ?? waitingGroupFile(stored) ?? stored.transfer;
1312
1353
  if (transfer?.state === "failed") throw new CliError("refused", `It ended: ${transfer.error ?? "failed"}`);
1354
+ if (transfer?.state === "transferring" && transfer.stage === "asking" && transfer.direction === "in") {
1355
+ let where;
1356
+ try {
1357
+ where = fileChat(ctx, params, fileId).where;
1358
+ } catch {}
1359
+ throw waitsForYou(stored.metadata.name, fileId, where, transfer.size);
1360
+ }
1313
1361
  if (transfer && transfer.state !== "done") throw new CliError("unavailable", `The file is not all here yet (${transfer.transferred} of ${transfer.size} bytes)`);
1314
1362
  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));
1315
1363
  const force = bool(params, "force");
1316
1364
  const path = str(params, "path");
1317
- if (path && (path.endsWith("/") || path.endsWith(sep)) && !(await stat(named).catch(() => void 0))?.isDirectory()) throw new CliError("bad_request", `${path} names a folder: name a file, or use --dir ${named} (dir over the socket)`);
1365
+ if (path && (path.endsWith("/") || path.endsWith(sep))) {
1366
+ const there = await stat(named).catch(() => void 0);
1367
+ if (!there) throw new CliError("not_found", `No such folder: ${named} (make it first, or name a file in a folder that is there)`);
1368
+ if (!there.isDirectory()) throw new CliError("not_found", `${named} is a file, not a folder: name a file in a folder that is there`);
1369
+ }
1318
1370
  const free = !force && !str(params, "path") && !!stored.metadata.voice;
1319
1371
  const ext = extname(named), stem = named.slice(0, named.length - ext.length);
1372
+ let next = 2;
1320
1373
  const taken = async (target, code) => {
1321
1374
  const there = await stat(target).catch(() => void 0);
1322
- if (there?.isDirectory()) return new CliError("bad_request", `${target} is a folder: name a file, or use --dir ${target} (dir over the socket)`);
1323
- if (there && !force || code === "EEXIST") return new CliError("confirm", `${target} exists: pass --force (force: true over the socket) to replace it`);
1375
+ if (there?.isDirectory() && free && next <= 1e3) return new CliError("confirm", `${target} is a folder`);
1376
+ if (there?.isDirectory()) return new CliError("bad_request", `${target} is a folder: name a file, or use --dir ${shellWord(target, "<the one in details.dir>")} (dir over the socket)`, { dir: target });
1377
+ if (!(there && !force || code === "EEXIST")) return;
1378
+ const replace = `${target} exists: pass --force (force: true over the socket) to replace it`;
1379
+ if (path) return new CliError("confirm", replace);
1380
+ if (free && next <= 1e3) return new CliError("confirm", replace);
1381
+ let n = 2;
1382
+ while (n <= 1e3 && await stat(`${stem} (${n})${ext}`).catch(() => void 0)) n += 1;
1383
+ const other = `${stem} (${n})${ext}`;
1384
+ return new CliError("confirm", `${replace}, or --path ${shellWord(other, "<the one in details.path>")} (path over the socket) to keep both`, { path: other });
1324
1385
  };
1325
1386
  let target = named;
1326
- for (let n = 2, refused = await taken(target); refused; n += 1, refused = await taken(target)) {
1327
- if (!free || refused.code !== "confirm" || n > 1e3) throw refused;
1328
- target = `${stem} (${n})${ext}`;
1387
+ for (let refused = await taken(target); refused; refused = await taken(target)) {
1388
+ if (!free || refused.code !== "confirm" || next > 1e3) throw refused;
1389
+ target = `${stem} (${next})${ext}`;
1390
+ next += 1;
1329
1391
  }
1330
1392
  const partial = join(dirname(target), `.ghostly-save-${process.pid}-${toBase64Url(randomBytes$1(6))}.partial`);
1331
1393
  const asked = (error, where) => {
@@ -1366,14 +1428,15 @@ var FILE_METHODS = {
1366
1428
  } else throw new CliError("not_found", "The file's bytes are not on this device");
1367
1429
  await out.close();
1368
1430
  out = null;
1369
- for (let n = 2; !complete; n += 1) try {
1431
+ while (!complete) try {
1370
1432
  await place(partial, target, force);
1371
1433
  complete = true;
1372
1434
  } catch (error) {
1373
1435
  const code = error.code;
1374
1436
  const refused = code === "EEXIST" || code === "EISDIR" || code === "ENOTEMPTY" ? await taken(target, code) : void 0;
1375
- if (free && refused?.code === "confirm" && n <= 1e3) {
1376
- target = `${stem} (${n})${ext}`;
1437
+ if (free && refused?.code === "confirm" && next <= 1e3) {
1438
+ target = `${stem} (${next})${ext}`;
1439
+ next += 1;
1377
1440
  continue;
1378
1441
  }
1379
1442
  throw refused ?? error;
@@ -1394,8 +1457,7 @@ var FILE_METHODS = {
1394
1457
  };
1395
1458
  }
1396
1459
  };
1397
- //#endregion
1398
- //#region src/statusCards.ts
1460
+ // src/statusCards.ts
1399
1461
  /** A card's updates go at most this often: the rest merge into the next, so a chatty bot spends few edits. */
1400
1462
  var CARD_UPDATE_GAP_MS = 2500;
1401
1463
  var paces = /* @__PURE__ */ new WeakMap();
@@ -1855,8 +1917,7 @@ var STATUS_CARD_METHODS = {
1855
1917
  /** WISP 405 § Usage: how much of a quota the bot has left, kept as one card per chat; `all` for every 1:1 chat. */
1856
1918
  "usage.send": sendUsage
1857
1919
  };
1858
- //#endregion
1859
- //#region src/holds.ts
1920
+ // src/holds.ts
1860
1921
  /**
1861
1922
  * `chat disconnect --hold <minutes>`: a chat kept off its direct link for a while. It is the chat's own "DHT only"
1862
1923
  * choice (WISP 400: either side choosing it keeps both off the live link, so the contact's app does not redial),
@@ -2041,8 +2102,7 @@ function resumeHolds(ctx) {
2041
2102
  if (gone.length) writeHolds(ctx, holds);
2042
2103
  for (const [linkId, hold] of Object.entries(holds)) schedule(ctx, linkId, hold.until);
2043
2104
  }
2044
- //#endregion
2045
- //#region src/views.ts
2105
+ // src/views.ts
2046
2106
  /**
2047
2107
  * A live session carries the chat now, in this run: its link is open and, on a paired chat, the session authenticated
2048
2108
  * on a transport. The engine's own rule for a chat's connection line (`observeTransport`). `textDelivery` alone says
@@ -2310,7 +2370,9 @@ function groupJson(group, showSecret = false) {
2310
2370
  chat: group.invitation.linkId,
2311
2371
  accepted: group.invitation.accepted,
2312
2372
  viaLink: !!group.invitation.viaLink,
2313
- stage: group.invitation.stage ?? null
2373
+ stage: group.invitation.stage ?? null,
2374
+ ...group.invitation.unanswered ? { unanswered: true } : {},
2375
+ ...group.invitation.takenBack ? { takenBack: true } : {}
2314
2376
  } : null,
2315
2377
  ...group.others?.length ? { others: group.others.map((o) => "link" in o ? { link: showSecret ? o.link : "<hidden>" } : {
2316
2378
  chat: o.linkId,
@@ -2319,11 +2381,14 @@ function groupJson(group, showSecret = false) {
2319
2381
  }) } : {},
2320
2382
  community: group.community ?? null,
2321
2383
  picture: !!group.picture,
2384
+ call: group.call ? {
2385
+ sfu: group.call.sfu,
2386
+ e2ee: group.call.e2ee === 1
2387
+ } : null,
2322
2388
  pin: pinJson(group.pin)
2323
2389
  };
2324
2390
  }
2325
- //#endregion
2326
- //#region src/groupAdmin.ts
2391
+ // src/groupAdmin.ts
2327
2392
  /**
2328
2393
  * Group administration and pictures (WISP 1100, phase 3): what the app's group menu and profile screen do. The
2329
2394
  * engine enforces who may do what (the admin); these check the arguments and name members.
@@ -2391,10 +2456,25 @@ async function pictureFrom(path) {
2391
2456
  return checked;
2392
2457
  }
2393
2458
  async function picture(params) {
2459
+ if (bool(params, "clear") && str(params, "path") !== void 0) throw new CliError("bad_request", "clear removes the picture: not with path");
2394
2460
  if (bool(params, "clear")) return null;
2395
2461
  return pictureFrom(str(params, "path", true));
2396
2462
  }
2397
2463
  /**
2464
+ * The node a group's calls go through (WISP 602): an https origin in its one spelling, refused here before anything is
2465
+ * signed. A URL that names an https origin in another spelling (a path, a trailing `/`, capitals) is told that origin.
2466
+ */
2467
+ function callNode(raw, ref, groupId) {
2468
+ const sfu = groupCallSfu(raw);
2469
+ if (sfu) return sfu;
2470
+ let origin;
2471
+ try {
2472
+ const url = new URL(raw);
2473
+ if (url.protocol === "https:" && url.origin.length <= 200) origin = url.origin;
2474
+ } catch {}
2475
+ throw new CliError("bad_request", origin ? `${JSON.stringify(raw)} is not an origin (no path, query or trailing /): ghostly group call ${shellWord(ref, groupId)} --sfu ${origin}` : `${JSON.stringify(raw)} is not an https origin: a call node is like https://call.example.com`);
2476
+ }
2477
+ /**
2398
2478
  * A group this profile administers or is in, not only an invitation: before, the engine answered `group rename`,
2399
2479
  * `picture`, `link`, `rotate` and `invite` on an invitation not yet joined with "Group not found" (engine, exit 1),
2400
2480
  * while `group show` listed it, and `remove`/`admin` said "No member" of a member list it had not received yet.
@@ -2402,16 +2482,25 @@ async function picture(params) {
2402
2482
  function joined(ctx, params, twin) {
2403
2483
  const group = groupOf(ctx, params, twin);
2404
2484
  if (group.status || !group.invitation) return group;
2405
- const ref = str(params, "group", true), shown = /^[\w.:-]+$/.test(ref) ? ref : JSON.stringify(ref);
2485
+ const shown = shellWord(str(params, "group", true), group.id);
2406
2486
  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`);
2407
2487
  }
2408
2488
  /** The member `params.member` names in `group`, this profile's own name said to be it; by its key only for a grant. */
2409
- var member = (ctx, group, params, grant = false) => findMember(group, str(params, "member", true), state(ctx).settings.nick, grant);
2410
- var view = (ctx, id, params) => groupJson(state(ctx).groups.find((g) => g.id === id) ?? groupOf(ctx, { group: id }), bool(params, "showSecret"));
2489
+ var member = (ctx, group, params, grant = false) => findMember(group, str(params, "member", true), settingsOf(ctx).nick, grant);
2490
+ /**
2491
+ * A group's link and the address that opens it in the app, as `invite create` answers `invite` and `link`. Only the
2492
+ * token (`group2/…`) was given: pasted in a chat it is no link anyone can tap, and the app's own Share link is this one.
2493
+ */
2494
+ var withUrl = (group, link) => ({
2495
+ group,
2496
+ link,
2497
+ ...link && { url: `https://app.ghostly.tools/#/join/${link}` }
2498
+ });
2499
+ var view = (ctx, id, params) => groupJson(groupOf(ctx, { group: id }), bool(params, "showSecret"));
2411
2500
  var GROUP_ADMIN_METHODS = {
2412
2501
  async "group.invite"(ctx, params) {
2413
2502
  const group = joined(ctx, params);
2414
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2503
+ const link = ownChatOf(ctx, params);
2415
2504
  await node(ctx).inviteToGroup({
2416
2505
  groupId: group.id,
2417
2506
  linkId: link.id
@@ -2425,7 +2514,7 @@ var GROUP_ADMIN_METHODS = {
2425
2514
  groupId: group.id,
2426
2515
  key: removed.key
2427
2516
  });
2428
- const linkOn = !!(state(ctx).groups.find((g) => g.id === group.id) ?? group).entryLink;
2517
+ const linkOn = !!(groupById(ctx, group.id) ?? group).entryLink;
2429
2518
  return {
2430
2519
  ...view(ctx, group.id, params),
2431
2520
  ...linkOn && { warning: `${removed.nick ?? "They"} can still join again with the group's link: ghostly group link ${group.id} --reset gives it a new one and keeps them out` }
@@ -2471,6 +2560,8 @@ var GROUP_ADMIN_METHODS = {
2471
2560
  },
2472
2561
  async "group.link"(ctx, params) {
2473
2562
  const group = joined(ctx, params);
2563
+ const out = outOf(group);
2564
+ if (out) throw new CliError("refused", out);
2474
2565
  const on = params.on === void 0 || bool(params, "on"), reset = bool(params, "reset");
2475
2566
  if (!on && reset) throw new CliError("bad_request", "on: false turns the link off: not with reset");
2476
2567
  if (!on) {
@@ -2484,10 +2575,7 @@ var GROUP_ADMIN_METHODS = {
2484
2575
  groupId: group.id,
2485
2576
  ...reset ? { reset: true } : {}
2486
2577
  });
2487
- return {
2488
- group: group.id,
2489
- link
2490
- };
2578
+ return withUrl(group.id, link);
2491
2579
  },
2492
2580
  async "group.picture"(ctx, params) {
2493
2581
  const group = joined(ctx, params);
@@ -2500,14 +2588,35 @@ var GROUP_ADMIN_METHODS = {
2500
2588
  picture: !bool(params, "clear")
2501
2589
  };
2502
2590
  },
2591
+ async "group.call"(ctx, params) {
2592
+ const group = joined(ctx, params);
2593
+ if (group.profile !== "community") throw new CliError("refused", `${group.name} is a private group: only a community group has calls through a node`);
2594
+ const out = outOf(group);
2595
+ if (out) throw new CliError("refused", out);
2596
+ if (!group.isAdmin) throw new CliError("refused", `Only the admin of ${group.name} sets its call node`);
2597
+ const ref = str(params, "group", true), raw = str(params, "sfu");
2598
+ const e2ee = params.e2ee === void 0 || params.e2ee === null ? void 0 : bool(params, "e2ee");
2599
+ let sfu;
2600
+ if (bool(params, "clear") && raw !== void 0) throw new CliError("bad_request", "clear removes the call node: not with sfu");
2601
+ if (bool(params, "clear") && e2ee !== void 0) throw new CliError("bad_request", "clear removes the call node: not with e2ee");
2602
+ if (bool(params, "clear")) sfu = null;
2603
+ else if (raw !== void 0 || e2ee === void 0) sfu = callNode(str(params, "sfu", true), ref, group.id);
2604
+ else if (group.call) sfu = group.call.sfu;
2605
+ else throw new CliError("refused", `${group.name} has no call node: ghostly group call ${shellWord(ref, group.id)} --sfu <https origin>${e2ee ? " --e2ee" : ""}`);
2606
+ await node(ctx).setGroupCall({
2607
+ groupId: group.id,
2608
+ sfu,
2609
+ ...sfu !== null && e2ee !== void 0 && { e2ee }
2610
+ });
2611
+ return view(ctx, group.id, params);
2612
+ },
2503
2613
  async "profile.picture"(ctx, params) {
2504
2614
  const avatar = await picture(params);
2505
2615
  await node(ctx).updateSettings({ settings: { avatar: avatar ?? "" } });
2506
2616
  return { picture: avatar !== null };
2507
2617
  }
2508
2618
  };
2509
- //#endregion
2510
- //#region src/identities.ts
2619
+ // src/identities.ts
2511
2620
  /**
2512
2621
  * Drafts per daemon: a proof made in two steps needs the same process for both. Kept as long as the engine keeps them,
2513
2622
  * and the oldest dropped when a fifth begins as the engine drops it, so what `identity add` promises still completes.
@@ -2534,7 +2643,7 @@ function headless(s) {
2534
2643
  function signerOf(p, id) {
2535
2644
  const usable = p.signers.filter(headless);
2536
2645
  const found = id ? p.signers.find((s) => s.id === id) : usable[0];
2537
- 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`);
2646
+ 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`);
2538
2647
  if (!headless(found)) {
2539
2648
  const instead = usable.length ? ` (here: --signer ${usable.map((s) => s.id).join(" or ")})` : "";
2540
2649
  throw new CliError("unavailable", `${found.label} needs a browser window: make this proof in the app${instead}`);
@@ -2645,6 +2754,12 @@ var IDENTITY_METHODS = {
2645
2754
  const values = params.fields ?? {};
2646
2755
  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");
2647
2756
  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)}`);
2757
+ const bunker = signer.fields?.find((f) => f.name === "bunker");
2758
+ if (bunker && values.bunker) try {
2759
+ parseProofBunker(values.bunker);
2760
+ } catch (error) {
2761
+ throw new CliError("bad_request", `${bunker.name} (${bunker.label}): ${error instanceof Error ? error.message : String(error)}`);
2762
+ }
2648
2763
  const seconds = num(params, "timeout", 300, {
2649
2764
  min: 5,
2650
2765
  max: 3600
@@ -2764,9 +2879,10 @@ var IDENTITY_METHODS = {
2764
2879
  return { removed: id };
2765
2880
  },
2766
2881
  async "identity.share"(ctx, params) {
2767
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2882
+ const s = state(ctx);
2883
+ const link = ownChatOf(ctx, params, s);
2768
2884
  const id = str(params, "id", true);
2769
- if (!state(ctx).identityProofs.some((p) => p.id === id)) throw new CliError("not_found", `No identity proof ${JSON.stringify(id)} (ghostly identity list)`);
2885
+ if (!s.identityProofs.some((p) => p.id === id)) throw new CliError("not_found", `No identity proof ${JSON.stringify(id)} (ghostly identity list)`);
2770
2886
  await node(ctx).shareIdentityProof({
2771
2887
  linkId: link.id,
2772
2888
  id
@@ -2777,7 +2893,7 @@ var IDENTITY_METHODS = {
2777
2893
  };
2778
2894
  },
2779
2895
  async "identity.withdraw"(ctx, params) {
2780
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
2896
+ const link = ownChatOf(ctx, params);
2781
2897
  const id = str(params, "id", true);
2782
2898
  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})`);
2783
2899
  await node(ctx).withdrawIdentityProof({
@@ -2823,8 +2939,7 @@ var IDENTITY_METHODS = {
2823
2939
  return IDENTITY_METHODS["identity.contact"](ctx, { chat: link.id });
2824
2940
  }
2825
2941
  };
2826
- //#endregion
2827
- //#region src/x401.ts
2942
+ // src/x401.ts
2828
2943
  /**
2829
2944
  * x401 credentials (WISP 3xx): the holder keys and issued credentials a bot keeps to show a website who stands behind
2830
2945
  * it. Here only keeping them: `x401 fetch`, which presents one, comes later. Claim values are printed only with
@@ -2864,8 +2979,7 @@ var X401_METHODS = {
2864
2979
  return { removed: id };
2865
2980
  }
2866
2981
  };
2867
- //#endregion
2868
- //#region src/services.ts
2982
+ // src/services.ts
2869
2983
  /**
2870
2984
  * Shared services (WISP 700/701, WISP 1100 phase 3b): a web app on this machine a contact may open over the chat's live
2871
2985
  * link, and a contact's app opened here on a loopback port. As on the Desktop: only loopback is reached, redirects are
@@ -2997,6 +3111,8 @@ function withoutReports(value) {
2997
3111
  }
2998
3112
  /** `service open` while Hide my IP from contacts is on (as the browser extension refuses to open one). */
2999
3113
  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";
3114
+ /** `service open` or `service close` in a one-shot: only the daemon keeps a contact's app open on a port. */
3115
+ var SERVICE_NEEDS_DAEMON = "An opened service lives in the daemon: start `ghostly daemon --detach` first";
3000
3116
  function plain(response, status, text, headers = {}) {
3001
3117
  response.writeHead(status, {
3002
3118
  "content-type": "text/plain; charset=utf-8",
@@ -3017,9 +3133,10 @@ async function openServiceServer(send, port = 0, { relayOnly = false } = {}) {
3017
3133
  const name = `${randomBytes(16).toString("hex")}.localhost`;
3018
3134
  const token = randomBytes(32).toString("hex");
3019
3135
  const cookies = /* @__PURE__ */ new Set();
3020
- let host = "";
3136
+ let host = "", portless = "";
3021
3137
  const server = createServer((request, response) => {
3022
- if (request.headers.host?.toLowerCase() !== host) return plain(response, 404, "Not found");
3138
+ const asked = request.headers.host?.toLowerCase();
3139
+ if (!asked || asked !== host && asked !== portless) return plain(response, 404, "Not found");
3023
3140
  const path = request.url ?? "/";
3024
3141
  if (path.startsWith(OPEN_PATH)) {
3025
3142
  if (!sameSecret(path.slice(15), token)) return plain(response, 404, "Not found");
@@ -3054,7 +3171,9 @@ async function openServiceServer(send, port = 0, { relayOnly = false } = {}) {
3054
3171
  resolve();
3055
3172
  });
3056
3173
  });
3057
- host = `${name}:${server.address().port}`;
3174
+ const on = server.address().port;
3175
+ host = `${name}:${on}`;
3176
+ if (on === 80) portless = name;
3058
3177
  return {
3059
3178
  server,
3060
3179
  host,
@@ -3121,9 +3240,35 @@ function serviceOf(ctx, params) {
3121
3240
  return serviceId;
3122
3241
  }
3123
3242
  /**
3243
+ * On, unless `off`; or as the answer's own key (`shared`, `enabled`) says, when a socket client sends it back. Before,
3244
+ * only `off` was read, so `{"shared": false}` shared the service with the contact and `{"enabled": false}` turned it on.
3245
+ * Both, saying the opposite, are refused: neither is guessed.
3246
+ */
3247
+ function onUnlessOff(params, key) {
3248
+ const on = !bool(params, "off");
3249
+ if (params[key] === void 0 || params[key] === null) return on;
3250
+ const said = bool(params, key);
3251
+ if (params.off !== void 0 && params.off !== null && said !== on) throw new CliError("bad_request", `${key}: ${said} and off: ${!on} say the opposite: give one of them`);
3252
+ return said;
3253
+ }
3254
+ /**
3124
3255
  * A port the person chose that could not be taken, in words that name it. Before, one in use was Node's EADDRINUSE as
3125
3256
  * `engine`, and one not allowed read as a file (`localFileError`): "Not allowed to write or read the path".
3126
3257
  */
3258
+ /** As long as the engine keeps a service's name (node.ts addService) and the Desktop's form takes it (Services.tsx). */
3259
+ var MAX_SERVICE_NAME_LENGTH = 48;
3260
+ /**
3261
+ * The `name` of `service add`, refused as a chat's or the profile's name is (`shownName`), before anything is made.
3262
+ * Before, one of spaces was the engine's plain error as `engine` (exit 1), and a longer one was cut with exit 0.
3263
+ */
3264
+ function serviceNameOf(params) {
3265
+ const name = shownName(str(params, "name", true), MAX_SERVICE_NAME_LENGTH, "A service's name");
3266
+ 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})`, {
3267
+ length: name.length,
3268
+ max: MAX_SERVICE_NAME_LENGTH
3269
+ });
3270
+ return name;
3271
+ }
3127
3272
  function portError(error, port) {
3128
3273
  const { code } = error ?? {};
3129
3274
  if (port && code === "EADDRINUSE") return new CliError("busy", `Port ${port} is in use on this machine: choose another, or leave out --port`);
@@ -3142,23 +3287,22 @@ var SERVICE_METHODS = {
3142
3287
  })) };
3143
3288
  },
3144
3289
  async "service.add"(ctx, params) {
3290
+ const name = serviceNameOf(params);
3145
3291
  const target = str(params, "target", true);
3146
- let url;
3147
- try {
3148
- url = new URL(target);
3149
- } catch {
3150
- throw new CliError("bad_request", `Not a URL: ${target}`);
3151
- }
3152
- 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");
3153
3292
  try {
3154
3293
  parseLocalTarget(target);
3155
3294
  } catch (error) {
3156
3295
  const said = error instanceof Error ? error.message : String(error);
3157
- const shown = `${url.protocol}//${url.host}${url.pathname}`;
3296
+ const text = target.trim();
3297
+ let shown = text;
3298
+ try {
3299
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text}`);
3300
+ shown = `${url.protocol}//${url.host}${url.pathname}`;
3301
+ } catch {}
3158
3302
  throw new CliError(/^Only services on this machine/.test(said) ? "refused" : "bad_request", `${said}: ${shown}`);
3159
3303
  }
3160
3304
  const { serviceId } = node(ctx).addService({
3161
- name: str(params, "name", true),
3305
+ name,
3162
3306
  target
3163
3307
  });
3164
3308
  return {
@@ -3172,19 +3316,20 @@ var SERVICE_METHODS = {
3172
3316
  return { removed: serviceId };
3173
3317
  },
3174
3318
  async "service.enable"(ctx, params) {
3319
+ const enabled = onUnlessOff(params, "enabled");
3175
3320
  const serviceId = serviceOf(ctx, params);
3176
3321
  await node(ctx).setServiceEnabled({
3177
3322
  serviceId,
3178
- enabled: !bool(params, "off")
3323
+ enabled
3179
3324
  });
3180
3325
  return {
3181
3326
  service: serviceId,
3182
- enabled: !bool(params, "off")
3327
+ enabled
3183
3328
  };
3184
3329
  },
3185
3330
  async "service.share"(ctx, params) {
3186
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
3187
- const shared = !bool(params, "off");
3331
+ const link = ownChatOf(ctx, params);
3332
+ const shared = onUnlessOff(params, "shared");
3188
3333
  const serviceId = serviceOf(ctx, params);
3189
3334
  await node(ctx).setServiceShared({
3190
3335
  serviceId,
@@ -3208,8 +3353,8 @@ var SERVICE_METHODS = {
3208
3353
  },
3209
3354
  /** A contact's shared app on a loopback port of this machine, as the Desktop opens it in a window. */
3210
3355
  async "service.open"(ctx, params) {
3211
- if (ctx.mode !== "daemon") throw new CliError("unavailable", "An opened service lives in the daemon: start `ghostly daemon --detach` first");
3212
- if (state(ctx).settings?.relayOnly === true) throw new CliError("unavailable", SERVICE_OPEN_OFF_RELAY_ONLY);
3356
+ if (ctx.mode !== "daemon") throw new CliError("unavailable", SERVICE_NEEDS_DAEMON);
3357
+ if (settingsOf(ctx).relayOnly === true) throw new CliError("unavailable", SERVICE_OPEN_OFF_RELAY_ONLY);
3213
3358
  const link = chatOf(ctx, params);
3214
3359
  const service = str(params, "service", true);
3215
3360
  const key = `${link.peerPubKeyZ32}/${service}`;
@@ -3244,6 +3389,7 @@ var SERVICE_METHODS = {
3244
3389
  };
3245
3390
  },
3246
3391
  async "service.close"(ctx, params) {
3392
+ if (ctx.mode !== "daemon") throw new CliError("unavailable", SERVICE_NEEDS_DAEMON);
3247
3393
  const key = `${chatOf(ctx, params).peerPubKeyZ32}/${str(params, "service", true)}`;
3248
3394
  const pending = open$1.get(key);
3249
3395
  open$1.delete(key);
@@ -3277,8 +3423,7 @@ async function closeServicesOf(ctx, peer) {
3277
3423
  if (entry) await closeOpened(entry);
3278
3424
  }));
3279
3425
  }
3280
- //#endregion
3281
- //#region src/calls/api.ts
3426
+ // src/calls/api.ts
3282
3427
  /** Voice calls (WISP 1100 § Calls): the API methods. The audio itself goes over each call's own socket. */
3283
3428
  var CALL_METHODS = {
3284
3429
  async "call.start"(ctx, params) {
@@ -3313,9 +3458,8 @@ var CALL_METHODS = {
3313
3458
  }) };
3314
3459
  }
3315
3460
  };
3316
- //#endregion
3317
- //#region src/appServe.ts
3318
- /** The permissions a bot can be granted: `internet` is a page's, and no page runs here. */
3461
+ // src/appServe.ts
3462
+ /** The permissions a bot can be granted: `internet` and `files` are a page's, and no page runs here. */
3319
3463
  var GRANTABLE = ["chat", "name"];
3320
3464
  var servedFile = (dir) => join(dir, "apps.json");
3321
3465
  /** The apps a profile serves, by its folder: none when the file is missing or not a list of them. */
@@ -3354,6 +3498,8 @@ function servedApp(apps, ref) {
3354
3498
  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`);
3355
3499
  return matches[0];
3356
3500
  }
3501
+ /** A link a contact's app reads a card's bundle from. */
3502
+ var readable = (url) => isAppFetchUrl(url) && appCardUrl(url) !== void 0;
3357
3503
  /** Whether this engine offers apps/1 now: it read the list when it started, so the first app served waits for a restart. */
3358
3504
  var offered = (ctx, apps) => ({
3359
3505
  offered: ctx.runtime.apps,
@@ -3363,12 +3509,14 @@ var APP_SERVE_METHODS = {
3363
3509
  async "app.serve"(ctx, params) {
3364
3510
  const source = str(params, "bundle", true);
3365
3511
  const grant = list(params, "grant");
3366
- const unknown = grant.filter((p) => !APP_PERMISSIONS.includes(p));
3367
- if (unknown.length) throw new CliError("bad_request", `grant takes ${GRANTABLE.join(" or ")}, not ${unknown.map((p) => JSON.stringify(p)).join(", ")}`);
3368
3512
  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");
3513
+ 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");
3514
+ const ungrantable = grant.filter((p) => !GRANTABLE.includes(p));
3515
+ if (ungrantable.length) throw new CliError("bad_request", `grant takes ${GRANTABLE.join(" or ")}, not ${ungrantable.map((p) => JSON.stringify(p)).join(", ")}`);
3369
3516
  const given = str(params, "url");
3370
3517
  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");
3371
3518
  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");
3519
+ 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");
3372
3520
  const { bundle, url } = await checkedBundle(source);
3373
3521
  const m = bundle.manifest;
3374
3522
  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`);
@@ -3380,7 +3528,7 @@ var APP_SERVE_METHODS = {
3380
3528
  missing
3381
3529
  });
3382
3530
  const ref = appRef(m.publisher, m.name);
3383
- const cardUrl = appCardUrl(given ?? url ?? m.sources?.[0]);
3531
+ const cardUrl = appCardUrl(given ?? [url, ...m.sources ?? []].find(readable));
3384
3532
  const app = {
3385
3533
  ref,
3386
3534
  title: m.title,
@@ -3416,6 +3564,7 @@ var APP_SERVE_METHODS = {
3416
3564
  const app = servedApp(apps, ref);
3417
3565
  const next = apps.filter((a) => a !== app);
3418
3566
  writeServed(ctx.runtime.paths.dir, next);
3567
+ if (ctx.mode === "daemon") node(ctx).appsCloseOf(app.ref);
3419
3568
  return {
3420
3569
  unserved: app.ref,
3421
3570
  apps: next.length,
@@ -3423,8 +3572,7 @@ var APP_SERVE_METHODS = {
3423
3572
  };
3424
3573
  }
3425
3574
  };
3426
- //#endregion
3427
- //#region src/appEvents.ts
3575
+ // src/appEvents.ts
3428
3576
  /** Per hub: what the contacts have open now, `<chat> <reference>` to the version they said. */
3429
3577
  var peers = /* @__PURE__ */ new WeakMap();
3430
3578
  /** The version of a served app the contact has open in a chat on this session, or undefined. */
@@ -3435,9 +3583,8 @@ function reportAppFrames(hub, node, profileDir) {
3435
3583
  const open = /* @__PURE__ */ new Map();
3436
3584
  peers.set(hub, open);
3437
3585
  /**
3438
- * Per chat: chat app id to reference, of the apps served when they were learned there; the list's stamp then
3439
- * (undefined when an id could not be derived, so the next open tries again); and the version of each served app's
3440
- * last open since.
3586
+ * Per chat: chat app id to reference, of the apps served when they were learned there; and the list's stamp then
3587
+ * (undefined when an id could not be derived, so the next open tries again).
3441
3588
  */
3442
3589
  const known = /* @__PURE__ */ new Map();
3443
3590
  let count = 0;
@@ -3454,29 +3601,25 @@ function reportAppFrames(hub, node, profileDir) {
3454
3601
  }
3455
3602
  const learnt = {
3456
3603
  ids,
3457
- stamp,
3458
- versions: /* @__PURE__ */ new Map()
3604
+ stamp
3459
3605
  };
3460
3606
  known.set(chat, learnt);
3461
3607
  return learnt;
3462
3608
  };
3463
3609
  /**
3464
- * An open learns the served list again only when it changed since (a stat, no read), or names another version of a
3465
- * served app than its last open did: an app served or unserved since is taken or left from its next open, and a
3466
- * contact repeating opens (up to 50 a second for each of 16 apps) costs no read of the list nor derivation of ids.
3610
+ * An open learns the served list again only when it changed since (a stat, no read): an app served or unserved since
3611
+ * is taken or left from its next open, and a contact repeating opens (up to 50 a second for each of 16 apps), at one
3612
+ * version or alternating two, costs no read of the list nor derivation of ids, which do not depend on the version.
3467
3613
  */
3468
3614
  const current = (chat, frame) => {
3469
3615
  const learnt = known.get(chat);
3470
3616
  if (!learnt) return learn(chat);
3471
3617
  if (!("o" in frame) || frame.o !== "open") return learnt;
3472
- const was = learnt.versions.get(frame.app);
3473
- return learnt.stamp === void 0 || learnt.stamp !== servedStamp(profileDir) || was !== void 0 && was !== frame.v ? learn(chat) : learnt;
3618
+ return learnt.stamp === void 0 || learnt.stamp !== servedStamp(profileDir) ? learn(chat) : learnt;
3474
3619
  };
3475
3620
  return hub.onAppFrame((chat, frame) => {
3476
- const learnt = current(chat, frame);
3477
- const app = learnt.ids.get(frame.app);
3621
+ const app = current(chat, frame).ids.get(frame.app);
3478
3622
  if (!app) return;
3479
- if ("o" in frame && frame.o === "open") learnt.versions.set(frame.app, frame.v);
3480
3623
  const id = `${chat}:${app}:${Date.now()}-${++count}`;
3481
3624
  if ("o" in frame) {
3482
3625
  if (frame.o === "open") open.set(`${chat} ${app}`, frame.v);
@@ -3499,8 +3642,7 @@ function reportAppFrames(hub, node, profileDir) {
3499
3642
  });
3500
3643
  });
3501
3644
  }
3502
- //#endregion
3503
- //#region src/appChat.ts
3645
+ // src/appChat.ts
3504
3646
  /** The chat and the served app a command names, on an engine that speaks apps/1. */
3505
3647
  function target(ctx, params) {
3506
3648
  const app = servedApp(servedApps(ctx.runtime.paths.dir), str(params, "ref", true));
@@ -3618,8 +3760,7 @@ var NOT_SENT = {
3618
3760
  message: `More than 48 frames in a second, or the connection is still sending earlier ones: slow down and send it again`
3619
3761
  }
3620
3762
  };
3621
- //#endregion
3622
- //#region src/wallets.ts
3763
+ // src/wallets.ts
3623
3764
  /**
3624
3765
  * Wallets and payments (WISP 1100, phase 2): the app's wallet deck and a chat's payment sheet, as methods. Test
3625
3766
  * networks move nothing real. On Mainnet every spend passes `confirmedReal`, which the engine requires, only when the
@@ -3653,8 +3794,7 @@ function createChecked(type, n, offer, provider, values, params) {
3653
3794
  if (!provider) throw new CliError("bad_request", `${type} needs --provider: one of ${sources.map((p) => p.id).join(", ")} (ghostly wallet list)`);
3654
3795
  const source = sources.find((p) => p.id === provider);
3655
3796
  if (!source) throw new CliError("bad_request", `No ${type} source ${JSON.stringify(provider)} on ${n} (ghostly wallet list)`);
3656
- const unknown = Object.keys(values).find((name) => !source.fields.some((f) => f.name === name));
3657
- 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"}`);
3797
+ 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"}`);
3658
3798
  const missing = source.fields.find((f) => !f.optional && !f.defaults?.[n] && !values[f.name]?.trim());
3659
3799
  if (missing) throw new CliError("bad_request", `${provider} needs --value ${missing.name}=<${missing.options?.map((o) => o.value).join("|") ?? missing.placeholder ?? missing.label.toLowerCase()}>`);
3660
3800
  }
@@ -3670,12 +3810,20 @@ function lightningCard(ctx, params) {
3670
3810
  if (!netView(state(ctx), n)?.lightnings?.some((c) => c.card === card)) throw new CliError("not_found", `No Lightning card ${JSON.stringify(card)} on ${n} (ghostly wallet list)`);
3671
3811
  }
3672
3812
  /**
3813
+ * The card a payment, a request or a wallet command names. "" (an unset variable in a script: `--card "$CARD"`) is a
3814
+ * usage error: taken as not given, it moved money through, or removed, the network's default card or the whole wallet.
3815
+ */
3816
+ function cardParam(params) {
3817
+ if (params.card === "") throw new CliError("usage", "--card needs a Lightning card id (ghostly wallet list)");
3818
+ return str(params, "card");
3819
+ }
3820
+ /**
3673
3821
  * The Lightning card `card` names, checked before the engine is asked: given with another type of wallet it is a usage
3674
3822
  * error, and one not on the network is not_found. Before, the engine dropped it for every type but Lightning, so a card
3675
3823
  * that named nothing removed the whole wallet of that type and the answer echoed the card as removed.
3676
3824
  */
3677
3825
  function cardOf(ctx, params, type) {
3678
- const card = str(params, "card");
3826
+ const card = cardParam(params);
3679
3827
  if (card === void 0) return void 0;
3680
3828
  if (type !== "lightning") throw new CliError("usage", `--card names a Lightning card: not with ${type}`);
3681
3829
  lightningCard(ctx, params);
@@ -3782,6 +3930,18 @@ function walletJson(instance, s) {
3782
3930
  config: instance.config
3783
3931
  };
3784
3932
  }
3933
+ /** A token amount (USDT) is in base units: its `decimals` say how many make one. Sats carry none. */
3934
+ var tokenDecimals = (p) => p.target?.method === "usdt" ? { decimals: p.target.decimals ?? 6 } : {};
3935
+ /** USDT typed as the app's composer takes it ("5", "0.25") in base units: more decimals than the token has is refused. */
3936
+ function tokenUnits(text, decimals) {
3937
+ try {
3938
+ const units = parsePaymentAmount(text.trim(), decimals);
3939
+ if (units > 0) return units;
3940
+ } catch (error) {
3941
+ throw new CliError("bad_request", `amount: ${error.message}`);
3942
+ }
3943
+ throw new CliError("bad_request", "amount must be above 0");
3944
+ }
3785
3945
  function paymentJson(p) {
3786
3946
  return {
3787
3947
  id: p.id,
@@ -3790,6 +3950,7 @@ function paymentJson(p) {
3790
3950
  direction: p.direction,
3791
3951
  amount: p.amount,
3792
3952
  unit: p.unit,
3953
+ ...tokenDecimals(p),
3793
3954
  memo: p.memo ?? null,
3794
3955
  state: p.state,
3795
3956
  error: p.error ?? null,
@@ -3867,7 +4028,7 @@ var engineCode = (error) => error instanceof Error ? error.engineCode : void 0;
3867
4028
  var NO_MINT = /^(No mint could create an invoice: No mint configured|You have no (Mainnet|Testnet) Cashu wallet: create one in Wallet → New)$/;
3868
4029
  function walletRefusal(error) {
3869
4030
  if (!(error instanceof Error) || error instanceof CliError) return error;
3870
- if (error.name === "SwapUnsettledError") return new CliError("unavailable", error.message);
4031
+ if (error.name === "SwapUnsettledError" || error.unsettled === true) return new CliError("unavailable", error.message);
3871
4032
  const code = WALLET_REFUSALS.find(([pattern]) => pattern.test(error.message))?.[1];
3872
4033
  return code ? new CliError(code, error.message) : error;
3873
4034
  }
@@ -3968,7 +4129,10 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
3968
4129
  await federationsOpen(ctx);
3969
4130
  return {
3970
4131
  network: n,
3971
- history: (netView(state(ctx), n)?.history ?? []).slice(0, limit)
4132
+ history: await node(ctx).walletHistory({
4133
+ network: n,
4134
+ limit
4135
+ })
3972
4136
  };
3973
4137
  },
3974
4138
  async "wallet.receive"(ctx, params) {
@@ -4051,12 +4215,12 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4051
4215
  async "pay"(ctx, params) {
4052
4216
  const comment = memoOf(params, "pay", "comment");
4053
4217
  const text = str(params, "target", true).trim();
4054
- const card = str(params, "card");
4218
+ const card = cardParam(params);
4055
4219
  let invoice = text.replace(/^lightning:/i, "");
4056
4220
  let n;
4057
4221
  let note;
4058
4222
  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");
4059
- const chat = params.chat === void 0 ? void 0 : findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
4223
+ const chat = params.chat === void 0 ? void 0 : ownChatOf(ctx, params);
4060
4224
  if (chat) inviteTaken(chat);
4061
4225
  if (isInvoice(text)) n = network(params);
4062
4226
  else if (isLnurl(text)) {
@@ -4110,7 +4274,7 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4110
4274
  /** Ecash to a contact in a chat (the payment sheet's Pay). */
4111
4275
  async "chat.pay"(ctx, params) {
4112
4276
  const memo = memoOf(params, "pay");
4113
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
4277
+ const link = ownChatOf(ctx, params);
4114
4278
  inviteTaken(link);
4115
4279
  const amount = num(params, "amount", 0, { min: 1 });
4116
4280
  if (!amount) throw new CliError("bad_request", "amount is required");
@@ -4132,16 +4296,21 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4132
4296
  paymentId
4133
4297
  };
4134
4298
  },
4135
- /** A request in a chat (the payment sheet's Request): the contact's app pays it. */
4299
+ /**
4300
+ * A request in a chat (the payment sheet's Request): the contact's app pays it. A USDT amount given as text ("5",
4301
+ * "0.25") is USDT, turned into base units with the wallet's decimals as the app's composer does; a number is base units.
4302
+ * The answer says the amount asked: USDT's carries the engine's tag of a few base units, and its decimals.
4303
+ */
4136
4304
  async "chat.request"(ctx, params) {
4137
4305
  const memo = memoOf(params, "request");
4306
+ const card = cardParam(params);
4138
4307
  const link = chatOf(ctx, params);
4139
- const amount = num(params, "amount", 0, { min: 1 });
4140
- if (!amount) throw new CliError("bad_request", "amount is required");
4141
4308
  const method = params.method === void 0 ? void 0 : oneOf(params, "method", PAY_METHODS, "cashu");
4309
+ const n = network(params);
4310
+ const amount = method === "usdt" && typeof params.amount === "string" ? tokenUnits(params.amount, netView(state(ctx), n)?.usdt?.decimals ?? 6) : num(params, "amount", 0, { min: 1 });
4311
+ if (!amount) throw new CliError("bad_request", "amount is required");
4142
4312
  const rail = params.rail === void 0 ? void 0 : oneOf(params, "rail", ["cashu", "lightning"], "cashu");
4143
4313
  await federationsOpen(ctx);
4144
- const n = network(params);
4145
4314
  const { paymentId } = await node(ctx).requestPayment({
4146
4315
  linkId: link.id,
4147
4316
  amount,
@@ -4150,21 +4319,32 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4150
4319
  ...memo ? { memo } : {},
4151
4320
  ...method ? { method } : {},
4152
4321
  ...rail ? { rail } : {},
4153
- ...str(params, "card") ? { card: str(params, "card") } : {}
4322
+ ...card ? { card } : {}
4154
4323
  }).catch((error) => {
4155
4324
  throw (!method || method === "cashu") && error instanceof Error && NO_MINT.test(error.message) ? noWalletOf(ctx, n, error) : error;
4156
4325
  });
4326
+ const asked = state(ctx).payments[paymentId];
4157
4327
  return {
4158
4328
  chat: link.id,
4159
- paymentId
4329
+ paymentId,
4330
+ ...asked ? {
4331
+ amount: asked.amount,
4332
+ unit: asked.unit,
4333
+ ...tokenDecimals(asked)
4334
+ } : {}
4160
4335
  };
4161
4336
  },
4162
4337
  /** Pays a request the contact made in a chat. */
4163
4338
  async "chat.payRequest"(ctx, params) {
4164
- const link = findOwnNamedChat(state(ctx).links, str(params, "chat", true), state(ctx).groups);
4339
+ const s = state(ctx);
4340
+ const link = ownChatOf(ctx, params, s);
4165
4341
  const paymentId = str(params, "payment", true);
4166
- const request = state(ctx).payments[paymentId];
4167
- if (!request || request.linkId !== link.id || request.kind !== "request") throw new CliError("not_found", `No request ${paymentId} in this chat`);
4342
+ const card = cardParam(params);
4343
+ const request = s.payments[paymentId];
4344
+ const listed = `(ghostly payment list --chat ${link.id})`;
4345
+ if (request?.linkId === link.id && request.kind !== "request") throw new CliError("not_found", `${JSON.stringify(paymentId)} is ${request.direction === "out" ? "a payment you sent" : "a payment you received"}, not a request: chat pay-request pays a request the contact made of you ${listed}`);
4346
+ if (!request || request.linkId !== link.id) throw new CliError("not_found", `No request ${JSON.stringify(paymentId)} in this chat ${listed}`);
4347
+ if (request.direction !== "in") throw new CliError("bad_request", `${JSON.stringify(paymentId)} is your own request: the contact pays it`);
4168
4348
  const n = paymentNetwork(request);
4169
4349
  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 });
4170
4350
  const via = params.via === void 0 ? void 0 : oneOf(params, "via", ["lightning"], "lightning");
@@ -4175,7 +4355,7 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4175
4355
  network: n,
4176
4356
  ...via ? { via } : {},
4177
4357
  ...params.maxFee !== void 0 ? { maxFee: num(params, "maxFee", 0) } : {},
4178
- ...str(params, "card") ? { card: str(params, "card") } : {},
4358
+ ...card ? { card } : {},
4179
4359
  ...real(params)
4180
4360
  });
4181
4361
  return paymentJson(state(ctx).payments[paymentId] ?? request);
@@ -4192,7 +4372,7 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4192
4372
  };
4193
4373
  }
4194
4374
  const method = oneOf(params, "method", CHAT_METHODS, "cashu");
4195
- const on = bool(params, "on");
4375
+ const on = params.on === void 0 || bool(params, "on");
4196
4376
  const nets = params.networks === void 0 ? void 0 : (() => {
4197
4377
  const value = params.networks;
4198
4378
  if (!Array.isArray(value) || !value.every((v) => v === "mainnet" || v === "testnet")) throw new CliError("bad_request", "networks must list mainnet and/or testnet");
@@ -4212,12 +4392,14 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4212
4392
  };
4213
4393
  },
4214
4394
  async "payment.list"(ctx, params) {
4215
- const chat = params.chat === void 0 ? null : chatOf(ctx, params).id;
4216
- return { payments: Object.values(state(ctx).payments).filter((p) => !chat || p.linkId === chat).sort((a, b) => b.createdAt - a.createdAt).map(paymentJson) };
4395
+ const s = state(ctx);
4396
+ const chat = params.chat === void 0 ? null : chatOf(ctx, params, s).id;
4397
+ return { payments: Object.values(s.payments).filter((p) => !chat || p.linkId === chat).sort((a, b) => b.createdAt - a.createdAt).map(paymentJson) };
4217
4398
  },
4218
4399
  async "payment.check"(ctx, params) {
4219
- const link = chatOf(ctx, params);
4220
- const p = state(ctx).payments[str(params, "payment", true)];
4400
+ const s = state(ctx);
4401
+ const link = chatOf(ctx, params, s);
4402
+ const p = s.payments[str(params, "payment", true)];
4221
4403
  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})`);
4222
4404
  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`);
4223
4405
  await node(ctx).checkPayment({
@@ -4238,8 +4420,7 @@ var WALLET_METHODS = Object.fromEntries(Object.entries({
4238
4420
  }).map(([name, method]) => [name, (ctx, params) => method(ctx, params).catch((error) => {
4239
4421
  throw walletRefusal(error);
4240
4422
  })]));
4241
- //#endregion
4242
- //#region src/api.ts
4423
+ // src/api.ts
4243
4424
  /**
4244
4425
  * A text past what a chat or a group carries (16 KiB of UTF-8, as the engine counts it: trimmed) is refused before the
4245
4426
  * engine is asked, with a code that says it never goes as it is, not "unavailable", which reads as "try later".
@@ -4461,6 +4642,7 @@ function inviteNotOut(detail) {
4461
4642
  var BAD_VALUE = /^Cannot (destructure|read properties of (undefined|null))|is not (a function|iterable)/;
4462
4643
  /** A one-shot's typing without `--for` (it opens the profile offline, `offlineCall`): said on no live session. */
4463
4644
  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";
4645
+ 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`)";
4464
4646
  /**
4465
4647
  * A removal on its way goes with the chat's row, and the contact kept the message for good, though `message delete
4466
4648
  * --everyone` had said its removal goes on: `chat remove`, the engine's `removeLink` and `clearProfileData` (every
@@ -4481,6 +4663,113 @@ function noRemovalOnItsWay(ctx, linkIds, clearing = false) {
4481
4663
  ];
4482
4664
  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 });
4483
4665
  }
4666
+ /**
4667
+ * Stages a one-shot `group join` stops waiting at. The link was replaced: knocking again does not get in. The group
4668
+ * has no room yet (`full`, or `blocked` while it waits for every member's app to take more than eight): the engine
4669
+ * goes on knocking until there is room, which a minute's wait seldom sees, so it says that the knock goes on only
4670
+ * while the profile runs.
4671
+ */
4672
+ var NO_ROOM = {
4673
+ full: "No room yet: the group is full",
4674
+ blocked: "No room yet: the group waits for every member's app to take more than eight members"
4675
+ };
4676
+ var JOIN_STOPS = /* @__PURE__ */ new Set(["replaced", ...Object.keys(NO_ROOM)]);
4677
+ /** How long a one-shot `group join` waits to be let in: as long as a one-shot `invite join` waits to pair. */
4678
+ var ONE_SHOT_JOIN_S = 60;
4679
+ /**
4680
+ * A one-shot `group join` waits to be let in, as a one-shot invite join waits to pair: a member's app lets the joiner
4681
+ * in only while its knocks go on, and they stop when the command leaves. It left at once with `{"group": id}` and exit
4682
+ * 0, in 0.5 s, the admin online: the group stayed an invitation at "knocking" and nothing said a daemon had to run for
4683
+ * the knock to be answered. The answer says whether it is in and at what stage it waits, and what to do when it is not.
4684
+ * A contact's invitation to the group keeps its place and the link is only kept beside it: nothing knocks, so it
4685
+ * answers at once. Not accepted, only `group accept` moves it; accepted, only its welcome does, over the contact's chat.
4686
+ * In a group under the link's id already (`held`, before the join), the link is only kept beside it unless it is this
4687
+ * profile's own group's (the engine's `joinByLink`): nothing knocks, and it answered `"joined": true` for a link whose
4688
+ * group it never joined, with a second group waiting under the id that only `group show`'s `others` said.
4689
+ * Through a daemon the knock goes on after the answer, so it waits for nothing; it answered `{"group": id}` only, with
4690
+ * neither whether it was in nor a word about a link only kept beside a group held.
4691
+ */
4692
+ async function letIn(ctx, groupId, link, held) {
4693
+ const seen = (s) => s.groups.find((g) => g.id === groupId);
4694
+ const id = shellWord(groupId, groupId);
4695
+ const invited = seen(state(ctx))?.invitation;
4696
+ if (invited && !invited.viaLink && !invited.takenBack) {
4697
+ const who = invited.contact || "a contact";
4698
+ if (!invited.accepted) return {
4699
+ group: groupId,
4700
+ joined: false,
4701
+ stage: null,
4702
+ warning: `Not in yet: ${who} invited you to this group and the invitation waits for your answer. Accept it: ghostly group accept ${id}`
4703
+ };
4704
+ return {
4705
+ group: groupId,
4706
+ joined: false,
4707
+ stage: null,
4708
+ warning: `Not in yet: you accepted ${who}'s invitation to this group, and its welcome has not arrived; the link was kept beside it, and knocks nowhere. The welcome arrives only while this profile is running: keep it running (ghostly daemon --detach), then ghostly group show ${id}`
4709
+ };
4710
+ }
4711
+ const opened = decodeGroupEntryLink(link);
4712
+ const own = held?.entryLink ? decodeGroupEntryLink(held.entryLink) : null;
4713
+ if (held?.status === "active" && opened && own?.host !== opened.host) {
4714
+ const kept = seen(state(ctx))?.others?.some((o) => "link" in o && decodeGroupEntryLink(o.link)?.host === opened.host);
4715
+ const pick = `keep the one you are in (ghostly engine keepGroup '{"groupId":"${groupId}"}') or take the link's instead (ghostly engine switchGroup '{"groupId":"${groupId}","to":"<its link, from group show --show-secret>"}')`;
4716
+ return {
4717
+ group: groupId,
4718
+ joined: false,
4719
+ stage: null,
4720
+ warning: kept ? `Not joined: you are in a group under this link's id already, and only a group's welcome says whose a link is, so the link was kept beside that group and knocks nowhere. ghostly group show ${id} lists it under "others": ${pick}` : `Not joined: you are in a group under this link's id already, and as many other groups as are kept already wait beside it to be picked, so the link was not kept. ghostly group show ${id} lists them under "others": ${pick}, then open the link again`
4721
+ };
4722
+ }
4723
+ if (ctx.mode !== "one-shot") {
4724
+ const now = seen(state(ctx));
4725
+ return {
4726
+ group: groupId,
4727
+ joined: now?.status === "active",
4728
+ stage: now?.invitation?.stage ?? null
4729
+ };
4730
+ }
4731
+ const done = (g) => !g || g.status === "active" || JOIN_STOPS.has(g.invitation?.stage ?? "");
4732
+ const group = await waitForState(ctx, (s) => {
4733
+ const g = seen(s);
4734
+ return done(g) ? { g } : void 0;
4735
+ }, ONE_SHOT_JOIN_S * 1e3, `group ${groupId} to let this profile in`).then(({ g }) => g, (error) => {
4736
+ if (error instanceof CliError && error.code === "timeout") return seen(state(ctx));
4737
+ throw error;
4738
+ });
4739
+ const joined = group?.status === "active", stage = group?.invitation?.stage ?? null;
4740
+ if (joined || !group) return {
4741
+ group: groupId,
4742
+ joined,
4743
+ stage
4744
+ };
4745
+ if (stage === "replaced") return {
4746
+ group: groupId,
4747
+ joined,
4748
+ stage,
4749
+ warning: "This link was replaced or turned off: ask someone in the group for the current link, then ghostly group join <link>"
4750
+ };
4751
+ const show = `keep it running (ghostly daemon --detach), then ghostly group show ${shellWord(groupId, groupId)}`;
4752
+ const full = stage === "full" ? group.invitation?.full : void 0;
4753
+ const noRoom = stage ? NO_ROOM[stage] : void 0;
4754
+ if (noRoom) return {
4755
+ group: groupId,
4756
+ joined,
4757
+ stage,
4758
+ warning: `${noRoom}${full ? ` (${full.n} of ${full.max} members)` : ""}. Your app goes on knocking only while this profile is running, and gets in when there is room: ${show}`
4759
+ };
4760
+ if (stage === "admitted") return {
4761
+ group: groupId,
4762
+ joined,
4763
+ stage,
4764
+ warning: `Not in yet: a member's app let you in, and the group's welcome has not finished arriving. It arrives only while this profile is running: ${show}`
4765
+ };
4766
+ return {
4767
+ group: groupId,
4768
+ joined,
4769
+ stage,
4770
+ warning: `Not in yet: no member's app has let you in. A member's app lets you in only while this profile is running: ${show}`
4771
+ };
4772
+ }
4484
4773
  var METHODS = {
4485
4774
  ...WALLET_METHODS,
4486
4775
  ...FILE_METHODS,
@@ -4496,6 +4785,7 @@ var METHODS = {
4496
4785
  ...APP_CHAT_METHODS,
4497
4786
  async status(ctx) {
4498
4787
  const s = state(ctx);
4788
+ const seen = ctx.mode === "daemon" ? s.transport.discovery : void 0;
4499
4789
  return {
4500
4790
  version: ctx.version,
4501
4791
  profile: ctx.runtime.paths.name,
@@ -4510,7 +4800,11 @@ var METHODS = {
4510
4800
  groups: s.groups.length,
4511
4801
  discovery: {
4512
4802
  protocol: s.transport.protocol,
4513
- relays: s.transport.relays
4803
+ relays: s.transport.relays,
4804
+ ...seen && {
4805
+ health: seen.relays,
4806
+ via: seen.path?.via ?? null
4807
+ }
4514
4808
  },
4515
4809
  events: { lastSeq: ctx.hub.lastSeq },
4516
4810
  ...ctx.listen && { listen: true }
@@ -4543,7 +4837,7 @@ var METHODS = {
4543
4837
  return statusJson(node(ctx).getOwnStatus().status);
4544
4838
  },
4545
4839
  async "profile.get"(ctx) {
4546
- const { settings } = state(ctx);
4840
+ const settings = settingsOf(ctx);
4547
4841
  return {
4548
4842
  profile: ctx.runtime.paths.name,
4549
4843
  name: settings.nick || null,
@@ -4561,7 +4855,7 @@ var METHODS = {
4561
4855
  return METHODS["profile.get"](ctx, {});
4562
4856
  },
4563
4857
  async "settings.get"(ctx, params) {
4564
- return redactSettings(settingsInEffect(state(ctx).settings), bool(params, "showSecret"));
4858
+ return redactSettings(settingsInEffect(settingsOf(ctx)), bool(params, "showSecret"));
4565
4859
  },
4566
4860
  async "settings.set"(ctx, params) {
4567
4861
  const patch = {};
@@ -4598,7 +4892,7 @@ var METHODS = {
4598
4892
  throw relayRefused(error, patch);
4599
4893
  });
4600
4894
  return {
4601
- ...redactSettings(settingsInEffect(state(ctx).settings)),
4895
+ ...redactSettings(settingsInEffect(settingsOf(ctx))),
4602
4896
  ...warning ? { warning } : {}
4603
4897
  };
4604
4898
  },
@@ -4779,15 +5073,16 @@ var METHODS = {
4779
5073
  const kept = seconds ? keepTyping(ctx, { linkId: link.id }, seconds * 1e3, word) : null;
4780
5074
  const open = (s) => s.links.find((l) => l.id === link.id)?.dataLink === "open";
4781
5075
  if (kept && ctx.mode === "one-shot") await keepOneShot(ctx, { linkId: link.id }, kept, open);
5076
+ const now = state(ctx);
4782
5077
  return {
4783
5078
  chat: link.id,
4784
5079
  typing,
4785
5080
  ...typing ? { kind } : {},
4786
5081
  ...status ? { status } : {},
4787
- live: open(state(ctx)),
4788
- sendTyping: state(ctx).settings.sendTyping !== false,
5082
+ live: open(now),
5083
+ sendTyping: now.settings.sendTyping !== false,
4789
5084
  ...until ? { until } : {},
4790
- ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
5085
+ ...!kept && ctx.mode === "one-shot" && { note: typing ? ONE_SHOT_TYPING : ONE_SHOT_TYPING_STOP }
4791
5086
  };
4792
5087
  },
4793
5088
  /**
@@ -4904,13 +5199,14 @@ var METHODS = {
4904
5199
  * took it), each file until its transfer is done. What a chat refused comes back per chat; any refusal fails the call.
4905
5200
  */
4906
5201
  async "chat.forward"(ctx, params) {
4907
- const from = chatOrGroup(ctx, str(params, "chat", true));
5202
+ const s = state(ctx);
5203
+ const from = chatOrGroup(ctx, str(params, "chat", true), s);
4908
5204
  const messageIds = [...new Set(list(params, "messages"))];
4909
5205
  if (!messageIds.length) throw new CliError("bad_request", "Name the messages to forward (their ids, from history or an event)");
4910
5206
  if (messageIds.length > 30) throw new CliError("bad_request", `Forward at most 30 messages at once, not ${messageIds.length}`);
4911
5207
  const to = [];
4912
5208
  for (const ref of new Set(list(params, "to"))) {
4913
- const target = chatOrGroup(ctx, ref);
5209
+ const target = chatOrGroup(ctx, ref, s);
4914
5210
  if (to.some((t) => t.linkId === target.linkId)) continue;
4915
5211
  if (to.length === 5) throw new CliError("bad_request", `Forward to at most 5 chats and groups at once`);
4916
5212
  to.push(target);
@@ -4955,32 +5251,50 @@ var METHODS = {
4955
5251
  sent: result.sent,
4956
5252
  error: result.error
4957
5253
  }));
5254
+ let short;
5255
+ const waited = async (wait, now) => {
5256
+ if (short) return now();
5257
+ try {
5258
+ return await wait();
5259
+ } catch (error) {
5260
+ short = asCliError(error);
5261
+ return now();
5262
+ }
5263
+ };
4958
5264
  for (const [i, result] of out.entries()) if (to[i].group) {
4959
5265
  let edges;
4960
5266
  for (const messageId of result.messageIds) {
4961
- const took = groupWait === "sent" ? await waitForGroupFrame(ctx, to[i].id, messageId, void 0, ms) : node(ctx).groupTaken({
5267
+ const taken = () => node(ctx).groupTaken({
4962
5268
  groupId: to[i].id,
4963
5269
  messageId
4964
5270
  });
5271
+ const took = groupWait === "sent" ? await waited(() => waitForGroupFrame(ctx, to[i].id, messageId, void 0, ms), taken) : taken();
4965
5272
  edges = Math.min(edges ?? took, took);
4966
5273
  }
4967
5274
  result.edges = edges ?? 0;
4968
5275
  }
4969
5276
  if (wait === "sent") for (const [i, result] of out.entries()) for (const messageId of result.messageIds) {
4970
5277
  if (to[i].group) continue;
4971
- const sent = await node(ctx).getMessage(to[i].id, messageId);
4972
- if (sent?.file) await FILE_METHODS["file.wait"](ctx, {
4973
- chat: to[i].id,
4974
- file: sent.file.id,
4975
- timeout: ms / 1e3
4976
- });
4977
- else await waitForMessage(ctx, to[i].id, messageId, "sent", ms);
5278
+ await waited(async () => {
5279
+ const sent = await node(ctx).getMessage(to[i].id, messageId);
5280
+ if (sent?.file) await FILE_METHODS["file.wait"](ctx, {
5281
+ chat: to[i].id,
5282
+ file: sent.file.id,
5283
+ timeout: ms / 1e3
5284
+ });
5285
+ else await waitForMessage(ctx, to[i].id, messageId, "sent", ms);
5286
+ }, () => void 0);
4978
5287
  }
4979
5288
  const failed = out.filter((r) => r.error);
4980
5289
  if (failed.length) throw new CliError(failed.length === out.length ? "refused" : "engine", failed.map((r) => `${r.to}: ${r.error}`).join("; "), {
4981
5290
  from: from.id,
4982
5291
  results: out
4983
5292
  });
5293
+ if (short) throw new CliError(short.code, short.message, {
5294
+ ...short.details,
5295
+ from: from.id,
5296
+ results: out
5297
+ });
4984
5298
  return {
4985
5299
  from: from.id,
4986
5300
  results: out
@@ -5010,6 +5324,7 @@ var METHODS = {
5010
5324
  };
5011
5325
  },
5012
5326
  async "chat.delete"(ctx, params) {
5327
+ const purge = bool(params, "purge"), purged = purge ? { purged: true } : {};
5013
5328
  if (bool(params, "everyone")) {
5014
5329
  const target = chatOrGroup(ctx, str(params, "chat", true));
5015
5330
  const wait = oneOf(params, "wait", [
@@ -5037,6 +5352,7 @@ var METHODS = {
5037
5352
  messageId: message.id
5038
5353
  });
5039
5354
  if (result.error) throw new CliError(result.refused ? "refused" : "unavailable", result.error);
5355
+ if (purge) await purgeMessage(ctx, message);
5040
5356
  if (target.group) {
5041
5357
  const e = result.e;
5042
5358
  const edges = !e ? 0 : wait === "sent" ? await waitForGroupFrame(ctx, target.id, message.id, e, ms) : node(ctx).groupTaken({
@@ -5050,7 +5366,8 @@ var METHODS = {
5050
5366
  deleted: message.id,
5051
5367
  everyone: true,
5052
5368
  sent: edges > 0,
5053
- edges
5369
+ edges,
5370
+ ...purged
5054
5371
  };
5055
5372
  }
5056
5373
  if (wait === "confirmed") await waitForRemoval(ctx, target.linkId, message.id, ms);
@@ -5062,13 +5379,30 @@ var METHODS = {
5062
5379
  confirmed: !node(ctx).removalPending({
5063
5380
  linkId: target.linkId,
5064
5381
  messageId: message.id
5065
- })
5382
+ }),
5383
+ ...purged
5066
5384
  };
5067
5385
  }
5068
- const ref = str(params, "message") ?? "<message>";
5069
- const link = chatNotGroup(ctx, params, "message delete", `${/^[\w.:<>-]+$/.test(ref) ? ref : JSON.stringify(ref)} --everyone`);
5386
+ const ref = str(params, "message") ?? "<message>", typed = str(params, "chat", true);
5387
+ const reachesGroup = (name) => {
5388
+ try {
5389
+ return "group" in findChatOrGroup(state(ctx).links, state(ctx).groups, name);
5390
+ } catch {
5391
+ return false;
5392
+ }
5393
+ };
5394
+ let link;
5395
+ try {
5396
+ link = notAGroup(ctx, params, () => chatOf(ctx, params), (shown, id) => `ghostly message delete ${groupPrefixed(typed) === null && reachesGroup(typed) ? shown : shellWord(groupPrefixed(typed) === null ? `group:${typed}` : typed, `group:${id}`)} ${ref === "<message>" ? ref : shellWord(ref, "<message>")} --everyone${purge ? " --purge" : ""}`);
5397
+ } catch (error) {
5398
+ const group = error instanceof CliError ? error.details?.group : void 0;
5399
+ const theirs = typeof group === "string" && ref !== "<message>" ? await messageOf(ctx, `group:${group}`, ref).catch(() => void 0) : void 0;
5400
+ if (theirs && theirs.sender !== "me") throw new CliError("not_found", `${JSON.stringify(typed)} is a group, and ${JSON.stringify(ref)} is another member's message in it: only its author deletes a group's message, for everyone`, { group });
5401
+ throw error;
5402
+ }
5070
5403
  const messageId = str(params, "message", true);
5071
- if (!await node(ctx).getMessage(link.id, messageId)) throw noMessage(messageId, {
5404
+ const message = await node(ctx).getMessage(link.id, messageId);
5405
+ if (!message) throw noMessage(messageId, {
5072
5406
  group: false,
5073
5407
  ref: str(params, "chat", true)
5074
5408
  });
@@ -5076,11 +5410,13 @@ var METHODS = {
5076
5410
  linkId: link.id,
5077
5411
  messageId
5078
5412
  });
5413
+ if (purge) await purgeMessage(ctx, message);
5079
5414
  return {
5080
5415
  chat: link.id,
5081
5416
  messageId,
5082
5417
  deleted: messageId,
5083
- everyone
5418
+ everyone,
5419
+ ...purged
5084
5420
  };
5085
5421
  },
5086
5422
  /** A chat's or a group's (`group:<id>`, or its name) message, as the app's details show it; a group's said `No chat`. */
@@ -5205,20 +5541,19 @@ var METHODS = {
5205
5541
  });
5206
5542
  let link = null;
5207
5543
  if (profile === "community") ({link} = await node(ctx).enableGroupLink({ groupId }));
5208
- return {
5209
- group: groupId,
5210
- link
5211
- };
5544
+ return withUrl(groupId, link);
5212
5545
  },
5213
5546
  async "group.join"(ctx, params) {
5214
5547
  let groupId;
5548
+ const link = str(params, "link", true);
5549
+ const before = state(ctx).groups;
5215
5550
  try {
5216
- ({groupId} = await node(ctx).joinGroupByLink({ link: str(params, "link", true) }));
5551
+ ({groupId} = await node(ctx).joinGroupByLink({ link }));
5217
5552
  } catch (error) {
5218
5553
  if (error instanceof Error && error.message === "This is not a link to a group") throw new CliError("bad_request", error.message);
5219
5554
  throw error;
5220
5555
  }
5221
- return { group: groupId };
5556
+ return letIn(ctx, groupId, link, before.find((g) => g.id === groupId));
5222
5557
  },
5223
5558
  async "group.list"(ctx, params) {
5224
5559
  const showSecret = bool(params, "showSecret");
@@ -5395,17 +5730,17 @@ var METHODS = {
5395
5730
  sayTyping(ctx, target, typing, word);
5396
5731
  const until = seconds ? Date.now() + seconds * 1e3 : null;
5397
5732
  const kept = seconds ? keepTyping(ctx, target, seconds * 1e3, word) : null;
5398
- const reached = (s) => (s.groups.find((g) => g.id === group.id) ?? group).members.filter((m) => !m.me && m.online && !m.viaHub).length;
5399
- if (kept && ctx.mode === "one-shot") await keepOneShot(ctx, target, kept, (s) => reached(s) > 0);
5733
+ const reached = (now) => (now ?? group).members.filter((m) => !m.me && m.online && !m.viaHub).length;
5734
+ if (kept && ctx.mode === "one-shot") await keepOneShot(ctx, target, kept, (s) => reached(s.groups.find((g) => g.id === group.id)) > 0);
5400
5735
  return {
5401
5736
  group: group.id,
5402
5737
  typing,
5403
5738
  ...typing ? { kind } : {},
5404
5739
  ...status ? { status } : {},
5405
- reached: reached(state(ctx)),
5406
- sendTyping: state(ctx).settings.sendTyping !== false,
5740
+ reached: reached(groupById(ctx, group.id)),
5741
+ sendTyping: settingsOf(ctx).sendTyping !== false,
5407
5742
  ...until ? { until } : {},
5408
- ...!kept && ctx.mode === "one-shot" && { note: ONE_SHOT_TYPING }
5743
+ ...!kept && ctx.mode === "one-shot" && { note: typing ? ONE_SHOT_TYPING : ONE_SHOT_TYPING_STOP }
5409
5744
  };
5410
5745
  },
5411
5746
  async "group.leave"(ctx, params) {
@@ -5429,6 +5764,7 @@ var METHODS = {
5429
5764
  },
5430
5765
  async "group.accept"(ctx, params) {
5431
5766
  const group = groupOf(ctx, params);
5767
+ if (!group.invitation) throw new CliError("refused", `${outOf(group) ?? `You are in ${group.name} already`}: there is no invitation to accept`);
5432
5768
  await node(ctx).acceptGroupInvitation({ groupId: group.id });
5433
5769
  return { group: group.id };
5434
5770
  },
@@ -5655,8 +5991,8 @@ function notAGroup(ctx, params, chat, hint) {
5655
5991
  } catch {
5656
5992
  throw error;
5657
5993
  }
5658
- const shown = /^[\w.:-]+$/.test(named) ? named : JSON.stringify(named);
5659
- throw new CliError("not_found", `${JSON.stringify(ref)} is a group, not a chat: ${hint(shown)}`, { group: group.id });
5994
+ const shown = shellWord(named, group.id);
5995
+ throw new CliError("not_found", `${JSON.stringify(ref)} is a group, not a chat: ${hint(shown, group.id)}`, { group: group.id });
5660
5996
  }
5661
5997
  }
5662
5998
  /** The chat a chat command with a group twin names: a group's name says so, with `command`, the twin (see `notAGroup`). */
@@ -5842,14 +6178,16 @@ function quoteChecked(json, message, originals) {
5842
6178
  };
5843
6179
  }
5844
6180
  var API_METHODS = Object.keys(METHODS);
5845
- /** Runs one method of the API: one the table lists itself (`constructor`, which every object has, is none). */
5846
- async function callApi(ctx, method, params = {}) {
6181
+ /**
6182
+ * Runs one method of the API: one the table lists itself (`constructor`, which every object has, is none). `call`: who
6183
+ * asked, from a daemon's connection (`host.ts`).
6184
+ */
6185
+ async function callApi(ctx, method, params = {}, call) {
5847
6186
  const run = Object.hasOwn(METHODS, method) ? METHODS[method] : void 0;
5848
6187
  if (!run) throw new CliError("not_found", `No method ${method}`);
5849
6188
  if (params === null || typeof params !== "object" || Array.isArray(params)) throw new CliError("bad_request", "params must be an object");
5850
- return run(ctx, await withStoredIds(ctx, params));
6189
+ return run(ctx, await withStoredIds(ctx, params), call);
5851
6190
  }
5852
- //#endregion
5853
6191
  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 };
5854
6192
 
5855
- //# sourceMappingURL=api-DBlaoz8i.js.map
6193
+ //# sourceMappingURL=api-DLzCtePC.js.map