@ghostlytools/cli 1.7.4 → 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 (84) hide show
  1. package/README.md +12 -6
  2. package/SKILL.md +1 -1
  3. package/dist/assets/{api-Chhvpwok.js → api-Dj1yn0px.js} +2 -2
  4. package/dist/assets/{api-D3i2hwy0.js → api-I_KbuXHa.js} +62 -16
  5. package/dist/assets/api-I_KbuXHa.js.map +1 -0
  6. package/dist/assets/{apiKit-BtsHrnoo.js → apiKit-C-_PWZvy.js} +17 -5
  7. package/dist/assets/{apiKit-BtsHrnoo.js.map → apiKit-C-_PWZvy.js.map} +1 -1
  8. package/dist/assets/{apps-BHl97rHs.js → apps-DKIe8VjF.js} +8 -7
  9. package/dist/assets/apps-DKIe8VjF.js.map +1 -0
  10. package/dist/assets/{apps-BFJTqvAt.js → apps-DbEfL_3b.js} +1 -1
  11. package/dist/assets/{arkade-BFE8KkEE.js → arkade-k1bdSm70.js} +2 -2
  12. package/dist/assets/{arkade-BFE8KkEE.js.map → arkade-k1bdSm70.js.map} +1 -1
  13. package/dist/assets/{backup-Bbsr6nDi.js → backup-Cdd6-HNu.js} +1 -1
  14. package/dist/assets/{backup-CxACdtQX.js → backup-beKfbfNk.js} +6 -6
  15. package/dist/assets/{backup-CxACdtQX.js.map → backup-beKfbfNk.js.map} +1 -1
  16. package/dist/assets/buttons-BO1_7V4L.js +2 -0
  17. package/dist/assets/{buttons-CieBtXEO.js → buttons-ClI13rdv.js} +7 -6
  18. package/dist/assets/buttons-ClI13rdv.js.map +1 -0
  19. package/dist/assets/{daemonProof-QmtwDj-N.js → daemonProof-DtrL5lE5.js} +2 -2
  20. package/dist/assets/{daemonProof-QmtwDj-N.js.map → daemonProof-DtrL5lE5.js.map} +1 -1
  21. package/dist/assets/{envelope-DYiGwzq_.js → envelope-B88yiCQj.js} +2 -2
  22. package/dist/assets/{envelope-DYiGwzq_.js.map → envelope-B88yiCQj.js.map} +1 -1
  23. package/dist/assets/{errors-QUGP-jIF.js → errors-R4S2SAEM.js} +7 -2
  24. package/dist/assets/errors-R4S2SAEM.js.map +1 -0
  25. package/dist/assets/{groupFiles-CBJIEvCE.js → groupFiles-DjQc5XXv.js} +135 -24
  26. package/dist/assets/groupFiles-DjQc5XXv.js.map +1 -0
  27. package/dist/assets/{host-Va-r_KJz.js → host-CNWGB3-j.js} +44 -20
  28. package/dist/assets/host-CNWGB3-j.js.map +1 -0
  29. package/dist/assets/{hyperdhtRelay-B2uK9tJv.js → hyperdhtRelay-g7eXzf5h.js} +2 -2
  30. package/dist/assets/{hyperdhtRelay-B2uK9tJv.js.map → hyperdhtRelay-g7eXzf5h.js.map} +1 -1
  31. package/dist/assets/{irohWeb-DxeEgQ-W.js → irohWeb-Bx8dI4be.js} +2 -2
  32. package/dist/assets/{irohWeb-DxeEgQ-W.js.map → irohWeb-Bx8dI4be.js.map} +1 -1
  33. package/dist/assets/{main-BX4oPWCJ.js → main-BRxhBctJ.js} +121 -37
  34. package/dist/assets/main-BRxhBctJ.js.map +1 -0
  35. package/dist/assets/{mainline-IfWQOB-J.js → mainline-CwuS6ngj.js} +2 -2
  36. package/dist/assets/{mainline-IfWQOB-J.js.map → mainline-CwuS6ngj.js.map} +1 -1
  37. package/dist/assets/mints-BaOmx517.js +2 -0
  38. package/dist/assets/{mints-BrlY773j.js → mints-j5XAOk4f.js} +15 -3
  39. package/dist/assets/mints-j5XAOk4f.js.map +1 -0
  40. package/dist/assets/{networkReason-N2vAaoth.js → networkReason-CIAMieQm.js} +2 -2
  41. package/dist/assets/{networkReason-N2vAaoth.js.map → networkReason-CIAMieQm.js.map} +1 -1
  42. package/dist/assets/{nwc-CzyCtNK2.js → nwc-C9JLJJkL.js} +3 -3
  43. package/dist/assets/{nwc-CzyCtNK2.js.map → nwc-C9JLJJkL.js.map} +1 -1
  44. package/dist/assets/{nwcProvider-DjWmEn3j.js → nwcProvider-pFMrsUJh.js} +2 -2
  45. package/dist/assets/{nwcProvider-DjWmEn3j.js.map → nwcProvider-pFMrsUJh.js.map} +1 -1
  46. package/dist/assets/{profiles-DcCeOi7J.js → profiles-MFtCmJwK.js} +3 -3
  47. package/dist/assets/{profiles-DcCeOi7J.js.map → profiles-MFtCmJwK.js.map} +1 -1
  48. package/dist/assets/{registry-CeW8XEQc.js → registry-Cks7FA_o.js} +3 -3
  49. package/dist/assets/{registry-CeW8XEQc.js.map → registry-Cks7FA_o.js.map} +1 -1
  50. package/dist/assets/{registry-BmS02J5h.js → registry-DY2ixQfU.js} +1 -1
  51. package/dist/assets/{resolve-BvHkAhDH.js → resolve-C4Y2HPqQ.js} +15 -3
  52. package/dist/assets/resolve-C4Y2HPqQ.js.map +1 -0
  53. package/dist/assets/{restoredRows-mTTp3XNs.js → restoredRows-BCRCjhdF.js} +26 -2
  54. package/dist/assets/{restoredRows-mTTp3XNs.js.map → restoredRows-BCRCjhdF.js.map} +1 -1
  55. package/dist/assets/{server-BUcJo4vz.js → server-D9RAmGdm.js} +650 -150
  56. package/dist/assets/server-D9RAmGdm.js.map +1 -0
  57. package/dist/assets/{src-BB5-5P3s.js → src-1RU4TilT.js} +878 -77
  58. package/dist/assets/src-1RU4TilT.js.map +1 -0
  59. package/dist/assets/{translate-2WyaRVCr.js → translate-od5GbpvR.js} +11 -7
  60. package/dist/assets/translate-od5GbpvR.js.map +1 -0
  61. package/dist/assets/{usdt-BLazHiaP.js → usdt-DldXV0MR.js} +3 -3
  62. package/dist/assets/{usdt-BLazHiaP.js.map → usdt-DldXV0MR.js.map} +1 -1
  63. package/dist/assets/waitNotice-Ck3el3_Z.js +45 -0
  64. package/dist/assets/waitNotice-Ck3el3_Z.js.map +1 -0
  65. package/dist/assets/{words-BaumxjXe.js → words-BS2qq_vV.js} +6 -3
  66. package/dist/assets/words-BS2qq_vV.js.map +1 -0
  67. package/dist/ghostly.mjs +1 -1
  68. package/examples/claude-code-agent.sh +1 -1
  69. package/package.json +1 -1
  70. package/dist/assets/api-D3i2hwy0.js.map +0 -1
  71. package/dist/assets/apps-BHl97rHs.js.map +0 -1
  72. package/dist/assets/buttons-CieBtXEO.js.map +0 -1
  73. package/dist/assets/buttons-YtAj3R_E.js +0 -2
  74. package/dist/assets/errors-QUGP-jIF.js.map +0 -1
  75. package/dist/assets/groupFiles-CBJIEvCE.js.map +0 -1
  76. package/dist/assets/host-Va-r_KJz.js.map +0 -1
  77. package/dist/assets/main-BX4oPWCJ.js.map +0 -1
  78. package/dist/assets/mints-BrlY773j.js.map +0 -1
  79. package/dist/assets/mints-CqTdA4Gk.js +0 -2
  80. package/dist/assets/resolve-BvHkAhDH.js.map +0 -1
  81. package/dist/assets/server-BUcJo4vz.js.map +0 -1
  82. package/dist/assets/src-BB5-5P3s.js.map +0 -1
  83. package/dist/assets/translate-2WyaRVCr.js.map +0 -1
  84. package/dist/assets/words-BaumxjXe.js.map +0 -1
@@ -1,15 +1,15 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $i as TRANSPORTS, $l as currentRelays, $o as HANDOFF_ACK, $r as checkPushEndpoint, $s as enrollDigits, $t as SEPOLIA_TEST_USDT, A as knockIdentity, Aa as forwardedAgain, Ac as APP_BUNDLE_MAGIC, An as fedimintRequestPayload, Ao as WATCH_PEER_MS, Ar as FILE_LIMITS, As as newHandoffId, Ba as readReaction, Bc as readAppBundleAsync, Bl as signTurnPacket, Bn as pairedMessageFrame, Bo as RTC_CONFIG, Br as PIN_LIMITS, C as communityHasFrame, Ca as MAX_REMOVAL_NUMBER, Cc as mergeContactKnocks, Cl as deviceEchoNonce, Co as verifyCommitSignature, Cr as pickHubs, Cs as handoffManifestFrames, Cu as randomBytes, D as decodeGroupEntryLink, Dc as requestRecords, Dl as newDeviceSetSecret, Dn as decodeBolt11, Do as DHT_POLL_INTERVALS, Dr as readLobby, Ds as handoffRetryAfter, Du as utf8Encode, Ea as dhtEditId, Ec as readLinkRecord, El as devicePingFrame, Er as readBeaconHead, Es as handoffReleaseFrame, Eu as utf8Decode, F as GroupWakeLimiter, Fa as ReactionWindow, Fi as capsDescriptors, Fl as TURN_LAST_SEQUENCE, Fn as GhostLink, Fo as webLocalFetch, Fs as readHandoffHello, Ga as replySnippet, Gc as appRef, Gl as turnStatedVerifier, Gn as GROUP_FILE_LIMITS, Go as contactRtcConfig, Gr as readPin, Gs as signTombstone, Gt as encodeDidDhtDeactivated, H as GroupSession, Ha as wireReaction, Hl as turnInstance, Hn as engineError, Hr as nextPinNumber, Hs as readSetUpdate, I as groupWakeFrame, Ia as nextReactionNumber, Ii as dialDescriptors, Il as TURN_MAX, In as INVITE_TAKEN, Io as LIMITS, Ir as TypingSender, Is as readHandoffPake, J as parseCommunityEdit, Jc as isAppKey, Jr as deviceWakeRequest, Jt as signDidDhtPacket, K as GROUP_EDIT_TEXT_BYTES, Ka as BUTTON_ID, Kl as turnVerifierMark, Kr as WAKE_CALL_INTERVAL_MS, Ks as verifySetUpdate, Kt as encodeDidDhtPacket, L as groupWakes, La as queueReaction, Lc as isAppUrl, Ll as firstDeviceSetSecret, Ln as LIVENESS_PING_MS, Lo as decodeControl, Ls as readHandoffTurnFrame, M as mergeKnocks, Ma as COMMUNITY_REACTION_FRAME, Ml as TURN_SETTLE_MS, Mn as isFederationId, Mo as GhostlyHttpError, Mr as transferEnded, Ms as readHandoffCancel, N as readKnocks, Na as GROUP_REACTION_FRAME, Nc as appDigest, Ni as CapsExchange, Nl as classifyTurnRead, Nn as parseCashuRequestPayload, No as formatLocalTarget, Nr as transferStalled, Ns as readHandoffDone, O as encodeGroupEntryLink, Oc as seenEntry, Ol as seedSigner, On as ENDPOINT, Or as shouldBeHub, Os as handoffStreamKey, Pa as REACTION_LIMITS, Pc as appViewOf, Pi as DHT_TEXT_CAPABILITY, Pl as turnPutSummary, Pn as parseFedimintRequestPayload, Po as parseLocalTarget, Ps as readHandoffHave, Qi as validExternalKey, Qn as readGroupFileMeta, Qo as serviceIdFromName, Qr as wakeRequest, Qs as enrollCancelReason, Qt as PaymentPreflightError, R as parseGroupWakeFrame, Ra as reactionEmoji, Rc as pacer, Rl as nextTurnPosition, Rn as PAIRED_FRAME_TOO_LARGE, Ro as encodeControl, Rr as typingActivity, Rs as readHandoffVerified, S as GROUP_READ_NOTE_COMMUNITY, Sa as EDIT_RATE_WINDOW_MS, Sc as makeStampPaced, Sl as deviceEchoFrame, So as rosterHas, Sr as newerHead, Ss as handoffHelloFrame, T as encodeCommunityLink, Ta as RateWindow, Tc as readKnockSlot, Tl as deviceLinkPairing, To as DirectPathWatch, Tr as readBeacon, Ts as handoffPakeFrame, Tu as toZ32, U as frameBytes, Ua as pairedReplyAuthor, Uc as APP_STATEMENT_LIMITS, Ui as emptyIdentityLedger, Ul as turnKeys, Un as engineText, Ur as pinIsNewer, Us as setAckFrame, Ut as didDhtDocument, V as GROUP_READ_NOTE, Va as validReactionNumber, Vc as sha256Paced, Vl as signTurnRelease, Vn as EngineError, Vr as mayPin, Wa as readReply, Wc as appFingerprint, Wl as turnName, Wn as parseEngineError, Wr as pinNumberHolds, Ws as setUpdateFrame, Wt as didDhtFromPublicKey, X as groupName, Xc as readAppRevocation, Xi as PeerProofs, Xl as RelayTransport, Xn as groupFileFallback, Xo as HTTP_SERVICE_PROTO, Xr as parseWakeFrame, Xt as EVM_TEST_CHAINS, Y as mentionsMember, Yc as isAppRef, Yi as lastSharedWithMe, Yo as emptyLinkRecords, Yr as newWakeToken, Yt as ETHEREUM_USDT, Zi as emptyProofLedger, Zo as LEGACY_SERVICES, Zr as relayRequest, Zs as enrollCancelFrame, Zt as ONCHAIN_PROVIDER, _ as groupTypingEpoch, _a as parseVoiceMeta, _c as contactDay, _i as newMailbox, _l as inviteOwnership, _r as freshHubs, _s as handoffContext, _t as normalizeAtprotoHandle, a as appRevocationFor, aa as peekDhtMailbox, ac as readEnrollHello, ai as isAppVersion, al as readCanonicalJson, an as assertTokenUnits, as as HANDOFF_PAKE, au as withRequestOptions, b as COMMUNITY_LIMITS, ba as parseVideoMeta, bc as knockSlotRecords, bl as ENROLL_CAPABILITY, bo as parseGroupCommit, br as mergeBeacon, bs as handoffDigest, bu as bytesEqual, c as checkAppBeforeRun, ca as formatFileSize, cc as endedRequests, ci as EDIT_CAPABILITY, cl as readContactLink, cn as validatePaymentTarget, cr as readGroupSignal, cs as HANDOFF_TIMINGS, cu as createRelayPayload, dc as planKnocks, di as HOLD_CAPABILITY, dl as readDeviceInvite, dn as SPARK_PROVIDER, do as claimedTime, dr as meshHubs, ds as filePartName, ea as automaticTransport, ec as enrollDoneFrame, ei as vapidKeysMatch, eo as STATUS_CARD_LIMITS, es as HANDOFF_CANCEL, eu as normalizeRelayUrl, fc as settleRequest, fi as HOLD_DATED_BACK_MS, fl as OwnInviteError, fn as sparkAddressKind, fo as heardTime, fr as pickMeshHubs, fs as handoffAttemptAllowed, fu as createIdentity, g as GroupTypingBoard, ga as fileMessageText, gc as REQUEST_LIFETIME_MS, gi as isHoldUrl, gl as inviteLink, gn as isPubkyKey, go as GROUP_MEMBER_CAP, gr as doorHubs, gs as handoffCancelFrame, gt as isAtprotoDid, gu as verify, hc as ContactRequestError, hi as HoldRefusedError, hl as encodeInviteCode, ho as GROUP_ADMIN_OFF_ERROR, hr as beaconRecords, hs as handoffBusyFrame, hu as publicKeyFromZ32, i as addedAppPermissions, ia as DHT_MESSAGE_TTL, ic as readEnrollGrant, ii as chatAppId, in as arkAddressPrefix, is as HANDOFF_OFFER, iu as isDiscoveryBudgetError, j as knockRecords, ja as readForwarded, jc as APP_ICON_PATH, jl as TURN_RAISE_READ_TIMEOUT_MS, jn as findEndpoint, jo as presenceSeenAt, js as readHandoffAck, k as entryParams, ka as parseLinkPreview, kc as APP_BUNDLE_LIMITS, kl as webCryptoSigner, kn as cashuRequestPayload, ko as RELAY_POLL_INTERVALS, kr as ChatFiles, ks as handoffVersions, l as planAppUpdate, la as sanitizeFileName, lc as inboxRecord, li as STATUS_CARD_CAPABILITY, ll as createDeviceInvite, ln as walletNetworkOf, lo as statusCardText, lr as MESH_HUBS, ls as HANDOFF_VERIFIED, mc as turnOff, mi as HoldKeys, ml as decodeInviteCode, mn as isBitcoinAddress, mo as shownTime, mr as beaconKeys, ms as handoffAttemptSucceeded, mu as identityFromSeedB64, n as readX401SdJwtVc, nc as enrollHelloFrame, ni as isServeId, nn as USDT_PUBLIC_RPC, nr as CarriedTransport, ns as HANDOFF_HAVE, nu as traceLink, o as appStoreDecision, oa as DHT_FILE_CAPABILITY, oc as verifyEnrollProof, oi as APPS_CAPABILITY, ol as createContactLink, on as assertWholeSats, oo as checkStatusCard, os as HANDOFF_PIECE_BYTES, ou as PacketTooLargeError, p as readAppStoreSteps, pc as takeRequest, pi as HOLD_LIMITS, pl as createChatInvite, pn as sparkInvoiceDetails, po as receivedTimestamp, pr as COMMUNITY_TOPOLOGY, ps as handoffAttemptFailed, pu as identityFromSeed, q as carryMentions, qc as isAppHash, qi as receivedIdentityStatus, ql as DEFAULT_RELAYS, qo as parseCallSignal, qr as WakeLimiter, r as sameX401HolderJwk, rc as enrollProofFrame, rl as canonicalJson, rn as WALLET_NETWORKS, rs as HANDOFF_HELLO, ru as budgetRetryMs, s as appUpdateDecision, sa as dhtFileId, sc as clearMissed, si as BUTTONS_CAPABILITY, sl as encodeContactLink, sn as formatPaymentAmount, so as sameButtonText, sr as groupSignalFrame, ss as HANDOFF_REQUEST, t as newX401HolderKey, tc as enrollGrantFrame, ti as APP_RANGE_LIMITS, tl as parseImageMeta, tn as TEST_USDT_FAUCET_AMOUNT, ts as HANDOFF_DONE, u as APP_STORE_LIMITS, ua as sanitizeMime, uc as newInbox, ui as UPGRADE_CAPABILITY, ul as deviceInviteJoinerParams, un as SPARK_NETWORKS, uo as arrivalKey, ur as mayBeHub, us as NO_ATTEMPTS, v as openGroupTyping, vc as knockSlotIdentity, vi as readManifest, vo as MEMBER_KEY, vr as lobbyKeys, vs as handoffContextProof, vu as sanitizeAvatar, w as decodeCommunityLink, wa as REMOVED_TEXT, wc as openRequest, wl as deviceKeyZ32, wo as edgeParams, wr as rankHubs, ws as handoffOfferFrame, wu as toBase64Url, x as CommunitySession, xa as EDIT_BUFFER_MS, xc as linkRecords, xl as HANDOFF_CAPABILITY, xo as rosterAdmin, xr as mergeLobby, xs as handoffEphemeral, xu as fromBase64Url, y as sealGroupTyping, yc as knockSlotOf, yl as DEVICES_CAPABILITY, yo as commitHash, yr as lobbyRecords, ys as handoffDataFrame, yu as sanitizeDisplayText, z as GROUP_LIMITS, za as reactionIsNewer, zl as readTurnPacket, zn as pairedMessageFits, zs as sealHandoffPiece } from "./src-BB5-5P3s.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-DjWmEn3j.js";
5
+ import { t as nwc } from "./nwcProvider-pFMrsUJh.js";
6
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-N2vAaoth.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-CBJIEvCE.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-DxeEgQ-W.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-BvHkAhDH.js";
12
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-DYiGwzq_.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
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";
@@ -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-BLazHiaP.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-BFE8KkEE.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. */
@@ -8602,7 +8602,7 @@ var NostrSocial = class {
8602
8602
  fetchedAt: c.follows.fetchedAt,
8603
8603
  relays: c.follows.relays,
8604
8604
  stale: this.stale(c.follows.fetchedAt),
8605
- follows: c.follows.follows,
8605
+ count: c.follows.follows.length,
8606
8606
  eventAt: c.follows.event?.created_at ?? 0
8607
8607
  };
8608
8608
  if (c?.mute) view.mute = {
@@ -8629,6 +8629,11 @@ var NostrSocial = class {
8629
8629
  ownFollows() {
8630
8630
  return [...new Set(this.host.ownSubjects().flatMap((s) => this.own[s]?.follows?.follows ?? []))];
8631
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
+ }
8632
8637
  /** The person's own mute lists hide this note by `author`. */
8633
8638
  hides(note, author) {
8634
8639
  return this.muted({
@@ -8672,7 +8677,7 @@ var NostrSocial = class {
8672
8677
  })).find((x) => x.follows);
8673
8678
  if (mine?.follows) view.follows.hints = this.hintsOf(c.follows, mine.follows, mine.key, myKeys, subject);
8674
8679
  }
8675
- if (c?.notes) view.notes = this.notesOf(c.notes, muteLists, subject);
8680
+ if (c?.notes) view.notes = this.notesOf(c.notes, muteLists, subject).view;
8676
8681
  const loading = this.loading.get(`${linkId}:${subject}`);
8677
8682
  if (loading) view.loading = loading;
8678
8683
  const error = this.errors.get(`${linkId}:${subject}`);
@@ -8702,31 +8707,44 @@ var NostrSocial = class {
8702
8707
  });
8703
8708
  return hints;
8704
8709
  }
8705
- /** A contact's posts as shown, past the person's mute lists. Every state asks; a list that changes is a new object. */
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
+ */
8706
8714
  notesOf(notes, lists, subject) {
8707
8715
  const kept = this.shownNotes.get(notes);
8708
- if (kept && kept.subject === subject && kept.lists.length === lists.length && kept.lists.every((list, i) => list === lists[i])) return kept.view;
8716
+ if (kept && kept.subject === subject && kept.lists.length === lists.length && kept.lists.every((list, i) => list === lists[i])) return kept;
8709
8717
  const authorMuted = lists.some((m) => m.pubkeys.includes(subject));
8710
8718
  const shown = authorMuted ? [] : notes.notes.filter((n) => !lists.some((m) => !!mutedBecause(n, subject, m)));
8711
- const view = {
8712
- fetchedAt: notes.fetchedAt,
8713
- relays: notes.relays,
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
+ },
8714
8730
  notes: shown.map((n) => ({
8715
8731
  id: n.id,
8716
8732
  createdAt: n.createdAt,
8717
8733
  content: n.content,
8718
8734
  reply: n.reply
8719
- })),
8720
- more: !notes.exhausted,
8721
- hidden: notes.notes.length - shown.length,
8722
- authorMuted
8735
+ }))
8723
8736
  };
8724
- this.shownNotes.set(notes, {
8725
- lists,
8726
- subject,
8727
- view
8728
- });
8729
- return view;
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] : [];
8730
8748
  }
8731
8749
  requireOnline() {
8732
8750
  if (!this.host.online()) throw new Error("Offline: turn the network on first");
@@ -10922,9 +10940,10 @@ async function noteBundles(change) {
10922
10940
  const settings = tx.objectStore(STORES$1.settings);
10923
10941
  const read = settings.get(APP_BUNDLES_KEY);
10924
10942
  read.onsuccess = () => {
10925
- const noted = new Set(bundleDigests(read.result));
10943
+ const before = bundleDigests(read.result);
10944
+ const noted = new Set(before);
10926
10945
  change(noted);
10927
- settings.put([...noted], APP_BUNDLES_KEY);
10946
+ if (noted.size !== before.length || before.some((d) => !noted.has(d))) settings.put([...noted], APP_BUNDLES_KEY);
10928
10947
  };
10929
10948
  await done(tx);
10930
10949
  }
@@ -11495,6 +11514,7 @@ var Apps = class {
11495
11514
  for (const kind of kinds) await this.removeBundle(kind, digest);
11496
11515
  gone.add(digest);
11497
11516
  }
11517
+ if (this.stopped) return;
11498
11518
  await noteBundles((noted) => {
11499
11519
  for (const digest of named) noted.add(digest);
11500
11520
  for (const digest of gone) noted.delete(digest);
@@ -12187,7 +12207,7 @@ var Apps = class {
12187
12207
  const before = await this.readRevocations(app.ref, [app.from, ...app.manifest.sources ?? []], revokeRead);
12188
12208
  app = withRevocations(app, before ?? []);
12189
12209
  if (app.pending && this.runStatus(versionOf(app.pending.manifest, app.pending.digest), this.storeViews(stores), app.revocations).status !== "ok") {
12190
- await this.removeBundle(app.pending.bytes, app.pending.digest);
12210
+ dropped.push(app.pending);
12191
12211
  const { pending: _p, ...rest } = app;
12192
12212
  app = rest;
12193
12213
  }
@@ -13930,7 +13950,8 @@ var raisedCounter = (value, floor) => Math.max((Number.isSafeInteger(value) ? va
13930
13950
  */
13931
13951
  function raisedLink(link, floor) {
13932
13952
  const paired = !!link.profile && !link.group;
13933
- const next = { ...link };
13953
+ const { ratchetState: _ratchet, ...rest } = link;
13954
+ const next = { ...rest };
13934
13955
  if (link.dhtDeliveryState) next.dhtDeliveryState = {
13935
13956
  ...link.dhtDeliveryState,
13936
13957
  sequence: raisedCounter(link.dhtDeliveryState.sequence, floor)
@@ -19992,7 +20013,7 @@ var FileDesk = class {
19992
20013
  chat.files.resume(direction, wireId);
19993
20014
  break;
19994
20015
  case "cancel":
19995
- chat.files.cancel(direction, wireId);
20016
+ if (!sentWhole(record)) chat.files.cancel(direction, wireId);
19996
20017
  break;
19997
20018
  case "retry":
19998
20019
  if (out) chat.files.retry(wireId);
@@ -20821,6 +20842,9 @@ var Outbox = class {
20821
20842
  writes = 0;
20822
20843
  stamp = 0;
20823
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;
20824
20848
  stopped = false;
20825
20849
  resender;
20826
20850
  policy;
@@ -20839,6 +20863,7 @@ var Outbox = class {
20839
20863
  }
20840
20864
  /** `messages`: the chat's history as the caller just read it (a start has), so it is not read a second time. */
20841
20865
  async recover(messages) {
20866
+ const at = this.writes ? void 0 : this.stamp;
20842
20867
  for (const message of messages ?? await this.store.read()) {
20843
20868
  if (message.via === "hold" || message.sender !== "me") continue;
20844
20869
  if (message.delivery === "queued") {
@@ -20857,6 +20882,7 @@ var Outbox = class {
20857
20882
  } else if (until !== void 0) await this.expired(message);
20858
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.");
20859
20884
  }
20885
+ if (at !== void 0 && !this.stopped) this.seen = at;
20860
20886
  }
20861
20887
  /**
20862
20888
  * One at a time, in the order asked: `run` starts when the turns before it are over. A turn that takes longer than
@@ -20966,12 +20992,31 @@ var Outbox = class {
20966
20992
  */
20967
20993
  async look(id) {
20968
20994
  if (!this.store.get || !this.known || this.waiting.size + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
20969
- return (await Promise.all([.../* @__PURE__ */ new Set([
20970
- id,
20995
+ const ids = /* @__PURE__ */ new Set([
20996
+ ...id === void 0 ? [] : [id],
20971
20997
  ...this.waiting.keys(),
20972
20998
  ...this.receipts.keys(),
20973
20999
  ...this.onTheirWay.keys()
20974
- ])].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
+ }
20975
21020
  }
20976
21021
  /** A row of mine still to go that this outbox holds nothing of: only a look at the chat finds it. */
20977
21022
  unknown(m, id) {
@@ -21129,10 +21174,12 @@ var Outbox = class {
21129
21174
  * nothing about it is unconfirmed; it counts no attempt until it goes.
21130
21175
  */
21131
21176
  async wait(id, reason) {
21177
+ const looked = this.looked;
21132
21178
  const message = await this.one(id);
21133
21179
  if (!message || this.stopped) return;
21134
21180
  await this.store.update(id, "waiting", reason, { resendUntil: message.resendUntil ?? this.now() + this.policy.windowMs });
21135
21181
  this.schedule(id);
21182
+ if (this.looks !== looked) this.flush().catch(() => {});
21136
21183
  }
21137
21184
  async received(wireId) {
21138
21185
  const id = `me_${wireId}`;
@@ -21155,7 +21202,7 @@ var Outbox = class {
21155
21202
  if (!reopened && this.lookAhead === look) this.lookAhead = void 0;
21156
21203
  if (this.stopped) return;
21157
21204
  if (reopened) for (const id of this.busy) this.reopenedWhileBusy.add(id);
21158
- await this.inOrder(this.due(await this.store.read(), opened));
21205
+ await this.inOrder(this.due(await this.held(), opened));
21159
21206
  });
21160
21207
  if (reopened) return look;
21161
21208
  this.lookAhead = look;
@@ -21395,7 +21442,7 @@ var EditQueue = class {
21395
21442
  wires = /* @__PURE__ */ new Map();
21396
21443
  dhtIds = /* @__PURE__ */ new Map();
21397
21444
  tick = 0;
21398
- /** 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`). */
21399
21446
  learnt = false;
21400
21447
  timer;
21401
21448
  flushing = null;
@@ -21436,10 +21483,11 @@ var EditQueue = class {
21436
21483
  * A new session: what the last one sent without a confirmation may go again at once, with a fresh count of attempts.
21437
21484
  * Said once, as the session opens and before anything goes on it: said again later, it would send a second time what
21438
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.
21439
21488
  */
21440
21489
  reopened() {
21441
21490
  this.sent.clear();
21442
- this.learnt = false;
21443
21491
  }
21444
21492
  /** This row has an edit to send (it was just written so): the next look reads it. */
21445
21493
  edited(id) {
@@ -23419,6 +23467,19 @@ var KNOCK_SLOT_OPEN_MS = 2e4;
23419
23467
  /** How long a hub missing from the beacon still counts as one for the edges already up. */
23420
23468
  var HUB_GRACE_MS = 18e4;
23421
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
+ /**
23422
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
23423
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
23424
23485
  * group that needs one more hub gets it.
@@ -24070,7 +24131,7 @@ var Communities = class {
24070
24131
  await this.closeEntries(group.id);
24071
24132
  await this.startJoining({
24072
24133
  g: group.id,
24073
- host: live.session.entryKey
24134
+ host: live.session.lostEntryKey
24074
24135
  }, live.session.state.seedB64, now);
24075
24136
  continue;
24076
24137
  }
@@ -24238,6 +24299,7 @@ var Communities = class {
24238
24299
  if ((gone.length || lost || bare) && !edges.has(key)) live.expect.add(key);
24239
24300
  if (gone.length || lost) (live.replacing ??= /* @__PURE__ */ new Set()).add(key);
24240
24301
  }
24302
+ await this.lookPast(groupId, live, others, kept, now);
24241
24303
  live.myHubs = kept;
24242
24304
  live.forceHub = !kept.length && others.length < COMMUNITY_TOPOLOGY.maxHubs;
24243
24305
  for (const hub of kept) {
@@ -24272,7 +24334,7 @@ var Communities = class {
24272
24334
  } else continue;
24273
24335
  if (linkId) await this.host.closeEdge(linkId);
24274
24336
  }
24275
- 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) {
24276
24338
  live.lastCatchUp = now;
24277
24339
  const ready = [...this.host.edges(groupId)].filter(([key, id]) => this.host.linkReady(id, 2) && !s.wasRemoved(key)).map(([key]) => key);
24278
24340
  for (const key of ready.slice(0, 3)) s.catchUp(key);
@@ -24302,6 +24364,52 @@ var Communities = class {
24302
24364
  }
24303
24365
  }
24304
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
+ /**
24305
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
24306
24414
  * (a hub cut off from the others would only come back as one). It then steps down in two steps: it takes itself
24307
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.
@@ -24323,9 +24431,12 @@ var Communities = class {
24323
24431
  hubLoad(groupId, live, now) {
24324
24432
  const edges = this.host.edges(groupId);
24325
24433
  if (now - live.beaconAt <= 2 * this.timings.beaconReadMs) {
24326
- const hubs = new Set(freshHubs(this.hubs(live), now).map((h) => h.key));
24327
- 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);
24328
- 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
+ }
24329
24440
  }
24330
24441
  for (const [key, since] of live.members) {
24331
24442
  const id = edges.get(key);
@@ -25101,7 +25212,12 @@ var Communities = class {
25101
25212
  if (f.t === "group-sync" && live.session.isMember) this.sayFarewell(groupId, live, peerKey, f);
25102
25213
  return;
25103
25214
  }
25104
- 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;
25105
25221
  if ((f.t === "group-secret" || f.t === "group-entry") && typeof f.to === "string" && f.to !== live.session.myKey) {
25106
25222
  if (!live.hub) return;
25107
25223
  const id = `${String(f.t)}:${f.to}:${String(f.h ?? f.x)}`;
@@ -29323,15 +29439,24 @@ function edgeView(live, now = Date.now(), noSlot = false) {
29323
29439
  const pairingError = live.pairing?.status === "error" ? live.pairing.error : void 0;
29324
29440
  const error = open ? void 0 : pairingError ?? live.discoveryError;
29325
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;
29326
29448
  return {
29327
29449
  linkId: live.stored.id,
29328
29450
  state,
29329
29451
  ...open && live.pairing?.transport ? { transport: live.pairing.transport } : {},
29330
- lastSeenAt: open ? now : Math.max(presenceSeenAt(live.presence), live.lastSyncAt),
29452
+ lastSeenAt: open ? now : heardAt,
29331
29453
  ...error ? {
29332
29454
  error,
29333
- cause: pairingError ? edgeErrorCause(pairingError) : "relays"
29334
- } : {}
29455
+ cause
29456
+ } : {},
29457
+ ...reconnecting ? { reconnecting: true } : {},
29458
+ ...retryAt && retryAt > now ? { retryAt } : {},
29459
+ ...attempt > 0 ? { attempt } : {}
29335
29460
  };
29336
29461
  }
29337
29462
  /**
@@ -29504,7 +29629,8 @@ var testOf = (p, federationNetwork) => {
29504
29629
  };
29505
29630
  /**
29506
29631
  * What this device says about one of its own payments in a group, or null when it says nothing (not a group's,
29507
- * 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.
29508
29634
  */
29509
29635
  function authoredNote(p, at, all, current, memberOf = () => void 0, federationNetwork = () => void 0) {
29510
29636
  const base = {
@@ -29611,11 +29737,17 @@ var GroupPayments = class {
29611
29737
  if (!known.has(groupId)) known.set(groupId, this.host.membership(groupId));
29612
29738
  return known.get(groupId);
29613
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
+ }
29614
29746
  for (const p of all) {
29615
29747
  const at = this.placement(p, membership);
29616
29748
  if (!at) continue;
29617
29749
  const current = (await this.load(at.groupId)).get(paymentWireId(p.id));
29618
- 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));
29619
29751
  if (!frame || JSON.stringify(frame) === JSON.stringify(current?.mine)) continue;
29620
29752
  const merged = mergeGroupPay(current, frame, at.me, membership(at.groupId).members) ?? current;
29621
29753
  if (!merged) continue;
@@ -30640,6 +30772,11 @@ var HoldEngine = class {
30640
30772
  /** A read the contact's word asked for, one waiting per chat, and when the last such read went out. */
30641
30773
  peerPolls = /* @__PURE__ */ new Map();
30642
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();
30643
30780
  constructor(host) {
30644
30781
  this.host = host;
30645
30782
  }
@@ -30697,6 +30834,8 @@ var HoldEngine = class {
30697
30834
  /** Items can be held for this contact now: both switched it on, storage is set up and the contact is pinned. */
30698
30835
  canHold(linkId) {
30699
30836
  const hold = this.state(linkId);
30837
+ const ratchet = this.host.ratchet?.(linkId);
30838
+ if (ratchet && ratchet.box.heardAny && !ratchet.peerSupports()) return false;
30700
30839
  return hold.enabled && !!hold.peerAllows && !!this.host.storage() && !!this.keysFor(linkId);
30701
30840
  }
30702
30841
  /** Ways of paying a request held for this contact may name: what its app allowed at the last session. */
@@ -30824,6 +30963,7 @@ var HoldEngine = class {
30824
30963
  outSeq: seq,
30825
30964
  outbox: [...hold.outbox, entry]
30826
30965
  });
30966
+ await this.resealStale(linkId);
30827
30967
  await this.upload(linkId, entry);
30828
30968
  });
30829
30969
  }
@@ -30838,11 +30978,38 @@ var HoldEngine = class {
30838
30978
  await this.host.delivery(linkId, messageId, "held");
30839
30979
  return;
30840
30980
  }
30981
+ await this.resealStale(linkId);
30841
30982
  await this.upload(linkId, entry);
30842
30983
  }).then(() => found);
30843
30984
  }
30844
30985
  /** Seals and uploads one queued or failed entry, then the manifest and the pointer. */
30845
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) {
30846
31013
  const storage = this.host.storage(), keys = this.keysFor(linkId), hold = this.state(linkId);
30847
31014
  const update = async (patch) => this.save(linkId, {
30848
31015
  ...this.state(linkId),
@@ -30851,16 +31018,7 @@ var HoldEngine = class {
30851
31018
  ...patch
30852
31019
  } : e)
30853
31020
  });
30854
- const fail = async (error) => {
30855
- await update({
30856
- state: "failed",
30857
- error
30858
- });
30859
- this.errors.set(linkId, error);
30860
- await this.host.delivery(linkId, entry.messageId, "failed", error);
30861
- this.host.changed();
30862
- throw new Error(error);
30863
- };
31021
+ const fail = (error) => this.failEntry(linkId, entry, error);
30864
31022
  if (!storage || !keys || !hold.mailbox) return fail("Held messages need S3 storage (Profile → Backups) and a pinned contact.");
30865
31023
  let body, meta;
30866
31024
  try {
@@ -30907,17 +31065,23 @@ var HoldEngine = class {
30907
31065
  } catch (error) {
30908
31066
  return fail(error instanceof Error ? error.message : String(error));
30909
31067
  }
30910
- 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);
30911
31079
  try {
30912
- bytes = keys.seal({
30913
- mailbox: hold.mailbox,
30914
- seq: entry.seq,
30915
- id: entry.id,
30916
- ts: entry.ts,
30917
- kind: entry.kind,
30918
- meta,
30919
- expires: entry.expires
30920
- }, 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);
30921
31085
  } catch (error) {
30922
31086
  return fail(error instanceof Error ? error.message : String(error));
30923
31087
  }
@@ -30930,16 +31094,23 @@ var HoldEngine = class {
30930
31094
  await update({
30931
31095
  state: "held",
30932
31096
  error: void 0,
30933
- bytes: bytes.length
31097
+ bytes: bytes.length,
31098
+ sid
30934
31099
  });
30935
- try {
30936
- await this.publishPointer(linkId, true);
30937
- } catch (error) {
30938
- return fail(`Stored, but could not tell the contact where: ${error instanceof Error ? error.message : String(error)}`);
30939
- }
30940
- this.errors.delete(linkId);
30941
- await this.host.delivery(linkId, entry.messageId, "held");
30942
- 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;
30943
31114
  }
30944
31115
  /** A message deleted here: its held item goes too, so the contact never picks it up. */
30945
31116
  forget(linkId, messageId) {
@@ -30977,6 +31148,7 @@ var HoldEngine = class {
30977
31148
  this.errors.delete(linkId);
30978
31149
  this.chains.delete(linkId);
30979
31150
  this.pointerDue.delete(linkId);
31151
+ this.waiting.delete(linkId);
30980
31152
  clearTimeout(this.peerPolls.get(linkId));
30981
31153
  this.peerPolls.delete(linkId);
30982
31154
  this.lastPeerPoll.delete(linkId);
@@ -31102,9 +31274,10 @@ var HoldEngine = class {
31102
31274
  this.host.changed();
31103
31275
  }
31104
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);
31105
31278
  hold = this.state(linkId);
31106
31279
  const held = hold.outbox.some((e) => e.state === "held");
31107
- 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)));
31108
31281
  else if (this.pointerDue.has(linkId) || held && (this.lastPublish.get(linkId) ?? 0) + REPUBLISH_MS <= now) await this.publishPointer(linkId, false).catch(() => {});
31109
31282
  }
31110
31283
  /**
@@ -31165,7 +31338,7 @@ var HoldEngine = class {
31165
31338
  this.host.changed();
31166
31339
  return;
31167
31340
  }
31168
- let entries, mailbox;
31341
+ let entries, mailbox, manifestRev;
31169
31342
  try {
31170
31343
  const manifest = keys.open(await this.fetchBytes(pointer.manifestUrl, HOLD_LIMITS.maxManifestBytes), {
31171
31344
  maxBytes: HOLD_LIMITS.maxManifestBytes,
@@ -31174,6 +31347,7 @@ var HoldEngine = class {
31174
31347
  });
31175
31348
  if (manifest.header.kind !== "manifest") throw new HoldRefusedError("format", "Not a manifest");
31176
31349
  mailbox = manifest.header.mailbox;
31350
+ manifestRev = manifest.header.seq;
31177
31351
  entries = readManifest(manifest.header.meta, this.host.loopbackStorage?.()).filter(([seq]) => seq > this.state(linkId).inSeq).sort((a, b) => a[0] - b[0]);
31178
31352
  } catch (error) {
31179
31353
  if (error instanceof HoldRefusedError) {
@@ -31187,6 +31361,7 @@ var HoldEngine = class {
31187
31361
  return;
31188
31362
  }
31189
31363
  let changed = false, stop = false;
31364
+ if ((this.waiting.get(linkId)?.seq ?? Infinity) <= this.state(linkId).inSeq) this.waiting.delete(linkId);
31190
31365
  for (const [seq, id, kind, bytes, url, expires] of entries) {
31191
31366
  if (stop) break;
31192
31367
  if (expires <= now) {
@@ -31197,12 +31372,30 @@ var HoldEngine = class {
31197
31372
  changed = true;
31198
31373
  continue;
31199
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;
31200
31382
  try {
31201
- 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, {
31202
31385
  maxBytes: HOLD_LIMITS.maxBundleBytes,
31203
31386
  now,
31204
- 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
+ }
31205
31396
  });
31397
+ const { header, body } = opened;
31398
+ ratcheted = opened.ratcheted;
31206
31399
  if (header.seq !== seq || header.id !== id || header.kind !== kind) throw new HoldRefusedError("format", "The item does not match the manifest");
31207
31400
  const held = {
31208
31401
  seq,
@@ -31265,13 +31458,29 @@ var HoldEngine = class {
31265
31458
  network: frame.n
31266
31459
  });
31267
31460
  }
31461
+ if (ratcheted && ratchet) await ratchet.box.commitOpen("hold", ratcheted);
31268
31462
  hold = await this.save(linkId, {
31269
31463
  ...this.state(linkId),
31270
31464
  inSeq: seq
31271
31465
  });
31272
31466
  changed = true;
31273
31467
  } catch (error) {
31274
- 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) {
31275
31484
  await this.save(linkId, {
31276
31485
  ...this.state(linkId),
31277
31486
  inSeq: seq,
@@ -32187,7 +32396,8 @@ var ProfilePeek = class {
32187
32396
  },
32188
32397
  state: link.dhtDeliveryState,
32189
32398
  transport: readOnly,
32190
- background: true
32399
+ background: true,
32400
+ ratchet: link.ratchetState
32191
32401
  });
32192
32402
  let held = 0;
32193
32403
  if (holdable(link)) {
@@ -32495,7 +32705,30 @@ function refusedRow(notice) {
32495
32705
  * asked for again (NUT-09) at any time.
32496
32706
  */
32497
32707
  var UNIT$1 = "sat";
32498
- 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
+ }
32499
32732
  /** A Lightning payment can stay in flight for minutes or hours; the mint is asked again this often. */
32500
32733
  var MELT_POLL_MS = 3e4;
32501
32734
  var MAX_AMOUNT = 1e6;
@@ -32512,6 +32745,8 @@ var SWAP_SLOW_POLL_MS = 6e5;
32512
32745
  var SWAP_WATCH_MS = 36e5;
32513
32746
  /** How many proofs of tokens refused as spent are remembered. */
32514
32747
  var SPENT_KEPT = 1e3;
32748
+ /** The most coins `sendCoins` makes for one token. */
32749
+ var MAX_SEND_COINS = 64;
32515
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. */
32516
32751
  var loadCashu = () => import("@cashu/cashu-ts");
32517
32752
  async function reviewedCashuFee(preview) {
@@ -32549,7 +32784,7 @@ function normalizeMintUrl(input) {
32549
32784
  }
32550
32785
  const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
32551
32786
  if (url.protocol !== "https:" && !(local && url.protocol === "http:")) throw engineError("mintNotHttps");
32552
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
32787
+ return mintUrlSpelling(url.href);
32553
32788
  }
32554
32789
  function assertAmount(amount) {
32555
32790
  if (!Number.isSafeInteger(amount) || amount <= 0) throw new Error("Enter an amount in sats");
@@ -32559,6 +32794,84 @@ function assertAmount(amount) {
32559
32794
  var asProofLike = (proofs) => proofs;
32560
32795
  var total = (proofs) => proofs.reduce((sum, p) => sum + p.amount, 0);
32561
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
+ }
32562
32875
  var MINT_QUOTE_MISMATCH = "The mint quoted another amount than this invoice's. Nothing was paid.";
32563
32876
  /** A melt quote that is not for this invoice (`invoice` lower case, as `decodeBolt11` gives it) and its amount. */
32564
32877
  var quoteMismatch = (quote, invoice, amount) => quote.request.trim().toLowerCase().replace(/^lightning:/, "") !== invoice || quote.amount.toNumber() !== amount;
@@ -32585,6 +32898,8 @@ var walletTx = (mint, kind, amount, fee, note) => ({
32585
32898
  });
32586
32899
  /** What a failed payment left in the wallet, said to the person: all of it, or all but the fee the mint kept. */
32587
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";
32588
32903
  /**
32589
32904
  * How long a mint gets to answer when it is only being asked something (its keys, an invoice). A mint
32590
32905
  * that is down can hold a request for minutes; the next mint should get its turn well before that.
@@ -32606,6 +32921,12 @@ var CashuWallet = class CashuWallet {
32606
32921
  infos = /* @__PURE__ */ new Map();
32607
32922
  locks = /* @__PURE__ */ new Map();
32608
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();
32609
32930
  meltTimer = null;
32610
32931
  restoredTimer = null;
32611
32932
  swapTimer = null;
@@ -32619,7 +32940,8 @@ var CashuWallet = class CashuWallet {
32619
32940
  * so the same token sent again, under any id or encoding, is refused without asking the mint again.
32620
32941
  */
32621
32942
  spentTokens = /* @__PURE__ */ new Set();
32622
- /** 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. */
32623
32945
  shownQuotes = /* @__PURE__ */ new Map();
32624
32946
  /**
32625
32947
  * `getMints`: the mints of one network (the engine's default when none is named), primary first: balances,
@@ -32802,10 +33124,23 @@ var CashuWallet = class CashuWallet {
32802
33124
  ...paysItsOwnInvoices(mint) ? { held: true } : {}
32803
33125
  };
32804
33126
  await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
33127
+ this.quoteAsked.set(quote.quote, Date.now());
32805
33128
  this.pollQuotes();
32806
33129
  return quote;
32807
33130
  }
32808
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
+ /**
32809
33144
  * A payer says it paid this invoice of ours (a contact's app, once its payment went through). A held quote (a test
32810
33145
  * mint's, which reads paid by itself) is minted from now on; on any other mint the mint's own answer decides, as
32811
33146
  * always. Returns whether the invoice is one of ours.
@@ -32818,7 +33153,8 @@ var CashuWallet = class CashuWallet {
32818
33153
  ...quote,
32819
33154
  held: void 0
32820
33155
  }));
32821
- await this.pollQuotes();
33156
+ this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);
33157
+ await this.pollQuotes(true);
32822
33158
  return true;
32823
33159
  }
32824
33160
  /** True while an invoice of ours waits for a payer's word (see `vouch`): whatever its mint says, it is not paid. */
@@ -32866,7 +33202,7 @@ var CashuWallet = class CashuWallet {
32866
33202
  * these mints (one network's wallet, before it is removed), claiming what is paid; the regular round is left alone.
32867
33203
  */
32868
33204
  async checkQuotes(mints) {
32869
- if (!mints) return this.pollQuotes();
33205
+ if (!mints) return this.pollQuotes(true);
32870
33206
  const at = new Set(mints);
32871
33207
  await this.settleQuotes((await this.quotes()).filter((q) => at.has(q.mint)));
32872
33208
  }
@@ -32877,25 +33213,63 @@ var CashuWallet = class CashuWallet {
32877
33213
  /**
32878
33214
  * Invoices are paid by someone else, somewhere else; all we can do is ask the mint. A quote is the only
32879
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.
32880
33218
  */
32881
- async pollQuotes() {
33219
+ async pollQuotes(now = false) {
32882
33220
  if (this.quoteTimer) clearTimeout(this.quoteTimer);
32883
33221
  this.quoteTimer = null;
32884
33222
  if (this.stopped) return;
32885
- const quotes = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32886
- 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));
32887
- await this.settleQuotes(quotes);
32888
- const remaining = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32889
- 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()));
32890
33257
  }
33258
+ /** Asks the mints about these quotes. Returns the ones minted. */
32891
33259
  async settleQuotes(quotes) {
32892
- for (const { quote, mint } of quotes.filter((q) => !q.issuedUnclaimed && !q.held)) try {
32893
- const paid = await this.locked(mint, () => this.settleQuote(quote));
32894
- if (paid) {
32895
- if (!paid.testCoins) this.events.onQuotePaid(paid);
32896
- this.events.onChange();
32897
- }
32898
- } 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;
32899
33273
  }
32900
33274
  /** Runs under the mint's lock, so two rounds never mint one quote twice. Returns the quote once its ecash is in. */
32901
33275
  async settleQuote(id) {
@@ -32980,11 +33354,23 @@ var CashuWallet = class CashuWallet {
32980
33354
  async createToken(amount, preferred, note, outbox, network) {
32981
33355
  assertAmount(amount);
32982
33356
  const mine = preferred ? this.getKnownMints() : this.getMints(network);
32983
- 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
+ };
32984
33368
  for (const mint of candidates) {
32985
- if (await this.balanceAt(mint) < amount) continue;
32986
- return this.locked(mint, async () => {
32987
- 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);
32988
33374
  const token = (await loadCashu()).getEncodedToken({
32989
33375
  mint,
32990
33376
  proofs: send,
@@ -33010,7 +33396,9 @@ var CashuWallet = class CashuWallet {
33010
33396
  mint
33011
33397
  };
33012
33398
  });
33399
+ if (sent) return sent;
33013
33400
  }
33401
+ if (room > 0) throw engineError("notEnoughForFee", { amount: room });
33014
33402
  throw engineError(candidates.length === 0 && preferred ? "noSharedMint" : "notEnoughSats");
33015
33403
  }
33016
33404
  async prepareReviewedCashu(mint, amount) {
@@ -33269,7 +33657,7 @@ var CashuWallet = class CashuWallet {
33269
33657
  try {
33270
33658
  if (/^cashu[AB]/i.test(value)) {
33271
33659
  const metadata = getTokenMetadata(value);
33272
- const mint = metadata.mint.replace(/\/+$/, "");
33660
+ const mint = mintUrlSpelling(metadata.mint);
33273
33661
  return {
33274
33662
  kind: "token",
33275
33663
  amount: Number(metadata.amount),
@@ -33285,7 +33673,7 @@ var CashuWallet = class CashuWallet {
33285
33673
  kind: "request",
33286
33674
  amount: request.amount === void 0 ? null : Number(request.amount),
33287
33675
  unit: request.unit ?? UNIT$1,
33288
- mints: request.mints ?? [],
33676
+ mints: (request.mints ?? []).map(mintUrlSpelling),
33289
33677
  description: request.description || void 0
33290
33678
  };
33291
33679
  }
@@ -33304,7 +33692,7 @@ var CashuWallet = class CashuWallet {
33304
33692
  try {
33305
33693
  const metadata = getTokenMetadata(token);
33306
33694
  unit = metadata.unit;
33307
- mint = metadata.mint.replace(/\/+$/, "");
33695
+ mint = mintUrlSpelling(metadata.mint);
33308
33696
  faceValue = Number(metadata.amount);
33309
33697
  } catch {
33310
33698
  throw new Error("That is not a valid ecash token");
@@ -33332,6 +33720,7 @@ var CashuWallet = class CashuWallet {
33332
33720
  if (preview.inputs.some((p) => this.spentTokens.has(`${mint} ${p.secret}`))) throw engineError("ecashAlreadySpent");
33333
33721
  const redeeming = new Set(written.flatMap((s) => (swapOf(s).inputs ?? []).map((p) => p.secret)));
33334
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) });
33335
33724
  swap = {
33336
33725
  id: swapId(),
33337
33726
  mint,
@@ -33382,17 +33771,17 @@ var CashuWallet = class CashuWallet {
33382
33771
  includeFees: true,
33383
33772
  exactMatch: true
33384
33773
  });
33385
- if (send.length > 0 && sats(send) === amount + wallet.getFeesForProofs(send).toNumber() && getEncodedToken({
33386
- mint,
33387
- proofs: send,
33388
- unit: UNIT$1
33389
- }).length <= LIMITS.maxPaymentEndpointChars) return {
33774
+ if (send.length > 0 && sats(send) === amount + wallet.getFeesForProofs(send).toNumber() && inOneFrame(getEncodedToken, mint)(send)) return {
33390
33775
  inputs: among(send),
33391
33776
  keep: [],
33392
33777
  send
33393
33778
  };
33394
33779
  } catch {}
33395
- 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 });
33396
33785
  const swap = {
33397
33786
  id: swapId(),
33398
33787
  mint,
@@ -33748,40 +34137,51 @@ var CashuWallet = class CashuWallet {
33748
34137
  });
33749
34138
  if (again && !mints) this.swapsAgainIn(again);
33750
34139
  }
33751
- /** What paying this invoice would cost, from the first mint that can afford it. */
33752
- 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) {
33753
34145
  let lastError = /* @__PURE__ */ new Error("Add a mint in Settings first");
33754
34146
  let mints = this.getMints(network);
33755
34147
  /** The most any mint asked could pay with its fee on top: a Max comes down to it. */
33756
34148
  let room = 0;
33757
34149
  const decoded = decodeBolt11(invoice);
33758
34150
  if (!decoded) throw new Error("That is not an invoice this wallet can pay");
33759
- 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;
33760
34155
  if (decoded.network === "bitcoin" && mints.some((mint) => mintNetwork(mint) === "testnet")) {
33761
34156
  mints = mints.filter((mint) => mintNetwork(mint) === "mainnet" || fakesLightning(mint));
33762
34157
  if (!mints.length) throw new Error(BITCOIN_INVOICE_ON_TESTNET);
33763
34158
  }
34159
+ if (chosen !== void 0 && mints.length) lastError = engineError("mintsNoAnyAmount");
33764
34160
  for (const mint of mints) try {
33765
- 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);
33766
34164
  const amount = quote.amount.toNumber();
33767
34165
  const feeReserve = quote.fee_reserve.toNumber();
33768
- if (quoteMismatch(quote, decoded.invoice, decoded.amountSat)) throw new Error(MINT_QUOTE_MISMATCH);
33769
- const balance = await this.balanceAt(mint);
33770
- if (balance < amount + feeReserve) {
33771
- 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));
33772
34171
  lastError = room > 0 ? engineError("notEnoughForFee", { amount: room }) : engineError("notEnoughSats");
33773
34172
  continue;
33774
34173
  }
34174
+ const fee = outlay - amount;
33775
34175
  this.shownQuotes.set(quote.quote, {
33776
34176
  request: decoded.invoice,
33777
34177
  amount,
33778
- feeReserve
34178
+ feeReserve: fee
33779
34179
  });
33780
34180
  return {
33781
34181
  quote: quote.quote,
33782
34182
  mint,
33783
34183
  amount,
33784
- feeReserve
34184
+ feeReserve: fee
33785
34185
  };
33786
34186
  } catch (error) {
33787
34187
  lastError = error;
@@ -33806,13 +34206,19 @@ var CashuWallet = class CashuWallet {
33806
34206
  }
33807
34207
  async melt(quoteId, mint, note, paymentId) {
33808
34208
  const wallet = await this.wallet(mint);
33809
- const { MeltChangeError, OutputData } = await loadCashu();
34209
+ const { MeltChangeError, OutputData, getEncodedToken } = await loadCashu();
33810
34210
  const quote = await wallet.checkMeltQuoteBolt11(quoteId);
33811
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");
33812
34212
  const shown = this.shownQuotes.get(quoteId);
33813
- if (!shown || quote.quote !== quoteId || quoteMismatch(quote, shown.request, shown.amount) || quote.fee_reserve.toNumber() > shown.feeReserve) throw new Error(MINT_QUOTE_MISMATCH);
33814
34213
  const needed = quote.amount.toNumber() + quote.fee_reserve.toNumber();
33815
- 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);
33816
34222
  let preview;
33817
34223
  try {
33818
34224
  preview = await wallet.prepareMelt("bolt11", quote, send);
@@ -33856,7 +34262,7 @@ var CashuWallet = class CashuWallet {
33856
34262
  const lost = this.takeFailedFee(melt.quote);
33857
34263
  if (this.spentAway.delete(melt.quote)) throw Object.assign(engineError("ecashAlreadySpent"), { cause: error });
33858
34264
  if (lost > 0) throw Object.assign(/* @__PURE__ */ new Error(`${error instanceof Error ? error.message : String(error)} ${backInWallet(lost)}`), { cause: error });
33859
- throw error;
34265
+ throw Object.assign(engineError("lightningRefused", { reason: mintReason(error) }), { cause: error });
33860
34266
  }
33861
34267
  return outcome;
33862
34268
  }
@@ -34029,6 +34435,8 @@ var CashuWallet = class CashuWallet {
34029
34435
  wallet = (async () => {
34030
34436
  const instance = new (await (loadCashu())).Wallet(mint, { unit: UNIT$1 });
34031
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);
34032
34440
  return instance;
34033
34441
  })();
34034
34442
  this.wallets.set(mint, wallet);
@@ -37918,8 +38326,14 @@ var GhostlyNode = class GhostlyNode {
37918
38326
  mint: melt.mint
37919
38327
  }),
37920
38328
  onTestMintNeeded: async (mint) => void await this.walletAddMint({ url: mint }),
37921
- 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)
37922
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
+ }
37923
38337
  registry;
37924
38338
  providers() {
37925
38339
  return this.registry ??= this.options.providers ?? defaultRegistry();
@@ -37946,7 +38360,8 @@ var GhostlyNode = class GhostlyNode {
37946
38360
  events: {
37947
38361
  changed: () => this.walletChanged(),
37948
38362
  received: (op) => void this.desk.onLightningPaid(op),
37949
- 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)
37950
38365
  }
37951
38366
  }));
37952
38367
  /** On-chain Bitcoin of each network, through its active source: none until the person sets one up. */
@@ -38217,17 +38632,25 @@ var GhostlyNode = class GhostlyNode {
38217
38632
  return null;
38218
38633
  },
38219
38634
  receivePaymentRequest: (linkId, request) => this.desk.onPaymentRequest(linkId, request, true),
38635
+ taken: (linkId, id) => db.hasMessage(linkId, `peer_${id}`),
38220
38636
  changed: () => this.emitState(),
38221
38637
  fetch: (...request) => (this.options.holdFetch ?? globalThis.fetch)(...request),
38222
38638
  loopbackStorage: () => this.options.holdLoopback === true,
38223
38639
  ttlMs: () => {
38224
- try {
38225
- const raw = typeof localStorage !== "undefined" ? localStorage.getItem("ghostly-test-hold-ttl") : null;
38226
- const ms = raw ? Number(raw) : NaN;
38227
- return Number.isFinite(ms) && ms > 0 ? ms : void 0;
38228
- } catch {
38229
- return;
38230
- }
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
+ };
38231
38654
  }
38232
38655
  });
38233
38656
  /** x401 credentials (WISP 3xx): kept for websites the headless CLI calls, never shared with a contact. */
@@ -40222,6 +40645,15 @@ var GhostlyNode = class GhostlyNode {
40222
40645
  nostrLoadOwn(params) {
40223
40646
  return this.nostrSocial.loadOwn(params);
40224
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
+ }
40225
40657
  nostrLookup(params) {
40226
40658
  return this.nostrSocial.lookup(params);
40227
40659
  }
@@ -41088,10 +41520,21 @@ var GhostlyNode = class GhostlyNode {
41088
41520
  return press;
41089
41521
  }
41090
41522
  /** A paired row's reply as it goes on the wire again (a resend, a hold). */
41091
- /** `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. */
41092
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() {
41093
41536
  try {
41094
- return typeof localStorage !== "undefined" && localStorage.getItem("ghostly-test-no-edit") === "1";
41537
+ return testBuild() && typeof localStorage !== "undefined" && localStorage.getItem("ghostly-test-no-ratchet") === "1";
41095
41538
  } catch {
41096
41539
  return false;
41097
41540
  }
@@ -41340,7 +41783,7 @@ var GhostlyNode = class GhostlyNode {
41340
41783
  /**
41341
41784
  * `restoreCards`, then what waits goes. One look at a time per chat, at most once per `CARD_RESTORE_EVERY_MS`: asked
41342
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
41343
- * edit queue reads the history once a session).
41786
+ * edit queue reads the history once a run).
41344
41787
  */
41345
41788
  restoreCardsSoon(linkId) {
41346
41789
  const flush = () => this.editsFor(linkId).flush().catch(() => {});
@@ -42672,6 +43115,26 @@ var GhostlyNode = class GhostlyNode {
42672
43115
  this.capsChanged(linkId);
42673
43116
  }
42674
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
+ }
42675
43138
  transportLogOf(live) {
42676
43139
  if (!live.stored.profile || live.stored.group) return void 0;
42677
43140
  if (live.transportLog) return live.transportLog;
@@ -44045,10 +44508,22 @@ var GhostlyNode = class GhostlyNode {
44045
44508
  source: created.source
44046
44509
  };
44047
44510
  }
44048
- /** `card`: the Lightning card that will pay; absent, the network's default one. */
44049
- 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 }) {
44050
44525
  const n = this.net(network);
44051
- 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));
44052
44527
  }
44053
44528
  /**
44054
44529
  * `confirmedReal`: the person confirmed a Mainnet payment as real money; without it one is refused. `linkId` +
@@ -44194,8 +44669,11 @@ var GhostlyNode = class GhostlyNode {
44194
44669
  return { inspection: await this.wallet.inspect(text) };
44195
44670
  }
44196
44671
  async walletReceiveToken({ token }) {
44197
- const { amount } = await this.wallet.receiveToken(token.trim());
44198
- return { amount };
44672
+ const { amount, fee } = await this.wallet.receiveToken(token.trim());
44673
+ return {
44674
+ amount,
44675
+ fee
44676
+ };
44199
44677
  }
44200
44678
  /** `network`: only that network's Cashu wallet (its mints). */
44201
44679
  walletExport(params) {
@@ -45801,6 +46279,7 @@ var GhostlyNode = class GhostlyNode {
45801
46279
  const native = this.keepsGroupNative(stored);
45802
46280
  const resumeOn = native ? TRANSPORTS.find((t) => t !== "webrtc/1" && t in this.nativeFactories && !!stored.peerTransports?.includes(t)) : "webrtc/1";
45803
46281
  live.pairing = { status: "connecting" };
46282
+ live.edgeStartedAt = Date.now();
45804
46283
  live.carried?.stop();
45805
46284
  live.carried = entry || this.groups.isCommunityGroup(group) ? void 0 : new CarriedTransport(this.groupTransport, live.myPubKeyZ32, stored.peerPubKeyZ32, {
45806
46285
  carry: (payload) => this.groups.carrySignal(group, peer, payload),
@@ -46156,7 +46635,11 @@ var GhostlyNode = class GhostlyNode {
46156
46635
  return !peer || peer.capabilities.includes("dht-text/1");
46157
46636
  },
46158
46637
  peerAcceptsFile: () => !!live.caps?.peer?.capabilities.includes(DHT_FILE_CAPABILITY),
46159
- 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
46160
46643
  } : void 0,
46161
46644
  native: {
46162
46645
  peerDescriptors: stored.peerDescriptors,
@@ -46563,6 +47046,7 @@ var GhostlyNode = class GhostlyNode {
46563
47046
  "chat/1",
46564
47047
  DHT_TEXT_CAPABILITY,
46565
47048
  DHT_FILE_CAPABILITY,
47049
+ ...GhostlyNode.testNoRatchet() ? [] : [RATCHET_CAPABILITY],
46566
47050
  ...live?.stored.hold?.enabled ? [HOLD_CAPABILITY] : [],
46567
47051
  "files/2",
46568
47052
  UPGRADE_CAPABILITY,
@@ -46634,7 +47118,7 @@ var GhostlyNode = class GhostlyNode {
46634
47118
  nativeFactoriesFor(relayOnly) {
46635
47119
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
46636
47120
  return {
46637
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-B2uK9tJv.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
47121
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-g7eXzf5h.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
46638
47122
  ...relayOnly ? {} : this.options.nativeTransports,
46639
47123
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
46640
47124
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -47601,7 +48085,7 @@ var EngineServer = class {
47601
48085
  kind: "response",
47602
48086
  id: request.id
47603
48087
  };
47604
- if (request.method === "setCallSignal") this.offers.delete(request.params?.linkId ?? "");
48088
+ if (request.method === "setCallSignal") this.callHandled(client, request.params);
47605
48089
  let params = request.params;
47606
48090
  if (request.method === "setCallOn") {
47607
48091
  if (request.params?.on === true) this.onCall.add(client);
@@ -47729,6 +48213,22 @@ var EngineServer = class {
47729
48213
  broadcast(event) {
47730
48214
  for (const client of [...this.clients]) this.post(client, event);
47731
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
+ }
47732
48232
  };
47733
48233
  /** Whether a call only reads a group's stored history (`GhostlyNode.groupsRead`). */
47734
48234
  function readsGroupHistory(request) {
@@ -47747,4 +48247,4 @@ function signalKind(signal) {
47747
48247
  //#endregion
47748
48248
  export { EngineServer };
47749
48249
 
47750
- //# sourceMappingURL=server-BUcJo4vz.js.map
48250
+ //# sourceMappingURL=server-D9RAmGdm.js.map