@ghostlytools/cli 1.7.3 → 1.8.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 (106) hide show
  1. package/README.md +30 -19
  2. package/SKILL.md +6 -4
  3. package/dist/assets/{api-B42F9ytB.js → api-Dj1yn0px.js} +2 -2
  4. package/dist/assets/{api-tf-wAAnB.js → api-I_KbuXHa.js} +192 -88
  5. package/dist/assets/api-I_KbuXHa.js.map +1 -0
  6. package/dist/assets/{apiKit-DJb9hulp.js → apiKit-C-_PWZvy.js} +44 -9
  7. package/dist/assets/apiKit-C-_PWZvy.js.map +1 -0
  8. package/dist/assets/{apps-DIrWmLgL.js → apps-DKIe8VjF.js} +11 -8
  9. package/dist/assets/apps-DKIe8VjF.js.map +1 -0
  10. package/dist/assets/{apps-BfoDISRg.js → apps-DbEfL_3b.js} +1 -1
  11. package/dist/assets/{arkade-CJAhhgPQ.js → arkade-k1bdSm70.js} +2 -2
  12. package/dist/assets/{arkade-CJAhhgPQ.js.map → arkade-k1bdSm70.js.map} +1 -1
  13. package/dist/assets/{backup-BkUeeduy.js → backup-Cdd6-HNu.js} +1 -1
  14. package/dist/assets/{backup-Bko-AAm0.js → backup-beKfbfNk.js} +7 -7
  15. package/dist/assets/{backup-Bko-AAm0.js.map → backup-beKfbfNk.js.map} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{blobFiles-Bckz9fjp.js → blobFiles-DOQDRdDI.js} +3 -3
  19. package/dist/assets/{blobFiles-Bckz9fjp.js.map → blobFiles-DOQDRdDI.js.map} +1 -1
  20. package/dist/assets/buttons-BO1_7V4L.js +2 -0
  21. package/dist/assets/{buttons-DeA6Yddq.js → buttons-ClI13rdv.js} +7 -6
  22. package/dist/assets/buttons-ClI13rdv.js.map +1 -0
  23. package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-DtrL5lE5.js} +2 -2
  24. package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-DtrL5lE5.js.map} +1 -1
  25. package/dist/assets/{envelope-Cz5fc7BM.js → envelope-B88yiCQj.js} +2 -2
  26. package/dist/assets/{envelope-Cz5fc7BM.js.map → envelope-B88yiCQj.js.map} +1 -1
  27. package/dist/assets/{errors-mnjSQlbX.js → errors-R4S2SAEM.js} +8 -3
  28. package/dist/assets/errors-R4S2SAEM.js.map +1 -0
  29. package/dist/assets/{fileBytes-OolN5cSY.js → fileBytes-BPDKufla.js} +1 -1
  30. package/dist/assets/{fileBytes-BD0v3rRG.js → fileBytes-DNgrRL0R.js} +3 -3
  31. package/dist/assets/{fileBytes-BD0v3rRG.js.map → fileBytes-DNgrRL0R.js.map} +1 -1
  32. package/dist/assets/{fileBytes-_fd-2JRY.js → fileBytes-Q3ehcEr8.js} +2 -2
  33. package/dist/assets/{fileBytes-_fd-2JRY.js.map → fileBytes-Q3ehcEr8.js.map} +1 -1
  34. package/dist/assets/fileBytesIdb-DZcESfTt.js +2 -0
  35. package/dist/assets/{fileBytesIdb-NtA8r9EM.js → fileBytesIdb-Dm1EyEbT.js} +3 -3
  36. package/dist/assets/{fileBytesIdb-NtA8r9EM.js.map → fileBytesIdb-Dm1EyEbT.js.map} +1 -1
  37. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js → fileBytesOpfs-ZGD21c4Q.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js.map → fileBytesOpfs-ZGD21c4Q.js.map} +1 -1
  39. package/dist/assets/{groupFiles-BlZRBWpt.js → groupFiles-DjQc5XXv.js} +151 -28
  40. package/dist/assets/groupFiles-DjQc5XXv.js.map +1 -0
  41. package/dist/assets/{host-BX0DmKW6.js → host-CNWGB3-j.js} +86 -24
  42. package/dist/assets/host-CNWGB3-j.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-DitYDnXx.js → hyperdhtRelay-g7eXzf5h.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-DitYDnXx.js.map → hyperdhtRelay-g7eXzf5h.js.map} +1 -1
  45. package/dist/assets/{idb-BlH8-O3R.js → idb-BkOJES5_.js} +5 -3
  46. package/dist/assets/idb-BkOJES5_.js.map +1 -0
  47. package/dist/assets/{irohWeb-R3bcd34h.js → irohWeb-Bx8dI4be.js} +2 -2
  48. package/dist/assets/{irohWeb-R3bcd34h.js.map → irohWeb-Bx8dI4be.js.map} +1 -1
  49. package/dist/assets/{main-6QOSvQ8b.js → main-BRxhBctJ.js} +462 -126
  50. package/dist/assets/main-BRxhBctJ.js.map +1 -0
  51. package/dist/assets/{mainline-BfwezHWi.js → mainline-CwuS6ngj.js} +39 -12
  52. package/dist/assets/mainline-CwuS6ngj.js.map +1 -0
  53. package/dist/assets/mints-BaOmx517.js +2 -0
  54. package/dist/assets/{mints-BrlY773j.js → mints-j5XAOk4f.js} +15 -3
  55. package/dist/assets/mints-j5XAOk4f.js.map +1 -0
  56. package/dist/assets/{networkReason-Ba9415nn.js → networkReason-CIAMieQm.js} +3 -3
  57. package/dist/assets/{networkReason-Ba9415nn.js.map → networkReason-CIAMieQm.js.map} +1 -1
  58. package/dist/assets/{nwc-ovXSN2M2.js → nwc-C9JLJJkL.js} +3 -3
  59. package/dist/assets/{nwc-ovXSN2M2.js.map → nwc-C9JLJJkL.js.map} +1 -1
  60. package/dist/assets/{nwcProvider-BzZbfFP3.js → nwcProvider-pFMrsUJh.js} +2 -2
  61. package/dist/assets/{nwcProvider-BzZbfFP3.js.map → nwcProvider-pFMrsUJh.js.map} +1 -1
  62. package/dist/assets/{profiles-C6XWqre5.js → profiles-MFtCmJwK.js} +104 -10
  63. package/dist/assets/profiles-MFtCmJwK.js.map +1 -0
  64. package/dist/assets/{registry-B0Uv9yL6.js → registry-Cks7FA_o.js} +45 -14
  65. package/dist/assets/registry-Cks7FA_o.js.map +1 -0
  66. package/dist/assets/{registry-CFtlhWCI.js → registry-DY2ixQfU.js} +1 -1
  67. package/dist/assets/{resolve-BzFG4WDU.js → resolve-C4Y2HPqQ.js} +79 -30
  68. package/dist/assets/resolve-C4Y2HPqQ.js.map +1 -0
  69. package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-BCRCjhdF.js} +27 -3
  70. package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-BCRCjhdF.js.map} +1 -1
  71. package/dist/assets/{server-BGCuHbmQ.js → server-D9RAmGdm.js} +1398 -358
  72. package/dist/assets/server-D9RAmGdm.js.map +1 -0
  73. package/dist/assets/{src-DWw2hUE5.js → src-1RU4TilT.js} +1416 -234
  74. package/dist/assets/src-1RU4TilT.js.map +1 -0
  75. package/dist/assets/{translate-DObb-1tq.js → translate-od5GbpvR.js} +19 -13
  76. package/dist/assets/translate-od5GbpvR.js.map +1 -0
  77. package/dist/assets/{usdt-Bkva90Vo.js → usdt-DldXV0MR.js} +3 -3
  78. package/dist/assets/{usdt-Bkva90Vo.js.map → usdt-DldXV0MR.js.map} +1 -1
  79. package/dist/assets/waitNotice-Ck3el3_Z.js +45 -0
  80. package/dist/assets/waitNotice-Ck3el3_Z.js.map +1 -0
  81. package/dist/assets/{words-odSAoasK.js → words-BS2qq_vV.js} +7 -4
  82. package/dist/assets/words-BS2qq_vV.js.map +1 -0
  83. package/dist/ghostly.mjs +1 -1
  84. package/examples/claude-code-agent.sh +1 -1
  85. package/package.json +1 -1
  86. package/dist/assets/api-tf-wAAnB.js.map +0 -1
  87. package/dist/assets/apiKit-DJb9hulp.js.map +0 -1
  88. package/dist/assets/apps-DIrWmLgL.js.map +0 -1
  89. package/dist/assets/buttons-Be7u0V5g.js +0 -2
  90. package/dist/assets/buttons-DeA6Yddq.js.map +0 -1
  91. package/dist/assets/errors-mnjSQlbX.js.map +0 -1
  92. package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
  93. package/dist/assets/groupFiles-BlZRBWpt.js.map +0 -1
  94. package/dist/assets/host-BX0DmKW6.js.map +0 -1
  95. package/dist/assets/idb-BlH8-O3R.js.map +0 -1
  96. package/dist/assets/main-6QOSvQ8b.js.map +0 -1
  97. package/dist/assets/mainline-BfwezHWi.js.map +0 -1
  98. package/dist/assets/mints-BrlY773j.js.map +0 -1
  99. package/dist/assets/mints-CqTdA4Gk.js +0 -2
  100. package/dist/assets/profiles-C6XWqre5.js.map +0 -1
  101. package/dist/assets/registry-B0Uv9yL6.js.map +0 -1
  102. package/dist/assets/resolve-BzFG4WDU.js.map +0 -1
  103. package/dist/assets/server-BGCuHbmQ.js.map +0 -1
  104. package/dist/assets/src-DWw2hUE5.js.map +0 -1
  105. package/dist/assets/translate-DObb-1tq.js.map +0 -1
  106. package/dist/assets/words-odSAoasK.js.map +0 -1
@@ -1,16 +1,16 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $i as automaticTransport, $l as traceLink, $o as HANDOFF_HAVE, $r as vapidKeysMatch, $s as enrollHelloFrame, A as knockRecords, Aa as GROUP_REACTION_FRAME, Ac as appDigest, Al as classifyTurnRead, An as findEndpoint, Ao as formatLocalTarget, As as readHandoffDone, B as GROUP_READ_NOTE, Ba as pairedReplyAuthor, Bc as APP_STATEMENT_LIMITS, Bl as turnKeys, Bn as EngineError, Br as mayPin, Bs as setAckFrame, C as decodeCommunityLink, Ca as REMOVED_TEXT, Cc as readLinkRecord, Cl as devicePingFrame, Cr as rankHubs, Cs as handoffReleaseFrame, Cu as utf8Decode, D as encodeGroupEntryLink, Da as forwardedAgain, Dc as APP_BUNDLE_MAGIC, Dn as ENDPOINT, Do as WATCH_PEER_MS, Dr as shouldBeHub, Ds as newHandoffId, E as decodeGroupEntryLink, Ea as parseLinkPreview, Ec as APP_BUNDLE_LIMITS, El as webCryptoSigner, En as decodeBolt11, Eo as RELAY_POLL_INTERVALS, Er as readLobby, Es as handoffVersions, F as groupWakeFrame, Fa as reactionEmoji, Fc as pacer, Fi as dialDescriptors, Fl as nextTurnPosition, Fn as INVITE_TAKEN, Fo as encodeControl, Fr as TypingSender, Fs as readHandoffVerified, G as GROUP_EDIT_TEXT_BYTES, Gc as isAppKey, Gr as WAKE_CALL_INTERVAL_MS, Gt as encodeDidDhtPacket, H as frameBytes, Ha as replySnippet, Hc as appRef, Hi as emptyIdentityLedger, Hl as turnStatedVerifier, Hn as engineText, Ho as contactRtcConfig, Hr as pinIsNewer, Hs as signTombstone, Ht as didDhtDocument, I as groupWakes, Ia as reactionIsNewer, Il as readTurnPacket, In as LIVENESS_PING_MS, Is as sealHandoffPiece, J as mentionsMember, Ji as lastSharedWithMe, Jo as LEGACY_SERVICES, Jr as newWakeToken, Js as enrollCancelFrame, Jt as ETHEREUM_USDT, K as carryMentions, Kc as isAppRef, Ki as receivedIdentityStatus, Ko as emptyLinkRecords, Kr as WakeLimiter, L as parseGroupWakeFrame, La as readReaction, Lc as readAppBundleAsync, Ll as signTurnPacket, Ln as PAIRED_FRAME_TOO_LARGE, Lo as RTC_CONFIG, Lr as typingActivity, M as readKnocks, Ma as ReactionWindow, Mi as CapsExchange, Ml as TURN_LAST_SEQUENCE, Mn as parseCashuRequestPayload, Mo as webLocalFetch, Mr as transferStalled, Ms as readHandoffHello, Na as nextReactionNumber, Ni as DHT_TEXT_CAPABILITY, Nl as TURN_MAX, Nn as parseFedimintRequestPayload, No as LIMITS, Ns as readHandoffPake, O as entryParams, Oa as readForwarded, Oc as APP_ICON_PATH, Ol as TURN_RAISE_READ_TIMEOUT_MS, On as cashuRequestPayload, Oo as presenceSeenAt, Or as ChatFiles, Os as readHandoffAck, P as GroupWakeLimiter, Pa as queueReaction, Pc as isAppUrl, Pi as capsDescriptors, Pl as firstDeviceSetSecret, Pn as GhostLink, Po as decodeControl, Ps as readHandoffTurnFrame, Qc as parseImageMeta, Qi as TRANSPORTS, Qo as HANDOFF_DONE, Qr as checkPushEndpoint, Qs as enrollGrantFrame, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as validReactionNumber, Rc as sha256Paced, Rl as signTurnRelease, Rn as pairedMessageFits, S as communityHasFrame, Sa as MAX_REMOVAL_NUMBER, Sc as readKnockSlot, Sl as deviceLinkPairing, So as DirectPathWatch, Sr as pickHubs, Ss as handoffPakeFrame, Su as toZ32, Ta as dhtEditId, Tc as seenEntry, Tl as seedSigner, Tr as readBeaconHead, Ts as handoffStreamKey, Ua as BUTTON_ID, Ul as turnVerifierMark, Un as parseEngineError, Ur as pinNumberHolds, Us as verifySetUpdate, Ut as didDhtFromPublicKey, V as GroupSession, Va as readReply, Vc as appFingerprint, Vl as turnName, Vn as engineError, Vr as nextPinNumber, Vs as setUpdateFrame, Wc as isAppHash, Wl as DEFAULT_RELAYS, Wn as GROUP_FILE_LIMITS, Wo as parseCallSignal, Wr as readPin, Wt as encodeDidDhtDeactivated, Xi as emptyProofLedger, Xl as currentRelays, Xo as HANDOFF_ACK, Xr as relayRequest, Xs as enrollDigits, Xt as ONCHAIN_PROVIDER, Y as groupName, Yi as PeerProofs, Yn as groupFileFallback, Yo as serviceIdFromName, Yr as parseWakeFrame, Ys as enrollCancelReason, Yt as EVM_TEST_CHAINS, Za as STATUS_CARD_LIMITS, Zi as validExternalKey, Zl as normalizeRelayUrl, Zn as readGroupFileMeta, Zo as HANDOFF_CANCEL, Zr as wakeRequest, Zs as enrollDoneFrame, Zt as PaymentPreflightError, _ as openGroupTyping, _c as knockSlotRecords, _i as readManifest, _l as ENROLL_CAPABILITY, _o as parseGroupCommit, _r as lobbyKeys, _s as handoffDigest, _u as bytesEqual, a as appStoreDecision, aa as DHT_FILE_CAPABILITY, ac as endedRequests, ai as APPS_CAPABILITY, al as readContactLink, an as assertWholeSats, as as HANDOFF_TIMINGS, au as createRelayPayload, b as CommunitySession, ba as EDIT_BUFFER_MS, bc as mergeContactKnocks, bl as deviceEchoNonce, bo as verifyCommitSignature, br as mergeLobby, bs as handoffManifestFrames, bu as randomBytes, c as planAppUpdate, ca as sanitizeFileName, cc as planKnocks, ci as STATUS_CARD_CAPABILITY, cl as readDeviceInvite, cn as walletNetworkOf, co as claimedTime, cr as MESH_HUBS, cs as filePartName, dc as turnOff, di as HOLD_DATED_BACK_MS, dl as decodeInviteCode, dn as sparkAddressKind, do as shownTime, dr as pickMeshHubs, ds as handoffAttemptSucceeded, du as identityFromSeedB64, ec as enrollProofFrame, ei as APP_RANGE_LIMITS, el as canonicalJson, en as TEST_USDT_FAUCET_AMOUNT, es as HANDOFF_HELLO, eu as budgetRetryMs, f as readAppStoreSteps, fc as ContactRequestError, fi as HOLD_LIMITS, fl as encodeInviteCode, fn as sparkInvoiceDetails, fo as GROUP_ADMIN_OFF_ERROR, fr as COMMUNITY_TOPOLOGY, fs as handoffBusyFrame, fu as publicKeyFromZ32, g as groupTypingEpoch, ga as parseVoiceMeta, gc as knockSlotOf, gi as newMailbox, gl as DEVICES_CAPABILITY, go as commitHash, gr as freshHubs, gs as handoffDataFrame, gt as normalizeAtprotoHandle, gu as sanitizeDisplayText, h as GroupTypingBoard, ha as fileMessageText, hc as knockSlotIdentity, hi as isHoldUrl, hn as isPubkyKey, ho as MEMBER_KEY, hr as doorHubs, hs as handoffContextProof, ht as isAtprotoDid, hu as sanitizeAvatar, i as appRevocationFor, ia as peekDhtMailbox, ic as clearMissed, ii as isAppVersion, il as encodeContactLink, in as assertTokenUnits, io as sameButtonText, is as HANDOFF_REQUEST, j as mergeKnocks, ja as REACTION_LIMITS, jc as appViewOf, jl as turnPutSummary, jn as isFederationId, jo as parseLocalTarget, jr as transferEnded, js as readHandoffHave, k as knockIdentity, ka as COMMUNITY_REACTION_FRAME, kl as TURN_SETTLE_MS, kn as fedimintRequestPayload, ko as GhostlyHttpError, kr as FILE_LIMITS, ks as readHandoffCancel, l as APP_STORE_LIMITS, la as sanitizeMime, lc as settleRequest, li as UPGRADE_CAPABILITY, ll as OwnInviteError, ln as SPARK_NETWORKS, lo as heardTime, lr as mayBeHub, ls as handoffAttemptAllowed, lu as createIdentity, mc as contactDay, mi as HoldRefusedError, ml as inviteOwnership, mr as beaconRecords, ms as handoffContext, n as readX401SdJwtVc, nc as readEnrollHello, nl as readCanonicalJson, nn as WALLET_NETWORKS, ns as HANDOFF_PAKE, nu as withRequestOptions, o as appUpdateDecision, oa as dhtFileId, oc as inboxRecord, oi as BUTTONS_CAPABILITY, ol as createDeviceInvite, on as formatPaymentAmount, oo as statusCardText, or as groupSignalFrame, os as HANDOFF_VERIFIED, pc as REQUEST_LIFETIME_MS, pi as HoldKeys, pl as inviteLink, pn as isBitcoinAddress, po as GROUP_MEMBER_CAP, pr as beaconKeys, ps as handoffCancelFrame, pu as verify, q as parseCommunityEdit, qc as readAppRevocation, ql as RelayTransport, qo as HTTP_SERVICE_PROTO, qr as deviceWakeRequest, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_MESSAGE_TTL, rc as verifyEnrollProof, ri as chatAppId, rl as createContactLink, rn as arkAddressPrefix, ro as checkStatusCard, rs as HANDOFF_PIECE_BYTES, ru as PacketTooLargeError, s as checkAppBeforeRun, sa as formatFileSize, sc as newInbox, si as EDIT_CAPABILITY, sl as deviceInviteJoinerParams, sn as validatePaymentTarget, so as arrivalKey, sr as readGroupSignal, ss as NO_ATTEMPTS, t as newX401HolderKey, tc as readEnrollGrant, ti as isServeId, tn as USDT_PUBLIC_RPC, tr as CarriedTransport, ts as HANDOFF_OFFER, tu as isDiscoveryBudgetError, uc as takeRequest, ui as HOLD_CAPABILITY, ul as createChatInvite, un as SPARK_PROVIDER, uo as receivedTimestamp, ur as meshHubs, us as handoffAttemptFailed, uu as identityFromSeed, v as sealGroupTyping, vc as linkRecords, vl as HANDOFF_CAPABILITY, vo as rosterAdmin, vr as lobbyRecords, vs as handoffEphemeral, vu as fromBase64Url, w as encodeCommunityLink, wa as RateWindow, wc as requestRecords, wl as newDeviceSetSecret, wo as DHT_POLL_INTERVALS, wr as readBeacon, ws as handoffRetryAfter, wu as utf8Encode, x as GROUP_READ_NOTE_COMMUNITY, xa as EDIT_RATE_WINDOW_MS, xc as openRequest, xl as deviceKeyZ32, xo as edgeParams, xr as newerHead, xs as handoffOfferFrame, xu as toBase64Url, y as COMMUNITY_LIMITS, ya as parseVideoMeta, yc as makeStampPaced, yl as deviceEchoFrame, yo as rosterHas, yr as mergeBeacon, ys as handoffHelloFrame, za as wireReaction, zl as turnInstance, zn as pairedMessageFrame, zr as PIN_LIMITS, zs as readSetUpdate } from "./src-DWw2hUE5.js";
2
+ import { $c as isAppHash, $i as validExternalKey, $l as DEFAULT_RELAYS, $o as parseCallSignal, $r as wakeRequest, $t as SEPOLIA_TEST_USDT, A as knockIdentity, Aa as parseLinkPreview, Ac as openRequest, Al as deviceKeyZ32, An as fedimintRequestPayload, Ao as DirectPathWatch, Ar as FILE_LIMITS, As as handoffOfferFrame, Au as toBase64Url, Ba as reactionIsNewer, Bc as appViewOf, Bl as turnPutSummary, Bn as pairedMessageFrame, Bo as parseLocalTarget, Bs as readHandoffHave, C as communityHasFrame, Ca as EDIT_RATE_WINDOW_MS, Cc as contactDay, Cl as inviteOwnership, Co as rosterHas, Cr as pickHubs, Cs as handoffContext, D as decodeGroupEntryLink, Da as dhtEditId, Dc as linkRecords, Dl as HANDOFF_CAPABILITY, Dn as decodeBolt11, Do as RatchetBox, Dr as readLobby, Ds as handoffEphemeral, Du as fromBase64Url, Ea as RateWindow, Ec as knockSlotRecords, El as ENROLL_CAPABILITY, Eo as RATCHET_CAPABILITY, Er as readBeaconHead, Es as handoffDigest, Eu as bytesEqual, F as GroupWakeLimiter, Fa as REACTION_LIMITS, Fc as APP_BUNDLE_LIMITS, Fi as DHT_TEXT_CAPABILITY, Fl as webCryptoSigner, Fn as GhostLink, Fo as RELAY_POLL_INTERVALS, Fs as handoffVersions, Ga as readReply, Gl as readTurnPacket, Gn as GROUP_FILE_LIMITS, Gr as pinNumberHolds, Gs as sealHandoffPiece, Gt as encodeDidDhtDeactivated, H as GroupSession, Ha as validReactionNumber, Hl as TURN_MAX, Hn as engineError, Ho as LIMITS, Hr as mayPin, Hs as readHandoffPake, I as groupWakeFrame, Ia as ReactionWindow, Ic as APP_BUNDLE_MAGIC, Ii as capsDescriptors, In as INVITE_TAKEN, Io as WATCH_PEER_MS, Is as newHandoffId, J as parseCommunityEdit, Ji as receivedIdentityStatus, Jl as turnInstance, Jr as WakeLimiter, Js as readSetUpdate, Jt as signDidDhtPacket, K as GROUP_EDIT_TEXT_BYTES, Ka as replySnippet, Kc as readAppBundleAsync, Kl as signTurnPacket, Ko as RTC_CONFIG, Kr as readPin, Kt as encodeDidDhtPacket, L as groupWakes, La as nextReactionNumber, Lc as APP_ICON_PATH, Li as dialDescriptors, Ll as TURN_RAISE_READ_TIMEOUT_MS, Ln as LIVENESS_PING_MS, Lo as presenceSeenAt, Lr as TypingSender, Ls as readHandoffAck, M as mergeKnocks, Ma as readForwarded, Mc as readLinkRecord, Ml as devicePingFrame, Mn as isFederationId, Mo as DHT_POLL_INTERVALS, Mr as sentWhole, Ms as handoffReleaseFrame, Mu as utf8Decode, N as readKnocks, Na as COMMUNITY_REACTION_FRAME, Nc as requestRecords, Nl as newDeviceSetSecret, Nn as parseCashuRequestPayload, Nr as transferEnded, Ns as handoffRetryAfter, Nu as utf8Encode, O as encodeGroupEntryLink, Oc as makeStampPaced, Ol as deviceEchoFrame, On as ENDPOINT, Oo as emptyRatchetState, Or as shouldBeHub, Os as handoffHelloFrame, Pa as GROUP_REACTION_FRAME, Pc as seenEntry, Pi as CapsExchange, Pl as seedSigner, Pn as parseFedimintRequestPayload, Po as PRESENCE_WINDOW, Pr as transferStalled, Ps as handoffStreamKey, Qi as emptyProofLedger, Ql as turnVerifierMark, Qn as readGroupFileMeta, Qr as relayRequest, Qs as verifySetUpdate, Qt as PaymentPreflightError, R as parseGroupWakeFrame, Ra as queueReaction, Rl as TURN_SETTLE_MS, Rn as PAIRED_FRAME_TOO_LARGE, Ro as GhostlyHttpError, Rs as readHandoffCancel, S as GROUP_READ_NOTE_COMMUNITY, Sa as EDIT_BUFFER_MS, Sc as REQUEST_LIFETIME_MS, Sl as inviteLink, So as rosterAdmin, Sr as newerHead, Ss as handoffCancelFrame, Su as verify, T as encodeCommunityLink, Ta as REMOVED_TEXT, Tc as knockSlotOf, Tl as DEVICES_CAPABILITY, To as edgeParams, Tr as readBeacon, Ts as handoffDataFrame, Tu as sanitizeDisplayText, U as frameBytes, Ua as wireReaction, Uc as isAppUrl, Ul as firstDeviceSetSecret, Un as engineText, Uo as decodeControl, Ur as nextPinNumber, Us as readHandoffTurnFrame, Ut as didDhtDocument, V as GROUP_READ_NOTE, Va as readReaction, Vl as TURN_LAST_SEQUENCE, Vn as EngineError, Vo as webLocalFetch, Vr as PIN_LIMITS, Vs as readHandoffHello, Wa as pairedReplyAuthor, Wc as pacer, Wi as emptyIdentityLedger, Wl as nextTurnPosition, Wn as parseEngineError, Wo as encodeControl, Wr as pinIsNewer, Ws as readHandoffVerified, Wt as didDhtFromPublicKey, X as groupName, Xc as appFingerprint, Xi as lastSharedWithMe, Xl as turnName, Xn as groupFileFallback, Xr as newWakeToken, Xs as setUpdateFrame, Xt as EVM_TEST_CHAINS, Y as mentionsMember, Yc as APP_STATEMENT_LIMITS, Yl as turnKeys, Yr as deviceWakeRequest, Ys as setAckFrame, Yt as ETHEREUM_USDT, Zc as appRef, Zi as PeerProofs, Zl as turnStatedVerifier, Zo as contactRtcConfig, Zr as parseWakeFrame, Zs as signTombstone, Zt as ONCHAIN_PROVIDER, _ as groupTypingEpoch, _a as fileMessageText, _c as planKnocks, _i as isHoldUrl, _l as readDeviceInvite, _o as GROUP_MEMBER_CAP, _r as freshHubs, _s as filePartName, _t as normalizeAtprotoHandle, a as appRevocationFor, aa as DHT_MESSAGE_TTL, ac as enrollDigits, ai as chatAppId, an as assertTokenUnits, as as HANDOFF_ACK, au as currentRelays, b as COMMUNITY_LIMITS, bc as turnOff, bl as decodeInviteCode, bo as commitHash, br as mergeBeacon, bs as handoffAttemptSucceeded, bu as identityFromSeedB64, c as checkAppBeforeRun, ca as dhtFileId, cc as enrollHelloFrame, ci as BUTTONS_CAPABILITY, cn as validatePaymentTarget, co as sameButtonText, cr as readGroupSignal, cs as HANDOFF_HAVE, cu as traceLink, da as sanitizeMime, dc as readEnrollHello, di as UPGRADE_CAPABILITY, dl as readCanonicalJson, dn as SPARK_PROVIDER, do as arrivalKey, dr as meshHubs, ds as HANDOFF_PAKE, du as withRequestOptions, ea as TRANSPORTS, ei as checkPushEndpoint, el as isAppKey, fc as verifyEnrollProof, fi as HOLD_CAPABILITY, fl as createContactLink, fn as sparkAddressKind, fo as claimedTime, fr as pickMeshHubs, fs as HANDOFF_PIECE_BYTES, fu as PacketTooLargeError, g as GroupTypingBoard, gc as newInbox, gi as HoldRefusedError, gl as deviceInviteJoinerParams, gn as isPubkyKey, go as GROUP_ADMIN_OFF_ERROR, gr as doorHubs, gs as NO_ATTEMPTS, gt as isAtprotoDid, hc as inboxRecord, hi as HoldKeys, hl as createDeviceInvite, ho as shownTime, hr as beaconRecords, hs as HANDOFF_VERIFIED, i as addedAppPermissions, ic as enrollCancelReason, in as arkAddressPrefix, is as serviceIdFromName, j as knockRecords, ja as forwardedAgain, jc as readKnockSlot, jl as deviceLinkPairing, jn as findEndpoint, js as handoffPakeFrame, ju as toZ32, k as entryParams, kc as mergeContactKnocks, kl as deviceEchoNonce, kn as cashuRequestPayload, ko as ratchetSessionOf, kr as ChatFiles, ks as handoffManifestFrames, ku as randomBytes, l as planAppUpdate, la as formatFileSize, lc as enrollProofFrame, li as EDIT_CAPABILITY, ll as canonicalJson, ln as walletNetworkOf, lr as MESH_HUBS, ls as HANDOFF_HELLO, lu as budgetRetryMs, mc as endedRequests, mi as HOLD_LIMITS, ml as readContactLink, mn as isBitcoinAddress, mo as receivedTimestamp, mr as beaconKeys, ms as HANDOFF_TIMINGS, mu as createRelayPayload, n as readX401SdJwtVc, ni as APP_RANGE_LIMITS, nl as readAppRevocation, nn as USDT_PUBLIC_RPC, nr as CarriedTransport, ns as HTTP_SERVICE_PROTO, nu as RelayTransport, o as appStoreDecision, oa as peekDhtMailbox, oc as enrollDoneFrame, oi as isAppVersion, on as assertWholeSats, os as HANDOFF_CANCEL, ou as normalizeRelayUrl, p as readAppStoreSteps, pc as clearMissed, pi as HOLD_DATED_BACK_MS, pl as encodeContactLink, pn as sparkInvoiceDetails, po as heardTime, pr as COMMUNITY_TOPOLOGY, ps as HANDOFF_REQUEST, q as carryMentions, qa as BUTTON_ID, qc as sha256Paced, ql as signTurnRelease, qr as WAKE_CALL_INTERVAL_MS, r as sameX401HolderJwk, rc as enrollCancelFrame, ri as isServeId, rn as WALLET_NETWORKS, rs as LEGACY_SERVICES, s as appUpdateDecision, sa as DHT_FILE_CAPABILITY, sc as enrollGrantFrame, si as APPS_CAPABILITY, sl as parseImageMeta, sn as formatPaymentAmount, so as checkStatusCard, sr as groupSignalFrame, ss as HANDOFF_DONE, t as newX401HolderKey, ta as automaticTransport, ti as vapidKeysMatch, tl as isAppRef, tn as TEST_USDT_FAUCET_AMOUNT, to as STATUS_CARD_LIMITS, ts as emptyLinkRecords, u as APP_STORE_LIMITS, ua as sanitizeFileName, uc as readEnrollGrant, ui as STATUS_CARD_CAPABILITY, un as SPARK_NETWORKS, uo as statusCardText, ur as mayBeHub, us as HANDOFF_OFFER, uu as isDiscoveryBudgetError, v as openGroupTyping, va as parseVoiceMeta, vc as settleRequest, vi as newMailbox, vl as OwnInviteError, vr as lobbyKeys, vs as handoffAttemptAllowed, vu as createIdentity, w as decodeCommunityLink, wa as MAX_REMOVAL_NUMBER, wc as knockSlotIdentity, wo as verifyCommitSignature, wr as rankHubs, ws as handoffContextProof, wu as sanitizeAvatar, x as CommunitySession, xa as parseVideoMeta, xc as ContactRequestError, xl as encodeInviteCode, xo as parseGroupCommit, xr as mergeLobby, xs as handoffBusyFrame, xu as publicKeyFromZ32, y as sealGroupTyping, yc as takeRequest, yi as readManifest, yl as createChatInvite, yo as MEMBER_KEY, yr as lobbyRecords, ys as handoffAttemptFailed, yu as identityFromSeed, z as GROUP_LIMITS, za as reactionEmoji, zc as appDigest, zl as classifyTurnRead, zn as pairedMessageFits, zo as formatLocalTarget, zr as typingActivity, zs as readHandoffDone } from "./src-1RU4TilT.js";
3
3
  import { i as SourceUnreachableError, n as PROVIDER_PLATFORMS, o as isNothingSpentError, r as SourceConfigError, t as NothingSpentError, u as redact } from "./types-C4_KafL_.js";
4
4
  import { t as bitcoindRpc } from "./bitcoindProvider-DGw3xBSa.js";
5
- import { t as nwc } from "./nwcProvider-BzZbfFP3.js";
6
- import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BlH8-O3R.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-Ba9415nn.js";
8
- import { $ as WrongNetworkError, A as IdentityProofs, B as ProviderSources, C as FileAppender, D as streamStored, E as storedSize, F as LightningCards, G as breezDatabaseInUse, H as CASHU_MINT_SOURCE, I as cardsKey, J as iceServerProblem, K as breezDatabasesFor, L as isRecoveryPhrase, M as sealSecret, N as whenDataKeyDropped, P as CASHU_CARD, Q as ModeGate, R as normalizePhrase, S as WALLET_TYPES, T as removeStored, U as cashuMint, V as sourceKey, W as breezDatabase, X as relayOnlyProblem, Y as iceServerSetting, Z as ModeChanged, _ as crossNetwork, a as storedGroupFiles, at as setSingleWriterGate, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as networkLabel, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as setAwayWallets, j as openSecret, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as refuseAway, o as groupReply, p as WALLET_NAMES, q as dropBreezDatabase, r as groupFileText, rt as requireTurn, s as pairedWireReply, t as GroupFileDesk, tt as awayFrom, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as lightningPaying } from "./groupFiles-BlZRBWpt.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-R3bcd34h.js";
10
- import { c as isTestMint, d as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-BrlY773j.js";
11
- import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch } from "./resolve-BzFG4WDU.js";
12
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-Cz5fc7BM.js";
13
- import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-BD0v3rRG.js";
5
+ import { t as nwc } from "./nwcProvider-pFMrsUJh.js";
6
+ import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BkOJES5_.js";
7
+ import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-CIAMieQm.js";
8
+ import { $ as ModeChanged, A as IdentityProofs, B as INVOICE_PACE, C as FileAppender, D as streamStored, E as storedSize, F as LightningCards, G as cashuMint, H as ProviderSources, I as cardsKey, J as breezDatabasesFor, K as breezDatabase, L as isRecoveryPhrase, M as sealSecret, N as whenDataKeyDropped, P as CASHU_CARD, Q as relayOnlyProblem, R as normalizePhrase, S as WALLET_TYPES, T as removeStored, U as sourceKey, V as nextInvoiceAsk, W as CASHU_MINT_SOURCE, X as iceServerProblem, Y as dropBreezDatabase, Z as iceServerSetting, _ as crossNetwork, a as storedGroupFiles, at as requireTurn, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as ModeGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as refuseAway, j as openSecret, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as networkLabel, o as groupReply, ot as setAwayWallets, p as WALLET_NAMES, q as breezDatabaseInUse, r as groupFileText, rt as awayFrom, s as pairedWireReply, st as setSingleWriterGate, t as GroupFileDesk, tt as WrongNetworkError, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as lightningPaying } from "./groupFiles-DjQc5XXv.js";
9
+ import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-Bx8dI4be.js";
10
+ import { c as isTestMint, d as mintUrlSpelling, f as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
11
+ import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, x as testSwitch } from "./resolve-C4Y2HPqQ.js";
12
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-B88yiCQj.js";
13
+ import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-DNgrRL0R.js";
14
14
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-BT_wRxab.js";
15
15
  import { sha256 } from "@noble/hashes/sha2.js";
16
16
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -198,7 +198,7 @@ function viewNews(before, after) {
198
198
  //#endregion
199
199
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
200
200
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
201
- var loadUsdt = () => import("./usdt-Bkva90Vo.js");
201
+ var loadUsdt = () => import("./usdt-DldXV0MR.js");
202
202
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
203
203
  var DEFAULT_USDT = {
204
204
  network: "ethereum",
@@ -647,7 +647,7 @@ async function restoreArkDatabase(walletId, snapshot) {
647
647
  //#endregion
648
648
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
649
649
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
650
- var loadArkade = () => import("./arkade-CJAhhgPQ.js");
650
+ var loadArkade = () => import("./arkade-k1bdSm70.js");
651
651
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
652
652
  var RETIRE_READ_MS = 1e4;
653
653
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -3553,6 +3553,16 @@ var SWAP_SETTLED_MS = 12e4;
3553
3553
  function swapSettledAt(review, prepared) {
3554
3554
  return Math.max((review.submittedAt ?? review.createdAt) + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS, (prepared.attemptEndedAt ?? 0) + SWAP_SETTLED_MS);
3555
3555
  }
3556
+ /**
3557
+ * The mint answered, and refused. cashu-ts turns a refusal of a keyset the mint retired or does not know (codes
3558
+ * 12xxx) into a `StaleKeysetError` once it has reloaded the mint's keysets: the mint's refusal all the same, with it
3559
+ * as its cause. By name, as cashu-ts's own `isMintOperationError`, so it needs no import of the library.
3560
+ */
3561
+ function mintRefused(error) {
3562
+ if (!(error instanceof Error)) return false;
3563
+ if (error.name === "StaleKeysetError") return mintRefused(error.cause);
3564
+ return error.name === "MintOperationError" && "code" in error;
3565
+ }
3556
3566
  var NEVER_REACHED_MINT = "The payment never reached the mint: nothing was sent, and the sats are back in your wallet. You can pay again.";
3557
3567
  var CashuAdapter = class {
3558
3568
  wallet;
@@ -3575,7 +3585,10 @@ var CashuAdapter = class {
3575
3585
  token = await this.wallet.executeReviewedCashu(review, prepared);
3576
3586
  } catch (error) {
3577
3587
  prepared.attemptEndedAt = Date.now();
3578
- if (persist && (await import("@cashu/cashu-ts")).isMintOperationError(error) && await this.wallet.reviewedCashuSpentElsewhere(prepared).catch(() => false)) return this.spentElsewhere(prepared, persist);
3588
+ if (persist && mintRefused(error)) {
3589
+ if (await this.wallet.reviewedCashuSpentElsewhere(prepared).catch(() => false)) return this.spentElsewhere(prepared, persist);
3590
+ if (await this.wallet.reviewedCashuNeverSwapped(prepared).catch(() => false)) return this.abandon(prepared, persist);
3591
+ }
3579
3592
  throw error;
3580
3593
  }
3581
3594
  await persist?.();
@@ -6945,6 +6958,12 @@ var ProfileDid = class {
6945
6958
  inFlight = null;
6946
6959
  again = false;
6947
6960
  unlisten;
6961
+ /** The last `samePacket` answer. */
6962
+ compared;
6963
+ /** "Clear all data" ended the DID: a publish still on its way saves nothing, or the cleared record comes back. */
6964
+ ended = false;
6965
+ /** The newest sequence number signed here, so the `deactivated` packet goes past one still on its way. */
6966
+ signedSeq = 0;
6948
6967
  constructor(host) {
6949
6968
  this.host = host;
6950
6969
  }
@@ -6994,15 +7013,16 @@ var ProfileDid = class {
6994
7013
  view() {
6995
7014
  if (!this.stored) return void 0;
6996
7015
  const published = this.stored.published;
7016
+ const alsoKnownAs = this.alsoKnownAs(this.listed());
6997
7017
  return {
6998
7018
  id: this.id,
6999
7019
  listed: this.listed(),
7000
- alsoKnownAs: this.alsoKnownAs(this.listed()),
7020
+ alsoKnownAs,
7001
7021
  ...published ? { published: {
7002
7022
  at: published.at,
7003
7023
  versionId: String(published.seq)
7004
7024
  } } : {},
7005
- upToDate: !!published && this.samePacket(published.payload),
7025
+ upToDate: !!published && this.samePacket(published.payload, alsoKnownAs),
7006
7026
  ...this.error ? { error: this.error } : {}
7007
7027
  };
7008
7028
  }
@@ -7064,7 +7084,7 @@ var ProfileDid = class {
7064
7084
  }, ms);
7065
7085
  }
7066
7086
  async publish() {
7067
- if (!this.stored || !this.host.online()) return;
7087
+ if (!this.stored || this.ended || !this.host.online()) return;
7068
7088
  const previous = this.stored.published;
7069
7089
  try {
7070
7090
  const packet = encodeDidDhtPacket(this.document());
@@ -7077,7 +7097,9 @@ var ProfileDid = class {
7077
7097
  seq = Math.max(Math.floor(Date.now() / 1e3), (previous?.seq ?? 0) + 1);
7078
7098
  payload = signDidDhtPacket(identityFromSeed(await this.unsealed()), packet, seq);
7079
7099
  }
7100
+ this.signedSeq = Math.max(this.signedSeq, seq);
7080
7101
  await this.host.publish(toZ32(this.publicKey()), payload);
7102
+ if (this.ended) return;
7081
7103
  this.error = void 0;
7082
7104
  await this.save({
7083
7105
  ...this.stored,
@@ -7093,14 +7115,15 @@ var ProfileDid = class {
7093
7115
  this.host.emit();
7094
7116
  }
7095
7117
  /**
7096
- * "Clear all data": the DID ends. When a document was ever published, a newer packet reading `deactivated` replaces
7118
+ * "Clear all data": the DID ends. When a document was ever published (or is on its way), a newer packet reading `deactivated` replaces
7097
7119
  * it, so resolvers say the DID is gone instead of showing the old document until it expires. Stops publishing first.
7098
7120
  */
7099
7121
  async deactivate() {
7122
+ this.ended = true;
7100
7123
  this.stop();
7101
7124
  const previous = this.stored?.published;
7102
- if (!this.stored || !previous) return;
7103
- const seq = Math.max(Math.floor(Date.now() / 1e3), previous.seq + 1);
7125
+ if (!this.stored || !previous && this.signedSeq === 0) return;
7126
+ const seq = Math.max(Math.floor(Date.now() / 1e3), (previous?.seq ?? 0) + 1, this.signedSeq + 1);
7104
7127
  const identity = identityFromSeed(fromBase64Url(await openSecret(this.stored.seed, SEED_AT)));
7105
7128
  await this.host.publish(toZ32(this.publicKey()), signDidDhtPacket(identity, encodeDidDhtDeactivated(this.publicKey()), seq));
7106
7129
  }
@@ -7108,6 +7131,7 @@ var ProfileDid = class {
7108
7131
  return this.stored?.listed ?? [];
7109
7132
  }
7110
7133
  alsoKnownAs(ids) {
7134
+ if (ids.length === 0) return [];
7111
7135
  const listable = this.host.listable();
7112
7136
  return [...new Set(ids.map((id) => listable.get(id)).filter((uri) => !!uri))];
7113
7137
  }
@@ -7115,13 +7139,23 @@ var ProfileDid = class {
7115
7139
  if (!this.stored) throw new Error("The profile's DID is not loaded yet");
7116
7140
  return fromBase64Url(this.stored.publicKey);
7117
7141
  }
7118
- /** Whether `payload` carries the document as it is now. Never throws: the engine's state is built from it. */
7119
- samePacket(payload) {
7142
+ /**
7143
+ * Whether `payload` carries the document as it is now. Never throws: the engine's state is built from it. Every state
7144
+ * asks, and the document follows from the key and its URIs alone, so it is encoded again only when those URIs or `payload` change.
7145
+ */
7146
+ samePacket(payload, alsoKnownAs = this.alsoKnownAs(this.listed())) {
7147
+ const uris = alsoKnownAs.join(" ");
7148
+ if (this.compared?.payload === payload && this.compared.uris === uris) return this.compared.same;
7149
+ let same = false;
7120
7150
  try {
7121
- return bytesEqual(fromBase64Url(payload).subarray(HEADER), encodeDidDhtPacket(this.document()));
7122
- } catch {
7123
- return false;
7124
- }
7151
+ same = bytesEqual(fromBase64Url(payload).subarray(HEADER), encodeDidDhtPacket(didDhtDocument(this.publicKey(), { alsoKnownAs })));
7152
+ } catch {}
7153
+ this.compared = {
7154
+ payload,
7155
+ uris,
7156
+ same
7157
+ };
7158
+ return same;
7125
7159
  }
7126
7160
  /**
7127
7161
  * A copy of the DID key's seed, for the first device-set secret of the profile (WISP 06 § Terms: `D0` comes from
@@ -7136,6 +7170,7 @@ var ProfileDid = class {
7136
7170
  return this.seed;
7137
7171
  }
7138
7172
  async save(next) {
7173
+ if (this.ended) return;
7139
7174
  await committed((await store(STORES$1.settings, "readwrite")).put(next, KEY$1));
7140
7175
  this.stored = next;
7141
7176
  }
@@ -8501,6 +8536,8 @@ var NostrSocial = class {
8501
8536
  loadingOwn = /* @__PURE__ */ new Set();
8502
8537
  errors = /* @__PURE__ */ new Map();
8503
8538
  drafts = /* @__PURE__ */ new Map();
8539
+ hints = /* @__PURE__ */ new WeakMap();
8540
+ shownNotes = /* @__PURE__ */ new WeakMap();
8504
8541
  constructor(host) {
8505
8542
  this.host = host;
8506
8543
  }
@@ -8565,7 +8602,7 @@ var NostrSocial = class {
8565
8602
  fetchedAt: c.follows.fetchedAt,
8566
8603
  relays: c.follows.relays,
8567
8604
  stale: this.stale(c.follows.fetchedAt),
8568
- follows: c.follows.follows,
8605
+ count: c.follows.follows.length,
8569
8606
  eventAt: c.follows.event?.created_at ?? 0
8570
8607
  };
8571
8608
  if (c?.mute) view.mute = {
@@ -8592,6 +8629,11 @@ var NostrSocial = class {
8592
8629
  ownFollows() {
8593
8630
  return [...new Set(this.host.ownSubjects().flatMap((s) => this.own[s]?.follows?.follows ?? []))];
8594
8631
  }
8632
+ /** The keys one of the person's own follow lists names, as last loaded (`nostrOwnFollows`); none for a key not theirs. */
8633
+ ownFollowList({ subject }) {
8634
+ if (!this.host.ownSubjects().includes(subject)) return [];
8635
+ return [...this.own[subject]?.follows?.follows ?? []];
8636
+ }
8595
8637
  /** The person's own mute lists hide this note by `author`. */
8596
8638
  hides(note, author) {
8597
8639
  return this.muted({
@@ -8607,6 +8649,7 @@ var NostrSocial = class {
8607
8649
  if (subjects.length === 0) return void 0;
8608
8650
  const cache = this.host.readContacts(linkId) ?? {};
8609
8651
  const myKeys = this.host.ownSubjects();
8652
+ const muteLists = myKeys.map((s) => this.own[s]?.mute?.list).filter((m) => !!m);
8610
8653
  return subjects.map((subject) => {
8611
8654
  const c = cache[subject];
8612
8655
  const view = {
@@ -8632,34 +8675,9 @@ var NostrSocial = class {
8632
8675
  key: k,
8633
8676
  follows: this.own[k]?.follows
8634
8677
  })).find((x) => x.follows);
8635
- if (mine?.follows) {
8636
- const h = followHints(c.follows.follows, mine.follows.follows, myKeys, subject);
8637
- view.follows.hints = {
8638
- followsYou: h.followsYou,
8639
- youFollow: h.youFollow,
8640
- mutual: h.mutual.length,
8641
- myKey: mine.key,
8642
- myFollowsAt: mine.follows.fetchedAt
8643
- };
8644
- }
8645
- }
8646
- if (c?.notes) {
8647
- const authorMuted = this.muteLists().some((m) => m.pubkeys.includes(subject));
8648
- const shown = authorMuted ? [] : c.notes.notes.filter((n) => !this.muted(n, subject));
8649
- view.notes = {
8650
- fetchedAt: c.notes.fetchedAt,
8651
- relays: c.notes.relays,
8652
- notes: shown.map((n) => ({
8653
- id: n.id,
8654
- createdAt: n.createdAt,
8655
- content: n.content,
8656
- reply: n.reply
8657
- })),
8658
- more: !c.notes.exhausted,
8659
- hidden: c.notes.notes.length - shown.length,
8660
- authorMuted
8661
- };
8678
+ if (mine?.follows) view.follows.hints = this.hintsOf(c.follows, mine.follows, mine.key, myKeys, subject);
8662
8679
  }
8680
+ if (c?.notes) view.notes = this.notesOf(c.notes, muteLists, subject).view;
8663
8681
  const loading = this.loading.get(`${linkId}:${subject}`);
8664
8682
  if (loading) view.loading = loading;
8665
8683
  const error = this.errors.get(`${linkId}:${subject}`);
@@ -8667,6 +8685,67 @@ var NostrSocial = class {
8667
8685
  return view;
8668
8686
  });
8669
8687
  }
8688
+ /** How a contact's follows meet the person's. Every state asks; a list that changes is a new object. */
8689
+ hintsOf(theirs, mine, myKey, myKeys, subject) {
8690
+ const keys = myKeys.join(" ");
8691
+ const kept = this.hints.get(theirs);
8692
+ if (kept?.mine === mine && kept.myKey === myKey && kept.keys === keys && kept.subject === subject) return kept.hints;
8693
+ const h = followHints(theirs.follows, mine.follows, myKeys, subject);
8694
+ const hints = {
8695
+ followsYou: h.followsYou,
8696
+ youFollow: h.youFollow,
8697
+ mutual: h.mutual.length,
8698
+ myKey,
8699
+ myFollowsAt: mine.fetchedAt
8700
+ };
8701
+ this.hints.set(theirs, {
8702
+ mine,
8703
+ myKey,
8704
+ keys,
8705
+ subject,
8706
+ hints
8707
+ });
8708
+ return hints;
8709
+ }
8710
+ /**
8711
+ * A contact's posts as shown, past the person's mute lists: the counts for every state's view, the posts for
8712
+ * `contactNotes`. Every state asks; a list that changes is a new object.
8713
+ */
8714
+ notesOf(notes, lists, subject) {
8715
+ const kept = this.shownNotes.get(notes);
8716
+ if (kept && kept.subject === subject && kept.lists.length === lists.length && kept.lists.every((list, i) => list === lists[i])) return kept;
8717
+ const authorMuted = lists.some((m) => m.pubkeys.includes(subject));
8718
+ const shown = authorMuted ? [] : notes.notes.filter((n) => !lists.some((m) => !!mutedBecause(n, subject, m)));
8719
+ const entry = {
8720
+ lists,
8721
+ subject,
8722
+ view: {
8723
+ fetchedAt: notes.fetchedAt,
8724
+ relays: notes.relays,
8725
+ count: shown.length,
8726
+ more: !notes.exhausted,
8727
+ hidden: notes.notes.length - shown.length,
8728
+ authorMuted
8729
+ },
8730
+ notes: shown.map((n) => ({
8731
+ id: n.id,
8732
+ createdAt: n.createdAt,
8733
+ content: n.content,
8734
+ reply: n.reply
8735
+ }))
8736
+ };
8737
+ this.shownNotes.set(notes, entry);
8738
+ return entry;
8739
+ }
8740
+ /**
8741
+ * The posts a contact's card shows (`nostrContactNotes`), newest first, past the person's mute lists: the engine
8742
+ * state carries only their count. None for a key this contact has not proved here, or before any were loaded.
8743
+ */
8744
+ contactNotes({ linkId, subject }) {
8745
+ if (!this.host.contactSubjects(linkId).includes(subject)) return [];
8746
+ const notes = this.host.readContacts(linkId)?.[subject]?.notes;
8747
+ return notes ? [...this.notesOf(notes, this.muteLists(), subject).notes] : [];
8748
+ }
8670
8749
  requireOnline() {
8671
8750
  if (!this.host.online()) throw new Error("Offline: turn the network on first");
8672
8751
  }
@@ -10844,6 +10923,30 @@ function markBuiltIns(settings, change) {
10844
10923
  settings.put(marks, BUILT_IN_APPS_KEY);
10845
10924
  };
10846
10925
  }
10926
+ /**
10927
+ * The key, in `STORES.settings`, of the digests of the bundles this profile may hold in file storage (one of
10928
+ * `PROFILE_SETTINGS_KEYS`): each one is noted before its bytes are written. File storage lists no files, and a bundle is
10929
+ * written or removed in a step of its own beside its app's record: a page gone between the two leaves one no record
10930
+ * names, which the next start finds here and removes.
10931
+ */
10932
+ var APP_BUNDLES_KEY = "appBundles";
10933
+ /** The digests as kept, read with nothing taken on trust. */
10934
+ function bundleDigests(kept) {
10935
+ return Array.isArray(kept) ? kept.filter((d) => typeof d === "string" && isAppHash(d)) : [];
10936
+ }
10937
+ /** Changes the digests noted (`APP_BUNDLES_KEY`), read and written in one transaction. */
10938
+ async function noteBundles(change) {
10939
+ const tx = (await openDb()).transaction(STORES$1.settings, "readwrite");
10940
+ const settings = tx.objectStore(STORES$1.settings);
10941
+ const read = settings.get(APP_BUNDLES_KEY);
10942
+ read.onsuccess = () => {
10943
+ const before = bundleDigests(read.result);
10944
+ const noted = new Set(before);
10945
+ change(noted);
10946
+ if (noted.size !== before.length || before.some((d) => !noted.has(d))) settings.put([...noted], APP_BUNDLES_KEY);
10947
+ };
10948
+ await done(tx);
10949
+ }
10847
10950
  var builtInRef = (app) => appRef(app.publisher, app.name);
10848
10951
  /**
10849
10952
  * The entries of the built-in list this profile is offered (WISP 1200 § Built-in apps): each reference once, not
@@ -10884,6 +10987,27 @@ function withRevocations(app, read) {
10884
10987
  revocations: [...merged.values()]
10885
10988
  } : app;
10886
10989
  }
10990
+ /** Of these revocations, the ones that stop one of these versions. */
10991
+ function stopping(versions, revocations) {
10992
+ return revocations.filter((r) => versions.some((v) => appRevocationFor(v, [r])));
10993
+ }
10994
+ /**
10995
+ * What installing `version` over `installed` does, for the install screen and for Install alike: the update rule, and an
10996
+ * equivocation for another bundle at the number of the update waiting (two different versions of that number exist).
10997
+ */
10998
+ function installDecision(installed, version) {
10999
+ if (!installed) return "new";
11000
+ if (installed.pending && installed.pending.sequence === version.sequence && installed.pending.digest !== version.digest) return "equivocation";
11001
+ return appUpdateDecision(installed, version);
11002
+ }
11003
+ /**
11004
+ * Whether `now` is still the record `was`: the same install, version, waiting update, files and mark. A store pinned or
11005
+ * unpinned meanwhile is not a change here: the update check unpins on its own (`removeStore`).
11006
+ */
11007
+ function sameRecord(now, was) {
11008
+ if (!was) return !now;
11009
+ return !!now && now.installedAt === was.installedAt && now.digest === was.digest && now.pending?.digest === was.pending?.digest && now.bytes === was.bytes && now.equivocation?.digest === was.equivocation?.digest;
11010
+ }
10887
11011
  /** Rows of one app (`[ref]`), or of one app in one scope (`[ref, scope]`), in `STORES.appStorage`, counter rows included. */
10888
11012
  var rowsOf = (...prefix) => IDBKeyRange.bound(prefix, [...prefix, []]);
10889
11013
  /** The app's own rows of one scope: its counter row left out. */
@@ -11004,6 +11128,10 @@ var Apps = class {
11004
11128
  }
11005
11129
  };
11006
11130
  stopped = false;
11131
+ /** Bundles written by this engine (`writeBundle`), by digest: one whose record is not written yet is not swept (`sweepBundles`). */
11132
+ written = /* @__PURE__ */ new Set();
11133
+ /** The sweep of `start` while it runs: a bundle written meanwhile waits for it. */
11134
+ sweeping = null;
11007
11135
  constructor(host) {
11008
11136
  this.host = host;
11009
11137
  }
@@ -11013,10 +11141,14 @@ var Apps = class {
11013
11141
  nowS() {
11014
11142
  return Math.floor(this.now() / 1e3);
11015
11143
  }
11016
- /** Preloads the default stores (no request), then checks for updates soon after start and every 24 hours. */
11144
+ /**
11145
+ * Preloads the default stores (no request) and removes the bundles no record names (`sweepBundles`), then checks for
11146
+ * updates soon after start and every 24 hours.
11147
+ */
11017
11148
  async start() {
11018
11149
  this.stopped = false;
11019
11150
  await this.seedDefaults();
11151
+ await (this.sweeping = this.sweepBundles().catch(() => {}));
11020
11152
  this.schedule(APP_CHECK_TIMINGS.afterStartMs, true);
11021
11153
  }
11022
11154
  stop() {
@@ -11161,6 +11293,14 @@ var Apps = class {
11161
11293
  digest
11162
11294
  };
11163
11295
  }
11296
+ /** The versions of an app a revocation it keeps may stop: the installed one, the one waiting, one started here before an update (it may still run). */
11297
+ versionsOf(app) {
11298
+ return [
11299
+ app,
11300
+ ...app.pending ? [versionOf(app.pending.manifest, app.pending.digest)] : [],
11301
+ ...this.startedBefore(app)
11302
+ ];
11303
+ }
11164
11304
  /** The versions started here that are not the installed one any more. */
11165
11305
  startedBefore(app) {
11166
11306
  return [...this.started.get(app.ref) ?? []].filter(([digest]) => digest !== app.digest).map(([digest, sequence]) => ({
@@ -11191,15 +11331,16 @@ var Apps = class {
11191
11331
  }
11192
11332
  }
11193
11333
  /**
11194
- * Writes an app's record back only while that install is still there (the same `installedAt`), read and written in
11195
- * one transaction: an app uninstalled (or installed again) while the update check was reading is not put back.
11334
+ * Writes an app's record back only while it is still the record `was` (`sameRecord`), read and written in one
11335
+ * transaction: an app uninstalled (or installed again) while the update check was reading is not put back, nor is the
11336
+ * version it read over an update the person accepted meanwhile. `was` undefined: only while the app has no record.
11196
11337
  */
11197
- async putAppIfInstalled(app, installedAt) {
11338
+ async putAppIfUnchanged(app, was) {
11198
11339
  const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
11199
11340
  let put = false;
11200
11341
  const read = tx.objectStore(STORES$1.apps).get(app.ref);
11201
11342
  read.onsuccess = () => {
11202
- if (read.result?.installedAt !== installedAt) return;
11343
+ if (!sameRecord(read.result, was)) return;
11203
11344
  tx.objectStore(STORES$1.apps).put(app);
11204
11345
  put = true;
11205
11346
  };
@@ -11239,8 +11380,22 @@ var Apps = class {
11239
11380
  });
11240
11381
  await written;
11241
11382
  }
11242
- putStore(record) {
11243
- return this.writeStores((records) => records.put(record), (held) => held.set(record.key, record));
11383
+ async putStore(record) {
11384
+ await this.writeStores((records) => records.put(record), (held) => held.set(record.key, record));
11385
+ await this.keepStoreRevocations(record);
11386
+ }
11387
+ /**
11388
+ * Keeps on each installed app the revocations a store's index carries of its versions: a client keeps every
11389
+ * revocation it verified (WISP 1200 § Publisher keys), so the store's next index without it, or the store removed,
11390
+ * does not let that version run again.
11391
+ */
11392
+ async keepStoreRevocations(record) {
11393
+ const revoked = record.index?.revoked ?? [];
11394
+ if (!revoked.length) return;
11395
+ for (const app of await this.installed()) {
11396
+ const next = withRevocations(app, stopping(this.versionsOf(app), revoked));
11397
+ if ((next.revocations?.length ?? 0) > (app.revocations?.length ?? 0)) await this.putAppIfUnchanged(next, app);
11398
+ }
11244
11399
  }
11245
11400
  /** The stores' views, made once and again after a store is written here: an app's every storage call and chat frame checks them. */
11246
11401
  heldViews() {
@@ -11283,11 +11438,14 @@ var Apps = class {
11283
11438
  * failure is `storage`, with the browser's own words after it for the logs, and leaves no piece behind.
11284
11439
  */
11285
11440
  async writeBundle(digest, bytes) {
11441
+ this.written.add(digest);
11286
11442
  const id = bundleId(digest);
11287
11443
  const expected = toBase64Url(await sha256Paced(bytes));
11288
11444
  let files;
11289
11445
  let stored;
11290
11446
  try {
11447
+ await this.sweeping;
11448
+ await noteBundles((noted) => noted.add(digest));
11291
11449
  files = await fileBytes();
11292
11450
  const size = await files.size(id);
11293
11451
  if (size === bytes.length && await files.digest(id) === expected) return files.kind;
@@ -11338,6 +11496,30 @@ var Apps = class {
11338
11496
  const app = await this.app(ref);
11339
11497
  if (app?.digest !== digest && app?.pending?.digest !== digest) await this.removeBundle(kind, digest);
11340
11498
  }
11499
+ /**
11500
+ * Removes the bundles noted (`APP_BUNDLES_KEY`) that no record names, as its version or the one waiting: what an
11501
+ * install, update, accept or uninstall cut short left. One written by this engine is left (its record may be on its
11502
+ * way); the next start sees it. The digests the records name are noted too, for the day they stop naming them.
11503
+ */
11504
+ async sweepBundles() {
11505
+ const tx = (await openDb()).transaction([STORES$1.apps, STORES$1.settings], "readonly");
11506
+ const [apps, kept] = await Promise.all([wrap(tx.objectStore(STORES$1.apps).getAll()), wrap(tx.objectStore(STORES$1.settings).get(APP_BUNDLES_KEY))]);
11507
+ const named = new Set(apps.flatMap((a) => a.pending ? [a.digest, a.pending.digest] : [a.digest]));
11508
+ const kinds = new Set(apps.flatMap((a) => a.pending ? [a.bytes, a.pending.bytes] : [a.bytes]));
11509
+ const current = await fileBytes().catch(() => null);
11510
+ if (current) kinds.add(current.kind);
11511
+ const gone = /* @__PURE__ */ new Set();
11512
+ for (const digest of bundleDigests(kept)) {
11513
+ if (named.has(digest) || this.written.has(digest)) continue;
11514
+ for (const kind of kinds) await this.removeBundle(kind, digest);
11515
+ gone.add(digest);
11516
+ }
11517
+ if (this.stopped) return;
11518
+ await noteBundles((noted) => {
11519
+ for (const digest of named) noted.add(digest);
11520
+ for (const digest of gone) noted.delete(digest);
11521
+ });
11522
+ }
11341
11523
  /** The installed bundle read back and checked again before it runs (WISP 1200 § Signatures: "again before it runs one"). */
11342
11524
  verifiedBundle(app, running) {
11343
11525
  if (running) this.runUsed.set(app.digest, this.now());
@@ -11654,6 +11836,7 @@ var Apps = class {
11654
11836
  async removeStore({ key }) {
11655
11837
  const held = await this.storeRecord(key);
11656
11838
  if (!held) return;
11839
+ await this.keepStoreRevocations(held);
11657
11840
  const seen = held.index ? {
11658
11841
  sequence: held.index.sequence,
11659
11842
  digest: held.digest ?? ""
@@ -11678,21 +11861,21 @@ var Apps = class {
11678
11861
  if (key !== void 0 && !stores.length) fail("no-store", "No such store");
11679
11862
  const out = [];
11680
11863
  for (const s of stores) {
11681
- let next;
11864
+ let read;
11682
11865
  try {
11683
- const read = await this.readStoreAt(s.url, s.key, s);
11684
- next = read.ok ? this.withIndex(s, read.store.index, read.store.digest) : {
11685
- ...s,
11686
- problem: read.reason
11687
- };
11866
+ read = await this.readStoreAt(s.url, s.key, s);
11688
11867
  } catch (error) {
11689
- next = {
11690
- ...s,
11691
- problem: error instanceof AppFetchError ? error.code : "network"
11868
+ read = {
11869
+ ok: false,
11870
+ reason: error instanceof AppFetchError ? error.code : "network"
11692
11871
  };
11693
11872
  }
11694
11873
  const now = await this.storeRecord(s.key);
11695
11874
  if (!now || now.removed) continue;
11875
+ const next = read.ok ? this.withIndex(now, read.store.index, read.store.digest) : {
11876
+ ...now,
11877
+ problem: read.reason
11878
+ };
11696
11879
  if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation) (await this.records()).set(s.key, next);
11697
11880
  else await this.putStore(next);
11698
11881
  out.push(this.summary(next));
@@ -11784,7 +11967,7 @@ var Apps = class {
11784
11967
  const { manifest, digest } = bundle;
11785
11968
  const version = versionOf(manifest, digest);
11786
11969
  const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
11787
- const decision = installed ? appUpdateDecision(installed, version) : "new";
11970
+ const decision = installDecision(installed, version);
11788
11971
  const install = decision === "other-app" ? "new" : decision;
11789
11972
  const asks = install === "new" ? [...manifest.permissions] : install === "update" ? manifest.permissions.filter((p) => !installed.permissions.includes(p)) : [];
11790
11973
  const listedBy = this.listedBy(version.ref, stores);
@@ -11819,47 +12002,54 @@ var Apps = class {
11819
12002
  const { manifest } = bundle;
11820
12003
  if (!Array.isArray(grant) || !manifest.permissions.every((p) => grant.includes(p))) fail("permissions", "Every permission the app asks for must be granted");
11821
12004
  const version = versionOf(manifest, digest);
11822
- const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
11823
- const run = this.runStatus(version, this.storeViews(stores), installed?.revocations);
11824
- if (run.status === "revoked") fail("revoked", "Its publisher revoked this version");
11825
- if (run.status === "removed") fail("removed", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
11826
- const pendingClash = installed?.pending && installed.pending.sequence === version.sequence && installed.pending.digest !== digest;
11827
- const decision = installed ? pendingClash ? "equivocation" : appUpdateDecision(installed, version) : "new";
11828
- if (decision === "rollback") fail("rollback", "A newer version of this app is installed");
11829
- if (decision === "equivocation") {
11830
- await this.putApp({
11831
- ...installed,
11832
- equivocation: {
11833
- sequence: version.sequence,
11834
- digest,
11835
- at: this.now()
12005
+ let wrote;
12006
+ try {
12007
+ for (;;) {
12008
+ const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
12009
+ const run = this.runStatus(version, this.storeViews(stores), installed?.revocations);
12010
+ if (run.status === "revoked") fail("revoked", "Its publisher revoked this version");
12011
+ if (run.status === "removed") fail("removed", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
12012
+ const decision = installDecision(installed, version);
12013
+ if (decision === "rollback") fail("rollback", "A newer version of this app is installed");
12014
+ if (decision === "equivocation") {
12015
+ if (!await this.putAppIfUnchanged({
12016
+ ...installed,
12017
+ equivocation: {
12018
+ sequence: version.sequence,
12019
+ digest,
12020
+ at: this.now()
12021
+ }
12022
+ }, installed)) continue;
12023
+ fail("equivocation", `Two different versions ${version.sequence} exist. Ghostly kept the one you have.`);
11836
12024
  }
11837
- });
11838
- fail("equivocation", `Two different versions ${version.sequence} exist. Ghostly kept the one you have.`);
11839
- }
11840
- if (decision === "same" && installed) {
11841
- const files = await this.hasBundle(installed.bytes, digest) ? null : await this.writeBundle(digest, bytes);
11842
- const pin = fromStore !== void 0 && installed.store !== fromStore;
11843
- if (files || pin) {
11844
- const { pending, ...rest } = installed;
11845
- if (pin && pending) await this.removeBundle(pending.bytes, pending.digest);
11846
- await this.putApp({
11847
- ...pin ? rest : installed,
11848
- ...files && { bytes: files },
11849
- ...pin && { store: fromStore }
11850
- });
12025
+ if (decision === "same" && installed) {
12026
+ const files = await this.hasBundle(installed.bytes, digest) ? null : wrote = await this.writeBundle(digest, bytes);
12027
+ const pin = fromStore !== void 0 && installed.store !== fromStore;
12028
+ if (files || pin) {
12029
+ const { pending, ...rest } = installed;
12030
+ if (!await this.putAppIfUnchanged({
12031
+ ...pin ? rest : installed,
12032
+ ...files && { bytes: files },
12033
+ ...pin && { store: fromStore }
12034
+ }, installed)) continue;
12035
+ if (pin && pending) await this.removeBundle(pending.bytes, pending.digest);
12036
+ }
12037
+ this.staged.delete(digest);
12038
+ return this.view(await this.app(version.ref), stores);
12039
+ }
12040
+ const kind = wrote = await this.writeBundle(digest, bytes);
12041
+ const next = this.versionRecord(installed, bundle, kind, from, fromStore);
12042
+ if (!await this.putAppIfUnchanged(next, installed)) continue;
12043
+ if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
12044
+ if (installed && installed.digest !== digest) await this.removeBundle(installed.bytes, installed.digest);
12045
+ if (installed?.pending && next.pending?.digest !== installed.pending.digest && installed.pending.digest !== digest) await this.removeBundle(installed.pending.bytes, installed.pending.digest);
12046
+ this.staged.delete(digest);
12047
+ return this.view(next, stores);
11851
12048
  }
11852
- this.staged.delete(digest);
11853
- return this.view(await this.app(version.ref), stores);
11854
- }
11855
- const kind = await this.writeBundle(digest, bytes);
11856
- const next = this.versionRecord(installed, bundle, kind, from, fromStore);
11857
- await this.putApp(next);
11858
- if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
11859
- if (installed && installed.digest !== digest) await this.removeBundle(installed.bytes, installed.digest);
11860
- if (installed?.pending && next.pending?.digest !== installed.pending.digest && installed.pending.digest !== digest) await this.removeBundle(installed.pending.bytes, installed.pending.digest);
11861
- this.staged.delete(digest);
11862
- return this.view(next, stores);
12049
+ } catch (error) {
12050
+ if (wrote) await this.removeUnusedBundle(version.ref, wrote, digest);
12051
+ throw error;
12052
+ }
11863
12053
  }
11864
12054
  /**
11865
12055
  * The record of a version installed now, keeping what the app had (its revocations, a newer version waiting). `store`
@@ -11869,7 +12059,11 @@ var Apps = class {
11869
12059
  versionRecord(installed, bundle, kind, from, store) {
11870
12060
  const { manifest, digest } = bundle;
11871
12061
  const now = this.now();
11872
- const keepPending = installed?.pending && installed.pending.sequence > manifest.sequence && installed.store === store ? installed.pending : void 0;
12062
+ const kept = installed?.pending && installed.pending.sequence > manifest.sequence && installed.store === store ? installed.pending : void 0;
12063
+ const keepPending = kept && {
12064
+ ...kept,
12065
+ added: addedAppPermissions(manifest.permissions, kept.manifest.permissions)
12066
+ };
11873
12067
  return {
11874
12068
  ref: appRef(manifest.publisher, manifest.name),
11875
12069
  publisher: manifest.publisher,
@@ -11910,9 +12104,25 @@ var Apps = class {
11910
12104
  permissions: read.bundle.manifest.permissions
11911
12105
  });
11912
12106
  if (plan.action === "refuse") fail(plan.decision, "This update can no longer be installed");
12107
+ const added = plan.action === "ask" ? plan.added : [];
12108
+ if (added.length !== pending.added.length || added.some((p) => !pending.added.includes(p))) {
12109
+ await this.putApp({
12110
+ ...installed,
12111
+ pending: {
12112
+ ...pending,
12113
+ added
12114
+ }
12115
+ });
12116
+ fail("permissions-changed", `This update now adds ${added.length ? added.join(", ") : "no permission"}; look at it again`);
12117
+ }
11913
12118
  const { pending: _p, ...without } = installed;
11914
12119
  const next = this.versionRecord(without, read.bundle, pending.bytes, pending.from, installed.store);
11915
- await this.putApp(next);
12120
+ if (!await this.putAppIfUnchanged(next, installed)) {
12121
+ const now = await this.app(ref);
12122
+ if (!now) fail("not-installed", "This app is not installed");
12123
+ if (now.digest === pending.digest) return this.view(now, await this.stores());
12124
+ fail("no-update", "This update can no longer be installed");
12125
+ }
11916
12126
  await this.removeBundle(installed.bytes, installed.digest);
11917
12127
  return this.view(next, stores);
11918
12128
  }
@@ -11948,15 +12158,17 @@ var Apps = class {
11948
12158
  if (!await this.hasBundle(listed.bytes, listed.digest)) await this.fetchFiles({ ref: listed.ref }).catch(() => {});
11949
12159
  const first = await this.app(listed.ref);
11950
12160
  if (!first) continue;
12161
+ let stored = first;
11951
12162
  let app = first;
11952
12163
  let outcome = "none";
11953
12164
  let wrote;
12165
+ const dropped = [];
11954
12166
  if (app.store !== void 0 && !stores.some((s) => s.key === app.store)) {
11955
12167
  const { store: _s, ...unpinned } = app;
11956
12168
  app = unpinned;
11957
12169
  }
11958
12170
  if (app.store !== void 0 && app.pending && stores.find((s) => s.key === app.store)?.index && this.pinnedListing(app, stores)?.digest !== app.pending.digest) {
11959
- await this.removeBundle(app.pending.bytes, app.pending.digest);
12171
+ dropped.push(app.pending);
11960
12172
  const { pending: _p, ...rest } = app;
11961
12173
  app = rest;
11962
12174
  }
@@ -11974,6 +12186,7 @@ var Apps = class {
11974
12186
  const missed = `${s.key} ${app.ref} ${url}`;
11975
12187
  if (candidates.has(url) || s.digest !== void 0 && this.listingMisses.get(missed) === seen) continue;
11976
12188
  candidates.set(url, {
12189
+ sequence: listing.sequence,
11977
12190
  ...pinned !== void 0 && { digest: listing.digest },
11978
12191
  peek: true,
11979
12192
  ...s.digest !== void 0 && { miss: [missed, seen] }
@@ -11984,13 +12197,21 @@ var Apps = class {
11984
12197
  if (candidates.has(url)) continue;
11985
12198
  try {
11986
12199
  const peek = await this.peekAt(url);
11987
- if (peek && newer(peek)) candidates.set(url, { holds: peek });
12200
+ if (peek && newer(peek)) candidates.set(url, {
12201
+ sequence: peek.sequence,
12202
+ holds: peek
12203
+ });
11988
12204
  } catch {}
11989
12205
  }
11990
12206
  const revokeRead = /* @__PURE__ */ new Set();
11991
12207
  const before = await this.readRevocations(app.ref, [app.from, ...app.manifest.sources ?? []], revokeRead);
11992
12208
  app = withRevocations(app, before ?? []);
11993
- for (const [url, want] of candidates) {
12209
+ if (app.pending && this.runStatus(versionOf(app.pending.manifest, app.pending.digest), this.storeViews(stores), app.revocations).status !== "ok") {
12210
+ dropped.push(app.pending);
12211
+ const { pending: _p, ...rest } = app;
12212
+ app = rest;
12213
+ }
12214
+ for (const [url, want] of [...candidates].sort(([, a], [, b]) => b.sequence - a.sequence)) {
11994
12215
  let holds = want.holds;
11995
12216
  if (want.peek) {
11996
12217
  let peek;
@@ -12059,13 +12280,13 @@ var Apps = class {
12059
12280
  const next = this.versionRecord(app, bundle, kind, url, app.store);
12060
12281
  const passed = old.pending && old.pending.sequence <= version.sequence ? old.pending : void 0;
12061
12282
  if (passed) delete next.pending;
12062
- if (!await this.putAppIfInstalled(next, first.installedAt)) break;
12063
- app = next;
12283
+ if (!await this.putAppIfUnchanged(next, stored)) break;
12284
+ app = stored = next;
12064
12285
  if (passed) await this.removeBundle(passed.bytes, passed.digest);
12065
12286
  await this.removeBundle(old.bytes, old.digest);
12066
12287
  outcome = "updated";
12067
12288
  } else {
12068
- if (app.pending) await this.removeBundle(app.pending.bytes, app.pending.digest);
12289
+ if (app.pending) dropped.push(app.pending);
12069
12290
  app = {
12070
12291
  ...app,
12071
12292
  pending: {
@@ -12084,13 +12305,14 @@ var Apps = class {
12084
12305
  }
12085
12306
  const after = await this.readRevocations(app.ref, [app.from, ...app.manifest.sources ?? []], revokeRead);
12086
12307
  const revocations = before || after ? [...before ?? [], ...after ?? []] : null;
12087
- const versions = [
12088
- app,
12089
- ...app.pending ? [versionOf(app.pending.manifest, app.pending.digest)] : [],
12090
- ...this.startedBefore(app)
12091
- ];
12092
- const stays = (app.revocations ?? []).filter((r) => !revocations || versions.some((v) => appRevocationFor(v, [r])));
12093
- const merged = new Map([...stays, ...revocations ?? []].map((r) => [canonicalJson(r), r]));
12308
+ const versions = this.versionsOf(app);
12309
+ const stays = revocations ? stopping(versions, app.revocations ?? []) : app.revocations ?? [];
12310
+ const carried = stopping(versions, stores.flatMap((s) => s.index?.revoked ?? []));
12311
+ const merged = new Map([
12312
+ ...stays,
12313
+ ...revocations ?? [],
12314
+ ...carried
12315
+ ].map((r) => [canonicalJson(r), r]));
12094
12316
  if ((await this.app(app.ref))?.store === void 0 && app.store !== void 0) {
12095
12317
  const { store: _s, ...unpinned } = app;
12096
12318
  app = unpinned;
@@ -12100,10 +12322,9 @@ var Apps = class {
12100
12322
  ...merged.size && { revocations: [...merged.values()] },
12101
12323
  checkedAt: this.now()
12102
12324
  };
12103
- if (!await this.putAppIfInstalled(app, first.installedAt)) {
12104
- if (wrote) await this.removeUnusedBundle(app.ref, wrote.bytes, wrote.digest);
12105
- continue;
12106
- }
12325
+ const put = await this.putAppIfUnchanged(app, stored);
12326
+ for (const files of [...dropped, ...!put && wrote ? [wrote] : []]) await this.removeUnusedBundle(app.ref, files.bytes, files.digest);
12327
+ if (!put) continue;
12107
12328
  out.push({
12108
12329
  ref: app.ref,
12109
12330
  outcome,
@@ -12748,6 +12969,12 @@ function isPush(value) {
12748
12969
  }
12749
12970
  return true;
12750
12971
  }
12972
+ /** One earlier device set as a record keeps it, and as a handoff's part `devices` carries it. */
12973
+ function isEarlierSet(value) {
12974
+ const set = value;
12975
+ if (!set || typeof set !== "object" || !bytes(set.d) || !bytes(set.tombstone) || !text(set.setUpdate) || !Array.isArray(set.pending) || !set.pending.every(bytes)) return false;
12976
+ return set.pending.length <= 4 && (set.foreign === void 0 || set.foreign === true) && optional(set.removed, bytes);
12977
+ }
12751
12978
  /** Why a stored record cannot be trusted. The gate then starts nothing (see `gate.ts`). */
12752
12979
  var DeviceRecordError = class extends Error {
12753
12980
  constructor(what) {
@@ -12786,7 +13013,7 @@ function parseDeviceRecord(value) {
12786
13013
  ]) if (!optional(r[field], bytes)) return bad(field);
12787
13014
  if (!optional(r.signingKey, (v) => DEVICE_SIGNING_KEY_KINDS.includes(v))) return bad("signingKey");
12788
13015
  if (r.network !== void 0 && !isNetwork(r.network)) return bad("network");
12789
- if (!optional(r.forks, (v) => Array.isArray(v) && v.length <= 8 && v.every((name) => text(name) && /^ghostly(_[A-Za-z0-9_-]{1,64})?$/.test(name)))) return bad("forks");
13016
+ if (!optional(r.forks, (v) => Array.isArray(v) && v.every((name) => text(name) && /^ghostly(_[A-Za-z0-9_-]{1,64})?$/.test(name)))) return bad("forks");
12790
13017
  if (!optional(r.breezDatabases, (v) => Array.isArray(v) && v.length <= 8 && v.every((name) => text(name) && /^ghostly-breez-/.test(name)))) return bad("breezDatabases");
12791
13018
  if (!optional(r.releasedTurn, (v) => count(v, 2 ** 32 - 1))) return bad("releasedTurn");
12792
13019
  if (!optional(r.seenSequence, (v) => count(v, Number.MAX_SAFE_INTEGER))) return bad("seenSequence");
@@ -12841,10 +13068,7 @@ function parseDeviceRecord(value) {
12841
13068
  if (!raise || typeof raise !== "object" || !bytes(raise.id) || raise.why !== "takeover" && raise.why !== "restore" || !count(raise.takeovers, 2 ** 32 - 1) || !count(raise.at, Number.MAX_SAFE_INTEGER)) return bad("raise");
12842
13069
  }
12843
13070
  if (!Array.isArray(r.earlierSets) || r.earlierSets.length > 8) return bad("the earlier device sets");
12844
- for (const set of r.earlierSets) {
12845
- if (!set || !bytes(set.d) || !bytes(set.tombstone) || !text(set.setUpdate) || !Array.isArray(set.pending) || !set.pending.every(bytes)) return bad("an earlier device set");
12846
- if (set.pending.length > 4 || set.foreign !== void 0 && set.foreign !== true) return bad("an earlier device set");
12847
- }
13071
+ if (!r.earlierSets.every(isEarlierSet)) return bad("an earlier device set");
12848
13072
  if (r.setNotice !== void 0) {
12849
13073
  const n = r.setNotice;
12850
13074
  if (!n || typeof n !== "object" || !texts(n.names, 4) || !count(n.at, Number.MAX_SAFE_INTEGER) || n.seen !== void 0 && n.seen !== true) return bad("setNotice");
@@ -13329,11 +13553,14 @@ async function enrollDevice(profile, state, patch = {}) {
13329
13553
  async function moveDevice(profile, to, patch = {}) {
13330
13554
  return change(profile, (current) => transition(current, profile, to, patch));
13331
13555
  }
13332
- /** Fields of the record changed, its state kept. There must be a record. */
13556
+ /**
13557
+ * Fields of the record changed, its state kept. There must be a record. A function makes the patch from the record
13558
+ * read inside this write, so a write that landed since the caller's own read is not written over (null: no change).
13559
+ */
13333
13560
  async function amendDevice(profile, patch) {
13334
13561
  return change(profile, (current) => {
13335
13562
  if (!current) throw new Error("This profile has no device set");
13336
- return amend(current, patch);
13563
+ return amend(current, (typeof patch === "function" ? patch(current) : patch) ?? {});
13337
13564
  });
13338
13565
  }
13339
13566
  /** One writer at a time in this page; across pages and documents, the Web Lock below and the check inside `swap`. */
@@ -13723,7 +13950,8 @@ var raisedCounter = (value, floor) => Math.max((Number.isSafeInteger(value) ? va
13723
13950
  */
13724
13951
  function raisedLink(link, floor) {
13725
13952
  const paired = !!link.profile && !link.group;
13726
- const next = { ...link };
13953
+ const { ratchetState: _ratchet, ...rest } = link;
13954
+ const next = { ...rest };
13727
13955
  if (link.dhtDeliveryState) next.dhtDeliveryState = {
13728
13956
  ...link.dhtDeliveryState,
13729
13957
  sequence: raisedCounter(link.dhtDeliveryState.sequence, floor)
@@ -14882,6 +15110,8 @@ var EnrollInviter = class extends Enrollment {
14882
15110
  seen = false;
14883
15111
  /** The person answered the digits: one answer is taken, before the record is read or written for it. */
14884
15112
  answered = false;
15113
+ /** When the code's ten minutes end, in ms. */
15114
+ expiresAt = 0;
14885
15115
  constructor(options) {
14886
15116
  super(options, {
14887
15117
  role: "inviter",
@@ -14951,6 +15181,7 @@ var EnrollInviter = class extends Enrollment {
14951
15181
  });
14952
15182
  }
14953
15183
  });
15184
+ this.expiresAt = side.invite.expires * 1e3;
14954
15185
  this.timer(Math.max(0, side.invite.expires * 1e3 - this.now()), () => {
14955
15186
  if (this.view.step === "waiting" || this.view.step === "confirm") this.fail("expired", "expired");
14956
15187
  });
@@ -14964,6 +15195,10 @@ var EnrollInviter = class extends Enrollment {
14964
15195
  return;
14965
15196
  }
14966
15197
  if (frame.t === "enroll-hello" && this.view.step === "waiting" && this.session && !this.joiner) {
15198
+ if (this.now() >= this.expiresAt) {
15199
+ await this.fail("expired", "expired");
15200
+ return;
15201
+ }
14967
15202
  const hello = readEnrollHello(frame, this.session.hash, this.key.publicKey, this.session.peerKey);
14968
15203
  if (!hello) {
14969
15204
  await this.fail("proof", "failed");
@@ -14998,6 +15233,10 @@ var EnrollInviter = class extends Enrollment {
14998
15233
  async confirm(match) {
14999
15234
  if (this.over || this.answered || this.view.step !== "confirm" || !this.joiner) throw new Error("There are no digits to confirm");
15000
15235
  this.answered = true;
15236
+ if (this.now() >= this.expiresAt) {
15237
+ await this.fail("expired", "expired", this.joiner.name);
15238
+ return this.view;
15239
+ }
15001
15240
  if (!match) {
15002
15241
  await this.fail("digits", "digits", this.joiner.name);
15003
15242
  return this.view;
@@ -15959,9 +16198,16 @@ async function planSetMove(record, signer, options = {}) {
15959
16198
  const was = JSON.parse(set.setUpdate);
15960
16199
  if (typeof was.rec === "string") oldRec = fromBase64Url(was.rec);
15961
16200
  } catch {}
15962
- const setUpdate = pending.length ? JSON.stringify(await setUpdateFrame(turnKeys(fromBase64Url(set.d)).address, {
16201
+ const setKeys = turnKeys(fromBase64Url(set.d)), tombBytes = fromBase64Url(set.tombstone);
16202
+ const oldTomb = readTurnPacket(setKeys, tombBytes);
16203
+ const kept = oldTomb.kind === "valid" ? turnSlots.map((slot, i) => {
16204
+ const was = oldTomb.record.slots[i];
16205
+ return slot && was && bytesEqual(was.key, slot.key) ? slot : null;
16206
+ }) : turnSlots;
16207
+ const setUpdate = pending.length ? JSON.stringify(await setUpdateFrame(setKeys.address, {
15963
16208
  ...update,
15964
- tomb: fromBase64Url(set.tombstone),
16209
+ set: kept,
16210
+ tomb: tombBytes,
15965
16211
  ...oldRec ? { rec: oldRec } : {}
15966
16212
  }, signer)) : set.setUpdate;
15967
16213
  earlier.push({
@@ -15974,7 +16220,8 @@ async function planSetMove(record, signer, options = {}) {
15974
16220
  d: record.d,
15975
16221
  tombstone: toBase64Url(tomb),
15976
16222
  setUpdate: JSON.stringify(frame),
15977
- pending: staying(slots.flatMap((slot) => slot ? [slot.key] : []))
16223
+ pending: staying(slots.flatMap((slot) => slot ? [slot.key] : [])),
16224
+ ...removed ? { removed: removed.key } : {}
15978
16225
  });
15979
16226
  return {
15980
16227
  removed,
@@ -17002,11 +17249,7 @@ var DeviceLinks = class {
17002
17249
  },
17003
17250
  onAnswersRefused: () => this.withoutRtc(running),
17004
17251
  onPresence: (presence) => {
17005
- if (!presence.online || running.rtcOff || running.rtcWait || running.link.isDataLinkOpen) return;
17006
- running.rtcWait = setTimeout(() => {
17007
- running.rtcWait = void 0;
17008
- if (!running.link.isDataLinkOpen) this.withoutRtc(running);
17009
- }, Math.min(DEVICE_RTC_MS * 2 ** (this.rtcBacks.get(running.id) ?? 0), DEVICE_RTC_MAX_MS));
17252
+ if (presence.online) this.waitForRtc(running);
17010
17253
  },
17011
17254
  onPacketTransports: (transports) => {
17012
17255
  if (!running.native && !transports.includes("webrtc/1")) this.startNative(running);
@@ -17311,9 +17554,8 @@ var DeviceLinks = class {
17311
17554
  }
17312
17555
  /** `key` holds the set under `d` (or the current one): its pending frame is done, and the old link goes. */
17313
17556
  async acked(key, d) {
17314
- const patch = acknowledged(await this.record(), key, d);
17315
- if (!patch) return;
17316
- await amendDevice(this.options.profile, patch);
17557
+ if (!acknowledged(await this.record(), key, d)) return;
17558
+ await amendDevice(this.options.profile, (current) => acknowledged(current, key, d));
17317
17559
  await this.refresh();
17318
17560
  this.changed();
17319
17561
  }
@@ -17401,9 +17643,13 @@ var DeviceLinks = class {
17401
17643
  * its own for it as for a Linux Desktop, and the two meet over Iroh's relay. Only with no session open, and only
17402
17644
  * where this app has a native transport to go on with.
17403
17645
  */
17404
- withoutRtc(running) {
17646
+ withoutRtc(running, waited = false) {
17405
17647
  if (this.stopped || running.rtcOff || running.native || !this.createPeerConnection || running.link.isDataLinkOpen) return;
17406
17648
  if (!Object.values(this.nativeFactories()).some(Boolean)) return;
17649
+ if (!waited && this.rtcBacks.get(running.id)) {
17650
+ this.waitForRtc(running);
17651
+ return;
17652
+ }
17407
17653
  const run = this.queue.catch(() => {}).then(async () => {
17408
17654
  if (this.stopped || this.running.get(running.id) !== running || running.link.isDataLinkOpen) return;
17409
17655
  this.running.delete(running.id);
@@ -17421,6 +17667,14 @@ var DeviceLinks = class {
17421
17667
  });
17422
17668
  this.queue = run;
17423
17669
  }
17670
+ /** `withoutRtc` once `DEVICE_RTC_MS` passed with no session open, twice as long for each time it went back (`rtcBacks`). */
17671
+ waitForRtc(running) {
17672
+ if (running.rtcOff || running.rtcWait || running.link.isDataLinkOpen) return;
17673
+ running.rtcWait = setTimeout(() => {
17674
+ running.rtcWait = void 0;
17675
+ if (!running.link.isDataLinkOpen) this.withoutRtc(running, true);
17676
+ }, Math.min(DEVICE_RTC_MS * 2 ** (this.rtcBacks.get(running.id) ?? 0), DEVICE_RTC_MAX_MS));
17677
+ }
17424
17678
  /**
17425
17679
  * The link that went on without WebRTC (`withoutRtc`) started none of its native transports: an Iroh relay neither
17426
17680
  * device reaches, and no HyperDHT relay. With nothing to go through it starts again with WebRTC, which may connect
@@ -17775,6 +18029,12 @@ var reportOf = (busy) => busy === null ? null : typeof busy === "string" ? { why
17775
18029
  var wireWhy = (report) => report.why === "call" ? "call" : "handoff";
17776
18030
  var name = (record, key) => record.deviceSet.find((slot) => slot?.key === key)?.name ?? "";
17777
18031
  var slotOf = (record, key) => record.deviceSet.findIndex((slot) => slot?.key === key);
18032
+ /**
18033
+ * The counts of the devices still in the set: a removed device cannot pull (`onRequest` refuses it), and one added again
18034
+ * has a new key, so the list stays within the set's size instead of growing to the record's cap of 16 and refusing every
18035
+ * write after it.
18036
+ */
18037
+ var setAttempts = (record, attempts) => Object.fromEntries(Object.entries(attempts ?? {}).filter(([key]) => slotOf(record, key) >= 0));
17778
18038
  /** One session of a handoff with the other device: its own X25519 key, the other's hello, and the stream key. */
17779
18039
  var Session = class {
17780
18040
  transcript;
@@ -17803,6 +18063,15 @@ function idsOf(files) {
17803
18063
  for (const list of Object.values(ids)) list.sort();
17804
18064
  return ids;
17805
18065
  }
18066
+ /**
18067
+ * The part `devices` (WISP 06 § What moves): the earlier device sets of the giver's record, so the device that takes
18068
+ * the turn puts their tombstones and delivers their frames. None when the record holds none: a profile that never
18069
+ * removed a device moves as it did before the part.
18070
+ */
18071
+ var DEVICES_PART = "devices";
18072
+ function devicesBytes(record) {
18073
+ return record?.earlierSets.length ? new TextEncoder().encode(JSON.stringify({ earlierSets: record.earlierSets })) : null;
18074
+ }
17806
18075
  /** Files over the taker's limit stay behind for later (WISP 06 § User experience, "Bring large files later"). */
17807
18076
  var isLater = (file, later) => !!later && later > 0 && file.size > later;
17808
18077
  /**
@@ -18242,7 +18511,7 @@ var HandoffGiver = class {
18242
18511
  const allowed = handoffAttemptAllowed(record.handoffAttempts?.[from], this.now());
18243
18512
  if (allowed !== "ok") return busy(allowed, allowed === "refused" ? 0 : handoffRetryAfter(record.handoffAttempts?.[from], this.now()));
18244
18513
  await this.ports.records.amend({ handoffAttempts: {
18245
- ...record.handoffAttempts,
18514
+ ...setAttempts(record, record.handoffAttempts),
18246
18515
  [from]: handoffAttemptFailed(record.handoffAttempts?.[from], this.now())
18247
18516
  } });
18248
18517
  this.begin(from, request.id, record);
@@ -18300,10 +18569,9 @@ var HandoffGiver = class {
18300
18569
  throw error;
18301
18570
  }
18302
18571
  const record = await this.ports.records.read();
18303
- await this.ports.records.amend({ handoffAttempts: {
18304
- ...record?.handoffAttempts,
18305
- [from]: handoffAttemptSucceeded()
18306
- } });
18572
+ const attempts = record ? setAttempts(record, record.handoffAttempts) : {};
18573
+ delete attempts[from];
18574
+ await this.ports.records.amend({ handoffAttempts: attempts });
18307
18575
  this.authorized(session, key);
18308
18576
  }
18309
18577
  wrongPassword(from) {
@@ -18371,12 +18639,13 @@ var HandoffGiver = class {
18371
18639
  });
18372
18640
  const parts = [...send];
18373
18641
  if (pass === 2) {
18374
- this.bundleMade ??= this.ports.source.bundle().then((bytes) => ({
18642
+ this.bundleMade ??= Promise.all([this.ports.source.bundle(), this.ports.records.read()]).then(([bytes, record]) => ({
18375
18643
  bytes,
18376
- digest: toBase64Url(sha256(bytes))
18644
+ digest: toBase64Url(sha256(bytes)),
18645
+ devices: devicesBytes(record)
18377
18646
  }));
18378
18647
  const made = this.bundleMade;
18379
- const { bytes: bundle, digest } = await made.catch((error) => {
18648
+ const { bytes: bundle, digest, devices } = await made.catch((error) => {
18380
18649
  if (this.bundleMade === made) this.bundleMade = null;
18381
18650
  throw error;
18382
18651
  });
@@ -18395,6 +18664,19 @@ var HandoffGiver = class {
18395
18664
  bundle.length,
18396
18665
  digest
18397
18666
  ];
18667
+ this.devicesPart = devices && [
18668
+ DEVICES_PART,
18669
+ devices.length,
18670
+ toBase64Url(sha256(devices))
18671
+ ];
18672
+ if (this.devicesPart) {
18673
+ parts.push(this.devicesPart);
18674
+ out.push({
18675
+ name: DEVICES_PART,
18676
+ size: devices.length,
18677
+ read: async (offset, length) => devices.subarray(offset, offset + length)
18678
+ });
18679
+ }
18398
18680
  }
18399
18681
  this.planned = {
18400
18682
  total: parts.reduce((sum, part) => sum + part[1], 0),
@@ -18427,6 +18709,7 @@ var HandoffGiver = class {
18427
18709
  else this.arm(HANDOFF_TIMINGS.verifiedMs, () => this.backToActive());
18428
18710
  }
18429
18711
  bundlePart = null;
18712
+ devicesPart = null;
18430
18713
  bundleMade = null;
18431
18714
  paused = false;
18432
18715
  stallTimer;
@@ -18469,7 +18752,11 @@ var HandoffGiver = class {
18469
18752
  const h = readHandoffVerified(frame, this.ports.turnAddress, this.turn + 1, fromBase64Url(from));
18470
18753
  if (!h) return;
18471
18754
  const later = new Set(this.laterParts.map((part) => part[2]));
18472
- const parts = [...fileParts(this.allFiles.filter((file) => !later.has(file.sha256))), this.bundlePart];
18755
+ const parts = [
18756
+ ...fileParts(this.allFiles.filter((file) => !later.has(file.sha256))),
18757
+ this.bundlePart,
18758
+ ...this.devicesPart ? [this.devicesPart] : []
18759
+ ];
18473
18760
  const expected = handoffDigest(this.turn + 1, this.ports.ownKey, fromBase64Url(from), parts);
18474
18761
  if (toBase64Url(expected) !== toBase64Url(h)) {
18475
18762
  this.out(handoffCancelFrame("damaged"));
@@ -19726,7 +20013,7 @@ var FileDesk = class {
19726
20013
  chat.files.resume(direction, wireId);
19727
20014
  break;
19728
20015
  case "cancel":
19729
- chat.files.cancel(direction, wireId);
20016
+ if (!sentWhole(record)) chat.files.cancel(direction, wireId);
19730
20017
  break;
19731
20018
  case "retry":
19732
20019
  if (out) chat.files.retry(wireId);
@@ -20555,6 +20842,9 @@ var Outbox = class {
20555
20842
  writes = 0;
20556
20843
  stamp = 0;
20557
20844
  seen = -1;
20845
+ /** How many looks at the chat (`held`) began, and how many are over: a row marked waiting meanwhile may not be in one. */
20846
+ looks = 0;
20847
+ looked = 0;
20558
20848
  stopped = false;
20559
20849
  resender;
20560
20850
  policy;
@@ -20573,6 +20863,7 @@ var Outbox = class {
20573
20863
  }
20574
20864
  /** `messages`: the chat's history as the caller just read it (a start has), so it is not read a second time. */
20575
20865
  async recover(messages) {
20866
+ const at = this.writes ? void 0 : this.stamp;
20576
20867
  for (const message of messages ?? await this.store.read()) {
20577
20868
  if (message.via === "hold" || message.sender !== "me") continue;
20578
20869
  if (message.delivery === "queued") {
@@ -20591,6 +20882,7 @@ var Outbox = class {
20591
20882
  } else if (until !== void 0) await this.expired(message);
20592
20883
  else await this.queue(message, "Not confirmed before the app closed. It is sent again, under the same ID, once your contact is reachable.");
20593
20884
  }
20885
+ if (at !== void 0 && !this.stopped) this.seen = at;
20594
20886
  }
20595
20887
  /**
20596
20888
  * One at a time, in the order asked: `run` starts when the turns before it are over. A turn that takes longer than
@@ -20700,12 +20992,31 @@ var Outbox = class {
20700
20992
  */
20701
20993
  async look(id) {
20702
20994
  if (!this.store.get || !this.known || this.waiting.size + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
20703
- return (await Promise.all([.../* @__PURE__ */ new Set([
20704
- id,
20995
+ const ids = /* @__PURE__ */ new Set([
20996
+ ...id === void 0 ? [] : [id],
20705
20997
  ...this.waiting.keys(),
20706
20998
  ...this.receipts.keys(),
20707
20999
  ...this.onTheirWay.keys()
20708
- ])].map((known) => this.store.get(known)))).filter((row) => !!row);
21000
+ ]);
21001
+ return (await Promise.all([...ids].map((known) => this.store.get(known)))).filter((row) => !!row);
21002
+ }
21003
+ /**
21004
+ * What a look at the chat takes up comes from: the rows this outbox holds, by id, where it knows them all (`look`);
21005
+ * else the chat's whole history, which, when it shows nothing of mine to go that this outbox did not know of, says
21006
+ * so until the next row stored by someone else. A session that opened with nothing queued, nothing awaiting a
21007
+ * receipt and nothing waiting read the chat's whole history for nothing, twice (the link says it is open in two
21008
+ * ways): 600 ms of a daemon's time per reconnect at 10,000 messages (agents#2468).
21009
+ */
21010
+ async held() {
21011
+ this.looks++;
21012
+ const at = this.writes ? void 0 : this.stamp;
21013
+ try {
21014
+ const messages = await this.look();
21015
+ if (at !== void 0 && !messages.some((m) => this.unknown(m))) this.seen = at;
21016
+ return messages;
21017
+ } finally {
21018
+ this.looked++;
21019
+ }
20709
21020
  }
20710
21021
  /** A row of mine still to go that this outbox holds nothing of: only a look at the chat finds it. */
20711
21022
  unknown(m, id) {
@@ -20863,10 +21174,12 @@ var Outbox = class {
20863
21174
  * nothing about it is unconfirmed; it counts no attempt until it goes.
20864
21175
  */
20865
21176
  async wait(id, reason) {
21177
+ const looked = this.looked;
20866
21178
  const message = await this.one(id);
20867
21179
  if (!message || this.stopped) return;
20868
21180
  await this.store.update(id, "waiting", reason, { resendUntil: message.resendUntil ?? this.now() + this.policy.windowMs });
20869
21181
  this.schedule(id);
21182
+ if (this.looks !== looked) this.flush().catch(() => {});
20870
21183
  }
20871
21184
  async received(wireId) {
20872
21185
  const id = `me_${wireId}`;
@@ -20889,7 +21202,7 @@ var Outbox = class {
20889
21202
  if (!reopened && this.lookAhead === look) this.lookAhead = void 0;
20890
21203
  if (this.stopped) return;
20891
21204
  if (reopened) for (const id of this.busy) this.reopenedWhileBusy.add(id);
20892
- await this.inOrder(this.due(await this.store.read(), opened));
21205
+ await this.inOrder(this.due(await this.held(), opened));
20893
21206
  });
20894
21207
  if (reopened) return look;
20895
21208
  this.lookAhead = look;
@@ -21129,7 +21442,7 @@ var EditQueue = class {
21129
21442
  wires = /* @__PURE__ */ new Map();
21130
21443
  dhtIds = /* @__PURE__ */ new Map();
21131
21444
  tick = 0;
21132
- /** The chat's history was read for the rows with an edit on its way: `known` has them all, until the next session. */
21445
+ /** The chat's history was read for the rows with an edit on its way: `known` has them all from then on (`edited`). */
21133
21446
  learnt = false;
21134
21447
  timer;
21135
21448
  flushing = null;
@@ -21170,10 +21483,11 @@ var EditQueue = class {
21170
21483
  * A new session: what the last one sent without a confirmation may go again at once, with a fresh count of attempts.
21171
21484
  * Said once, as the session opens and before anything goes on it: said again later, it would send a second time what
21172
21485
  * this session already sent (two flushes of one opening, each starting over, sent a restored question's edit twice).
21486
+ * What it learnt stays: every edit of this run is told (`edited`), so the rows it knows are still all of them, and a
21487
+ * session that opened read the chat's whole history to find none (agents#2468). A new run learns them once.
21173
21488
  */
21174
21489
  reopened() {
21175
21490
  this.sent.clear();
21176
- this.learnt = false;
21177
21491
  }
21178
21492
  /** This row has an edit to send (it was just written so): the next look reads it. */
21179
21493
  edited(id) {
@@ -22097,6 +22411,29 @@ var db = {
22097
22411
  }
22098
22412
  },
22099
22413
  /**
22414
+ * The oldest `limit` messages of a chat after `after` (and before `before`, when given), oldest first, and whether
22415
+ * newer ones remain in that window. Reads those rows only: a bot that reads what came since its last message costs
22416
+ * a page, where reading the whole history and cutting it cost 94 ms of the daemon's time a call at 7,000 messages.
22417
+ */
22418
+ async getMessagePageAfter(linkId, { limit, before, after }) {
22419
+ const upper = before?.timestamp ?? Infinity;
22420
+ if (after.timestamp > upper || after.timestamp === upper && (after.id === void 0 || before?.id === void 0)) return {
22421
+ messages: [],
22422
+ more: false
22423
+ };
22424
+ const range = IDBKeyRange.bound([linkId, after.timestamp], [linkId, upper], after.id === void 0, !!before && before.id === void 0);
22425
+ const kept = (m) => !(after.id !== void 0 && m.timestamp === after.timestamp && m.id <= after.id) && !(before?.id !== void 0 && m.timestamp === before.timestamp && m.id >= before.id);
22426
+ for (let want = limit + 1;;) {
22427
+ const oldest = await wrap((await store(STORES$1.messages, "readonly")).index("byLinkTime").getAll(range, want));
22428
+ const page = oldest.filter(kept);
22429
+ if (page.length > limit || oldest.length < want) return {
22430
+ messages: page.slice(0, limit),
22431
+ more: page.length > limit
22432
+ };
22433
+ want += oldest.length - page.length;
22434
+ }
22435
+ },
22436
+ /**
22100
22437
  * Every message of this profile that carries a task, a routine or a usage card, from every chat and group, oldest first (time,
22101
22438
  * then id). Reads the card index only (`CARD_INDEX`): no chat's history is read, however long. The index follows the
22102
22439
  * rows, so an edit's card, a deleted message and a deleted chat or group are in step with no bookkeeping.
@@ -23094,6 +23431,8 @@ var COMMUNITY_TIMINGS = {
23094
23431
  newcomerMs: 3e4
23095
23432
  };
23096
23433
  var KNOCK_BELL = 0;
23434
+ /** What `CommunitySession.join` says of a welcome whose entry is not the link's: the link was replaced since. */
23435
+ var LINK_REPLACED = "This link was replaced or turned off";
23097
23436
  var knockRecord = (link, n) => ({
23098
23437
  g: `${link.g}.${n}`,
23099
23438
  host: link.host
@@ -23128,6 +23467,19 @@ var KNOCK_SLOT_OPEN_MS = 2e4;
23128
23467
  /** How long a hub missing from the beacon still counts as one for the edges already up. */
23129
23468
  var HUB_GRACE_MS = 18e4;
23130
23469
  /**
23470
+ * A member's look past its hubs (`tipCheck`): the beacon's head names a newer epoch than mine for this long, or readings
23471
+ * of the beacon this far apart left my hub out while listing another (`HUB_MISSING_MS`, kept that long). A hub the
23472
+ * admin removed whose app does not take that in keeps my edge up and lists itself: heard only from it, I stayed on the
23473
+ * epoch before, and what I wrote went to it alone (bug hunt, 2026-11-02). Then another hub is asked too, for a while,
23474
+ * and not again before `TIP_CHECK_EVERY_MS`.
23475
+ */
23476
+ var TIP_AHEAD_MS = 45e3;
23477
+ var HUB_MISSING_MS = 2e4;
23478
+ var HUB_MISSING_KEPT_MS = 18e4;
23479
+ var TIP_CHECK_MS = 12e4;
23480
+ var TIP_CHECK_UP_MS = 2e4;
23481
+ var TIP_CHECK_EVERY_MS = 3e5;
23482
+ /**
23131
23483
  * A member cut off by a hub that left waits this long for the hub that takes it in its place before it may step up as
23132
23484
  * a hub itself: long enough for that hub's lobby reading (every 6 s once a hub left) and an edge, short enough that a
23133
23485
  * group that needs one more hub gets it.
@@ -23427,6 +23779,7 @@ var Communities = class {
23427
23779
  /** How far a join through the link got, as the joiner's app knows it. */
23428
23780
  joinStage(group) {
23429
23781
  const joining = group.joining;
23782
+ if (joining.replaced) return "replaced";
23430
23783
  if (joining.inviter) return "admitted";
23431
23784
  if (this.host.linkReady(joining.linkId, 2) || this.host.linkSeen?.(joining.linkId)) return "answered";
23432
23785
  return this.knocked.has(group.id) ? "knocked" : "knocking";
@@ -23749,7 +24102,7 @@ var Communities = class {
23749
24102
  };
23750
24103
  for (const group of [...this.stored.values()]) {
23751
24104
  const live = this.live.get(group.id);
23752
- if (group.joining && (this.knocking(group, live) || group.joining.check) && !this.gaveUp.has(group.id)) {
24105
+ if (group.joining && (this.knocking(group, live) || group.joining.check) && !this.gaveUp.has(group.id) && !group.joining.replaced) {
23753
24106
  const knocking = this.knocking(group, live), waited = now - group.joining.since;
23754
24107
  const answered = this.host.linkReady(group.joining.linkId, 2) || !!this.host.linkSeen?.(group.joining.linkId);
23755
24108
  const since = this.knockingSince.get(group.id);
@@ -23778,7 +24131,7 @@ var Communities = class {
23778
24131
  await this.closeEntries(group.id);
23779
24132
  await this.startJoining({
23780
24133
  g: group.id,
23781
- host: live.session.entryKey
24134
+ host: live.session.lostEntryKey
23782
24135
  }, live.session.state.seedB64, now);
23783
24136
  continue;
23784
24137
  }
@@ -23805,6 +24158,10 @@ var Communities = class {
23805
24158
  live.lingering.delete(linkId);
23806
24159
  if ([...this.host.entries(groupId).values()].includes(linkId)) await this.host.closeEdge(linkId);
23807
24160
  }
24161
+ if (live.doorKey && live.doorKey !== s.entryKey) {
24162
+ live.doorKey = void 0;
24163
+ await this.closeEntries(groupId);
24164
+ }
23808
24165
  const alone = live.hub && !freshHubs(this.hubs(live), now).some((h) => h.key !== me);
23809
24166
  if ((live.beaconFailedAt ? now - live.beaconFailedAt >= BEACON_RETRY_MS : now - live.lastBeaconRead >= this.beaconEvery(groupId, live, alone)) || live.lastBeaconRead === 0) await this.readBeacon(groupId, live, now);
23810
24167
  if (!live.beaconKnown) {
@@ -23942,6 +24299,7 @@ var Communities = class {
23942
24299
  if ((gone.length || lost || bare) && !edges.has(key)) live.expect.add(key);
23943
24300
  if (gone.length || lost) (live.replacing ??= /* @__PURE__ */ new Set()).add(key);
23944
24301
  }
24302
+ await this.lookPast(groupId, live, others, kept, now);
23945
24303
  live.myHubs = kept;
23946
24304
  live.forceHub = !kept.length && others.length < COMMUNITY_TOPOLOGY.maxHubs;
23947
24305
  for (const hub of kept) {
@@ -23976,7 +24334,7 @@ var Communities = class {
23976
24334
  } else continue;
23977
24335
  if (linkId) await this.host.closeEdge(linkId);
23978
24336
  }
23979
- if (s.needsCatchUp && now - (live.lastCatchUp ?? 0) >= 5e3 || now - (live.lastCatchUp ?? 0) >= 3e4) {
24337
+ if ((s.needsCatchUp || live.tipCheck?.upAt) && now - (live.lastCatchUp ?? 0) >= 5e3 || now - (live.lastCatchUp ?? 0) >= 3e4) {
23980
24338
  live.lastCatchUp = now;
23981
24339
  const ready = [...this.host.edges(groupId)].filter(([key, id]) => this.host.linkReady(id, 2) && !s.wasRemoved(key)).map(([key]) => key);
23982
24340
  for (const key of ready.slice(0, 3)) s.catchUp(key);
@@ -24006,6 +24364,52 @@ var Communities = class {
24006
24364
  }
24007
24365
  }
24008
24366
  /**
24367
+ * As a member: does my hub pass the chain on? A hub removed whose app does not take that in keeps my edge up and goes
24368
+ * on listing itself, and I heard of the removal only from it (`TIP_AHEAD_MS`). The other hubs drop it from the beacon
24369
+ * each time they write, and the head they carry names their newer epoch once someone speaks in it. On either, another
24370
+ * hub is asked too (`kept`, for its lobby and edge) and the catch-up asks it with mine, until its edge has been up a
24371
+ * while: the commit I lacked comes with it, and a hub the chain took out goes as after a leave (`gone`).
24372
+ */
24373
+ async lookPast(groupId, live, others, kept, now) {
24374
+ const s = live.session, edges = this.host.edges(groupId);
24375
+ const up = (key) => {
24376
+ const id = edges.get(key);
24377
+ return !!id && this.host.linkReady(id, 2);
24378
+ };
24379
+ live.aheadSince = live.head && live.head.e > s.epoch ? live.aheadSince ?? now : void 0;
24380
+ if (live.beaconAt === now) {
24381
+ const listed = freshHubs(live.beacon, now);
24382
+ if (kept.some((key) => up(key) && !listed.some((h) => h.key === key)) && listed.some((h) => h.key !== s.myKey && !kept.includes(h.key))) (live.hubMissing ??= []).push(now);
24383
+ }
24384
+ if (live.hubMissing) live.hubMissing = live.hubMissing.filter((at) => now - at <= HUB_MISSING_KEPT_MS);
24385
+ const check = live.tipCheck;
24386
+ if (check) {
24387
+ if (up(check.key)) check.upAt ??= now;
24388
+ if (!(kept.includes(check.key) || live.hubsAvoided.has(check.key) || this.gone(live, check.key) || check.upAt !== void 0 && now - check.upAt >= TIP_CHECK_UP_MS || now - check.since >= TIP_CHECK_MS)) {
24389
+ kept.push(check.key);
24390
+ return;
24391
+ }
24392
+ live.tipCheck = void 0;
24393
+ live.tipCheckedAt = now;
24394
+ live.hubMissing = void 0;
24395
+ const id = edges.get(check.key);
24396
+ if (id && !kept.includes(check.key)) await this.host.closeEdge(id);
24397
+ return;
24398
+ }
24399
+ const missing = live.hubMissing ?? [];
24400
+ const ahead = live.aheadSince !== void 0 && now - live.aheadSince >= TIP_AHEAD_MS;
24401
+ if (!kept.length || !(ahead || missing.length >= 2 && missing[missing.length - 1] - missing[0] >= HUB_MISSING_MS)) return;
24402
+ if (now - (live.tipCheckedAt ?? -Infinity) < TIP_CHECK_EVERY_MS) return;
24403
+ if ([...edges].some(([key, id]) => !kept.includes(key) && this.host.linkReady(id, 2) && !this.gone(live, key))) return;
24404
+ const [key] = pickHubs(s.myKey, others, now, /* @__PURE__ */ new Set([...kept, ...live.hubsAvoided.keys()]));
24405
+ if (!key) return;
24406
+ live.tipCheck = {
24407
+ key,
24408
+ since: now
24409
+ };
24410
+ kept.push(key);
24411
+ }
24412
+ /**
24009
24413
  * May this idle hub step down? When enough other hubs are listed and it has an edge up to one that is listed now
24010
24414
  * (a hub cut off from the others would only come back as one). It then steps down in two steps: it takes itself
24011
24415
  * out of the beacon, still a hub, and is a member only once a later reading still lists a hub it has an edge to.
@@ -24027,9 +24431,12 @@ var Communities = class {
24027
24431
  hubLoad(groupId, live, now) {
24028
24432
  const edges = this.host.edges(groupId);
24029
24433
  if (now - live.beaconAt <= 2 * this.timings.beaconReadMs) {
24030
- const hubs = new Set(freshHubs(this.hubs(live), now).map((h) => h.key));
24031
- for (const [key, id] of edges) if (!hubs.has(key) && !live.members.has(key) && this.host.linkReady(id, 2) && rosterHas(live.session.roster, key) && !this.gone(live, key)) live.members.set(key, now);
24032
- for (const key of [...live.members.keys()]) if (hubs.has(key)) live.members.delete(key);
24434
+ const listed = new Map(freshHubs(this.hubs(live), now).map((h) => [h.key, h]));
24435
+ for (const [key, id] of edges) if (!listed.has(key) && !live.members.has(key) && this.host.linkReady(id, 2) && rosterHas(live.session.roster, key) && !this.gone(live, key)) live.members.set(key, now);
24436
+ for (const key of [...live.members.keys()]) {
24437
+ const hub = listed.get(key);
24438
+ if (hub && !this.hubDead(groupId, live, hub, now)) live.members.delete(key);
24439
+ }
24033
24440
  }
24034
24441
  for (const [key, since] of live.members) {
24035
24442
  const id = edges.get(key);
@@ -24523,6 +24930,7 @@ var Communities = class {
24523
24930
  if (live.members.size >= this.capacity(groupId, live, now)) break;
24524
24931
  if (this.host.adminTurn && !await this.host.adminTurn(groupId, { wait: false })) break;
24525
24932
  live.pendingEntries.set(key, now);
24933
+ live.doorKey = link.host;
24526
24934
  traceJoin(groupId, "knock.seen", {
24527
24935
  age: now - ts,
24528
24936
  turn
@@ -24677,6 +25085,7 @@ var Communities = class {
24677
25085
  const live = this.live.get(g);
24678
25086
  const peer = [...this.host.entries(g)].find(([, id]) => id === linkId)?.[0];
24679
25087
  if (!live || !peer || frame.key !== peer || !live.pendingEntries.has(peer)) return;
25088
+ if (live.doorKey !== live.session.entryKey) return;
24680
25089
  let welcome;
24681
25090
  try {
24682
25091
  welcome = rosterHas(live.session.roster, peer) ? await live.session.rewelcome(peer) : await live.session.admit(peer, this.now());
@@ -24716,6 +25125,23 @@ var Communities = class {
24716
25125
  g,
24717
25126
  host: joining.host
24718
25127
  }, joining.pieces, frame, joining.seedB64);
25128
+ if ("error" in joined && joined.error === LINK_REPLACED && !joining.check) {
25129
+ joining.replaced = true;
25130
+ joining.inviter = "";
25131
+ joining.pieces = [];
25132
+ if (this.knocked.has(g)) this.unknock({
25133
+ g,
25134
+ host: joining.host
25135
+ }, this.knockAt.get(g) ?? KNOCK_BELL, joining.seedB64).catch(() => {});
25136
+ this.knocked.delete(g);
25137
+ this.knockAt.delete(g);
25138
+ countWaitingJoin(this.host, g, this.now(), false);
25139
+ traceJoin(g, "join.replaced");
25140
+ await this.store.putGroup(group);
25141
+ await this.host.closeEdge(linkId);
25142
+ this.host.emit();
25143
+ return;
25144
+ }
24719
25145
  if ("error" in joined) {
24720
25146
  joining.pieces = [];
24721
25147
  return;
@@ -24786,7 +25212,12 @@ var Communities = class {
24786
25212
  if (f.t === "group-sync" && live.session.isMember) this.sayFarewell(groupId, live, peerKey, f);
24787
25213
  return;
24788
25214
  }
24789
- if (!live.session.isRecentMember(peerKey) && f.t !== "group-commit" && f.t !== "group-msg" && f.t !== "group-secrets" && !(f.t === "group-secret" && f.to === live.session.myKey)) return;
25215
+ const named = live.session.isRecentMember(peerKey);
25216
+ if (!named && f.t === "group-sync") {
25217
+ await live.session.handle(peerKey, frame);
25218
+ return;
25219
+ }
25220
+ if (!named && f.t !== "group-commit" && f.t !== "group-msg" && f.t !== "group-secrets" && !(f.t === "group-secret" && f.to === live.session.myKey)) return;
24790
25221
  if ((f.t === "group-secret" || f.t === "group-entry") && typeof f.to === "string" && f.to !== live.session.myKey) {
24791
25222
  if (!live.hub) return;
24792
25223
  const id = `${String(f.t)}:${f.to}:${String(f.h ?? f.x)}`;
@@ -28083,7 +28514,7 @@ var Groups = class {
28083
28514
  if (!viaLink) await this.sessions.get(g).setNick(group.invitation.admin, this.host.contactName(linkId));
28084
28515
  const session = this.sessions.get(g);
28085
28516
  for (const [key, nick] of Object.entries(group.formerNames ?? {})) if (!session.state.nicks[key]) await session.setNick(key, nick);
28086
- await this.event(g, "joined", `You joined. ${GROUP_READ_NOTE}`, Date.now(), joined.state.chain.length - 1);
28517
+ await this.event(g, "joined", group.invitation.genesis ? "You joined again" : `You joined. ${GROUP_READ_NOTE}`, Date.now(), joined.state.chain.length - 1);
28087
28518
  if (viaLink) traceJoin(g, "welcome.received");
28088
28519
  if (viaLink) {
28089
28520
  this.lastKnock.delete(g);
@@ -28907,13 +29338,17 @@ var Groups = class {
28907
29338
  for (const [key] of after) if (!rosterHas(before, key) && key !== session.myKey) await this.event(groupId, "joined", `${name(key)} joined`, when, top.e, key);
28908
29339
  const gone = before.filter(([key]) => !rosterHas(after, key)).map(([key]) => key);
28909
29340
  this.hubs.removed(groupId, gone, this.now());
28910
- const left = (key) => {
28911
- const chain = session.state.chain;
28912
- for (let e = chain.length - 1; e > 0; e--) if (chain[e].k === "remove" && chain[e].s === key) return !!session.state.leftMarks?.[e];
28913
- return false;
29341
+ const chain = session.state.chain;
29342
+ const removal = (key) => {
29343
+ for (let e = chain.length - 1; e > 0; e--) if (chain[e].k === "remove" && chain[e].s === key) return e;
29344
+ return -1;
28914
29345
  };
28915
- for (const key of gone) if (left(key)) await this.event(groupId, "left", `${name(key)} left`, when, top.e, key);
28916
- else await this.event(groupId, "gone", `${name(key)} is no longer a member`, when, top.e, key);
29346
+ for (const key of gone) {
29347
+ const e = removal(key), by = e > 0 && chain[e].by !== key ? chain[e].by : void 0;
29348
+ if (e > 0 && session.state.leftMarks?.[e]) await this.event(groupId, "left", `${name(key)} left`, when, top.e, key);
29349
+ else if (by) await this.event(groupId, "gone", `${name(by)} removed ${name(key)}`, when, top.e, key, by);
29350
+ else await this.event(groupId, "gone", `${name(key)} is no longer a member`, when, top.e, key);
29351
+ }
28917
29352
  if (top.k === "role") await this.event(groupId, "admin", `${name(top.s)} ${top.s === session.myKey ? "are" : "is"} now the admin`, when, top.e, top.s);
28918
29353
  if (top.k === "rotate") await this.event(groupId, "rotated", "Keys rotated: a fresh epoch", when, top.e);
28919
29354
  }
@@ -28966,7 +29401,7 @@ var Groups = class {
28966
29401
  }
28967
29402
  /** `member`: whom it is about, so the apps can name them as they are known now, not as they were then. */
28968
29403
  /** A line in the group's history; lines at the same time (two members gone in one change) get distinct ones, see `eventTime`. */
28969
- async event(groupId, event, text, timestamp, epoch, member) {
29404
+ async event(groupId, event, text, timestamp, epoch, member, by) {
28970
29405
  timestamp = eventTime(this.eventTimes, groupId, timestamp);
28971
29406
  const id = `event:${epoch}:${event}:${timestamp}`;
28972
29407
  this.lineOrder.placing(MESSAGE_LINK(groupId), {
@@ -28980,6 +29415,7 @@ var Groups = class {
28980
29415
  sender: "peer",
28981
29416
  event,
28982
29417
  member,
29418
+ ...by && { by },
28983
29419
  timestamp,
28984
29420
  via: "datalink"
28985
29421
  }) !== false);
@@ -29003,15 +29439,24 @@ function edgeView(live, now = Date.now(), noSlot = false) {
29003
29439
  const pairingError = live.pairing?.status === "error" ? live.pairing.error : void 0;
29004
29440
  const error = open ? void 0 : pairingError ?? live.discoveryError;
29005
29441
  const state = open ? "open" : error ? "error" : live.dataLink !== "idle" ? "connecting" : "waiting";
29442
+ const cause = error ? pairingError ? edgeErrorCause(pairingError) : "relays" : void 0;
29443
+ const heardAt = Math.max(presenceSeenAt(live.presence), live.lastSyncAt);
29444
+ const seen = heardAt > 0 ? now - heardAt < PRESENCE_WINDOW : !!live.stored.edgeLive && now - (live.edgeStartedAt ?? now) < 6e5;
29445
+ const reconnecting = !open && seen && (live.lastSyncAt > 0 || !!live.stored.edgeLive) && cause !== "other";
29446
+ const retryAt = reconnecting ? live.link?.liveAttempt?.retryAt : void 0;
29447
+ const attempt = reconnecting ? live.link?.dialAttempts ?? 0 : 0;
29006
29448
  return {
29007
29449
  linkId: live.stored.id,
29008
29450
  state,
29009
29451
  ...open && live.pairing?.transport ? { transport: live.pairing.transport } : {},
29010
- lastSeenAt: open ? now : Math.max(presenceSeenAt(live.presence), live.lastSyncAt),
29452
+ lastSeenAt: open ? now : heardAt,
29011
29453
  ...error ? {
29012
29454
  error,
29013
- cause: pairingError ? edgeErrorCause(pairingError) : "relays"
29014
- } : {}
29455
+ cause
29456
+ } : {},
29457
+ ...reconnecting ? { reconnecting: true } : {},
29458
+ ...retryAt && retryAt > now ? { retryAt } : {},
29459
+ ...attempt > 0 ? { attempt } : {}
29015
29460
  };
29016
29461
  }
29017
29462
  /**
@@ -29184,7 +29629,8 @@ var testOf = (p, federationNetwork) => {
29184
29629
  };
29185
29630
  /**
29186
29631
  * What this device says about one of its own payments in a group, or null when it says nothing (not a group's,
29187
- * or nothing to say yet). `all` is every desk record, to find a request's payments and whether this device paid it.
29632
+ * or nothing to say yet). `all` is the desk records to find a request's payments in (and whether this device paid it):
29633
+ * every record, or only that request's.
29188
29634
  */
29189
29635
  function authoredNote(p, at, all, current, memberOf = () => void 0, federationNetwork = () => void 0) {
29190
29636
  const base = {
@@ -29291,11 +29737,17 @@ var GroupPayments = class {
29291
29737
  if (!known.has(groupId)) known.set(groupId, this.host.membership(groupId));
29292
29738
  return known.get(groupId);
29293
29739
  };
29740
+ const answers = /* @__PURE__ */ new Map();
29741
+ for (const x of all) if (x.requestId) {
29742
+ const list = answers.get(x.requestId);
29743
+ if (list) list.push(x);
29744
+ else answers.set(x.requestId, [x]);
29745
+ }
29294
29746
  for (const p of all) {
29295
29747
  const at = this.placement(p, membership);
29296
29748
  if (!at) continue;
29297
29749
  const current = (await this.load(at.groupId)).get(paymentWireId(p.id));
29298
- const frame = authoredNote(p, at, all, current, (linkId) => this.host.edgeOf(linkId)?.member, (federation) => this.host.federationNetwork?.(federation));
29750
+ const frame = authoredNote(p, at, answers.get(p.id) ?? [], current, (linkId) => this.host.edgeOf(linkId)?.member, (federation) => this.host.federationNetwork?.(federation));
29299
29751
  if (!frame || JSON.stringify(frame) === JSON.stringify(current?.mine)) continue;
29300
29752
  const merged = mergeGroupPay(current, frame, at.me, membership(at.groupId).members) ?? current;
29301
29753
  if (!merged) continue;
@@ -29581,13 +30033,14 @@ var GroupEdits = class {
29581
30033
  }
29582
30034
  /**
29583
30035
  * An edit from a member, authenticated as `sender` by the group. Believed only while the sender is in the group (a
29584
- * removed member's edits are dropped) and only of the sender's own message; the highest number wins. One of a message
30036
+ * removed member's edits are dropped) and only of the sender's own message; the highest number wins. In a private
30037
+ * group a removal stands once its author is out too (`outlives`): the group took it under the epoch rules. One of a message
29585
30038
  * not here yet waits a minute for it. Past `EDIT_RECEIVE_LIMIT` a window from one member, the rest wait for the next
29586
30039
  * window (`hold`): a catch-up hands back every edit of an author at once, and one dropped is never handed again.
29587
30040
  */
29588
30041
  async receive(groupId, sender, edit) {
29589
30042
  const membership = this.host.membership(groupId);
29590
- if (!membership?.members.has(sender) || sender === membership.me || !edit.id.startsWith(`${sender}:`)) return "dropped";
30043
+ if (!membership || !(membership.members.has(sender) || outlives(membership, edit)) || sender === membership.me || !edit.id.startsWith(`${sender}:`)) return "dropped";
29591
30044
  const key = `${groupId}\n${sender}`;
29592
30045
  let pace = this.receivePace.get(key);
29593
30046
  if (!pace) this.receivePace.set(key, pace = new RateWindow(30, EDIT_RATE_WINDOW_MS, this.now));
@@ -29631,10 +30084,14 @@ var GroupEdits = class {
29631
30084
  if (this.stopped || !group || !waiting || !pace) return;
29632
30085
  for (const [id, edit] of [...waiting]) {
29633
30086
  const membership = this.host.membership(groupId);
29634
- if (!membership?.members.has(sender)) {
30087
+ if (!membership) {
29635
30088
  waiting.clear();
29636
30089
  break;
29637
30090
  }
30091
+ if (!membership.members.has(sender) && !outlives(membership, edit)) {
30092
+ waiting.delete(id);
30093
+ continue;
30094
+ }
29638
30095
  if (!pace.take()) break;
29639
30096
  if (waiting.get(id) !== edit) continue;
29640
30097
  waiting.delete(id);
@@ -29808,6 +30265,14 @@ var GroupEdits = class {
29808
30265
  else this.held.delete(groupId);
29809
30266
  }
29810
30267
  };
30268
+ /**
30269
+ * A private group's removal (WISP 902 § Edits): it stands once its author left or was removed, since it only takes
30270
+ * away what the author wrote while in. The group's session checked it (signed by the author, for an epoch the author
30271
+ * and I were both in, handed on by a member). A community's member out of it edits nothing at all.
30272
+ */
30273
+ function outlives(membership, edit) {
30274
+ return edit.rm === true && !membership.community;
30275
+ }
29811
30276
  //#endregion
29812
30277
  //#region ../browser/src/shared/payLinks.ts
29813
30278
  /**
@@ -30307,6 +30772,11 @@ var HoldEngine = class {
30307
30772
  /** A read the contact's word asked for, one waiting per chat, and when the last such read went out. */
30308
30773
  peerPolls = /* @__PURE__ */ new Map();
30309
30774
  lastPeerPoll = /* @__PURE__ */ new Map();
30775
+ /**
30776
+ * Per chat, the contact's item this device waits on (`seq`) because it came in a ratchet session this device never had,
30777
+ * and the manifest that listed it (its `seq`): it is fetched again only once the contact rewrites its manifest.
30778
+ */
30779
+ waiting = /* @__PURE__ */ new Map();
30310
30780
  constructor(host) {
30311
30781
  this.host = host;
30312
30782
  }
@@ -30364,6 +30834,8 @@ var HoldEngine = class {
30364
30834
  /** Items can be held for this contact now: both switched it on, storage is set up and the contact is pinned. */
30365
30835
  canHold(linkId) {
30366
30836
  const hold = this.state(linkId);
30837
+ const ratchet = this.host.ratchet?.(linkId);
30838
+ if (ratchet && ratchet.box.heardAny && !ratchet.peerSupports()) return false;
30367
30839
  return hold.enabled && !!hold.peerAllows && !!this.host.storage() && !!this.keysFor(linkId);
30368
30840
  }
30369
30841
  /** Ways of paying a request held for this contact may name: what its app allowed at the last session. */
@@ -30491,6 +30963,7 @@ var HoldEngine = class {
30491
30963
  outSeq: seq,
30492
30964
  outbox: [...hold.outbox, entry]
30493
30965
  });
30966
+ await this.resealStale(linkId);
30494
30967
  await this.upload(linkId, entry);
30495
30968
  });
30496
30969
  }
@@ -30505,11 +30978,38 @@ var HoldEngine = class {
30505
30978
  await this.host.delivery(linkId, messageId, "held");
30506
30979
  return;
30507
30980
  }
30981
+ await this.resealStale(linkId);
30508
30982
  await this.upload(linkId, entry);
30509
30983
  }).then(() => found);
30510
30984
  }
30511
30985
  /** Seals and uploads one queued or failed entry, then the manifest and the pointer. */
30512
30986
  async upload(linkId, entry) {
30987
+ await this.store(linkId, entry);
30988
+ try {
30989
+ await this.publishPointer(linkId, true);
30990
+ } catch (error) {
30991
+ return this.failEntry(linkId, entry, `Stored, but could not tell the contact where: ${error instanceof Error ? error.message : String(error)}`);
30992
+ }
30993
+ this.errors.delete(linkId);
30994
+ await this.host.delivery(linkId, entry.messageId, "held");
30995
+ this.host.changed();
30996
+ }
30997
+ async failEntry(linkId, entry, error) {
30998
+ await this.save(linkId, {
30999
+ ...this.state(linkId),
31000
+ outbox: this.state(linkId).outbox.map((e) => e.seq === entry.seq ? {
31001
+ ...e,
31002
+ state: "failed",
31003
+ error
31004
+ } : e)
31005
+ });
31006
+ this.errors.set(linkId, error);
31007
+ await this.host.delivery(linkId, entry.messageId, "failed", error);
31008
+ this.host.changed();
31009
+ throw new Error(error);
31010
+ }
31011
+ /** Seals one entry and puts it in storage under its name; the manifest and the pointer are the caller's. */
31012
+ async store(linkId, entry) {
30513
31013
  const storage = this.host.storage(), keys = this.keysFor(linkId), hold = this.state(linkId);
30514
31014
  const update = async (patch) => this.save(linkId, {
30515
31015
  ...this.state(linkId),
@@ -30518,16 +31018,7 @@ var HoldEngine = class {
30518
31018
  ...patch
30519
31019
  } : e)
30520
31020
  });
30521
- const fail = async (error) => {
30522
- await update({
30523
- state: "failed",
30524
- error
30525
- });
30526
- this.errors.set(linkId, error);
30527
- await this.host.delivery(linkId, entry.messageId, "failed", error);
30528
- this.host.changed();
30529
- throw new Error(error);
30530
- };
31021
+ const fail = (error) => this.failEntry(linkId, entry, error);
30531
31022
  if (!storage || !keys || !hold.mailbox) return fail("Held messages need S3 storage (Profile → Backups) and a pinned contact.");
30532
31023
  let body, meta;
30533
31024
  try {
@@ -30574,17 +31065,23 @@ var HoldEngine = class {
30574
31065
  } catch (error) {
30575
31066
  return fail(error instanceof Error ? error.message : String(error));
30576
31067
  }
30577
- let bytes;
31068
+ let bytes, sid;
31069
+ const item = {
31070
+ mailbox: hold.mailbox,
31071
+ seq: entry.seq,
31072
+ id: entry.id,
31073
+ ts: entry.ts,
31074
+ kind: entry.kind,
31075
+ meta,
31076
+ expires: entry.expires
31077
+ };
31078
+ const ratchet = this.host.ratchet?.(linkId);
30578
31079
  try {
30579
- bytes = keys.seal({
30580
- mailbox: hold.mailbox,
30581
- seq: entry.seq,
30582
- id: entry.id,
30583
- ts: entry.ts,
30584
- kind: entry.kind,
30585
- meta,
30586
- expires: entry.expires
30587
- }, body);
31080
+ bytes = ratchet && (ratchet.box.heardAny || ratchet.peerSupports()) ? await keys.sealRatcheted(item, body, (plaintext) => ratchet.box.lock(async (tx) => {
31081
+ const sealed = await tx.seal("hold", plaintext);
31082
+ sid = ratchetSessionOf(sealed, "hold");
31083
+ return sealed;
31084
+ })) : keys.seal(item, body);
30588
31085
  } catch (error) {
30589
31086
  return fail(error instanceof Error ? error.message : String(error));
30590
31087
  }
@@ -30597,16 +31094,23 @@ var HoldEngine = class {
30597
31094
  await update({
30598
31095
  state: "held",
30599
31096
  error: void 0,
30600
- bytes: bytes.length
31097
+ bytes: bytes.length,
31098
+ sid
30601
31099
  });
30602
- try {
30603
- await this.publishPointer(linkId, true);
30604
- } catch (error) {
30605
- return fail(`Stored, but could not tell the contact where: ${error instanceof Error ? error.message : String(error)}`);
30606
- }
30607
- this.errors.delete(linkId);
30608
- await this.host.delivery(linkId, entry.messageId, "held");
30609
- this.host.changed();
31100
+ }
31101
+ /**
31102
+ * WISP 4xx § Held items, "A contact that started anew": the items still held that were sealed in a session other than
31103
+ * the one the chat's ratchet seals with now are sealed again in it, under the same sequence, id and name. The contact
31104
+ * moved to another device or restored, its floor envelope made its new session current here, and its new device never
31105
+ * had the old one: it leaves those items unopened, unacknowledged, until they come in a session it has. True when
31106
+ * something was sealed again: the manifest and the pointer are the caller's.
31107
+ */
31108
+ async resealStale(linkId) {
31109
+ const current = this.host.ratchet?.(linkId)?.box.session;
31110
+ if (!current || !this.host.storage()) return false;
31111
+ const stale = this.state(linkId).outbox.filter((e) => e.state === "held" && e.sid && e.sid !== current);
31112
+ for (const entry of stale) await this.store(linkId, entry).catch(() => {});
31113
+ return stale.length > 0;
30610
31114
  }
30611
31115
  /** A message deleted here: its held item goes too, so the contact never picks it up. */
30612
31116
  forget(linkId, messageId) {
@@ -30644,6 +31148,7 @@ var HoldEngine = class {
30644
31148
  this.errors.delete(linkId);
30645
31149
  this.chains.delete(linkId);
30646
31150
  this.pointerDue.delete(linkId);
31151
+ this.waiting.delete(linkId);
30647
31152
  clearTimeout(this.peerPolls.get(linkId));
30648
31153
  this.peerPolls.delete(linkId);
30649
31154
  this.lastPeerPoll.delete(linkId);
@@ -30769,9 +31274,10 @@ var HoldEngine = class {
30769
31274
  this.host.changed();
30770
31275
  }
30771
31276
  for (const entry of hold.outbox.filter((e) => e.state === "queued")) await this.upload(linkId, entry).catch(() => {});
31277
+ const resealed = await this.resealStale(linkId);
30772
31278
  hold = this.state(linkId);
30773
31279
  const held = hold.outbox.some((e) => e.state === "held");
30774
- if (this.host.storage() && (expired.length || held && (hold.manifestSignedAt ?? 0) + RENEW_AFTER_MS <= now)) await this.publishPointer(linkId, true).catch((error) => this.errors.set(linkId, String(error instanceof Error ? error.message : error)));
31280
+ if (this.host.storage() && (expired.length || resealed || held && (hold.manifestSignedAt ?? 0) + RENEW_AFTER_MS <= now)) await this.publishPointer(linkId, true).catch((error) => this.errors.set(linkId, String(error instanceof Error ? error.message : error)));
30775
31281
  else if (this.pointerDue.has(linkId) || held && (this.lastPublish.get(linkId) ?? 0) + REPUBLISH_MS <= now) await this.publishPointer(linkId, false).catch(() => {});
30776
31282
  }
30777
31283
  /**
@@ -30832,7 +31338,7 @@ var HoldEngine = class {
30832
31338
  this.host.changed();
30833
31339
  return;
30834
31340
  }
30835
- let entries, mailbox;
31341
+ let entries, mailbox, manifestRev;
30836
31342
  try {
30837
31343
  const manifest = keys.open(await this.fetchBytes(pointer.manifestUrl, HOLD_LIMITS.maxManifestBytes), {
30838
31344
  maxBytes: HOLD_LIMITS.maxManifestBytes,
@@ -30841,6 +31347,7 @@ var HoldEngine = class {
30841
31347
  });
30842
31348
  if (manifest.header.kind !== "manifest") throw new HoldRefusedError("format", "Not a manifest");
30843
31349
  mailbox = manifest.header.mailbox;
31350
+ manifestRev = manifest.header.seq;
30844
31351
  entries = readManifest(manifest.header.meta, this.host.loopbackStorage?.()).filter(([seq]) => seq > this.state(linkId).inSeq).sort((a, b) => a[0] - b[0]);
30845
31352
  } catch (error) {
30846
31353
  if (error instanceof HoldRefusedError) {
@@ -30854,6 +31361,7 @@ var HoldEngine = class {
30854
31361
  return;
30855
31362
  }
30856
31363
  let changed = false, stop = false;
31364
+ if ((this.waiting.get(linkId)?.seq ?? Infinity) <= this.state(linkId).inSeq) this.waiting.delete(linkId);
30857
31365
  for (const [seq, id, kind, bytes, url, expires] of entries) {
30858
31366
  if (stop) break;
30859
31367
  if (expires <= now) {
@@ -30864,12 +31372,30 @@ var HoldEngine = class {
30864
31372
  changed = true;
30865
31373
  continue;
30866
31374
  }
31375
+ const waiting = this.waiting.get(linkId);
31376
+ if (waiting?.seq === seq && waiting.manifest === manifestRev) {
31377
+ stop = true;
31378
+ break;
31379
+ }
31380
+ const ratchet = this.host.ratchet?.(linkId);
31381
+ let ratcheted, fetched, unknownSession = false;
30867
31382
  try {
30868
- const { header, body } = keys.open(await this.fetchBytes(url, Math.min(bytes, HOLD_LIMITS.maxBundleBytes)), {
31383
+ fetched = await this.fetchBytes(url, Math.min(bytes, HOLD_LIMITS.maxBundleBytes));
31384
+ const opened = keys.open(fetched, {
30869
31385
  maxBytes: HOLD_LIMITS.maxBundleBytes,
30870
31386
  now,
30871
- mailbox
31387
+ mailbox,
31388
+ ...ratchet && {
31389
+ ratchet: (sealed) => {
31390
+ const plain = ratchet.box.peek("hold", sealed);
31391
+ unknownSession = !plain && ratchet.box.unknownSession("hold", sealed);
31392
+ return plain;
31393
+ },
31394
+ refusePlain: ratchet.box.heard("hold")
31395
+ }
30872
31396
  });
31397
+ const { header, body } = opened;
31398
+ ratcheted = opened.ratcheted;
30873
31399
  if (header.seq !== seq || header.id !== id || header.kind !== kind) throw new HoldRefusedError("format", "The item does not match the manifest");
30874
31400
  const held = {
30875
31401
  seq,
@@ -30932,13 +31458,29 @@ var HoldEngine = class {
30932
31458
  network: frame.n
30933
31459
  });
30934
31460
  }
31461
+ if (ratcheted && ratchet) await ratchet.box.commitOpen("hold", ratcheted);
30935
31462
  hold = await this.save(linkId, {
30936
31463
  ...this.state(linkId),
30937
31464
  inSeq: seq
30938
31465
  });
30939
31466
  changed = true;
30940
31467
  } catch (error) {
30941
- if (error instanceof HoldRefusedError) {
31468
+ const opened = ratcheted ?? (error instanceof HoldRefusedError ? error.ratcheted : void 0);
31469
+ if (error instanceof HoldRefusedError && opened && ratchet) await ratchet.box.commitOpen("hold", opened).catch(() => {});
31470
+ if (error instanceof HoldRefusedError && error.reason === "tampered" && fetched?.[4] === 2 && await this.host.taken?.(linkId, id)) {
31471
+ await this.save(linkId, {
31472
+ ...this.state(linkId),
31473
+ inSeq: seq
31474
+ });
31475
+ changed = true;
31476
+ } else if (error instanceof HoldRefusedError && error.reason === "tampered" && unknownSession) {
31477
+ this.waiting.set(linkId, {
31478
+ seq,
31479
+ manifest: manifestRev
31480
+ });
31481
+ this.errors.set(linkId, "Could not pick up held items: the contact's app sealed them for the device this profile was on before. They come once it seals them again for this one.");
31482
+ stop = true;
31483
+ } else if (error instanceof HoldRefusedError) {
30942
31484
  await this.save(linkId, {
30943
31485
  ...this.state(linkId),
30944
31486
  inSeq: seq,
@@ -31854,7 +32396,8 @@ var ProfilePeek = class {
31854
32396
  },
31855
32397
  state: link.dhtDeliveryState,
31856
32398
  transport: readOnly,
31857
- background: true
32399
+ background: true,
32400
+ ratchet: link.ratchetState
31858
32401
  });
31859
32402
  let held = 0;
31860
32403
  if (holdable(link)) {
@@ -32127,6 +32670,26 @@ var S3Store = class {
32127
32670
  }
32128
32671
  };
32129
32672
  //#endregion
32673
+ //#region ../browser/src/shared/refusals.ts
32674
+ /** The English line for `notice`, stored as the row's `text`. */
32675
+ function refusedText(notice) {
32676
+ return `Could not receive ${notice.method === "fedimint" ? "Fedimint ecash" : notice.amount === void 0 ? "a payment" : `${notice.amount.toLocaleString("en-US")} ${notice.network === "testnet" ? "test sats" : "sats"}`}: ${notice.reason}`;
32677
+ }
32678
+ /** The row the engine stores for a refusal: the values, and their English as the text. */
32679
+ function refusedRow(notice) {
32680
+ const values = {
32681
+ type: "paymentRefused",
32682
+ ...notice.amount !== void 0 && { amount: notice.amount },
32683
+ ...notice.network && { network: notice.network },
32684
+ ...notice.method && { method: notice.method },
32685
+ reason: notice.reason
32686
+ };
32687
+ return {
32688
+ text: refusedText(values),
32689
+ notice: values
32690
+ };
32691
+ }
32692
+ //#endregion
32130
32693
  //#region ../browser/src/engine/wallet.ts
32131
32694
  /**
32132
32695
  * The peer's Cashu wallet. Ecash is custodial: the mint holds the sats and the
@@ -32142,7 +32705,30 @@ var S3Store = class {
32142
32705
  * asked for again (NUT-09) at any time.
32143
32706
  */
32144
32707
  var UNIT$1 = "sat";
32145
- var QUOTE_POLL_MS = 4e3;
32708
+ /**
32709
+ * cdk-mintd 0.17 writes NUT-05's `amountless` beside the method, not under its `options` as 0.18 does, and cashu-ts reads
32710
+ * `options` only: such a mint would be taken for one that refuses an invoice with no amount, and never sent the amount.
32711
+ */
32712
+ var saysAmountlessBeside = (method) => method.amountless === true;
32713
+ function amountlessUnderOptions(info) {
32714
+ const moved = info.nuts[5].methods.map((method) => saysAmountlessBeside(method) ? {
32715
+ ...method,
32716
+ options: {
32717
+ ...method.options,
32718
+ amountless: true
32719
+ }
32720
+ } : method);
32721
+ return {
32722
+ ...info,
32723
+ nuts: {
32724
+ ...info.nuts,
32725
+ 5: {
32726
+ ...info.nuts[5],
32727
+ methods: moved
32728
+ }
32729
+ }
32730
+ };
32731
+ }
32146
32732
  /** A Lightning payment can stay in flight for minutes or hours; the mint is asked again this often. */
32147
32733
  var MELT_POLL_MS = 3e4;
32148
32734
  var MAX_AMOUNT = 1e6;
@@ -32159,6 +32745,8 @@ var SWAP_SLOW_POLL_MS = 6e5;
32159
32745
  var SWAP_WATCH_MS = 36e5;
32160
32746
  /** How many proofs of tokens refused as spent are remembered. */
32161
32747
  var SPENT_KEPT = 1e3;
32748
+ /** The most coins `sendCoins` makes for one token. */
32749
+ var MAX_SEND_COINS = 64;
32162
32750
  /** Cashu's library (174 KiB) loads with the wallet's first use of a mint or a token, not with the app's start. */
32163
32751
  var loadCashu = () => import("@cashu/cashu-ts");
32164
32752
  async function reviewedCashuFee(preview) {
@@ -32184,6 +32772,8 @@ var SwapUnsettledError = class extends Error {
32184
32772
  };
32185
32773
  /** When a swap with no answer can no longer reach the mint: a request's longest life, and a margin after its last try. */
32186
32774
  var swapOverdueAt = (swap) => Math.max(swap.createdAt + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS, (swap.attemptEndedAt ?? Number.POSITIVE_INFINITY) + SWAP_SETTLED_MS);
32775
+ /** When a melt with no answer can no longer reach the mint: its one request is sent right after it is written down. */
32776
+ var meltOverdueAt = (melt) => melt.createdAt + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS;
32187
32777
  var swapOf = (swap) => swap.swap;
32188
32778
  function normalizeMintUrl(input) {
32189
32779
  let url;
@@ -32194,7 +32784,7 @@ function normalizeMintUrl(input) {
32194
32784
  }
32195
32785
  const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
32196
32786
  if (url.protocol !== "https:" && !(local && url.protocol === "http:")) throw engineError("mintNotHttps");
32197
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
32787
+ return mintUrlSpelling(url.href);
32198
32788
  }
32199
32789
  function assertAmount(amount) {
32200
32790
  if (!Number.isSafeInteger(amount) || amount <= 0) throw new Error("Enter an amount in sats");
@@ -32204,6 +32794,84 @@ function assertAmount(amount) {
32204
32794
  var asProofLike = (proofs) => proofs;
32205
32795
  var total = (proofs) => proofs.reduce((sum, p) => sum + p.amount, 0);
32206
32796
  var sats = (proofs) => total(proofs.map((p) => ({ amount: p.amount.toNumber() })));
32797
+ /**
32798
+ * Whether `split` can take `amount` out of `proofs`, as it does: coins that add up exactly with the fee their receiver
32799
+ * pays to redeem them, or a swap whose inputs also pay the mint's fee for taking them in. Asks nothing of the mint.
32800
+ */
32801
+ /** Whether exact coins go as one token a payment frame carries: a wallet of many small coins can add up in hundreds. */
32802
+ var inOneFrame = (encode, mint) => (send) => encode({
32803
+ mint,
32804
+ proofs: send,
32805
+ unit: UNIT$1
32806
+ }).length <= LIMITS.maxPaymentEndpointChars;
32807
+ /**
32808
+ * The coins a swap makes to send `amount` with the fee their receiver pays to redeem them: the fewest sats whose coins,
32809
+ * less that fee, are exactly `amount`. cashu-ts' includeFees adds coins for the fee that can be worth more than it, and
32810
+ * the contact is credited more than was sent. Undefined at a mint that charges nothing for coins, or when no such
32811
+ * coins are found up to what cashu-ts would make: its own choice is used then.
32812
+ */
32813
+ function sendCoins(wallet, amount) {
32814
+ const included = wallet.getFeesToInclude(amount).toNumber();
32815
+ if (included === 0) return void 0;
32816
+ const keyset = wallet.getKeyset();
32817
+ const fee = (coins) => wallet.getFeesForKeyset(coins, keyset.id).toNumber();
32818
+ const sizes = Object.keys(keyset.keys).map(Number).filter((size) => size > 0).sort((a, b) => b - a);
32819
+ const coinsOf = (value, among = sizes) => {
32820
+ const coins = [];
32821
+ for (const size of among) while (value >= size) {
32822
+ coins.push(size);
32823
+ value -= size;
32824
+ }
32825
+ return value === 0 ? coins : void 0;
32826
+ };
32827
+ for (let value = amount; value <= amount + included; value++) {
32828
+ let coins = coinsOf(value);
32829
+ while (coins && coins.length <= MAX_SEND_COINS && fee(coins.length) < value - amount) {
32830
+ const [largest, ...rest] = coins;
32831
+ const parts = coinsOf(largest, sizes.filter((size) => size < largest));
32832
+ coins = parts && [...parts, ...rest].sort((a, b) => b - a);
32833
+ }
32834
+ if (coins && coins.length <= MAX_SEND_COINS && fee(coins.length) === value - amount) return coins;
32835
+ }
32836
+ }
32837
+ function fitsAt(wallet, proofs, amount) {
32838
+ return outlayAt(wallet, proofs, amount) !== void 0;
32839
+ }
32840
+ /**
32841
+ * The sats `split` takes out of the wallet for `amount`, the mint's fees for the coins it takes in included, as `fitsAt`
32842
+ * works it out: undefined when it cannot. `inOneFrame`: whether exact coins fit in one token, as `split` asks of them.
32843
+ */
32844
+ function outlayAt(wallet, proofs, amount, inOneFrame = (_send) => true) {
32845
+ try {
32846
+ const { send } = wallet.sendOffline(amount, asProofLike(proofs), {
32847
+ includeFees: true,
32848
+ exactMatch: true
32849
+ });
32850
+ if (send.length > 0 && sats(send) === amount + wallet.getFeesForProofs(send).toNumber() && inOneFrame(send)) return sats(send);
32851
+ } catch {}
32852
+ try {
32853
+ const coins = sendCoins(wallet, amount);
32854
+ const outputs = coins ? coins.reduce((sum, coin) => sum + coin, 0) : amount + wallet.getFeesToInclude(amount).toNumber();
32855
+ const { send } = wallet.selectProofsToSend(asProofLike(proofs), outputs, true);
32856
+ const taken = outputs + wallet.getFeesForProofs(send).toNumber();
32857
+ return send.length > 0 && sats(send) >= taken ? taken : void 0;
32858
+ } catch {
32859
+ return;
32860
+ }
32861
+ }
32862
+ /** The most `fitsAt` takes out of `proofs` with `extra` on top (a Lightning fee reserve): 0 when nothing fits. */
32863
+ function roomAt(wallet, proofs, extra = 0) {
32864
+ const most = total(proofs) - wallet.getFeesForProofs(asProofLike(proofs)).toNumber() - extra;
32865
+ if (most <= 0 || fitsAt(wallet, proofs, most + extra)) return Math.max(0, most);
32866
+ let low = 0;
32867
+ let high = most - 1;
32868
+ while (low < high) {
32869
+ const middle = Math.ceil((low + high) / 2);
32870
+ if (fitsAt(wallet, proofs, middle + extra)) low = middle;
32871
+ else high = middle - 1;
32872
+ }
32873
+ return low;
32874
+ }
32207
32875
  var MINT_QUOTE_MISMATCH = "The mint quoted another amount than this invoice's. Nothing was paid.";
32208
32876
  /** A melt quote that is not for this invoice (`invoice` lower case, as `decodeBolt11` gives it) and its amount. */
32209
32877
  var quoteMismatch = (quote, invoice, amount) => quote.request.trim().toLowerCase().replace(/^lightning:/, "") !== invoice || quote.amount.toNumber() !== amount;
@@ -32230,6 +32898,8 @@ var walletTx = (mint, kind, amount, fee, note) => ({
32230
32898
  });
32231
32899
  /** What a failed payment left in the wallet, said to the person: all of it, or all but the fee the mint kept. */
32232
32900
  var backInWallet = (lost) => lost > 0 ? `The sats are back in your wallet, less ${lost} sat${lost === 1 ? "" : "s"} the mint kept as its fee.` : "The sats are back in your wallet.";
32901
+ /** A mint's own words for a refusal, as one short line: the reason at the end of `lightningRefused`. */
32902
+ var mintReason = (error) => (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim().slice(0, 160) || "no reason given";
32233
32903
  /**
32234
32904
  * How long a mint gets to answer when it is only being asked something (its keys, an invoice). A mint
32235
32905
  * that is down can hold a request for minutes; the next mint should get its turn well before that.
@@ -32251,6 +32921,12 @@ var CashuWallet = class CashuWallet {
32251
32921
  infos = /* @__PURE__ */ new Map();
32252
32922
  locks = /* @__PURE__ */ new Map();
32253
32923
  quoteTimer = null;
32924
+ /** When `quoteTimer` fires: a round that would fire later leaves it as it is. */
32925
+ quoteTimerAt = 0;
32926
+ /** Per open quote: when its mint was last asked about it, in this run (`nextInvoiceAsk`). */
32927
+ quoteAsked = /* @__PURE__ */ new Map();
32928
+ /** Per quote the screen shows: until when (`watch`). */
32929
+ quoteWatched = /* @__PURE__ */ new Map();
32254
32930
  meltTimer = null;
32255
32931
  restoredTimer = null;
32256
32932
  swapTimer = null;
@@ -32264,7 +32940,8 @@ var CashuWallet = class CashuWallet {
32264
32940
  * so the same token sent again, under any id or encoding, is refused without asking the mint again.
32265
32941
  */
32266
32942
  spentTokens = /* @__PURE__ */ new Set();
32267
- /** Per melt quote shown to the person: the invoice, its amount and the fee reserve the mint quoted. Only these are paid. */
32943
+ /** Per melt quote shown to the person: the invoice, its amount and the most it was said to cost in fees
32944
+ * (the mint's reserve and the coins' own fees). Only these are paid, for no more. */
32268
32945
  shownQuotes = /* @__PURE__ */ new Map();
32269
32946
  /**
32270
32947
  * `getMints`: the mints of one network (the engine's default when none is named), primary first: balances,
@@ -32447,10 +33124,23 @@ var CashuWallet = class CashuWallet {
32447
33124
  ...paysItsOwnInvoices(mint) ? { held: true } : {}
32448
33125
  };
32449
33126
  await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
33127
+ this.quoteAsked.set(quote.quote, Date.now());
32450
33128
  this.pollQuotes();
32451
33129
  return quote;
32452
33130
  }
32453
33131
  /**
33132
+ * The screen shows this invoice of ours (Receive): it is asked about at the fast pace for `INVOICE_PACE.watchMs`, and
33133
+ * now if it was not just asked. The screen says it again while it shows it. Returns whether it is one of ours here.
33134
+ */
33135
+ async watch(invoice) {
33136
+ const wanted = invoice.trim().toLowerCase();
33137
+ const quote = (await this.quotes()).find((q) => q.invoice.toLowerCase() === wanted);
33138
+ if (!quote) return false;
33139
+ this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);
33140
+ await this.pollQuotes();
33141
+ return true;
33142
+ }
33143
+ /**
32454
33144
  * A payer says it paid this invoice of ours (a contact's app, once its payment went through). A held quote (a test
32455
33145
  * mint's, which reads paid by itself) is minted from now on; on any other mint the mint's own answer decides, as
32456
33146
  * always. Returns whether the invoice is one of ours.
@@ -32463,7 +33153,8 @@ var CashuWallet = class CashuWallet {
32463
33153
  ...quote,
32464
33154
  held: void 0
32465
33155
  }));
32466
- await this.pollQuotes();
33156
+ this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);
33157
+ await this.pollQuotes(true);
32467
33158
  return true;
32468
33159
  }
32469
33160
  /** True while an invoice of ours waits for a payer's word (see `vouch`): whatever its mint says, it is not paid. */
@@ -32511,7 +33202,7 @@ var CashuWallet = class CashuWallet {
32511
33202
  * these mints (one network's wallet, before it is removed), claiming what is paid; the regular round is left alone.
32512
33203
  */
32513
33204
  async checkQuotes(mints) {
32514
- if (!mints) return this.pollQuotes();
33205
+ if (!mints) return this.pollQuotes(true);
32515
33206
  const at = new Set(mints);
32516
33207
  await this.settleQuotes((await this.quotes()).filter((q) => at.has(q.mint)));
32517
33208
  }
@@ -32522,32 +33213,70 @@ var CashuWallet = class CashuWallet {
32522
33213
  /**
32523
33214
  * Invoices are paid by someone else, somewhere else; all we can do is ask the mint. A quote is the only
32524
33215
  * claim on the sats paid to it, so it is dropped only once the mint says it is unpaid and it has expired.
33216
+ * Each quote is asked about at its own pace (`nextInvoiceAsk`): often while it is new or on screen, then less.
33217
+ * `now`: every open quote is asked about, whatever its pace (someone says it was paid). The store is read once.
32525
33218
  */
32526
- async pollQuotes() {
33219
+ async pollQuotes(now = false) {
32527
33220
  if (this.quoteTimer) clearTimeout(this.quoteTimer);
32528
33221
  this.quoteTimer = null;
32529
33222
  if (this.stopped) return;
32530
- const quotes = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32531
- for (const held of quotes.filter((q) => q.held && q.expiresAt && q.expiresAt + 6e4 < Date.now())) await committed((await store(STORES$1.quotes, "readwrite")).delete(held.quote));
32532
- await this.settleQuotes(quotes);
32533
- const remaining = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32534
- if (!this.stopped && remaining.some((q) => !q.issuedUnclaimed && !q.held)) this.quoteTimer = setTimeout(() => void this.pollQuotes(), QUOTE_POLL_MS);
33223
+ const quotes = await this.quotes();
33224
+ const gone = /* @__PURE__ */ new Set();
33225
+ for (const held of quotes.filter((q) => q.held && q.expiresAt && q.expiresAt + INVOICE_PACE.expiryGraceMs < Date.now())) {
33226
+ await committed((await store(STORES$1.quotes, "readwrite")).delete(held.quote));
33227
+ gone.add(held.quote);
33228
+ }
33229
+ const stored = new Set(quotes.map((q) => q.quote));
33230
+ for (const pace of [this.quoteAsked, this.quoteWatched]) for (const id of pace.keys()) if (!stored.has(id)) pace.delete(id);
33231
+ const open = quotes.filter((q) => !q.issuedUnclaimed && !q.held);
33232
+ const at = Date.now();
33233
+ for (const settled of await this.settleQuotes(open.filter((q) => now || this.nextAsk(q, at) <= at + INVOICE_PACE.dueSlackMs))) gone.add(settled);
33234
+ const next = open.filter((q) => !gone.has(q.quote)).map((q) => this.nextAsk(q, Date.now()));
33235
+ if (next.length) this.scheduleQuotes(Math.min(...next));
33236
+ }
33237
+ /** When the mint is next asked about this quote. */
33238
+ nextAsk(quote, now) {
33239
+ return nextInvoiceAsk({
33240
+ createdAt: quote.createdAt,
33241
+ expiresAt: quote.expiresAt,
33242
+ watchedUntil: this.quoteWatched.get(quote.quote),
33243
+ closed: !!quote.paymentId && !!this.events.requestClosed?.(quote.paymentId),
33244
+ paid: !!quote.paid
33245
+ }, this.quoteAsked.get(quote.quote), now);
33246
+ }
33247
+ /** The next round at `at`, unless one is due sooner. */
33248
+ scheduleQuotes(at) {
33249
+ if (this.stopped) return;
33250
+ if (this.quoteTimer && this.quoteTimerAt <= at) return;
33251
+ if (this.quoteTimer) clearTimeout(this.quoteTimer);
33252
+ this.quoteTimerAt = at;
33253
+ this.quoteTimer = setTimeout(() => {
33254
+ this.quoteTimer = null;
33255
+ this.pollQuotes();
33256
+ }, Math.max(0, at - Date.now()));
32535
33257
  }
33258
+ /** Asks the mints about these quotes. Returns the ones minted. */
32536
33259
  async settleQuotes(quotes) {
32537
- for (const { quote, mint } of quotes.filter((q) => !q.issuedUnclaimed && !q.held)) try {
32538
- const paid = await this.locked(mint, () => this.settleQuote(quote));
32539
- if (paid) {
32540
- if (!paid.testCoins) this.events.onQuotePaid(paid);
32541
- this.events.onChange();
32542
- }
32543
- } catch {}
33260
+ const minted = [];
33261
+ for (const { quote, mint } of quotes.filter((q) => !q.issuedUnclaimed && !q.held)) {
33262
+ this.quoteAsked.set(quote, Date.now());
33263
+ try {
33264
+ const paid = await this.locked(mint, () => this.settleQuote(quote));
33265
+ if (paid) {
33266
+ minted.push(quote);
33267
+ if (!paid.testCoins) this.events.onQuotePaid(paid);
33268
+ this.events.onChange();
33269
+ }
33270
+ } catch {}
33271
+ }
33272
+ return minted;
32544
33273
  }
32545
33274
  /** Runs under the mint's lock, so two rounds never mint one quote twice. Returns the quote once its ecash is in. */
32546
33275
  async settleQuote(id) {
32547
33276
  const quote = await wrap((await store(STORES$1.quotes, "readonly")).get(id));
32548
33277
  if (!quote || quote.issuedUnclaimed || quote.held) return null;
32549
33278
  const wallet = await this.wallet(quote.mint);
32550
- const { OutputData, isMintOperationError } = await loadCashu();
33279
+ const { OutputData } = await loadCashu();
32551
33280
  const answer = await wallet.checkMintQuoteBolt11(quote.quote);
32552
33281
  const { state } = answer;
32553
33282
  if (state === "UNPAID") {
@@ -32580,7 +33309,7 @@ var CashuWallet = class CashuWallet {
32580
33309
  try {
32581
33310
  proofs = await wallet.completeMint(preview);
32582
33311
  } catch (error) {
32583
- if (saved && isMintOperationError(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
33312
+ if (mintRefused(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
32584
33313
  const { outputs: _refused, ...fresh } = written;
32585
33314
  await committed((await store(STORES$1.quotes, "readwrite")).put(fresh));
32586
33315
  }
@@ -32625,11 +33354,23 @@ var CashuWallet = class CashuWallet {
32625
33354
  async createToken(amount, preferred, note, outbox, network) {
32626
33355
  assertAmount(amount);
32627
33356
  const mine = preferred ? this.getKnownMints() : this.getMints(network);
32628
- const candidates = (preferred ? preferred.map((m) => m.replace(/\/+$/, "")).filter((m) => mine.includes(m)) : mine).filter((m) => !network || mintNetwork(m) === network);
33357
+ const candidates = (preferred ? preferred.map(mintUrlSpelling).filter((m) => mine.includes(m)) : mine).filter((m) => !network || mintNetwork(m) === network);
33358
+ /** The most a mint that holds the amount could send with its fees on top. */
33359
+ let room = 0;
33360
+ /** The coins held at `mint` when they send the amount. */
33361
+ const fitting = async (mint) => {
33362
+ const proofs = await this.proofsAt(mint);
33363
+ if (total(proofs) < amount) return void 0;
33364
+ const wallet = await this.wallet(mint);
33365
+ if (fitsAt(wallet, proofs, amount)) return proofs;
33366
+ room = Math.max(room, roomAt(wallet, proofs));
33367
+ };
32629
33368
  for (const mint of candidates) {
32630
- if (await this.balanceAt(mint) < amount) continue;
32631
- return this.locked(mint, async () => {
32632
- const { inputs, keep, send, swap } = await this.split(mint, amount, await this.proofsAt(mint));
33369
+ if (!await fitting(mint)) continue;
33370
+ const sent = await this.locked(mint, async () => {
33371
+ const proofs = await fitting(mint);
33372
+ if (!proofs) return void 0;
33373
+ const { inputs, keep, send, swap } = await this.split(mint, amount, proofs);
32633
33374
  const token = (await loadCashu()).getEncodedToken({
32634
33375
  mint,
32635
33376
  proofs: send,
@@ -32655,7 +33396,9 @@ var CashuWallet = class CashuWallet {
32655
33396
  mint
32656
33397
  };
32657
33398
  });
33399
+ if (sent) return sent;
32658
33400
  }
33401
+ if (room > 0) throw engineError("notEnoughForFee", { amount: room });
32659
33402
  throw engineError(candidates.length === 0 && preferred ? "noSharedMint" : "notEnoughSats");
32660
33403
  }
32661
33404
  async prepareReviewedCashu(mint, amount) {
@@ -32914,7 +33657,7 @@ var CashuWallet = class CashuWallet {
32914
33657
  try {
32915
33658
  if (/^cashu[AB]/i.test(value)) {
32916
33659
  const metadata = getTokenMetadata(value);
32917
- const mint = metadata.mint.replace(/\/+$/, "");
33660
+ const mint = mintUrlSpelling(metadata.mint);
32918
33661
  return {
32919
33662
  kind: "token",
32920
33663
  amount: Number(metadata.amount),
@@ -32930,7 +33673,7 @@ var CashuWallet = class CashuWallet {
32930
33673
  kind: "request",
32931
33674
  amount: request.amount === void 0 ? null : Number(request.amount),
32932
33675
  unit: request.unit ?? UNIT$1,
32933
- mints: request.mints ?? [],
33676
+ mints: (request.mints ?? []).map(mintUrlSpelling),
32934
33677
  description: request.description || void 0
32935
33678
  };
32936
33679
  }
@@ -32949,7 +33692,7 @@ var CashuWallet = class CashuWallet {
32949
33692
  try {
32950
33693
  const metadata = getTokenMetadata(token);
32951
33694
  unit = metadata.unit;
32952
- mint = metadata.mint.replace(/\/+$/, "");
33695
+ mint = mintUrlSpelling(metadata.mint);
32953
33696
  faceValue = Number(metadata.amount);
32954
33697
  } catch {
32955
33698
  throw new Error("That is not a valid ecash token");
@@ -32977,6 +33720,7 @@ var CashuWallet = class CashuWallet {
32977
33720
  if (preview.inputs.some((p) => this.spentTokens.has(`${mint} ${p.secret}`))) throw engineError("ecashAlreadySpent");
32978
33721
  const redeeming = new Set(written.flatMap((s) => (swapOf(s).inputs ?? []).map((p) => p.secret)));
32979
33722
  if (preview.inputs.some((p) => redeeming.has(p.secret))) throw engineError("ecashBeingReceived");
33723
+ if (preview.amount.toNumber() <= 0) throw engineError("ecashFeeTakesAll", { amount: String(faceValue) });
32980
33724
  swap = {
32981
33725
  id: swapId(),
32982
33726
  mint,
@@ -33027,17 +33771,17 @@ var CashuWallet = class CashuWallet {
33027
33771
  includeFees: true,
33028
33772
  exactMatch: true
33029
33773
  });
33030
- if (send.length > 0 && sats(send) === amount + wallet.getFeesForProofs(send).toNumber() && getEncodedToken({
33031
- mint,
33032
- proofs: send,
33033
- unit: UNIT$1
33034
- }).length <= LIMITS.maxPaymentEndpointChars) return {
33774
+ if (send.length > 0 && sats(send) === amount + wallet.getFeesForProofs(send).toNumber() && inOneFrame(getEncodedToken, mint)(send)) return {
33035
33775
  inputs: among(send),
33036
33776
  keep: [],
33037
33777
  send
33038
33778
  };
33039
33779
  } catch {}
33040
- const preview = await wallet.prepareSwapToSend(amount, asProofLike(proofs), { includeFees: true });
33780
+ const coins = sendCoins(wallet, amount);
33781
+ const preview = coins ? await wallet.prepareSwapToSend(coins.reduce((sum, coin) => sum + coin, 0), asProofLike(proofs), {}, { send: {
33782
+ type: "random",
33783
+ denominations: coins
33784
+ } }) : await wallet.prepareSwapToSend(amount, asProofLike(proofs), { includeFees: true });
33041
33785
  const swap = {
33042
33786
  id: swapId(),
33043
33787
  mint,
@@ -33069,11 +33813,11 @@ var CashuWallet = class CashuWallet {
33069
33813
  * `pollSwaps` settles it. Runs under the mint's lock.
33070
33814
  */
33071
33815
  async completeSwap(swap) {
33072
- const { deserializeSwapPreview, isMintOperationError } = await loadCashu();
33816
+ const { deserializeSwapPreview } = await loadCashu();
33073
33817
  try {
33074
33818
  return await (await this.wallet(swap.mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
33075
33819
  } catch (error) {
33076
- const refused = isMintOperationError(error) && swap.attemptEndedAt === void 0;
33820
+ const refused = mintRefused(error) && swap.attemptEndedAt === void 0;
33077
33821
  const ended = {
33078
33822
  ...swap,
33079
33823
  attemptEndedAt: Date.now()
@@ -33325,7 +34069,7 @@ var CashuWallet = class CashuWallet {
33325
34069
  if (stuck === 1) this.events.onChange();
33326
34070
  later(wait);
33327
34071
  } else if (outcome.idle && swap.kind === "receive" && !swap.released) {
33328
- const { deserializeSwapPreview, isMintOperationError } = await loadCashu();
34072
+ const { deserializeSwapPreview } = await loadCashu();
33329
34073
  try {
33330
34074
  const { keep } = await (await this.wallet(mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
33331
34075
  if (await this.finishSwap(swap, keep, [], true)) {
@@ -33340,7 +34084,7 @@ var CashuWallet = class CashuWallet {
33340
34084
  attemptEndedAt: Date.now()
33341
34085
  };
33342
34086
  await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
33343
- const refusal = isMintOperationError(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
34087
+ const refusal = mintRefused(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
33344
34088
  if (refusal?.state === "done") {
33345
34089
  if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
33346
34090
  const told = await this.tellSwap(swap, true);
@@ -33393,40 +34137,51 @@ var CashuWallet = class CashuWallet {
33393
34137
  });
33394
34138
  if (again && !mints) this.swapsAgainIn(again);
33395
34139
  }
33396
- /** What paying this invoice would cost, from the first mint that can afford it. */
33397
- async quoteInvoice(invoice, network) {
34140
+ /**
34141
+ * What paying this invoice would cost, from the first mint that can afford it. `chosen`: the sats the person typed for
34142
+ * an invoice with no amount, the only way one is paid (WISP 203); only a mint that says it takes one is asked.
34143
+ */
34144
+ async quoteInvoice(invoice, network, chosen) {
33398
34145
  let lastError = /* @__PURE__ */ new Error("Add a mint in Settings first");
33399
34146
  let mints = this.getMints(network);
33400
34147
  /** The most any mint asked could pay with its fee on top: a Max comes down to it. */
33401
34148
  let room = 0;
33402
34149
  const decoded = decodeBolt11(invoice);
33403
34150
  if (!decoded) throw new Error("That is not an invoice this wallet can pay");
33404
- if (decoded.amountSat === null) throw new Error("Invoices without an amount are not supported");
34151
+ if (decoded.amountSat === null && chosen === void 0) throw new Error("Invoices without an amount are not supported");
34152
+ if (decoded.amountSat !== null && chosen !== void 0) throw new Error(MINT_QUOTE_MISMATCH);
34153
+ if (chosen !== void 0) assertAmount(chosen);
34154
+ const expected = decoded.amountSat ?? chosen;
33405
34155
  if (decoded.network === "bitcoin" && mints.some((mint) => mintNetwork(mint) === "testnet")) {
33406
34156
  mints = mints.filter((mint) => mintNetwork(mint) === "mainnet" || fakesLightning(mint));
33407
34157
  if (!mints.length) throw new Error(BITCOIN_INVOICE_ON_TESTNET);
33408
34158
  }
34159
+ if (chosen !== void 0 && mints.length) lastError = engineError("mintsNoAnyAmount");
33409
34160
  for (const mint of mints) try {
33410
- const quote = await (await this.wallet(mint)).createMeltQuoteBolt11(invoice.trim());
34161
+ const wallet = await this.wallet(mint);
34162
+ if (chosen !== void 0 && !wallet.getMintInfo().supportsAmountless("bolt11", UNIT$1)) continue;
34163
+ const quote = chosen === void 0 ? await wallet.createMeltQuoteBolt11(invoice.trim()) : await wallet.createMeltQuoteBolt11(invoice.trim(), chosen * 1e3);
33411
34164
  const amount = quote.amount.toNumber();
33412
34165
  const feeReserve = quote.fee_reserve.toNumber();
33413
- if (quoteMismatch(quote, decoded.invoice, decoded.amountSat)) throw new Error(MINT_QUOTE_MISMATCH);
33414
- const balance = await this.balanceAt(mint);
33415
- if (balance < amount + feeReserve) {
33416
- room = Math.max(room, balance - feeReserve);
34166
+ if (quoteMismatch(quote, decoded.invoice, expected)) throw new Error(MINT_QUOTE_MISMATCH);
34167
+ const proofs = await this.proofsAt(mint);
34168
+ const outlay = outlayAt(wallet, proofs, amount + feeReserve, inOneFrame((await loadCashu()).getEncodedToken, mint));
34169
+ if (outlay === void 0) {
34170
+ room = Math.max(room, roomAt(wallet, proofs, feeReserve));
33417
34171
  lastError = room > 0 ? engineError("notEnoughForFee", { amount: room }) : engineError("notEnoughSats");
33418
34172
  continue;
33419
34173
  }
34174
+ const fee = outlay - amount;
33420
34175
  this.shownQuotes.set(quote.quote, {
33421
34176
  request: decoded.invoice,
33422
34177
  amount,
33423
- feeReserve
34178
+ feeReserve: fee
33424
34179
  });
33425
34180
  return {
33426
34181
  quote: quote.quote,
33427
34182
  mint,
33428
34183
  amount,
33429
- feeReserve
34184
+ feeReserve: fee
33430
34185
  };
33431
34186
  } catch (error) {
33432
34187
  lastError = error;
@@ -33451,13 +34206,19 @@ var CashuWallet = class CashuWallet {
33451
34206
  }
33452
34207
  async melt(quoteId, mint, note, paymentId) {
33453
34208
  const wallet = await this.wallet(mint);
33454
- const { MeltChangeError, OutputData, isMintOperationError } = await loadCashu();
34209
+ const { MeltChangeError, OutputData, getEncodedToken } = await loadCashu();
33455
34210
  const quote = await wallet.checkMeltQuoteBolt11(quoteId);
33456
34211
  if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => m.quote === quote.quote || m.request === quote.request)) throw new Error("This invoice is already being paid");
33457
34212
  const shown = this.shownQuotes.get(quoteId);
33458
- if (!shown || quote.quote !== quoteId || quoteMismatch(quote, shown.request, shown.amount) || quote.fee_reserve.toNumber() > shown.feeReserve) throw new Error(MINT_QUOTE_MISMATCH);
33459
34213
  const needed = quote.amount.toNumber() + quote.fee_reserve.toNumber();
33460
- const { inputs, keep, send, swap } = await this.split(mint, needed, await this.proofsAt(mint));
34214
+ const proofs = await this.proofsAt(mint);
34215
+ const outlay = outlayAt(wallet, proofs, needed, inOneFrame(getEncodedToken, mint));
34216
+ if (!shown || quote.quote !== quoteId || quoteMismatch(quote, shown.request, shown.amount) || (outlay ?? needed) > shown.amount + shown.feeReserve) throw new Error(MINT_QUOTE_MISMATCH);
34217
+ if (outlay === void 0) {
34218
+ const room = roomAt(wallet, proofs, quote.fee_reserve.toNumber());
34219
+ throw room > 0 ? engineError("notEnoughForFee", { amount: room }) : engineError("notEnoughSats");
34220
+ }
34221
+ const { inputs, keep, send, swap } = await this.split(mint, needed, proofs);
33461
34222
  let preview;
33462
34223
  try {
33463
34224
  preview = await wallet.prepareMelt("bolt11", quote, send);
@@ -33495,13 +34256,13 @@ var CashuWallet = class CashuWallet {
33495
34256
  try {
33496
34257
  result = await wallet.completeMelt(preview);
33497
34258
  } catch (error) {
33498
- if (!isMintOperationError(error) && !(error instanceof MeltChangeError)) return "pending";
33499
- const outcome = await this.settleMelt(melt).catch(() => "pending");
34259
+ if (!mintRefused(error) && !(error instanceof MeltChangeError)) return "pending";
34260
+ const outcome = await this.settleMelt(melt, true).catch(() => "pending");
33500
34261
  if (outcome === "unpaid") {
33501
34262
  const lost = this.takeFailedFee(melt.quote);
33502
34263
  if (this.spentAway.delete(melt.quote)) throw Object.assign(engineError("ecashAlreadySpent"), { cause: error });
33503
34264
  if (lost > 0) throw Object.assign(/* @__PURE__ */ new Error(`${error instanceof Error ? error.message : String(error)} ${backInWallet(lost)}`), { cause: error });
33504
- throw error;
34265
+ throw Object.assign(engineError("lightningRefused", { reason: mintReason(error) }), { cause: error });
33505
34266
  }
33506
34267
  return outcome;
33507
34268
  }
@@ -33509,7 +34270,7 @@ var CashuWallet = class CashuWallet {
33509
34270
  await this.finishMelt(melt, result.change);
33510
34271
  return "paid";
33511
34272
  }
33512
- return this.settleMelt(melt).catch(() => "pending");
34273
+ return this.settleMelt(melt, true).catch(() => "pending");
33513
34274
  }
33514
34275
  /**
33515
34276
  * Whether a Lightning payment of this invoice is written down as in flight. A melt is written before the mint sees
@@ -33541,9 +34302,10 @@ var CashuWallet = class CashuWallet {
33541
34302
  /**
33542
34303
  * Asks the mint where a recorded melt stands and books the answer. Paid: the reserved proofs are gone and
33543
34304
  * the change is ours. Unpaid: what the mint says is unspent is spendable again. Pending: nothing moves.
33544
- * Throws when the mint cannot be asked, and the melt stays as it is.
34305
+ * Throws when the mint cannot be asked, and the melt stays as it is. `answered`: the mint answered the melt request
34306
+ * itself, so it has acted on it; without that, an unpaid quote may only mean the request has not landed yet.
33545
34307
  */
33546
- async settleMelt(melt) {
34308
+ async settleMelt(melt, answered = false) {
33547
34309
  const wallet = await this.wallet(melt.mint);
33548
34310
  const { Amount, OutputData } = await loadCashu();
33549
34311
  const quote = await wallet.checkMeltQuoteBolt11(melt.quote);
@@ -33562,6 +34324,7 @@ var CashuWallet = class CashuWallet {
33562
34324
  return "paid";
33563
34325
  }
33564
34326
  if (quote.state === "PENDING") return "pending";
34327
+ if (!answered && Date.now() < meltOverdueAt(melt)) return "pending";
33565
34328
  const inputs = await this.reservedProofs(melt);
33566
34329
  const states = inputs.length > 0 ? await wallet.checkProofsStates(inputs) : [];
33567
34330
  if (states.some((s) => s.state === "PENDING")) return "pending";
@@ -33616,20 +34379,26 @@ var CashuWallet = class CashuWallet {
33616
34379
  */
33617
34380
  async forget(mints, acceptLoss = false) {
33618
34381
  const at = new Set(mints);
33619
- if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
34382
+ const inFlight = async () => {
34383
+ if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
34384
+ };
34385
+ await inFlight();
33620
34386
  await this.pollSwaps(mints).catch(() => {});
33621
- if ((await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
33622
- const proofs = (await this.allProofs()).filter((p) => at.has(p.mint));
33623
- const quotes = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).filter((q) => at.has(q.mint));
33624
- const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint));
33625
- await transact([
33626
- STORES$1.proofs,
33627
- STORES$1.quotes,
33628
- STORES$1.swaps
33629
- ], (stores) => {
33630
- for (const p of proofs) stores[STORES$1.proofs].delete(p.secret);
33631
- for (const q of quotes) stores[STORES$1.quotes].delete(q.quote);
33632
- for (const s of swaps) stores[STORES$1.swaps].delete(s.id);
34387
+ await this.lockedAll(mints, async () => {
34388
+ await inFlight();
34389
+ if ((await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
34390
+ const proofs = (await this.allProofs()).filter((p) => at.has(p.mint));
34391
+ const quotes = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).filter((q) => at.has(q.mint));
34392
+ const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint));
34393
+ await transact([
34394
+ STORES$1.proofs,
34395
+ STORES$1.quotes,
34396
+ STORES$1.swaps
34397
+ ], (stores) => {
34398
+ for (const p of proofs) stores[STORES$1.proofs].delete(p.secret);
34399
+ for (const q of quotes) stores[STORES$1.quotes].delete(q.quote);
34400
+ for (const s of swaps) stores[STORES$1.swaps].delete(s.id);
34401
+ });
33633
34402
  });
33634
34403
  for (const mint of mints) {
33635
34404
  this.wallets.delete(mint);
@@ -33666,6 +34435,8 @@ var CashuWallet = class CashuWallet {
33666
34435
  wallet = (async () => {
33667
34436
  const instance = new (await (loadCashu())).Wallet(mint, { unit: UNIT$1 });
33668
34437
  await within(MINT_TIMEOUT_MS, instance.loadMint(), mint);
34438
+ const info = instance.getMintInfo();
34439
+ if (info.isSupported(5).params.some(saysAmountlessBeside)) instance.loadMintFromCache(amountlessUnderOptions(info.cache), instance.keyChain.cache);
33669
34440
  return instance;
33670
34441
  })();
33671
34442
  this.wallets.set(mint, wallet);
@@ -33691,6 +34462,10 @@ var CashuWallet = class CashuWallet {
33691
34462
  this.locks.set(mint, next.catch(() => {}));
33692
34463
  return next;
33693
34464
  }
34465
+ /** `task` under the locks of every one of `mints`, taken in one order (no other task holds two, so none waits on this one). */
34466
+ lockedAll(mints, task) {
34467
+ return [...new Set(mints)].sort().reduceRight((inner, mint) => () => this.locked(mint, inner), task)();
34468
+ }
33694
34469
  async allProofs() {
33695
34470
  return wrap((await store(STORES$1.proofs, "readonly")).getAll());
33696
34471
  }
@@ -33740,8 +34515,18 @@ function parseSats(value, asset) {
33740
34515
  if (asset !== UNIT || !/^[1-9]\d{0,8}$/.test(value)) return null;
33741
34516
  return Number(value);
33742
34517
  }
33743
- /** Paying in ecash failed before any token existed, so nothing reached the contact and Lightning is safe to try. */
33744
- var NoEcashError = class extends Error {};
34518
+ /**
34519
+ * Paying in ecash failed before any token existed, so nothing reached the contact and Lightning is safe to try. The
34520
+ * wallet's `engineCode` and `values` stay on it: a host reads why by them (the CLI's `refused`, the app's words).
34521
+ */
34522
+ var NoEcashError = class extends Error {
34523
+ constructor(cause) {
34524
+ super(cause instanceof Error ? cause.message : String(cause));
34525
+ const { engineCode, values } = cause ?? {};
34526
+ if (engineCode !== void 0) Object.assign(this, { engineCode });
34527
+ if (values !== void 0) Object.assign(this, { values });
34528
+ }
34529
+ };
33745
34530
  var arkSats = (network) => network === "bitcoin" ? "sats" : "test sats";
33746
34531
  /** The English line kept with a payment message (the CLI and older apps show it): test sats say so. */
33747
34532
  var satsOn = (network) => network === "testnet" ? "test sats" : "sats";
@@ -34962,11 +35747,17 @@ var PaymentDesk = class {
34962
35747
  });
34963
35748
  const sats = parseSats(payment.amount.value, payment.amount.asset);
34964
35749
  const spent = error instanceof EngineError && error.engineCode === "ecashAlreadySpent";
35750
+ const network = inspected?.kind === "token" ? mintNetwork(inspected.mint) : void 0;
35751
+ const line = refusedRow({
35752
+ amount: sats ?? void 0,
35753
+ network,
35754
+ reason
35755
+ });
34965
35756
  try {
34966
35757
  await this.host.storeMessage({
34967
35758
  linkId,
34968
35759
  id: spent ? `peer_spent_${digestHex(token).slice(0, 32)}` : `peer_${payment.timestamp}_refused`,
34969
- text: `Could not receive ${sats === null ? "a payment" : `${sats.toLocaleString()} sats`}: ${reason}`,
35760
+ ...line,
34970
35761
  sender: "peer",
34971
35762
  timestamp: payment.timestamp,
34972
35763
  via: "datalink"
@@ -35033,11 +35824,16 @@ var PaymentDesk = class {
35033
35824
  ok: false,
35034
35825
  error: reason
35035
35826
  });
35827
+ const line = refusedRow({
35828
+ amount: record.amount,
35829
+ network: record.mint ? mintNetwork(record.mint) : void 0,
35830
+ reason
35831
+ });
35036
35832
  try {
35037
35833
  await this.host.storeMessage({
35038
35834
  linkId: record.linkId,
35039
35835
  id: `peer_${record.createdAt}_refused`,
35040
- text: `Could not receive ${record.amount.toLocaleString()} sats: ${reason}`,
35836
+ ...line,
35041
35837
  sender: "peer",
35042
35838
  timestamp: record.createdAt,
35043
35839
  via: "datalink"
@@ -35973,17 +36769,23 @@ var PaymentDesk = class {
35973
36769
  });
35974
36770
  return;
35975
36771
  }
35976
- const refuse = async (reason) => {
36772
+ const refuse = async (reason, network) => {
35977
36773
  link?.sendPaymentResult({
35978
36774
  id: payment.id,
35979
36775
  ok: false,
35980
36776
  error: reason
35981
36777
  });
36778
+ const line = refusedRow({
36779
+ amount: parseSats(payment.amount.value, payment.amount.asset) ?? void 0,
36780
+ network,
36781
+ method: "fedimint",
36782
+ reason
36783
+ });
35982
36784
  try {
35983
36785
  await this.host.storeMessage({
35984
36786
  linkId,
35985
36787
  id: `peer_${payment.timestamp}_refused`,
35986
- text: `Could not receive Fedimint ecash: ${reason}`,
36788
+ ...line,
35987
36789
  sender: "peer",
35988
36790
  timestamp: payment.timestamp,
35989
36791
  via: "datalink"
@@ -36019,7 +36821,7 @@ var PaymentDesk = class {
36019
36821
  }
36020
36822
  const network = this.fedimintOf(found.federation)?.federation(found.federation)?.network;
36021
36823
  if (network && !this.accepts(linkId, "fedimint", walletNetworkOf(network))) {
36022
- await refuse(`${networkLabel(walletNetworkOf(network))} Fedimint is off in this chat`);
36824
+ await refuse(`${networkLabel(walletNetworkOf(network))} Fedimint is off in this chat`, walletNetworkOf(network));
36023
36825
  return;
36024
36826
  }
36025
36827
  const digest = fedimintNotesDigest(notes);
@@ -36096,11 +36898,17 @@ var PaymentDesk = class {
36096
36898
  ok: false,
36097
36899
  error: "These notes were already redeemed"
36098
36900
  });
36901
+ const line = refusedRow({
36902
+ amount: payment.amount,
36903
+ network: payment.network,
36904
+ method: "fedimint",
36905
+ reason: "These notes were already redeemed"
36906
+ });
36099
36907
  try {
36100
36908
  await this.host.storeMessage({
36101
36909
  linkId: payment.linkId,
36102
36910
  id: `peer_${payment.createdAt}_refused`,
36103
- text: "Could not receive Fedimint ecash: These notes were already redeemed",
36911
+ ...line,
36104
36912
  sender: "peer",
36105
36913
  timestamp: payment.createdAt,
36106
36914
  via: "datalink"
@@ -36294,7 +37102,7 @@ var PaymentDesk = class {
36294
37102
  paidFrom = created.mint;
36295
37103
  this.payments.set(id, record(created.token, created.mint));
36296
37104
  } catch (error) {
36297
- throw new NoEcashError(error instanceof Error ? error.message : String(error));
37105
+ throw new NoEcashError(error);
36298
37106
  }
36299
37107
  this.host.onChange();
36300
37108
  await this.host.storeMessage({
@@ -36865,7 +37673,11 @@ var WalletSetup = class {
36865
37673
  };
36866
37674
  //#endregion
36867
37675
  //#region ../browser/src/engine/node.ts
36868
- /** How long a chat waits before listening again after its HyperDHT relay went away. */
37676
+ /**
37677
+ * How long a chat waits, on average, before listening again after its HyperDHT relay went away. Each app draws its own
37678
+ * wait within half of it either side: a relay that restarts closes every app's socket at once, and with one fixed wait
37679
+ * they all came back in the same instant, more listens than its one HyperDHT node sends out in time.
37680
+ */
36869
37681
  var RELAY_RETRY_MS = 3e4;
36870
37682
  /** Native listeners an app may hold per transport (the Desktop's Rust Iroh allows eight, `paired_transport.rs`). */
36871
37683
  var NATIVE_SLOTS = 8;
@@ -36910,6 +37722,8 @@ var DEFAULT_SETTINGS = {
36910
37722
  mints: [],
36911
37723
  mintsInitialized: false
36912
37724
  };
37725
+ /** A link's `removedRefs` with `ref`, the newest `MAX_DELETED_IDS`. */
37726
+ var withRemovedRef = (refs, ref) => [...(refs ?? []).filter((r) => r !== ref), ref].slice(-500);
36913
37727
  /**
36914
37728
  * A card that went on the DHT floor or into a hold goes again live (`restoreCards`) only for the newest this many
36915
37729
  * messages of a chat, sent within this long: an old chat's cards are not worth a burst of edits.
@@ -37207,6 +38021,7 @@ var GhostlyNode = class GhostlyNode {
37207
38021
  const key = type + ":" + id;
37208
38022
  if (this.feedbackIds.has(key)) return;
37209
38023
  this.feedbackIds.add(key);
38024
+ if (this.feedbackIds.size > 4096) this.feedbackIds.delete(this.feedbackIds.values().next().value);
37210
38025
  this.events.onAttention?.({
37211
38026
  type,
37212
38027
  id: key,
@@ -37511,8 +38326,14 @@ var GhostlyNode = class GhostlyNode {
37511
38326
  mint: melt.mint
37512
38327
  }),
37513
38328
  onTestMintNeeded: async (mint) => void await this.walletAddMint({ url: mint }),
37514
- onSwapSettled: (swap, done) => this.desk.onSwapSettled(swap, done).then(() => swap.payment?.direction === "out" ? this.reviewTakenBack(swap.payment.id) : void 0)
38329
+ onSwapSettled: (swap, done) => this.desk.onSwapSettled(swap, done).then(() => swap.payment?.direction === "out" ? this.reviewTakenBack(swap.payment.id) : void 0),
38330
+ requestClosed: (paymentId) => this.requestClosed(paymentId)
37515
38331
  }, () => this.settings.mints);
38332
+ /** A chat request of ours that nobody is meant to pay any more: its invoice is asked about only once it expired. */
38333
+ requestClosed(paymentId) {
38334
+ const request = this.desk.payment(paymentId);
38335
+ return request?.kind === "request" && request.direction === "out" && request.state !== "pending";
38336
+ }
37516
38337
  registry;
37517
38338
  providers() {
37518
38339
  return this.registry ??= this.options.providers ?? defaultRegistry();
@@ -37539,7 +38360,8 @@ var GhostlyNode = class GhostlyNode {
37539
38360
  events: {
37540
38361
  changed: () => this.walletChanged(),
37541
38362
  received: (op) => void this.desk.onLightningPaid(op),
37542
- resolved: (op, paid) => void this.desk.onLightningResolved(op, paid)
38363
+ resolved: (op, paid) => void this.desk.onLightningResolved(op, paid),
38364
+ requestClosed: (paymentId) => this.requestClosed(paymentId)
37543
38365
  }
37544
38366
  }));
37545
38367
  /** On-chain Bitcoin of each network, through its active source: none until the person sets one up. */
@@ -37810,17 +38632,25 @@ var GhostlyNode = class GhostlyNode {
37810
38632
  return null;
37811
38633
  },
37812
38634
  receivePaymentRequest: (linkId, request) => this.desk.onPaymentRequest(linkId, request, true),
38635
+ taken: (linkId, id) => db.hasMessage(linkId, `peer_${id}`),
37813
38636
  changed: () => this.emitState(),
37814
38637
  fetch: (...request) => (this.options.holdFetch ?? globalThis.fetch)(...request),
37815
38638
  loopbackStorage: () => this.options.holdLoopback === true,
37816
38639
  ttlMs: () => {
37817
- try {
37818
- const raw = typeof localStorage !== "undefined" ? localStorage.getItem("ghostly-test-hold-ttl") : null;
37819
- const ms = raw ? Number(raw) : NaN;
37820
- return Number.isFinite(ms) && ms > 0 ? ms : void 0;
37821
- } catch {
37822
- return;
37823
- }
38640
+ const raw = testSwitch("ghostly-test-hold-ttl");
38641
+ const ms = raw ? Number(raw) : NaN;
38642
+ return Number.isFinite(ms) && ms > 0 ? ms : void 0;
38643
+ },
38644
+ ratchet: (linkId) => {
38645
+ const live = this.links.get(linkId), stored = live?.stored;
38646
+ if (!live || !stored?.profile || !stored.participationSeed || !stored.pairedPeerKey || GhostlyNode.testNoRatchet()) return void 0;
38647
+ return {
38648
+ box: this.ratchetOf(linkId, live, {
38649
+ seedB64: stored.participationSeed,
38650
+ peerKey: stored.pairedPeerKey
38651
+ }),
38652
+ peerSupports: () => this.peerRatchets(live)
38653
+ };
37824
38654
  }
37825
38655
  });
37826
38656
  /** x401 credentials (WISP 3xx): kept for websites the headless CLI calls, never shared with a contact. */
@@ -39466,6 +40296,10 @@ var GhostlyNode = class GhostlyNode {
39466
40296
  const message = await db.getMessage(linkId, id);
39467
40297
  return message && withoutFrame(message);
39468
40298
  }
40299
+ /**
40300
+ * A page of a chat's or a group's history: the newest `limit` (before `before`), or with `after` the oldest `limit`
40301
+ * after it (and before `before`). Each bound is a time or a message's place; only the page's rows are read.
40302
+ */
39469
40303
  async messagePage(asked) {
39470
40304
  const page = await this.storedPage(asked);
39471
40305
  return {
@@ -39473,23 +40307,29 @@ var GhostlyNode = class GhostlyNode {
39473
40307
  messages: page.messages.map(withoutFrame)
39474
40308
  };
39475
40309
  }
39476
- async storedPage({ linkId, limit = 50, before }) {
40310
+ async storedPage({ linkId, limit = 50, before, after }) {
39477
40311
  if (!Number.isSafeInteger(limit) || limit < 1) throw new Error("limit: a whole number of messages, at least 1");
39478
- if (before === void 0) return db.getMessagePage(linkId, { limit });
39479
- if (typeof before === "number") {
39480
- if (Number.isNaN(before)) throw new Error("before: a time or a message id");
39481
- return db.getMessagePage(linkId, {
39482
- limit,
39483
- before: { timestamp: before }
39484
- });
39485
- }
39486
- const from = await db.getMessage(linkId, before);
39487
- if (!from) throw new Error(`No message ${before}`);
39488
- return db.getMessagePage(linkId, {
40312
+ const end = before === void 0 ? void 0 : await this.pagePlace(linkId, before, "before");
40313
+ if (after === void 0) return db.getMessagePage(linkId, {
40314
+ limit,
40315
+ before: end
40316
+ });
40317
+ return db.getMessagePageAfter(linkId, {
39489
40318
  limit,
39490
- before: from
40319
+ before: end,
40320
+ after: await this.pagePlace(linkId, after, "after")
39491
40321
  });
39492
40322
  }
40323
+ /** A page's bound: a time, or the place of a message of the chat. */
40324
+ async pagePlace(linkId, bound, side) {
40325
+ if (typeof bound === "number") {
40326
+ if (Number.isNaN(bound)) throw new Error(`${side}: a time or a message id`);
40327
+ return { timestamp: bound };
40328
+ }
40329
+ const from = await db.getMessage(linkId, bound);
40330
+ if (!from) throw new Error(`No message ${bound}`);
40331
+ return from;
40332
+ }
39493
40333
  /** Saves a message on this device, or unsaves it (`engine/saved.ts`): nothing is sent. */
39494
40334
  saveMessage(params) {
39495
40335
  return this.saved.save(params);
@@ -39805,6 +40645,15 @@ var GhostlyNode = class GhostlyNode {
39805
40645
  nostrLoadOwn(params) {
39806
40646
  return this.nostrSocial.loadOwn(params);
39807
40647
  }
40648
+ nostrOwnFollows(params) {
40649
+ return this.nostrSocial.ownFollowList({ subject: String(params?.subject) });
40650
+ }
40651
+ nostrContactNotes(params) {
40652
+ return this.nostrSocial.contactNotes({
40653
+ linkId: String(params?.linkId),
40654
+ subject: String(params?.subject)
40655
+ });
40656
+ }
39808
40657
  nostrLookup(params) {
39809
40658
  return this.nostrSocial.lookup(params);
39810
40659
  }
@@ -40599,6 +41448,27 @@ var GhostlyNode = class GhostlyNode {
40599
41448
  break;
40600
41449
  }
40601
41450
  }
41451
+ if (!original && group && this.groups.isRemoved(message.linkId.slice(6), reply.id)) return {
41452
+ ...message,
41453
+ replyTo: {
41454
+ ...reply,
41455
+ snippet: "",
41456
+ messageId: reply.id
41457
+ }
41458
+ };
41459
+ const live = group ? void 0 : this.links.get(message.linkId)?.stored;
41460
+ if (!original && live?.removedRefs?.includes(reply.id)) {
41461
+ const row = [`peer_${reply.id}`, `me_${reply.id}`].find((id) => live.deletedIds?.includes(id));
41462
+ return {
41463
+ ...message,
41464
+ replyTo: {
41465
+ ...reply,
41466
+ snippet: "",
41467
+ messageId: row ?? reply.id,
41468
+ from: reply.from ?? (row?.startsWith("peer_") ? "peer" : "me")
41469
+ }
41470
+ };
41471
+ }
40602
41472
  if (!original && !group) {
40603
41473
  history = await db.getMessages(message.linkId);
40604
41474
  original = history.find((m) => m.id !== message.id && replyRef(m) === reply.id);
@@ -40650,10 +41520,21 @@ var GhostlyNode = class GhostlyNode {
40650
41520
  return press;
40651
41521
  }
40652
41522
  /** A paired row's reply as it goes on the wire again (a resend, a hold). */
40653
- /** `localStorage["ghostly-test-no-edit"]`: this app offers no edit/1, as an older one (the e2e's old contact). Nothing else reads it. */
41523
+ /** `localStorage["ghostly-test-no-edit"]`: this app offers no edit/1, as an older one (the e2e's old contact). A test build only. */
40654
41524
  static testNoEdit() {
41525
+ return testSwitch("ghostly-test-no-edit") === "1";
41526
+ }
41527
+ /**
41528
+ * Whether the contact's capability record lists `ratchet/1` (WISP 4xx): the record read this run, or else the last one
41529
+ * kept with the chat (the run's is cleared while offline and on a restart of the chat's transports).
41530
+ */
41531
+ peerRatchets(live) {
41532
+ return !!(live.caps?.peer ?? live.stored.capsState?.peer)?.capabilities.includes(RATCHET_CAPABILITY);
41533
+ }
41534
+ /** An e2e run playing an app from before forward secrecy (WISP 4xx): no ratchet/1, no ratchet, as that app. A release build ignores the key. */
41535
+ static testNoRatchet() {
40655
41536
  try {
40656
- return typeof localStorage !== "undefined" && localStorage.getItem("ghostly-test-no-edit") === "1";
41537
+ return testBuild() && typeof localStorage !== "undefined" && localStorage.getItem("ghostly-test-no-ratchet") === "1";
40657
41538
  } catch {
40658
41539
  return false;
40659
41540
  }
@@ -40763,17 +41644,28 @@ var GhostlyNode = class GhostlyNode {
40763
41644
  const live = this.links.get(linkId);
40764
41645
  if (!live?.stored.profile || live.stored.group) return false;
40765
41646
  const id = `peer_${edit.id}`;
41647
+ const ref = edit.rm && !await this.namesMine(linkId, edit.id);
40766
41648
  if (live.stored.deletedIds?.includes(id)) {
40767
- if (edit.rm) this.quoteSweeps.add(linkId, id, replyRef({
40768
- id,
40769
- linkId
40770
- }));
41649
+ if (ref) {
41650
+ this.quoteSweeps.add(linkId, id, replyRef({
41651
+ id,
41652
+ linkId
41653
+ }));
41654
+ if (!live.stored.removedRefs?.includes(edit.id)) {
41655
+ live.stored = {
41656
+ ...live.stored,
41657
+ removedRefs: withRemovedRef(live.stored.removedRefs, edit.id)
41658
+ };
41659
+ await this.writeDeletions(linkId, { removedRefs: live.stored.removedRefs });
41660
+ this.emitState();
41661
+ }
41662
+ }
40771
41663
  return true;
40772
41664
  }
40773
41665
  if (edit.rm) {
40774
41666
  const message = await db.getMessage(linkId, id);
40775
- if (!message && PAYMENT_LINE_ID.test(edit.id)) return true;
40776
- if (!message || canRemove(message)) await this.forgetMessage(linkId, id, true);
41667
+ if (PAYMENT_LINE_ID.test(edit.id)) return true;
41668
+ if (!message || canRemove(message)) await this.forgetMessage(linkId, id, ref && (message ?? true));
40777
41669
  return true;
40778
41670
  }
40779
41671
  const message = await db.getMessage(linkId, id);
@@ -40891,7 +41783,7 @@ var GhostlyNode = class GhostlyNode {
40891
41783
  /**
40892
41784
  * `restoreCards`, then what waits goes. One look at a time per chat, at most once per `CARD_RESTORE_EVERY_MS`: asked
40893
41785
  * again while one runs or within the gap, one more look goes once it is over, and what waits still goes at once (the
40894
- * edit queue reads the history once a session).
41786
+ * edit queue reads the history once a run).
40895
41787
  */
40896
41788
  restoreCardsSoon(linkId) {
40897
41789
  const flush = () => this.editsFor(linkId).flush().catch(() => {});
@@ -41355,7 +42247,7 @@ var GhostlyNode = class GhostlyNode {
41355
42247
  const out = `${linkId}-out-`;
41356
42248
  const wireId = message.wireId ?? (message.file?.id.startsWith(out) ? message.file.id.slice(out.length) : void 0);
41357
42249
  if (!wireId || message.delivery === "waiting") {
41358
- await this.forgetMessage(linkId, messageId, true);
42250
+ await this.forgetMessage(linkId, messageId, message);
41359
42251
  return { error: null };
41360
42252
  }
41361
42253
  const removal = {
@@ -41370,7 +42262,7 @@ var GhostlyNode = class GhostlyNode {
41370
42262
  removals: withRemoval(live.stored.removals, removal)
41371
42263
  };
41372
42264
  const written = this.writeDeletions(linkId, { removals: live.stored.removals });
41373
- const forgot = this.forgetMessage(linkId, messageId, true);
42265
+ const forgot = this.forgetMessage(linkId, messageId, message);
41374
42266
  await written;
41375
42267
  await forgot;
41376
42268
  const edits = this.editsFor(linkId);
@@ -41417,19 +42309,35 @@ var GhostlyNode = class GhostlyNode {
41417
42309
  });
41418
42310
  return entry.done;
41419
42311
  }
42312
+ /** Whether a 1:1 chat's wire id names a message of mine: here, deleted here, removed, or a file or payment of mine. */
42313
+ async namesMine(linkId, wireId) {
42314
+ const stored = this.links.get(linkId)?.stored, row = `me_${wireId}`;
42315
+ if (stored?.deletedIds?.includes(row) || stored?.removals?.some((r) => r.id === row || r.wireId === wireId)) return true;
42316
+ for (const id of [row, ...await this.rowsNamed(linkId, wireId)]) if ((await db.getMessage(linkId, id))?.sender === "me") return true;
42317
+ return false;
42318
+ }
41420
42319
  /**
41421
42320
  * Forgets one message of a chat on this device, the bytes of its file and any transfer of it, and keeps its id so a
41422
42321
  * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
41423
- * also of a message not here yet. `removed`: deleted for everyone, so the replies here that quote it lose its line too.
42322
+ * also of a message not here yet. `removed`: deleted for everyone (its row, when the caller read it), so the replies
42323
+ * here that quote it lose its line too, and a pin of it goes (`removedRefs`).
41424
42324
  */
41425
42325
  async forgetMessage(linkId, messageId, removed = false) {
41426
42326
  const live = this.links.get(linkId);
41427
42327
  if (!live) return;
42328
+ const ref = removed ? replyRef(removed === true ? {
42329
+ id: messageId,
42330
+ linkId
42331
+ } : removed) : void 0;
41428
42332
  live.stored = {
41429
42333
  ...live.stored,
41430
- deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500)
42334
+ deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500),
42335
+ ...ref && { removedRefs: withRemovedRef(live.stored.removedRefs, ref) }
41431
42336
  };
41432
- this.writeDeletions(linkId, { deletedIds: live.stored.deletedIds }).catch(() => {});
42337
+ this.writeDeletions(linkId, {
42338
+ deletedIds: live.stored.deletedIds,
42339
+ ...ref && { removedRefs: live.stored.removedRefs }
42340
+ }).catch(() => {});
41433
42341
  this.hold.forget(linkId, messageId).catch(() => {});
41434
42342
  const message = await db.getMessage(linkId, messageId);
41435
42343
  if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
@@ -41467,7 +42375,12 @@ var GhostlyNode = class GhostlyNode {
41467
42375
  async forgetQuotes(linkId, removed) {
41468
42376
  const byRef = /* @__PURE__ */ new Map();
41469
42377
  for (const [id, ref] of removed) if (ref !== void 0) byRef.set(ref, id);
41470
- const quoted = (reply) => !reply ? void 0 : reply.messageId !== void 0 && removed.has(reply.messageId) ? reply.messageId : byRef.get(reply.id);
42378
+ const side = (id) => id.startsWith("peer_") ? "peer" : id.startsWith("me_") ? "me" : void 0;
42379
+ const byReference = (reply) => {
42380
+ const id = byRef.get(reply.id);
42381
+ return id === void 0 || !reply.from || !side(id) || side(id) === reply.from ? id : void 0;
42382
+ };
42383
+ const quoted = (reply) => !reply ? void 0 : reply.messageId !== void 0 && removed.has(reply.messageId) ? reply.messageId : byReference(reply);
41471
42384
  const ids = (await db.getMessages(linkId)).filter((m) => {
41472
42385
  const id = quoted(m.replyTo);
41473
42386
  return id !== void 0 && (m.replyTo.snippet || m.replyTo.messageId !== id);
@@ -42202,6 +43115,26 @@ var GhostlyNode = class GhostlyNode {
42202
43115
  this.capsChanged(linkId);
42203
43116
  }
42204
43117
  /** The chat's connection story, for paired chats (not group edges). */
43118
+ /**
43119
+ * The chat's ratchet (WISP 4xx), made once per chat: its keys are read from the chat's row when used (each start of
43120
+ * the link has credentials of its own), so a contact pinned later is the one it seals to. Saved in the row as
43121
+ * `ratchetState`, which no backup or handoff takes along.
43122
+ */
43123
+ ratchetOf(linkId, live, credentials) {
43124
+ return live.ratchet ??= new RatchetBox(() => ({
43125
+ seed: fromBase64Url(live.stored.participationSeed ?? credentials.seedB64),
43126
+ self: identityFromSeedB64(live.stored.participationSeed ?? credentials.seedB64).pubKeyZ32,
43127
+ peer: live.stored.pairedPeerKey ?? credentials.peerKey,
43128
+ rendezvous: [identityFromSeedB64(live.stored.seedB64).pubKeyZ32, live.stored.peerPubKeyZ32],
43129
+ secret: fromBase64Url(live.stored.encKeyB64)
43130
+ }), live.stored.ratchetState ?? emptyRatchetState(), async (state) => {
43131
+ await db.patchLink(linkId, { ratchetState: state });
43132
+ live.stored = {
43133
+ ...live.stored,
43134
+ ratchetState: state
43135
+ };
43136
+ });
43137
+ }
42205
43138
  transportLogOf(live) {
42206
43139
  if (!live.stored.profile || live.stored.group) return void 0;
42207
43140
  if (live.transportLog) return live.transportLog;
@@ -42873,17 +43806,32 @@ var GhostlyNode = class GhostlyNode {
42873
43806
  async appOpen({ linkId, ref, version, digest }) {
42874
43807
  const { live, app } = this.appChat(linkId, ref);
42875
43808
  if (!isAppVersion(version)) throw new Error("Not an app version");
43809
+ const turn = this.appTurn(linkId, app);
42876
43810
  await this.appChatRunnable(ref, digest);
43811
+ if (this.appTurns.get(`${linkId} ${app}`) !== turn) return { app };
42877
43812
  const open = live.appsOpen ??= /* @__PURE__ */ new Map();
42878
43813
  if (live.link) live.link.openApp(app, version);
42879
43814
  else open.set(app, version);
42880
43815
  return { app };
42881
43816
  }
43817
+ /** The last open or close of each app in each chat, by chat and chat app id: an open still reading the store is not the last. */
43818
+ appTurns = /* @__PURE__ */ new Map();
43819
+ nextAppTurn = 0;
43820
+ appTurn(linkId, app) {
43821
+ const turn = ++this.nextAppTurn;
43822
+ this.appTurns.set(`${linkId} ${app}`, turn);
43823
+ return turn;
43824
+ }
43825
+ /** Closes `app` in a chat, and any open of it still on its way. */
43826
+ appCloseIn(linkId, live, app) {
43827
+ this.appTurn(linkId, app);
43828
+ if (live.link) live.link.closeApp(app);
43829
+ else live.appsOpen?.delete(app);
43830
+ }
42882
43831
  /** This side closed an app in a paired chat: `close` goes now when the session is live. */
42883
43832
  appClose({ linkId, ref }) {
42884
43833
  const { live, app } = this.appChat(linkId, ref);
42885
- if (live.link) live.link.closeApp(app);
42886
- else live.appsOpen?.delete(app);
43834
+ this.appCloseIn(linkId, live, app);
42887
43835
  }
42888
43836
  /** One data frame of an app open on both sides, on the live session only; nothing is kept to send later. */
42889
43837
  async appSend({ linkId, ref, data, digest }) {
@@ -42970,17 +43918,15 @@ var GhostlyNode = class GhostlyNode {
42970
43918
  }
42971
43919
  /** Every page went away: no app runs here any more, so each open one is closed (`close` goes where it can). */
42972
43920
  appsCloseAll() {
42973
- for (const live of this.links.values()) for (const app of [...live.appsOpen?.keys() ?? []]) if (live.link) live.link.closeApp(app);
42974
- else live.appsOpen?.delete(app);
43921
+ for (const [linkId, live] of this.links) for (const app of [...live.appsOpen?.keys() ?? []]) this.appCloseIn(linkId, live, app);
43922
+ for (const key of this.appTurns.keys()) this.appTurns.set(key, ++this.nextAppTurn);
42975
43923
  }
42976
43924
  /** An app that went (uninstalled) is closed in every chat it was open in, as `appClose` does. */
42977
43925
  appsCloseOf(ref) {
42978
43926
  for (const [linkId, live] of this.links) {
42979
43927
  if (!live.appsOpen?.size) continue;
42980
43928
  const { app } = this.appChat(linkId, ref);
42981
- if (!live.appsOpen.has(app)) continue;
42982
- if (live.link) live.link.closeApp(app);
42983
- else live.appsOpen.delete(app);
43929
+ if (live.appsOpen.has(app)) this.appCloseIn(linkId, live, app);
42984
43930
  }
42985
43931
  }
42986
43932
  /** Keeps a pin of a 1:1 chat when it is newer than the chat's; `out`: mine, to say until the contact confirms it. */
@@ -43022,6 +43968,29 @@ var GhostlyNode = class GhostlyNode {
43022
43968
  };
43023
43969
  await db.patchLink(linkId, { pinOut: void 0 });
43024
43970
  }
43971
+ /**
43972
+ * A 1:1 chat's pin that came before its message (pinned while I was away: the pin goes as the session opens, ahead of
43973
+ * what waited) names its row once the row is here. Only the rows that changed are read, and only while such a pin stands.
43974
+ */
43975
+ async pinnedRowCame(linkId, ids) {
43976
+ const live = this.links.get(linkId), pin = live?.stored.pin;
43977
+ if (!live || live.stored.group || !pin?.id || pin.messageId) return;
43978
+ for (const id of new Set(ids)) {
43979
+ const row = await db.getMessage(linkId, id);
43980
+ if (!row || replyRef(row) !== pin.id) continue;
43981
+ if (live.stored.pin !== pin) return;
43982
+ live.stored = {
43983
+ ...live.stored,
43984
+ pin: {
43985
+ ...pin,
43986
+ messageId: row.id
43987
+ }
43988
+ };
43989
+ await db.patchLink(linkId, { pin: live.stored.pin });
43990
+ this.emitState();
43991
+ return;
43992
+ }
43993
+ }
43025
43994
  /** A pin that came, as it is kept: who pinned, and its row when it is here. */
43026
43995
  async pinCame(chat, by, pin) {
43027
43996
  const row = await pinnedRow(this.pinsHost, chat, pin.id);
@@ -43539,10 +44508,22 @@ var GhostlyNode = class GhostlyNode {
43539
44508
  source: created.source
43540
44509
  };
43541
44510
  }
43542
- /** `card`: the Lightning card that will pay; absent, the network's default one. */
43543
- walletQuoteInvoice({ invoice, via, network, card }) {
44511
+ /**
44512
+ * The screen shows this invoice of ours (Receive): its mint or its Lightning card asks about it at the fast pace for a
44513
+ * while (`INVOICE_PACE.watchMs`), so a payment shows within seconds. The screen says it again while it shows it.
44514
+ */
44515
+ async walletWatchInvoice({ invoice, network }) {
44516
+ if (typeof invoice !== "string" || !invoice.trim()) throw new Error("invoice is required");
44517
+ if (await this.wallet.watch(invoice)) return;
44518
+ await this.lightnings[this.net(network)].watch(invoice);
44519
+ }
44520
+ /**
44521
+ * `card`: the Lightning card that will pay; absent, the network's default one. `amount`: the sats chosen for an
44522
+ * invoice with no amount, which only the mints pay (`via: "cashu"`); a Lightning source refuses one.
44523
+ */
44524
+ walletQuoteInvoice({ invoice, via, network, card, amount }) {
43544
44525
  const n = this.net(network);
43545
- return via === "cashu" ? this.wallet.quoteInvoice(invoice, n) : this.lightningCard(n, card).then((c) => c.quote(invoice));
44526
+ return via === "cashu" ? this.wallet.quoteInvoice(invoice, n, amount) : this.lightningCard(n, card).then((c) => c.quote(invoice));
43546
44527
  }
43547
44528
  /**
43548
44529
  * `confirmedReal`: the person confirmed a Mainnet payment as real money; without it one is refused. `linkId` +
@@ -43688,8 +44669,11 @@ var GhostlyNode = class GhostlyNode {
43688
44669
  return { inspection: await this.wallet.inspect(text) };
43689
44670
  }
43690
44671
  async walletReceiveToken({ token }) {
43691
- const { amount } = await this.wallet.receiveToken(token.trim());
43692
- return { amount };
44672
+ const { amount, fee } = await this.wallet.receiveToken(token.trim());
44673
+ return {
44674
+ amount,
44675
+ fee
44676
+ };
43693
44677
  }
43694
44678
  /** `network`: only that network's Cashu wallet (its mints). */
43695
44679
  walletExport(params) {
@@ -44444,6 +45428,7 @@ var GhostlyNode = class GhostlyNode {
44444
45428
  }
44445
45429
  this.watchActiveTurn();
44446
45430
  this.watchTombstones();
45431
+ await this.finishRemovals().catch(() => {});
44447
45432
  await this.rotateIfDue().catch(() => {});
44448
45433
  }
44449
45434
  /**
@@ -44544,6 +45529,12 @@ var GhostlyNode = class GhostlyNode {
44544
45529
  async moveDeviceSet(remove) {
44545
45530
  this.setMoveAllowed();
44546
45531
  if (this.settingMove) throw new Error("remove-busy: The device set is already changing.");
45532
+ const record = remove === void 0 ? null : await readDeviceRecord(databaseName()).catch(() => null);
45533
+ if (record?.state === "active" && record.earlierSets.some((set) => set.removed === remove) && !record.deviceSet.some((slot) => slot?.key === remove)) {
45534
+ await this.finishRemovals().catch(() => {});
45535
+ this.watchTombstones();
45536
+ return this.deviceSet();
45537
+ }
44547
45538
  const work = (async () => {
44548
45539
  const ports = await this.setMovePorts();
44549
45540
  if (!ports) throw new Error("remove-state: This device cannot sign for its device set.");
@@ -44555,7 +45546,7 @@ var GhostlyNode = class GhostlyNode {
44555
45546
  } finally {
44556
45547
  this.settingMove = null;
44557
45548
  }
44558
- if (remove !== void 0) await this.afterDeviceRemoved(remove).catch(() => {});
45549
+ if (remove !== void 0) await this.finishRemovals().catch(() => {});
44559
45550
  if (this.handoffGiver) {
44560
45551
  this.deviceLinks?.setHandoff(null);
44561
45552
  this.handoffGiver = null;
@@ -44590,6 +45581,28 @@ var GhostlyNode = class GhostlyNode {
44590
45581
  }
44591
45582
  }
44592
45583
  /**
45584
+ * What each removal left in the profile (`afterDeviceRemoved`), for every earlier set that still names the device it
45585
+ * removed: after the move, and at start for one a reload, a crash or a stop cut short after its write. The name is
45586
+ * dropped once its device's leftovers are cleared.
45587
+ */
45588
+ async finishRemovals() {
45589
+ const profile = databaseName();
45590
+ const record = await readDeviceRecord(profile);
45591
+ if (record?.state !== "active") return;
45592
+ const done = /* @__PURE__ */ new Set();
45593
+ for (const set of record.earlierSets) {
45594
+ if (set.removed === void 0 || done.has(set.removed)) continue;
45595
+ if (await this.afterDeviceRemoved(set.removed).then(() => true, () => false)) done.add(set.removed);
45596
+ }
45597
+ if (!done.size) return;
45598
+ const now = await readDeviceRecord(profile);
45599
+ if (now?.state !== "active") return;
45600
+ await amendDevice(profile, { earlierSets: now.earlierSets.map(({ removed, ...set }) => removed === void 0 || done.has(removed) ? set : {
45601
+ ...set,
45602
+ removed
45603
+ }) });
45604
+ }
45605
+ /**
44593
45606
  * Remove: the device with this signing key can no longer take the profile (WISP 06 § Removing a device). The set
44594
45607
  * moves to a new secret, which the other devices get over their old links; the removed one gets nothing, and reads
44595
45608
  * its removal from the tombstone. Only the active device removes.
@@ -44664,7 +45677,7 @@ var GhostlyNode = class GhostlyNode {
44664
45677
  await this.startDeviceSet();
44665
45678
  },
44666
45679
  onChange: (view) => {
44667
- if (view.step === "failed") setTimeout(() => void this.rotateIfDue().catch(() => {}), 0);
45680
+ if (view.step === "failed" || view.step === "done") setTimeout(() => void this.rotateIfDue().catch(() => {}), 0);
44668
45681
  }
44669
45682
  });
44670
45683
  this.enrollment = inviter;
@@ -45266,6 +46279,7 @@ var GhostlyNode = class GhostlyNode {
45266
46279
  const native = this.keepsGroupNative(stored);
45267
46280
  const resumeOn = native ? TRANSPORTS.find((t) => t !== "webrtc/1" && t in this.nativeFactories && !!stored.peerTransports?.includes(t)) : "webrtc/1";
45268
46281
  live.pairing = { status: "connecting" };
46282
+ live.edgeStartedAt = Date.now();
45269
46283
  live.carried?.stop();
45270
46284
  live.carried = entry || this.groups.isCommunityGroup(group) ? void 0 : new CarriedTransport(this.groupTransport, live.myPubKeyZ32, stored.peerPubKeyZ32, {
45271
46285
  carry: (payload) => this.groups.carrySignal(group, peer, payload),
@@ -45621,7 +46635,11 @@ var GhostlyNode = class GhostlyNode {
45621
46635
  return !peer || peer.capabilities.includes("dht-text/1");
45622
46636
  },
45623
46637
  peerAcceptsFile: () => !!live.caps?.peer?.capabilities.includes(DHT_FILE_CAPABILITY),
45624
- reactions: () => live.stored.reactionsOut ?? []
46638
+ reactions: () => live.stored.reactionsOut ?? [],
46639
+ ratchet: credentials && !GhostlyNode.testNoRatchet() ? {
46640
+ box: this.ratchetOf(linkId, live, credentials),
46641
+ peerSupports: () => this.peerRatchets(live)
46642
+ } : void 0
45625
46643
  } : void 0,
45626
46644
  native: {
45627
46645
  peerDescriptors: stored.peerDescriptors,
@@ -46028,6 +47046,7 @@ var GhostlyNode = class GhostlyNode {
46028
47046
  "chat/1",
46029
47047
  DHT_TEXT_CAPABILITY,
46030
47048
  DHT_FILE_CAPABILITY,
47049
+ ...GhostlyNode.testNoRatchet() ? [] : [RATCHET_CAPABILITY],
46031
47050
  ...live?.stored.hold?.enabled ? [HOLD_CAPABILITY] : [],
46032
47051
  "files/2",
46033
47052
  UPGRADE_CAPABILITY,
@@ -46099,7 +47118,7 @@ var GhostlyNode = class GhostlyNode {
46099
47118
  nativeFactoriesFor(relayOnly) {
46100
47119
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
46101
47120
  return {
46102
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-DitYDnXx.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
47121
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-g7eXzf5h.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46103
47122
  ...relayOnly ? {} : this.options.nativeTransports,
46104
47123
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
46105
47124
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -46155,7 +47174,7 @@ var GhostlyNode = class GhostlyNode {
46155
47174
  this.relayRetry = setTimeout(() => {
46156
47175
  this.relayRetry = null;
46157
47176
  for (const [linkId, live] of this.links) if (live.link && live.stored.profile && (!live.stored.group || this.keepsGroupNative(live.stored)) && live.stored.deliveryMode !== "dht" && !live.link.availableTransports.includes("hyperdht/1") && this.keepsNativeEndpoints(linkId, live.stored)) this.ensureNativeEndpoints(linkId);
46158
- }, RELAY_RETRY_MS);
47177
+ }, RELAY_RETRY_MS / 2 + Math.random() * RELAY_RETRY_MS);
46159
47178
  }
46160
47179
  /** A new relay (or none): chats give up their endpoints on the old one, as soon as none of them carries a session. */
46161
47180
  async relayChanged() {
@@ -46599,6 +47618,7 @@ var GhostlyNode = class GhostlyNode {
46599
47618
  */
46600
47619
  async messagesChanged(linkId, ids) {
46601
47620
  this.chatSearch.changed(linkId);
47621
+ await this.pinnedRowCame(linkId, ids);
46602
47622
  const reacted = this.reactionNotes.get(linkId);
46603
47623
  if (reacted?.message && ids.includes(reacted.message)) {
46604
47624
  const row = await db.getMessage(linkId, reacted.message);
@@ -46807,7 +47827,11 @@ var GhostlyNode = class GhostlyNode {
46807
47827
  ...stored.wakeMuted && { wakeMuted: true }
46808
47828
  },
46809
47829
  ...this.reactionNotes.has(stored.id) && { lastReaction: this.reactionNotes.get(stored.id) },
46810
- ...stored.pin && { pin: pinView(stored.pin) },
47830
+ ...stored.pin && { pin: pinView(stored.pin.id && stored.removedRefs?.includes(stored.pin.id) ? {
47831
+ ...stored.pin,
47832
+ id: "",
47833
+ messageId: void 0
47834
+ } : stored.pin) },
46811
47835
  participationKey: participationKeyOf(live),
46812
47836
  peerParticipationKey: stored.pairedPeerKey,
46813
47837
  publicProfiles: void 0,
@@ -47061,7 +48085,7 @@ var EngineServer = class {
47061
48085
  kind: "response",
47062
48086
  id: request.id
47063
48087
  };
47064
- if (request.method === "setCallSignal") this.offers.delete(request.params?.linkId ?? "");
48088
+ if (request.method === "setCallSignal") this.callHandled(client, request.params);
47065
48089
  let params = request.params;
47066
48090
  if (request.method === "setCallOn") {
47067
48091
  if (request.params?.on === true) this.onCall.add(client);
@@ -47189,6 +48213,22 @@ var EngineServer = class {
47189
48213
  broadcast(event) {
47190
48214
  for (const client of [...this.clients]) this.post(client, event);
47191
48215
  }
48216
+ /**
48217
+ * A page sent a call signal in a chat. While the contact's offer rang there, an answer or a hang-up is that page taking
48218
+ * the call or declining it: the other pages (the extension's tabs share one engine) stop ringing. Before, they rang
48219
+ * on to their timeout and then wrote "Missed call" into the history of a call that was on, and a Decline pressed in
48220
+ * one of them ended it.
48221
+ */
48222
+ callHandled(from, params) {
48223
+ const { linkId, signal } = params ?? {};
48224
+ if (typeof linkId !== "string" || !this.offers.delete(linkId)) return;
48225
+ const kind = typeof signal === "string" ? signalKind(signal) : void 0;
48226
+ if (kind !== "a" && kind !== "h") return;
48227
+ for (const client of [...this.clients]) if (client !== from) this.post(client, {
48228
+ kind: "call-handled",
48229
+ linkId
48230
+ });
48231
+ }
47192
48232
  };
47193
48233
  /** Whether a call only reads a group's stored history (`GhostlyNode.groupsRead`). */
47194
48234
  function readsGroupHistory(request) {
@@ -47207,4 +48247,4 @@ function signalKind(signal) {
47207
48247
  //#endregion
47208
48248
  export { EngineServer };
47209
48249
 
47210
- //# sourceMappingURL=server-BGCuHbmQ.js.map
48250
+ //# sourceMappingURL=server-D9RAmGdm.js.map