@ghostlytools/cli 1.12.1 → 1.13.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 (63) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{api-jRUXnBdX.js → api-CVtg7MpI.js} +2 -2
  3. package/dist/assets/{api-BwEgbvvK.js → api-CjOaoG-v.js} +16 -16
  4. package/dist/assets/api-CjOaoG-v.js.map +1 -0
  5. package/dist/assets/{apiKit-BlsNk-Cx.js → apiKit-BAGvlQtm.js} +2 -2
  6. package/dist/assets/{apiKit-BlsNk-Cx.js.map → apiKit-BAGvlQtm.js.map} +1 -1
  7. package/dist/assets/{appFetch-CW9fJPHh.js → appFetch-BwJd-kNq.js} +2 -2
  8. package/dist/assets/{appFetch-CW9fJPHh.js.map → appFetch-BwJd-kNq.js.map} +1 -1
  9. package/dist/assets/{apps-CL8TXHhu.js → apps-Cuk45sz5.js} +5 -5
  10. package/dist/assets/{apps-CL8TXHhu.js.map → apps-Cuk45sz5.js.map} +1 -1
  11. package/dist/assets/{apps-BcG4u6SM.js → apps-DjY095Af.js} +1 -1
  12. package/dist/assets/{backup-xZfV-ytw.js → backup-B56sQqoQ.js} +1 -1
  13. package/dist/assets/{backup-BA41EDvh.js → backup-DekVCDWv.js} +3 -3
  14. package/dist/assets/{backup-BA41EDvh.js.map → backup-DekVCDWv.js.map} +1 -1
  15. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
  16. package/dist/assets/{bitcoind-Dh7n9amb.js → bitcoind-B2bbVSzh.js} +2 -2
  17. package/dist/assets/{bitcoind-Dh7n9amb.js.map → bitcoind-B2bbVSzh.js.map} +1 -1
  18. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
  19. package/dist/assets/{buttons-SH1tNRh7.js → buttons-BGxzOtrq.js} +26 -5
  20. package/dist/assets/buttons-BGxzOtrq.js.map +1 -0
  21. package/dist/assets/buttons-CsN2WJOf.js +1 -0
  22. package/dist/assets/{client-DGS-atRu.js → client-DcQAfc3h.js} +2 -2
  23. package/dist/assets/{client-DGS-atRu.js.map → client-DcQAfc3h.js.map} +1 -1
  24. package/dist/assets/{fixedHosts-CPSsGOI2.js → fixedHosts-C3hBliM9.js} +2 -2
  25. package/dist/assets/{fixedHosts-CPSsGOI2.js.map → fixedHosts-C3hBliM9.js.map} +1 -1
  26. package/dist/assets/{groupMeta-DxuJzko_.js → groupMeta-goASqzOt.js} +94 -17
  27. package/dist/assets/{groupMeta-DxuJzko_.js.map → groupMeta-goASqzOt.js.map} +1 -1
  28. package/dist/assets/{host-BxM-HMr0.js → host-C2WRKj3g.js} +52 -32
  29. package/dist/assets/host-C2WRKj3g.js.map +1 -0
  30. package/dist/assets/{irohWeb-CbnGtUo6.js → irohWeb-NfthOL98.js} +6 -6
  31. package/dist/assets/{irohWeb-CbnGtUo6.js.map → irohWeb-NfthOL98.js.map} +1 -1
  32. package/dist/assets/{main-CwTaepxR.js → main-Dh7fePd8.js} +19 -19
  33. package/dist/assets/main-Dh7fePd8.js.map +1 -0
  34. package/dist/assets/{mainline-CVrd0C1n.js → mainline-DY95WbuK.js} +2 -2
  35. package/dist/assets/{mainline-CVrd0C1n.js.map → mainline-DY95WbuK.js.map} +1 -1
  36. package/dist/assets/{ownDid-DY3rYqDI.js → ownDid-BErplN7N.js} +2 -2
  37. package/dist/assets/{ownDid-DY3rYqDI.js.map → ownDid-BErplN7N.js.map} +1 -1
  38. package/dist/assets/{ownStatus-DtzIllg2.js → ownStatus-ClrFjd7h.js} +4 -3
  39. package/dist/assets/ownStatus-ClrFjd7h.js.map +1 -0
  40. package/dist/assets/{profiles-BOYGlmu2.js → profiles-B8xO8-oj.js} +2 -2
  41. package/dist/assets/{profiles-BOYGlmu2.js.map → profiles-B8xO8-oj.js.map} +1 -1
  42. package/dist/assets/{registry-4W1LGlCF.js → registry--Rg2YvOH.js} +1 -1
  43. package/dist/assets/{registry-Bep4umOM.js → registry-CU8PevhI.js} +3 -3
  44. package/dist/assets/{registry-Bep4umOM.js.map → registry-CU8PevhI.js.map} +1 -1
  45. package/dist/assets/{relay-Cjfmdec0.js → relay-CHWg5hpZ.js} +73 -11
  46. package/dist/assets/relay-CHWg5hpZ.js.map +1 -0
  47. package/dist/assets/{resolve-CIc3KZMV.js → resolve-B1upovPM.js} +2 -2
  48. package/dist/assets/{resolve-CIc3KZMV.js.map → resolve-B1upovPM.js.map} +1 -1
  49. package/dist/assets/{server-D4gf-LnD.js → server-Dgxx_DaN.js} +221 -22
  50. package/dist/assets/server-Dgxx_DaN.js.map +1 -0
  51. package/dist/assets/{waitNotice-DQvZgz2T.js → waitNotice-ylU3XwjO.js} +2 -2
  52. package/dist/assets/{waitNotice-DQvZgz2T.js.map → waitNotice-ylU3XwjO.js.map} +1 -1
  53. package/dist/ghostly.mjs +1 -1
  54. package/npm-shrinkwrap.json +2 -2
  55. package/package.json +1 -1
  56. package/dist/assets/api-BwEgbvvK.js.map +0 -1
  57. package/dist/assets/buttons-CsGdQNnR.js +0 -1
  58. package/dist/assets/buttons-SH1tNRh7.js.map +0 -1
  59. package/dist/assets/host-BxM-HMr0.js.map +0 -1
  60. package/dist/assets/main-CwTaepxR.js.map +0 -1
  61. package/dist/assets/ownStatus-DtzIllg2.js.map +0 -1
  62. package/dist/assets/relay-Cjfmdec0.js.map +0 -1
  63. package/dist/assets/server-D4gf-LnD.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay-CHWg5hpZ.js","names":[],"sources":["../../../core/src/transport.ts","../../../core/src/relayBreaker.ts","../../../core/src/linkTrace.ts","../../../core/src/relay.ts"],"sourcesContent":["import type { DiscoveryStatus } from \"./relayBreaker\";\nimport type { Identity } from \"./identity\";\nimport type { GhostRecord, SignedPacket } from \"./pkarr\";\nimport type { TurnConditions, TurnSourceAnswer, TurnSourcePut } from \"./turnRead\";\n\n/**\n * How a Ghostly peer reaches Pkarr. Desktop talks to the Mainline DHT directly\n * through the Rust client; browsers cannot open UDP sockets, so they go through\n * Pkarr relays. Both end up in the same DHT and see each other's packets.\n */\n/**\n * `background`: a request that can wait (a periodic look at a shared record, not a link's\n * signaling). A transport with a request budget spends only part of it on these, so they never\n * starve the links; one without ignores it.\n */\n/**\n * `urgent`: a signal is due any moment (a link polling fast). A transport with more than one relay may\n * ask a second one when the first had nothing new: relays behind one name do not all serve a fresh\n * packet at the same moment.\n */\n/**\n * `group`: a group's request (its edges' signaling, a knock, a community's shared records). A transport with a\n * request budget keeps the last part of each minute for a 1:1 chat it had to hold back; one without ignores it.\n */\n/** What changed in how discovery goes: a relay tripped (left alone), or one answered again. */\nexport type DiscoveryChange = \"tripped\" | \"recovered\";\n\n/**\n * `door`: a community's records that open edges: the knock bell the door reads, a hub's lobby and the beacon it reads\n * and writes, and a member's request in a hub's lobby. Background requests, but not held to the small share while a\n * link signals (`BACKGROUND_WHILE_SIGNALING`): the door admitting one person opens links that signal, and the next\n * person's knock would wait for them (2026-09-28). When a hub's app is killed, the edges to it dial it again and look\n * fast for a while, on the hub left and on its members alike: on CLI daemons the hub left got 2 of 24 beacon writes\n * through in 90 s (its entry went stale, and members it should have carried became hubs), and the members' requests\n * in its lobby went out 40 s after they asked (2026-10-03).\n * A hub's reads say `door` only while someone is coming in (`Communities.doorBusy`): otherwise they give way like any\n * background read, and an app that was a hub of several communities left its edges' signaling the share (2026-10-13).\n *\n * `signal`: a link's WebRTC signaling, what its contact waits for: the write of a new offer or answer, or a read for\n * the answer while this side's offer is out, or the reads of a DHT-only contact's mailbox once it shows it is leaving,\n * up to three while it still says DHT only (the live link waits on them). A 1:1 chat's may go a little over the relay's minute\n * (`SIGNALING_ALLOWANCE_SHARE` in relay.ts).\n */\nexport interface PkarrRequestOptions {\n background?: boolean; urgent?: boolean; group?: boolean; door?: boolean; signal?: boolean;\n /**\n * A read for a contact that went away from a live session and has not shown itself back (`LinkSession.watchPeer`), or\n * a write while a link watches for one: what that contact, back, reads first.\n */\n watch?: boolean;\n /**\n * A 1:1 chat's read of a contact that went away from a live session within `DEPARTED_READ_MS` (link.ts): an app that\n * restarts publishes its offer then. So is a chat's read of the mailbox of a contact on DHT only, this side not, out of\n * the background (`DhtDelivery.departedRead`): its envelope saying it left is what the live link waits on. A few may go\n * over the relay's minute (`DEPARTED_READS` in relay.ts).\n */\n departed?: boolean;\n /**\n * A 1:1 chat's read of an invite this side made, while its joiner is due (`AWAITING_PEER_MS` in link.ts) and has not\n * shown: the joiner's knock is read there. A few may go over the relay's minute (`AWAITED_READS` in relay.ts).\n */\n awaited?: boolean;\n /**\n * A read of a contact that was live when this app last ran, made before any read of it this run was answered\n * (`LinkSessionOptions.resumed`): the link's offer waits on it. A group edge's goes on the edges' floor\n * (`GROUP_SIGNALING_ALLOWANCE_SHARE` in relay.ts).\n */\n resume?: boolean;\n /**\n * A community member's way back to its group while it has no edge up there (`Communities.wayBack`): its readings of the\n * beacon and its request in a hub's lobby. Its own small allowance past the relay's minute (`WAY_BACK_SHARE` in\n * relay.ts), not the edges' signaling's.\n */\n back?: boolean;\n /**\n * `publishPayload` only: the payload was signed in this process, dated so (a group edge's, `CarriedTransport`). Its\n * signature is not checked again on the way to the relays, as `RelayTransport.putSigned`'s is not.\n */\n signedAt?: bigint;\n /**\n * `publishPayload` only, with `signedAt`: the same records signed again, dated past `after` (what a relay that answered\n * 409 holds under the key); null when a newer packet of the key took over. The relays' transport puts that one at\n * once rather than leave the relay's copy in place until the next publish (`RelayTransport.publishPayload`).\n */\n redate?: (after: bigint) => { payload: Uint8Array; signedAt: bigint } | null;\n}\n\n/**\n * `transport` with `extra` added to every request's options: a group's edges say `group` so. The optional methods\n * stay optional (a caller reads `configure` as \"the DHT is reached directly\").\n */\nexport function withRequestOptions(transport: PkarrTransport, extra: PkarrRequestOptions): PkarrTransport {\n const wrapped: PkarrTransport = {\n publish: (identity, records, options) => transport.publish(identity, records, { ...options, ...extra }),\n resolve: (pubKeyZ32, options) => transport.resolve(pubKeyZ32, { ...options, ...extra }),\n describe: () => transport.describe(),\n };\n if (transport.publishPayload) wrapped.publishPayload = (pubKeyZ32, payload, options) => transport.publishPayload!(pubKeyZ32, payload, { ...options, ...extra });\n if (transport.discovery) wrapped.discovery = () => transport.discovery!();\n if (transport.subscribe) wrapped.subscribe = (listener) => transport.subscribe!(listener);\n if (transport.networkChanged) wrapped.networkChanged = () => transport.networkChanged!();\n if (transport.readAnsweredAt) wrapped.readAnsweredAt = (pubKeyZ32) => transport.readAnsweredAt!(pubKeyZ32);\n if (transport.readHeldBackFor) wrapped.readHeldBackFor = (pubKeyZ32) => transport.readHeldBackFor!(pubKeyZ32);\n if (transport.publishHeld) wrapped.publishHeld = (pubKeyZ32, options) => transport.publishHeld!(pubKeyZ32, { ...options, ...extra });\n if (transport.onServerTime) wrapped.onServerTime = (listener) => transport.onServerTime!(listener);\n if (transport.configure) wrapped.configure = (options) => transport.configure!(options);\n if (transport.turnRead) wrapped.turnRead = (pubKeyZ32, options) => transport.turnRead!(pubKeyZ32, options);\n if (transport.turnPut) wrapped.turnPut = (pubKeyZ32, payload, conditions) => transport.turnPut!(pubKeyZ32, payload, conditions);\n if (transport.turnWarm) wrapped.turnWarm = () => transport.turnWarm!();\n if (transport.forget) wrapped.forget = (keys) => transport.forget!(keys);\n return wrapped;\n}\n\n/**\n * A request the transport held back to stay within a request budget, its own or a relay's rate limit: nothing went\n * out, and the same request goes through once the budget frees one, in about `retryInMs`. A wait, never a failure:\n * whoever publishes tries again then, and says nothing is wrong meanwhile.\n */\nexport class DiscoveryBudgetError extends Error {\n declare readonly code: \"discovery-budget\";\n declare readonly retryInMs: number;\n constructor(retryInMs: number, message = \"Discovery request budget reached; retry shortly\") {\n // Made at every request the budget holds, thousands a minute with many contacts away, and never a failure: no\n // stack, which took a tenth of such a daemon's CPU. Where the engine has no such limit (Firefox), as it was.\n const errors = Error as { stackTraceLimit?: number };\n const limit = errors.stackTraceLimit;\n if (typeof limit === \"number\") errors.stackTraceLimit = 0;\n try { super(message); } finally { if (typeof limit === \"number\") errors.stackTraceLimit = limit; }\n this.code = \"discovery-budget\";\n this.retryInMs = retryInMs;\n this.name = \"DiscoveryBudgetError\";\n }\n}\n\n/** Whether `error` is a request the budget held back (`DiscoveryBudgetError`), also from another copy of this module. */\nexport function isDiscoveryBudgetError(error: unknown): error is DiscoveryBudgetError {\n return error instanceof DiscoveryBudgetError || (typeof error === \"object\" && error !== null && (error as { code?: unknown }).code === \"discovery-budget\"\n && typeof (error as { retryInMs?: unknown }).retryInMs === \"number\");\n}\n\n/**\n * A publish no relay took (`RelayTransport`), saying whether one of them may hold the packet all the same. Not\n * `mayBeStored` only when every relay was not asked now (its budget, its rate limit, its breaker, its network\n * cooldown), answered that it did not take it (a 4xx), or could not be reached before the request went (a refused\n * connection or a name that does not resolve, where the runtime says so: Node does, a browser does not), or when there\n * is no relay at all. A relay that did not answer in time, dropped the connection, or answered with a server error\n * may have stored it. The message is the publish's usual one.\n */\nexport class PublishFailedError extends Error {\n readonly code = \"publish-failed\";\n constructor(message: string, readonly mayBeStored: boolean) { super(message); }\n}\n\n/**\n * Whether `error` is a publish that went nowhere (`PublishFailedError` with `mayBeStored` false), also from another\n * copy of this module. Anything else (a timeout, the DHT's own failure beside the relays', a Desktop's error in\n * words) may have left this device.\n */\nexport function publishedNowhere(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && (error as { code?: unknown }).code === \"publish-failed\"\n && (error as { mayBeStored?: unknown }).mayBeStored === false;\n}\n\n/**\n * A publish Ghostly Desktop's Rust relay client held back, as it says it in words (`pkarr_network.rs`\n * `publish_failure`: \"Publish held back on every relay…; retry in N ms: …\"), as the `DiscoveryBudgetError` it is: every\n * relay held the packet back for its rate limit, or held it back beside relays left alone for failing, and nothing failed\n * now. Anything else is returned as it came.\n */\nexport function heldBackError(error: unknown): unknown {\n const text = typeof error === \"string\" ? error : error instanceof Error ? error.message : \"\";\n const wait = /^Publish held back [^;]*; retry in (\\d+) ms/.exec(text);\n return wait ? new DiscoveryBudgetError(Number(wait[1]), text) : error;\n}\n\n/** When to try again after the budget held a request back: when it frees one, but never sooner than `min` nor later than `max`. */\nexport function budgetRetryMs(error: DiscoveryBudgetError, min: number, max: number): number {\n return Math.min(max, Math.max(min, Number.isFinite(error.retryInMs) ? error.retryInMs : max));\n}\n\n/**\n * A server's own time: the `Date` header (ms, to the second) of its answer to a request that went out at `sent` and\n * came back at `received`, both by this device's clock. `source` names the server (a relay's origin), never a key.\n */\nexport interface ServerTime { source: string; date: number; sent: number; received: number }\n\nexport interface PkarrTransport {\n publish(identity: Identity, records: GhostRecord[], options?: PkarrRequestOptions): Promise<void>;\n /**\n * Puts a relay payload signed elsewhere, byte for byte (a did:dht document: its own record names and\n * a sequence number in seconds). A transport without it cannot publish one.\n */\n publishPayload?(pubKeyZ32: string, payload: Uint8Array, options?: PkarrRequestOptions): Promise<void>;\n /**\n * Most recent packet known for this key, or null when nothing is published. `keptOnFailure` false: a read nothing\n * answered throws `RelaysFailedError` with the packet known before, rather than handing it back as the answer.\n */\n resolve(pubKeyZ32: string, options?: PkarrRequestOptions, keptOnFailure?: boolean): Promise<SignedPacket | null>;\n describe(): { protocol: string; relays: string[] };\n /** How reads go and how each relay is doing, for the connection panel; absent where nothing is known. */\n discovery?(): DiscoveryStatus;\n /**\n * Called when that changes in a way worth showing (a relay trips or recovers), with `\"recovered\"` when a relay\n * answered again after failing: links then look and publish at once rather than at their pace. Returns the unsubscribe.\n */\n subscribe?(listener: (change?: DiscoveryChange) => void): () => void;\n /** The device changed networks (back online): what was learnt about failing relays is forgotten, and links look again. */\n networkChanged?(): void;\n /**\n * When the network last answered a read of this key (this clock), whatever it answered. A `resolve` may hand back a\n * copy it kept (the budget held the read, every relay was resting, the same key was read a moment ago): a caller\n * that reasons from \"the record did not have this at my last read\" asks this to know the read was one. Absent\n * where the transport cannot say; such a caller then takes no read for one.\n */\n readAnsweredAt?(pubKeyZ32: string): number | undefined;\n /**\n * How long the budget still holds back a read of this key, when its last read was held back and answered from a kept\n * copy (`readAnsweredAt` did not move): when to read again. Undefined once a read went out, or where it cannot say.\n */\n readHeldBackFor?(pubKeyZ32: string): number | undefined;\n /**\n * A publish of this key with these options that nothing would take now, said before anything is signed: the wait\n * (`DiscoveryBudgetError`) a put would be refused with, or null when it would go (or where the transport cannot say,\n * or it also puts packets where no budget holds them, the CLI's DHT). As `publish` checks itself before signing; a\n * caller that signs its own payloads (`CarriedTransport`) asks first. A wait said is a refusal noted, as a put's.\n */\n publishHeld?(pubKeyZ32: string, options?: PkarrRequestOptions): DiscoveryBudgetError | null;\n /**\n * Called with each time a server gave (`ServerTime`), where the transport can read one: what `ClockWatch` holds this\n * device's clock against. Returns the unsubscribe.\n */\n onServerTime?(listener: (time: ServerTime) => void): () => void;\n /**\n * Where the DHT is reached directly (Desktop): the relays from Settings, and whether reads may use them too\n * (`readRelays`, \"Also use Pkarr relays\"). Writes go to them either way, so browser contacts see this peer's packets.\n * `dhtDirect: false` (Hide my IP from contacts, WISP 100 § Relay only): reads and writes go through the relays alone,\n * and no UDP goes to a DHT node; absent leaves the DHT as it is.\n */\n configure?(options: { relays: string[]; readRelays: boolean; dhtDirect?: boolean }): void;\n /**\n * The turn record's own read (WISP 06 § Publishing and reading): every source is asked, in parallel, and each\n * one's answer is handed back as it came, not verified, not cached and never taken from this client's own writes.\n * Only the turn uses it; a transport without it cannot hold a profile on several devices.\n */\n turnRead?(pubKeyZ32: string, options?: { timeoutMs?: number }): Promise<TurnSourceAnswer[]>;\n /**\n * The turn record's own put: the stored bytes, to each source named in `conditions`, on that source's condition\n * (`cas` on the DHT, `If-Match` on a relay). Every source's answer is reported, and a refusal is never tried again\n * without its condition.\n */\n turnPut?(pubKeyZ32: string, payload: Uint8Array, conditions: TurnConditions): Promise<TurnSourcePut[]>;\n /** The profile has a device set: the turn's sources are made ready ahead of the first read (`TurnNetwork.turnWarm`). */\n turnWarm?(): Promise<void>;\n /**\n * Nothing will be put or read under these keys any more (a spare invite replaced unused): what the transport kept\n * per key for them (the last packet put, its dates, each relay's last put) goes. Absent where nothing is kept.\n */\n forget?(keys: Iterable<string>): void;\n}\n","/**\n * A circuit breaker per Pkarr relay. A relay that failed `threshold` times in a row (no answer, a server error,\n * its own rate limit, 429, or an answer too slow to use, `SLOW_MS` in relay.ts) is left alone for a while: a minute the first time, twice as long each time it\n * trips again, five minutes at most. When the wait is over, one request goes to it (the probe); an answer\n * closes the breaker, a failure opens it again for longer. The relays still closed take its turns meanwhile.\n *\n * Only what the relay did counts: a request this client held back for its own budget is not a failure, and an\n * answer the protocol expects (404, 409, 412, 428) is a relay working as it should.\n */\n\n/** Failures in a row that trip a relay's breaker. */\nexport const BREAKER_THRESHOLD = 3;\n/** How long a relay is left alone the first time its breaker trips; doubled on each trip in a row. */\nexport const BREAKER_BASE_MS = 60_000;\n/** The longest a relay is left alone. */\nexport const BREAKER_MAX_MS = 5 * 60_000;\n/**\n * While every relay is left alone for failing, one of them is asked this often anyway: with nothing else to try, a\n * long wait only delays noticing that they answer again (a link stayed down minutes after the relays came back).\n */\nexport const BREAKER_ALL_DOWN_PROBE_MS = 15_000;\n\n/** Why a request to a relay failed: its rate limit (`throttled`), or anything else (`error`). */\nexport type RelayFailure = \"throttled\" | \"error\";\n\n/** A relay as the connection panel shows it: `ok`, `throttled` (its rate limit) or `failing`, until when. */\nexport interface RelayHealth {\n relay: string;\n state: \"ok\" | \"throttled\" | \"failing\";\n /** When the relay is asked again (ms since the epoch), while it is left alone. */\n until?: number;\n /** What went wrong last, in a few words; never a key. */\n reason?: string;\n}\n\n/**\n * How this client reaches Pkarr right now, for the connection panel: the path its last read took (\"dht\", or\n * the relay that answered), and the health of each relay it uses (none where it reads the DHT alone).\n */\nexport interface DiscoveryStatus {\n path: { via: \"dht\" } | { via: \"relay\"; relay: string } | null;\n relays: RelayHealth[];\n}\n\nexport interface RelayBreakerOptions {\n threshold?: number;\n baseMs?: number;\n maxMs?: number;\n /** `BREAKER_ALL_DOWN_PROBE_MS`. */\n allDownProbeMs?: number;\n now?: () => number;\n /** Told each time a relay trips: which, why, and for how long. */\n onTrip?: (relay: string, reason: string, forMs: number) => void;\n /** Told when a tripped relay answered its probe. */\n onRecover?: (relay: string) => void;\n}\n\ninterface Circuit {\n failures: number;\n /** Trips in a row, without an answer in between: the next wait doubles with each. */\n trips: number;\n /** Left alone until then (0: closed). */\n openUntil: number;\n /** The one request allowed once the wait is over is out. */\n probing: boolean;\n kind?: RelayFailure;\n reason?: string;\n}\n\nexport class RelayBreaker {\n private readonly circuits = new Map<string, Circuit>();\n private readonly threshold: number;\n private readonly baseMs: number;\n private readonly maxMs: number;\n private readonly allDownProbeMs: number;\n private readonly now: () => number;\n /** When a relay was last asked because every relay was left alone. */\n private lastAllDownProbe = -Infinity;\n\n constructor(private readonly options: RelayBreakerOptions = {}) {\n this.threshold = options.threshold ?? BREAKER_THRESHOLD;\n this.baseMs = options.baseMs ?? BREAKER_BASE_MS;\n this.maxMs = options.maxMs ?? BREAKER_MAX_MS;\n this.allDownProbeMs = options.allDownProbeMs ?? BREAKER_ALL_DOWN_PROBE_MS;\n this.now = options.now ?? Date.now;\n }\n\n private circuit(relay: string): Circuit {\n let circuit = this.circuits.get(relay);\n if (!circuit) this.circuits.set(relay, circuit = { failures: 0, trips: 0, openUntil: 0, probing: false });\n return circuit;\n }\n\n /** How long the relay is still left alone, in ms; 0 when a request may go (closed, or its probe is due). */\n blockedFor(relay: string): number {\n const circuit = this.circuits.get(relay);\n if (!circuit || circuit.openUntil === 0) return 0;\n const left = circuit.openUntil - this.now();\n if (left > 0) return left;\n // The wait is over: one probe at a time, the others wait for its answer.\n return circuit.probing ? this.baseMs : 0;\n }\n\n /** Why the relay is left alone, while it is: its rate limit or failures. */\n blockedKind(relay: string): RelayFailure | undefined {\n return this.blockedFor(relay) > 0 ? this.circuits.get(relay)?.kind : undefined;\n }\n\n /** A request is going to the relay now: its probe, when the wait is over. Call only when `blockedFor` is 0. */\n begin(relay: string): void {\n const circuit = this.circuits.get(relay);\n if (circuit && circuit.openUntil !== 0 && circuit.openUntil <= this.now()) circuit.probing = true;\n }\n\n /**\n * When every relay of `relays` is left alone for failing (none for its rate limit, none with its probe due or out),\n * the one whose wait ends first may be asked now, once every `BREAKER_ALL_DOWN_PROBE_MS`. Returns it, or null. The\n * caller marks the request with `beginAllDown` when it really goes (a request its budget holds back is no probe).\n */\n allDownProbe(relays: string[]): string | null {\n const now = this.now();\n if (!relays.length || now - this.lastAllDownProbe < this.allDownProbeMs) return null;\n let pick: string | null = null, soonest = Infinity;\n for (const relay of relays) {\n const circuit = this.circuits.get(relay);\n if (!circuit || circuit.openUntil <= now || circuit.probing || circuit.kind !== \"error\") return null;\n if (circuit.openUntil < soonest) { soonest = circuit.openUntil; pick = relay; }\n }\n return pick;\n }\n\n /** The probe `allDownProbe` named is going now: its answer closes the breaker, a failure trips it again. */\n beginAllDown(relay: string): void {\n const circuit = this.circuits.get(relay);\n if (circuit) circuit.probing = true;\n this.lastAllDownProbe = this.now();\n }\n\n /**\n * A request that went to the relay was dropped before it answered, by this client (another relay answered first), or\n * its answer says nothing either way: a probe among them is no longer out, and the next request may probe again.\n */\n cancel(relay: string): void {\n const circuit = this.circuits.get(relay);\n if (circuit) circuit.probing = false;\n }\n\n /**\n * The relay answered: whatever was wrong is over. When it was left alone and so was every other relay of `relays`\n * (by default those that failed), for failing, the outage is over for them too: they are asked again now, not at the\n * end of a wait of up to `BREAKER_MAX_MS` (two clients whose probes another relay answered each would share none\n * for minutes). Their trips stay: one really down trips again at once, for longer.\n */\n success(relay: string, relays: string[] = [...this.circuits.keys()]): void {\n const circuit = this.circuits.get(relay);\n if (!circuit) return;\n const recovered = circuit.openUntil !== 0;\n this.circuits.delete(relay);\n if (!recovered) return;\n const others = relays.filter((r) => r !== relay).map((r) => this.circuits.get(r));\n if (others.length && others.every((other): other is Circuit => !!other && other.openUntil !== 0 && other.kind === \"error\")) {\n const now = this.now();\n for (const other of others) other.openUntil = Math.min(other.openUntil, now);\n }\n this.options.onRecover?.(relay);\n }\n\n /**\n * The relay failed a request; a probe that fails trips it again at once. While it is left alone and no probe is out,\n * a failure is a request sent before it tripped (a start burst): already counted in, it trips nothing again.\n */\n failure(relay: string, kind: RelayFailure, reason: string): void {\n const circuit = this.circuit(relay);\n if (!circuit.probing && circuit.openUntil > this.now()) return;\n circuit.failures++;\n circuit.kind = kind;\n circuit.reason = reason;\n if (circuit.probing || circuit.failures >= this.threshold) this.trip(relay, circuit);\n }\n\n private trip(relay: string, circuit: Circuit): void {\n // What just failed was an answer of sorts: the next early probe (`allDownProbe`) is a full interval away.\n this.lastAllDownProbe = Math.max(this.lastAllDownProbe, this.now());\n const forMs = Math.min(this.baseMs * 2 ** circuit.trips, this.maxMs);\n circuit.openUntil = this.now() + forMs;\n circuit.trips++;\n circuit.failures = 0;\n circuit.probing = false;\n this.options.onTrip?.(relay, circuit.reason ?? \"\", forMs);\n }\n\n /** How long until a relay left alone is asked again: its wait, or the next probe while every relay of `relays` is left alone. */\n askedAgainIn(relay: string, relays: string[]): number {\n const wait = this.blockedFor(relay);\n if (!relays.every((r) => this.blockedFor(r) > 0)) return wait;\n return Math.min(wait, Math.max(0, this.lastAllDownProbe + this.allDownProbeMs - this.now()));\n }\n\n /** A new network: every relay starts fresh. */\n reset(): void {\n this.circuits.clear();\n this.lastAllDownProbe = -Infinity;\n }\n\n /**\n * Each relay's health, in the order given. While every one is left alone for failing, `until` is the next probe\n * (`allDownProbe`, every 15 s), whose answer ends the wait of them all: said as the end of each one's wait, a daemon's\n * `status` and the connection panel named a time up to 5 minutes after the relays were seen answering again.\n */\n health(relays: string[]): RelayHealth[] {\n const allDown = relays.length > 0 && relays.every((relay) => this.blockedFor(relay) > 0 && this.circuits.get(relay)?.kind === \"error\");\n return relays.map((relay) => {\n const circuit = this.circuits.get(relay);\n if (!circuit || circuit.openUntil === 0 || this.blockedFor(relay) === 0) return { relay, state: \"ok\" };\n const until = allDown ? this.now() + this.askedAgainIn(relay, relays) : Math.max(circuit.openUntil, this.now());\n return { relay, state: circuit.kind === \"throttled\" ? \"throttled\" : \"failing\", until, ...(circuit.reason && { reason: circuit.reason }) };\n });\n }\n}\n","/**\n * Timestamps along a paired link's way to a live connection, for measuring where the time goes.\n * Silent unless `globalThis.__ghostlyLinkTrace` is set (the e2e measurements set it): each step is\n * then one `console.debug` line, `[ghostly:link] {\"t\":…,\"me\":…,\"step\":…}`, read back by the test.\n * A host may also install a sink (the desktop app writes the lines to its log file), which gets every\n * line whether or not the global is set.\n */\ntype LinkTraceSink = (line: string) => void;\nlet sink: LinkTraceSink | null = null;\n\n/** Where the lines go besides the console; `null` removes it. */\nexport function setLinkTraceSink(next: LinkTraceSink | null): void {\n sink = next;\n}\n\nexport function traceLink(me: string, step: string, detail?: Record<string, unknown>): void {\n const console_ = (globalThis as { __ghostlyLinkTrace?: boolean }).__ghostlyLinkTrace;\n if (!console_ && !sink) return;\n const line = JSON.stringify({ t: Date.now(), me: me.slice(0, 6), step, ...detail });\n if (console_) console.debug(`[ghostly:link] ${line}`);\n try { sink?.(line); } catch { /* a sink that fails must not fail the link */ }\n}\n","import type { Identity } from \"./identity\";\nimport { createRelayPayload, newerPacket, openRelayPayload, parseRelayPayload, PKARR_FUTURE_SKEW_MS, readOwnRelayPayload, RELAY_PAYLOAD_MAX_BYTES, type GhostRecord, type SignedPacket } from \"./pkarr\";\nimport { RelayBreaker, type DiscoveryStatus, type RelayBreakerOptions, type RelayFailure } from \"./relayBreaker\";\nimport { DiscoveryBudgetError, isDiscoveryBudgetError, PublishFailedError, publishedNowhere, type DiscoveryChange, type PkarrRequestOptions, type PkarrTransport, type ServerTime } from \"./transport\";\nimport { traceLink } from \"./linkTrace\";\nimport type { TurnConditions, TurnSourceAnswer, TurnSourcePut } from \"./turnRead\";\n\n/** Who asks, for the budget: a 1:1 chat's link comes before a group's, and both before background looks. */\ninterface Asker { background: boolean; group: boolean; urgent: boolean; door: boolean; write: boolean; signal: boolean; watch: boolean; watchWrite: boolean; departed: boolean; awaited: boolean; resume: boolean; back: boolean; catchUp?: boolean }\nconst asker = (options: PkarrRequestOptions, write: boolean): Asker =>\n ({ background: !!options.background, group: !!options.group, urgent: !!options.urgent, door: !!options.door, write, signal: !!options.signal, watch: !!options.watch && !write, watchWrite: !!options.watch && write, departed: !!options.departed && !write, awaited: !!options.awaited && !write, resume: !!options.resume && !write, back: !!options.back });\n/** A 1:1 chat's request: neither a group's nor a background one. */\nconst isChat = (who: Asker): boolean => !who.background && !who.group;\n/** A 1:1 chat's offer or answer, or its read for the answer to its offer: it may use the allowance (`SIGNALING_ALLOWANCE_SHARE`). */\nconst isChatSignal = (who: Asker): boolean => who.signal && isChat(who);\n/** A 1:1 chat's read of a contact that just went away: a few may use the chat's allowance (`DEPARTED_READS`). */\nconst isDepartedRead = (who: Asker): boolean => who.departed && isChat(who);\n/** A 1:1 chat's read of an invite this side made, its joiner due: a few may use the chat's allowance (`AWAITED_READS`). */\nconst isAwaitedRead = (who: Asker): boolean => who.awaited && isChat(who);\n/** A group's edge looking fast for a signal (`GROUP_BURST_MS`). */\nconst isGroupUrgentRead = (who: Asker): boolean => who.group && who.urgent && !who.write && !who.background;\n/**\n * A group edge's read for a member that went away from a live session and has not shown itself back (`WATCH_SHARE`).\n * A 1:1 chat's is not one: chats have their own reserve (`CHAT_RESERVE`), and a chat watching its contact must not wait\n * behind the edges that watch the same contact.\n */\nconst isWatch = (who: Asker): boolean => who.watch && who.group && !who.write;\n/** A 1:1 chat's read of a contact that went away from a live session and has not shown itself back (`CHAT_WATCH_SHARE`). */\nconst isChatWatch = (who: Asker): boolean => who.watch && isChat(who);\n/**\n * A group edge's request for a member that may be back: it may use the groups' allowance (`GROUP_SIGNALING_ALLOWANCE_SHARE`).\n * So may its reads of a member that was live when this app last ran, until one is answered (`resume`): its offer waits on them.\n */\nconst isGroupSignal = (who: Asker): boolean => who.group && !who.background && (who.signal || isWatch(who) || who.watchWrite || who.resume);\n/** A group edge's read for the signal it waits for, the answer to its offer (`signal`): first on the floor (`ANSWER_READ_FIRST_MS`). */\nconst isGroupAnswerRead = (who: Asker): boolean => isGroupSignal(who) && who.signal && !who.write;\n/** Such a read, as the budget weighs it (`ANSWER_READ_FIRST_MS`). */\nconst ANSWER_READER: Asker = { background: false, group: true, urgent: true, door: false, write: false, signal: true, watch: false, watchWrite: false, departed: false, awaited: false, resume: false, back: false };\n/** A community member's way back to its group while it has no edge up: it may use its own allowance (`WAY_BACK_SHARE`). */\nconst isWayBack = (who: Asker): boolean => who.back && who.group && !who.background;\n/** Watch reads that the same other limits hold take turns together: urgent or not, background or not; the chats' on their own. */\nconst watchLane = (who: Asker): string => (isChat(who) ? \"chat\" : `${+who.urgent}${+who.background}`);\n/** A group's read that is not a background one: an edge's, a private group's knock poll (`GROUP_RATION_WINDOW_MS`). */\nconst isGroupRead = (who: Asker): boolean => who.group && !who.write && !who.background;\n/**\n * A read that takes its turn per key with the others (`READ_TURN_MS`): a background one, and a 1:1 chat's at any pace.\n * Not a community door's bell.\n */\nconst isTurnRead = (who: Asker): boolean => !who.write && !who.door && (who.background || !who.group);\n/** A write that goes first once the budget frees a request (see `WRITE_FIRST_MS`): a chat's or a group's, never a background one. */\nconst firstWriter = (who: Asker): \"chat\" | \"group\" | null => (!who.write || who.background ? null : who.group ? \"group\" : \"chat\");\n/** A key's turn neither asked nor read in the last minute: it is dropped, and asking again starts a new one (`TURNS_PRUNE_MS`). */\nconst staleTurn = (turn: { servedAt: number; askedAt: number }, now: number): boolean => now - Math.max(turn.askedAt, turn.servedAt) >= 60_000;\n/**\n * The times of `list` (oldest first) within the last `ms`. One dated after now, the device clock gone back since (an NTP\n * step, a clock that ran ahead fixed by hand), counts as of now: as just spent, not for as long as the clock went back.\n * Counted as they were, an hour's step back held every background read for 59 minutes, and a daemon with 50 contacts\n * away read 4 of them in the next 15 (bug hunt, 2026-11-07).\n * `list` itself when every time is already so (the usual case): `heldFor` reads eight lists at each request the budget\n * holds, and copying each twice was a third of the CPU of a daemon whose 200 contacts were away.\n */\nconst within = (list: number[], now: number, ms: number): number[] => {\n let kept = true;\n for (const at of list) if (at > now || now - at >= ms) { kept = false; break; }\n return kept ? list : list.map((at) => Math.min(at, now)).filter((at) => now - at < ms);\n};\n\n/**\n * Keys and when each was last set, those of the last minute: how many and the latest, without walking them all (the\n * chats that need a relay, `chatNeeds`). Each is set at the time it is set, so the sets come oldest first; a clock\n * gone back makes the later ones as of now.\n */\nclass RecentKeys {\n private readonly at = new Map<string, number>();\n /** Every set, oldest first, from `head`; one a later set or a delete replaced is skipped. */\n private order: [string, number][] = [];\n private head = 0;\n\n set(key: string, now: number): void {\n this.prune(now);\n this.at.set(key, now);\n this.order.push([key, now]);\n }\n\n delete(key: string): void {\n this.at.delete(key);\n }\n\n size(now: number): number {\n this.prune(now);\n return this.at.size;\n }\n\n /** When the key set last was, -Infinity with none in the last minute. */\n latest(now: number): number {\n this.prune(now);\n while (this.order.length > this.head) {\n const [key, at] = this.order[this.order.length - 1];\n if (this.at.get(key) === at) return at;\n this.order.pop();\n }\n return -Infinity;\n }\n\n /** The keys set in the last minute, oldest first. */\n *entries(now: number): Generator<[string, number]> {\n this.prune(now);\n for (let i = this.head; i < this.order.length; i++) if (this.at.get(this.order[i][0]) === this.order[i][1]) yield this.order[i];\n }\n\n /** Drops the keys set a minute ago or more. */\n private prune(now: number): void {\n if (this.order.length > this.head && now < this.order[this.order.length - 1][1]) {\n for (const [key, at] of this.at) this.at.set(key, Math.min(at, now));\n this.order = [...this.at].sort((a, b) => a[1] - b[1]);\n this.head = 0;\n }\n while (this.head < this.order.length) {\n const [key, at] = this.order[this.head];\n if (this.at.get(key) === at) {\n if (now - at < 60_000) break;\n this.at.delete(key);\n }\n this.head++;\n }\n if (this.head > 64 && this.head * 2 > this.order.length) {\n this.order = this.order.slice(this.head);\n this.head = 0;\n }\n }\n}\n\n/**\n * Public Pkarr relays. They are generic Pkarr infrastructure (an HTTP bridge to\n * the Mainline DHT), not a Ghostly backend: they only ever see signed,\n * encrypted packets. Every client uses this list: the browser clients read and\n * write through it, Ghostly Desktop writes to it (so browser contacts see its\n * packets) and reads from it only when \"Also use Pkarr relays\" is on. Adding a\n * relay is one line here; see docs/RELAYS.md for how one is chosen.\n */\nexport const DEFAULT_RELAYS = [\"https://pkarr.pubky.org\", \"https://pkarr.pubky.app\", \"https://pkarr.miguelmedeiros.dev\"];\n/**\n * Relay lists that were the defaults once: a profile that still has one gets today's defaults. When a relay\n * joins `DEFAULT_RELAYS`, the list as it was goes here, so profiles on the old defaults move with it.\n */\nexport const PREVIOUS_DEFAULT_RELAYS: string[][] = [\n // Before pkarr.miguelmedeiros.dev joined (2026-10-17).\n [\"https://pkarr.pubky.org\", \"https://pkarr.pubky.app\"],\n];\n\n/** The defaults for `relays` when it is one of the old default lists, `relays` itself otherwise. */\nexport function currentRelays(relays: string[]): string[] {\n const same = (a: string[], b: string[]) => a.length === b.length && a.every((relay, i) => relay === b[i]);\n return PREVIOUS_DEFAULT_RELAYS.some((old) => same(old, relays)) ? [...DEFAULT_RELAYS] : relays;\n}\n\n/**\n * Requests this client allows itself per relay and minute. Relays limit by IP\n * (120 a minute when this was written) and one address is often shared by\n * several peers: two browser profiles, a tab and an extension, a household.\n */\nexport const REQUESTS_PER_MINUTE = 30;\n/**\n * Of those, what background requests (`{ background: true }`: periodic looks at shared records, as a\n * community group's hub makes) may spend, counted on their own: the rest is kept for links, whose\n * signaling cannot wait, and a burst of signaling does not hold the background ones back afterwards.\n */\nexport const BACKGROUND_REQUESTS_PER_MINUTE = 20;\n/**\n * Of the background share, what background writes may spend in a minute on a relay (10 of the 20): the rest is kept\n * for background reads. Those writes are mostly the upkeep of chats whose contacts are away (the link's heartbeat, the\n * DHT floor's keep-alive, the capability record), about one a minute for every two chats. A profile with 200 such chats\n * spent the share on them, and on one relay 147 of its 200 contacts were not read once in 25 minutes: a contact back\n * then went unnoticed (bug hunt, 2026-11-01). Upkeep held back goes when a request of this share frees.\n */\nexport const BACKGROUND_WRITES_SHARE = 1 / 2;\n/**\n * A link's write the budget refused (its presence, its offer, its answer) goes first when the minute\n * frees a request: reads on that relay wait this long after the refusal. A link that polls fast for a\n * peer while its offer waits would otherwise take every request the minute frees, and the offer (the\n * only thing that peer is waiting for) would go out only once the polling slowed down, half a minute later.\n */\nexport const WRITE_FIRST_MS = 5_000;\n/**\n * Once a 1:1 chat needs the relays (the budget refused one of its requests there, or it read urgently anywhere: it polls\n * fast for a signal due any moment), group requests and background ones leave it the last this many of each minute (more\n * for several chats, `CHAT_RESERVE_PER_CHAT`), for a minute. Groups that spend the whole budget spend it over the minute, so the chat then takes the next request that frees, within\n * seconds, and has room for what follows (the receipt). Waiting for a refusal was too late when a contact went away\n * from a chat and from groups at once: the chat and the groups' edges all watched fast for it, the edges spent both\n * relays' minute in 40 s, and the chat read the contact's offer half a minute late (2026-09-27). A chat with nothing\n * to wait for leaves groups the whole budget: a community door alone costs about 22 requests a minute, and a reserve\n * kept for any chat starved a new group's edges. The reserve is per chat: a chat that reads its contact at a slow pace\n * again (it is live) gives its part back at once. Kept for the minute, a daemon back after a restart with its chats\n * live in 18 s held a group's edge that had just missed its read for 48 s more (bug hunt r6a, 2026-09-29).\n */\nexport const CHAT_RESERVE = 10;\n/**\n * …and more while several chats need the relays at once: this many requests each (a read, an offer or answer, the read\n * for the answer to it), up to `CHAT_RESERVE_MOST_SHARE` of the minute. Background requests leave it too, not the\n * groups' alone: the looks of chats whose contacts are not there, and their presence (upkeep, `LinkSession`). An app\n * opened while 30 of its 50 chats' contacts were online spent both relays' minute in its first second, on the presence\n * of the chats whose contacts were long gone, its groups' records and every chat's first read: 12 of the 30 offers and\n * answers went out, no read for an answer could, and 0 of the 30 chats were live 60 s after the start (bug hunt,\n * 2026-10-13).\n */\nexport const CHAT_RESERVE_PER_CHAT = 3;\n/** The most of a relay's minute the chats' reserve takes, however many chats need it: the rest stays for everything else. */\nexport const CHAT_RESERVE_MOST_SHARE = 5 / 6;\n/**\n * A 1:1 chat's signaling (a new offer or answer, and its reads for the answer to its offer, `signal`) may go over a\n * relay's minute by this fraction of it: 6 on a relay of 30, 12 on one of 60, 1 on a relay of 5 (relay.pkarr.org and\n * pkarr.miguelmedeiros.dev allow 10), and never more than that in any minute; its reads leave the last of those to a write. Everything else still stops at\n * the limit. The minute before a chat leaves DHT only can be spent by then (the pairing, the texts over the DHT), and\n * its offer or answer, the one thing the contact waits for, then waited 40 s for requests to age out while the\n * contact's attempt gave up: the matrix's extension chat stayed \"On DHT · retrying live\" 46 times in 120 (2026-09-30).\n */\nexport const SIGNALING_ALLOWANCE_SHARE = 1 / 5;\n/**\n * A 1:1 chat's reads of a contact that went away from a live session, in their first seconds (`departed`,\n * `DEPARTED_READ_MS` in link.ts), may go over a relay's minute within the chat's allowance (`SIGNALING_ALLOWANCE_SHARE`):\n * at most this many of each contact's in a minute, every relay together, leaving the last of the allowance to an offer or\n * answer. Their fast poll reads every 2 s, on the relays in turn: 6 cover 12 s from the goodbye, by when an app that\n * restarts has its offer out (2.5 to 10 s in the lab of #1441), and add at most 3 to a relay's minute. They wait for no\n * write the minute refused: that write cannot go before the minute frees anyway. A daemon restarted 20 s after its last\n * restart found its contact's minute spent on both relays: every read of it was held back, the offer it published as it\n * came up was never read, and the chat came back only through the race's DHT dial, 8 s on (2026-10-07).\n */\nexport const DEPARTED_READS = 6;\n/**\n * A 1:1 chat's reads of an invite this side made, while its joiner is due and has not shown (`awaited`, `AWAITING_PEER_MS`\n * in link.ts), may go over a relay's minute within the chat's allowance (`SIGNALING_ALLOWANCE_SHARE`) the same way: at\n * most this many in a minute, every invite and every relay together. And while one asked in the last minute, the departed\n * reads leave them half of that on each relay: the last `AWAITED_READS / 2` of the allowance's reads (`DEPARTED_READS`\n * then take at most 3 on a relay of 30, against 5). Read every 2 to 4 s, they cover the seconds in which a joiner that\n * opened the link at once knocks. Within the chats' allowance, they add nothing to what a relay may see in a minute\n * (`WAY_BACK_SHARE`): 36 at most from the chats on a relay of 30, none past 5 on a relay of 5. An inviter pairing one joiner after\n * another on relays of 30 spent the minute on both 12 s in (two pairings, about 15 requests a relay each), the departed\n * reads of the contact that had just left took the allowance, and the third invite's key was read once, then not until\n * the minute freed: the joiner's knock 48 s late, and join to live in 60 s, against 2.6 and 4.6 s (CLI lab, 2026-11-07).\n * Not this many per invite: a web profile with 150 chats added from old sessions, each an invite awaited from that start,\n * had their reads take the whole allowance at every refill, and a live contact's reads after a reload went once a\n * minute: the chat came back in 2 to 7 min, against 41 to 69 s before (2026-11-07).\n */\nexport const AWAITED_READS = 4;\n/**\n * A group edge's requests for a member that may be back may go over a relay's minute by this fraction of it (4 on a\n * relay of 30, 8 on one of 60, none on a relay of 5): its reads of a member that went away and its packet\n * written meanwhile, which that member reads first when it is back (`watch`), its offer or answer, and its reads for\n * the answer to its offer (`signal`). Its reads leave the last of those to a write and go\n * one at a time (`GROUP_OVER_PACE_MS`), so the allowance lasts until the member is back, and the read that finds its\n * offer still has the answer behind it. Less than a chat's (`SIGNALING_ALLOWANCE_SHARE`), which keeps room past the\n * groups'. A private group's admin that had just let members in and seen them restart had spent its minute in 30 s;\n * a member back then, with no other member online to carry its offer, had it read only when the minute freed: 18 to\n * 42 s later, one round in four of the member-back runs (2026-10-03).\n *\n * It is also theirs whatever the chats do: while the edges' signaling has had fewer than that many requests on a relay\n * in the last minute, neither the limit, nor the chats' own allowance past it, nor their reserve (`CHAT_RESERVE`) holds\n * it back. Its reads leave the last of it to a write there too. A daemon with 30 chats and 5 groups, back after a\n * restart, had its chats signal for 332 s: they kept their reserve, their allowance took what the limit left, and the\n * edges got nothing. By then their attempts had failed and backed off, and the group members were reachable again 13\n * to 25 min after the restart (CLI bug hunt, 2026-10-08).\n *\n * An edge back after a restart reads its member before it offers (`resume`), and those reads are on the floor too: as\n * plain reads, they waited behind the chats as before, and the edges never got to signal. The same daemon had its first\n * member back 71 to 367 s after the restart, and group texts sent in its first minutes were read 2 to 7 min late (CLI\n * bug hunt, 2026-10-14).\n */\nexport const GROUP_SIGNALING_ALLOWANCE_SHARE = 2 / 15;\n/**\n * A community member's way back to its group while it has no edge up (its readings of the beacon, its request in a hub's\n * lobby: `back`) may go past everything that holds a group's request back by this fraction of a relay's minute (6 on a\n * relay of 30, 12 on one of 60, 1 on a relay of 5), its own: not the edges' (`GROUP_SIGNALING_ALLOWANCE_SHARE`),\n * and what it takes counts there alone, so it shortens no one else's minute or allowance. Its reads leave the last of it\n * to a write. A web app opened with 30 chats whose contacts were online and 15 groups whose edges all offered at once:\n * the edges' offers and reads for their members spent the groups' allowance in its first second, the chats' reserve\n * and their offers still waiting held the rest, and its 5 communities read their beacon (who the hubs are) a minute\n * later, or not in 3 minutes; 2 of them were not back in 6 (bug hunt, 2026-10-14). Sized for 5 communities' way back\n * in the first minute on the default relays: a reading of each beacon, and a read and a write in a hub's lobby (a write\n * goes to every relay). A member asks it only while it has no edge up in that community.\n *\n * At worst a relay then sees, in one minute, its limit, the chats' allowance past it, the edges', this one and the edges'\n * answer reads' (`ANSWER_READ_ALLOWANCE`): 49 on a relay of 30 (pkarr.pubky.org allows 50 an address,\n * `x-ratelimit-limit`), 95 on pkarr.pubky.app's 60 (it allows 1000) and 7 on a relay of 5 (relay.pkarr.org and\n * pkarr.miguelmedeiros.dev allow 10). A share raised past those limits gets 429s (docs/TRANSPORTS.md, \"The default list\").\n */\nexport const WAY_BACK_SHARE = 1 / 5;\n/** Past the limit, a group's reads within its allowance go no more often than this on a relay. */\nexport const GROUP_OVER_PACE_MS = 5_000;\n/**\n * A group edge's read for the answer to its offer (`signal`) that the budget refused on a relay goes first there among\n * the groups' signaling (`GROUP_SIGNALING_ALLOWANCE_SHARE`): the edges' offers and answers, their reads back after a\n * restart (`resume`) and their watch reads wait this long after the refusal, while it is not read, for what it could\n * take then. It waits for no group write the budget refused (`WRITE_FIRST_MS`), nor for the turn of a group's key that\n * is not read for an answer (`GROUP_RATION_WINDOW_MS`), and the groups' other urgent reads do not spend its burst\n * (`GROUP_BURST_MS`): it has one of its own. Of everything on the floor it is the closest to a member back: the\n * offer is out, and the member has often answered already. A daemon back after a restart had its edges' offers and\n * reads back spend the floor in its first seconds, and read the answers to offers it had out at 0.4 s only once the\n * minute freed: 66 to 97 s on, and an answer read that late often found the member's attempt over (agents#971, CLI lab,\n * 2026-11-03).\n */\nexport const ANSWER_READ_FIRST_MS = 5_000;\n/**\n * A group edge's read for the answer to its offer (`signal`) that everything else holds back (the limit, the groups'\n * allowance, the chats' reserve, a write the budget refused) goes within an allowance of its own on that relay: this\n * many in a minute, never more than the groups' allowance there (`GROUP_SIGNALING_ALLOWANCE_SHARE`: none on a relay of\n * 5), one at a time (`ANSWER_READ_SPACING_MS`). What it takes counts there alone, as a way back's (`WAY_BACK_SHARE`),\n * so it shortens no one else's minute. Going first on the floor (`ANSWER_READ_FIRST_MS`) was not enough: a daemon back\n * after a restart had its edges' reads back and offers spend its whole minute on each relay 6 s on, before any member\n * had answered (7 to 19 s on), and read the answers when the minute freed: from an answer going out to the hub\n * reading it, 60 to 66 s at the median in each of four runs. With this allowance, 2 to 60 s (14 s over the four runs,\n * against 63 s), and all 18 members were back 77 to 108 s on, against 102 to 153 s (agents#971, CLI lab, 2026-11-05).\n *\n * At worst it adds 3 to a relay's minute: 49 on a relay of 30 (pkarr.pubky.org allows 50), 95 on pkarr.pubky.app's 60,\n * and nothing on a relay of 5.\n */\nexport const ANSWER_READ_ALLOWANCE = 3;\n/** Within that allowance, an edge's read for its answer goes no more often than this on a relay (`ANSWER_READ_ALLOWANCE`). */\nexport const ANSWER_READ_SPACING_MS = 20_000;\n/**\n * Groups' urgent reads (their edges looking fast for a signal) take at most a quarter of a relay's minute in any this\n * long, so that they never spend it in a burst. An app back after a restart has every edge offering and looking fast at\n * once; the members at the other end answer only once they notice its old sessions went (about 20 s with\n * node-datachannel). On the default relays the edges spent the groups' share of the minute in those seconds, and read\n * nothing for 40 s more: a private group's edges were live again 75 to 110 s after a restart (bug hunt r5a, 2026-09-29).\n */\nexport const GROUP_BURST_MS = 15_000;\n/** …and never fewer than one link polling fast (every 2 s) reads in that time: one edge alone is never held back. */\nexport const GROUP_BURST_ONE_LINK = 8;\n/**\n * A group's edges' reads of members that went away from a live session and have not shown themselves back (`watch`: a\n * link looks for them closely for two minutes, `WATCH_PEER_MS`) take at most this share of a relay's requests, whatever\n * their number, spread over the minute (`GROUP_RATION_WINDOW_MS`): 2 in any 10 s on a relay of 30. Under it, the key\n * read longest ago goes first. A member alone in a private group whose three other members left at once watched each of\n * them every 2 s: those reads and the admin's knock poll spent both relays' minute, the member back first had its offer\n * read only when the minute freed, 25 to 44 s on, and its edge came up then (bug hunt r12, measured again 2026-10-03).\n */\nexport const WATCH_SHARE = 1 / 3;\n/**\n * 1:1 chats' reads of contacts that went away from a live session and have not shown themselves back (`watch`) take at\n * most this share of a relay's requests the same way, on their own (a chat never waits behind the edges that watch the\n * same contact): 3 in any 10 s on a relay of 30, more than one contact's fast poll asks for. The key read longest ago\n * goes first. Not the few reads of a contact that just went away past the limit (`DEPARTED_READS`). Ten contacts that\n * left a CLI daemon at once were read every 2 s each: those reads spent both relays' minute in the 10 s after their\n * goodbyes, when none could be back yet, then the daemon read nobody, nor answered anyone, for 45 s, and the chats with\n * no HyperDHT listener at the daemon were live again 42 to 51 s after their contacts were back (CLI bug hunt, 2026-10-14).\n */\nexport const CHAT_WATCH_SHARE = 1 / 2;\n/**\n * A key a group reads that asked within this long and was not read since keeps its turn: while one read longer ago\n * waits, the others wait too (`WATCH_SHARE`, `GROUP_RATION_WINDOW_MS`). One that stops asking loses it.\n */\nconst WATCH_TURN_MS = 5_000;\n/**\n * Background reads, and a 1:1 chat's at any pace, take turns per key the same way: while a key read longer ago asked\n * within this long and was not read since, a read of another key waits (a chat's, at a pace that is not the background\n * one, only for another chat's key). A saved chat that is not live reads its contact every 30 s in the\n * background, and one the budget refused read again only at its next poll. A request frees 60 s after the one that took\n * it, which is the poll after next of the chat that took it: the same chats took every request that freed. A daemon with\n * 30 chats and 5 groups, back after a restart while its groups signaled, read some contacts once in 10 min, and those\n * chats stayed down although both sides were online and offering (CLI bug hunt, 2026-10-12). A link's background read\n * the budget refused reads again when it frees a request (`LinkSession`), so the key whose turn it is is there to take it.\n * A chat not live after a restart looks fast while its offer is out, and those reads took no turn: the budget answered\n * them from the packet read before, every 2 to 8 s for 10 minutes, while the chats that were live already, the groups'\n * edges and the writes took every request that freed. A quarter of a daemon's 30 chats read their contact once in 10\n * minutes, their contacts online and offering, and showed them offline at 6 minutes (CLI bug hunt, 2026-10-13).\n */\nconst READ_TURN_MS = 5_000;\n/**\n * The keys' turns asked and read over a minute ago are dropped at most this often: walking every key on each ask cost in\n * proportion to the chats, 12-14% of an idle web app's script with 200 chats.\n */\nconst TURNS_PRUNE_MS = 1_000;\n/**\n * A 1:1 chat's read the budget held back this long without a break is starved: it goes before the writes that wait\n * (`WRITE_FIRST_MS`) and past the background share, within the minute, the key held back longest first. A daemon back\n * after a restart spends its whole minute on writes (each chat's and edge's offer, its packets after the attempt), which\n * go first, and requests free in bursts as the minute's first requests age out: every burst went to the writes that\n * waited, and the reads of the chats that were not in an attempt never had their turn (CLI restart lab, 2026-10-13).\n */\nconst READ_STARVED_MS = 60_000;\n/** How long a read that let an older one go first waits before it asks again. */\nconst TURN_WAIT_MS = 1_000;\n/**\n * A background read the budget held back far down the turns asks again no later than this (`backgroundTurnIn`). The\n * requests past the background share go to a read held back long (`READ_STARVED_MS`) that is there when one frees: asked\n * only at its estimated turn, a web app with 200 chats away read each contact every 7 to 8 minutes, not every 6, and\n * one with 100 left half the writes' share unused at 20 s.\n */\nconst BACKGROUND_TURN_MAX_MS = 15_000;\n/**\n * Once a group's read found a relay's minute full, the groups' reads there are spread over the minute for a minute\n * (`GROUP_RATION_MS`): at most a sixth of it in any 10 s (5 on a relay of 30), the key read longest ago first. A sliding\n * minute that demand keeps full hands out its requests in bursts: the minute is spent in 25 to 35 s as requests age\n * out, then nothing frees for the rest of it. A private group's admin (its knock poll every 2 s while its link is new)\n * whose members left and came back read nothing for 18 to 42 s at a time, and the member back first waited that long\n * for its edge (bug hunt r12, measured again on 2026-10-03). Writes are not counted: they go first anyway.\n */\nexport const GROUP_RATION_WINDOW_MS = 10_000;\nconst GROUP_RATION_MS = 60_000;\n/**\n * While a link polls fast (an `urgent` read: its peer, or the peer's offer or answer, is due any moment) within this\n * long, background requests (a community's periodic looks) are held to `BACKGROUND_WHILE_SIGNALING` a minute on each\n * relay rather than their usual share. A fast poll reads every 2 s, one relay after the other.\n */\nexport const SIGNALING_WINDOW_MS = 10_000;\n/**\n * Background requests a minute on each relay while a link signals: one look every 12 s. Next to a community's\n * lookups (20 a minute), a new group edge on one relay got 10 and read every 6 s, and its offer and answer missed each\n * other's fast windows (2026-09-27). Not none: fast windows can follow one another, and a hub still reads its knocks.\n */\nexport const BACKGROUND_WHILE_SIGNALING = 5;\n/**\n * A read of a key the relays answered this recently is answered from that answer, with no request. Several parts of\n * a chat read the contact's keys (the link's poll, its capabilities, DHT delivery), and each tends to read again\n * within a few dozen milliseconds of its last read, when a pace changes or a signal goes out: nothing new can be there\n * yet, and a pairing spent a sixth of its requests on those reads (2026-09-27). A publish under the key forgets it.\n */\nexport const FRESH_READ_MS = 500;\n/** A relay that missed a key's newest packet gets it (`catchUpLater`) no sooner than this, and tries again this often. */\nconst CATCH_UP_MIN_MS = 1_000;\nconst CATCH_UP_RETRY_MS = 5_000;\n/**\n * The longest another background write is told to wait behind the packets queued for a relay (`catchUpLater`): the\n * link and the DHT floor try again within a minute anyway, and longer kept a chat's upkeep off a relay with a long queue\n * for most of the presence window.\n */\nconst CATCH_UP_BEHIND_MAX_MS = 60_000;\n/** A catch-up put waits behind every link's request: a background write. A group edge's offer or answer goes as its own (`putEverywhere`). */\nconst CATCH_UP_ASKER: Asker = { background: true, group: false, urgent: false, door: false, write: true, signal: false, watch: false, watchWrite: false, departed: false, awaited: false, resume: false, back: false };\n/** Keys whose last relay is remembered for their next read (`resolve`): a profile's links and lookups, with room. */\nconst READ_TURNS_KEPT = 512;\n/** A relay that fails at the network level is left alone for this long. */\nconst NETWORK_ERROR_COOLDOWN_MS = 20_000;\n/**\n * Relays whose limit per address is far from the others': this client's share of theirs, a minute, in place of\n * `REQUESTS_PER_MINUTE`. relay.pkarr.org (not a default, see docs/RELAYS.md) and pkarr.miguelmedeiros.dev (a default\n * since 2026-10-17) allow 10 (`x-ratelimit-limit`), which a browser cannot read without CORS exposing it: half of it\n * leaves room for a second app behind the same address. pkarr.pubky.app allows 1000 (pkarr.pubky.org, on the same address,\n * 50): 60 of ours leaves room for many peers behind one address, and a page that pairs three contacts in a minute,\n * about ten requests a relay each, still has requests to spare there (2026-09-28). Writes go to every relay and\n * count once one took them; reads go to a relay with requests left.\n */\nexport const RELAY_REQUESTS_PER_MINUTE: Record<string, number> = {\n \"https://relay.pkarr.org\": 5,\n \"https://pkarr.pubky.app\": 60,\n \"https://pkarr.miguelmedeiros.dev\": 5,\n};\n/**\n * A read asks the next relay too when the one it asked has not answered within this long, and takes the first good\n * answer. Measured on 2026-10-03 from a home connection: a relay hands over a packet it holds in 0.25 s (0.7 s on a new\n * connection), and one that has to fetch the packet from the DHT first takes 2.7 s. Reads used to wait for a relay's\n * answer before asking the next one, up to the 10 s timeout: a relay that answered slowly or not at all (pkarr.pubky.org\n * on 2026-10-03) made every read of a pairing that slow, and the pairing never finished.\n */\nexport const HEDGE_MS = 1_500;\n/**\n * The hedge delay for a key whose last read found nothing (404): a relay takes 3 to 5 s to say so (it asks the DHT\n * every time), and a hedge at `HEDGE_MS` would double every poll of a key nobody has published yet.\n */\nexport const HEDGE_MISSING_MS = 6_000;\n/**\n * A packet that took longer than this to arrive, or a hedge lost to a relay that answered with the packet, is slow: it\n * counts against the relay's breaker like a failure (three in a row trip it, logged as \"slow\"), while another relay is\n * there to ask. A 404 says nothing either way: every relay is slow to give one.\n */\nexport const SLOW_MS = 3_000;\n/** A relay found slow goes after the others in every read for this long, unless it answers fast meanwhile. */\nexport const SLOW_DEMOTE_MS = 60_000;\n\n/** How long each source has to answer a read or a put of the turn record (WISP 06 § Publishing and reading). */\nexport const TURN_SOURCE_TIMEOUT_MS = 8_000;\n/** A relay's refusals of a turn put: someone else wrote (409 an older or equal packet, 412 the condition, 428 a put in flight). */\nconst TURN_REFUSALS = [409, 412, 428];\n/** How many times a payload signed here goes again past a relay's later copy (`putRedated`): three puts at most. */\nconst PAYLOAD_REDATES = 2;\n/** On a relay's 404: the sequence of an item the DHT holds under the key that is no signed packet. */\nconst INVALID_PACKET_SEQ_HEADER = \"pkarr-invalid-signed-packet-seq\";\n\nexport interface RelayTransportOptions {\n relays?: string[];\n timeoutMs?: number;\n fetch?: typeof fetch;\n /**\n * Requests allowed per relay and minute (`REQUESTS_PER_MINUTE`); background ones get a share of it.\n * `Infinity` for relays of one's own, with no limit to stay under (a test's relay in the same process).\n */\n requestsPerMinute?: number;\n /** How long a read answers the next ones of the same key (`FRESH_READ_MS`); 0 makes every read a request. */\n freshReadMs?: number;\n /** `HEDGE_MS`; `Infinity` asks the next relay only once the one asked failed. */\n hedgeMs?: number;\n /** The circuit breaker's settings (tests shorten its waits); trips are logged with `log`. */\n breaker?: RelayBreakerOptions;\n /** Where a relay that trips or recovers is reported; never with a key. `console.info` by default. */\n log?: (line: string) => void;\n}\n\n/** What `answer` says, or false when it has not said within `ms`. */\nfunction answeredWithin(answer: Promise<boolean>, ms: number): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<boolean>((resolve) => { timer = setTimeout(() => resolve(false), ms); });\n return Promise.race([answer, late]).finally(() => clearTimeout(timer));\n}\n\nexport function normalizeRelayUrl(input: string): string | null {\n try {\n const url = new URL(input.trim());\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return null;\n return `${url.origin}${url.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return null;\n }\n}\n\n/**\n * Why a line of a Pkarr relay list is not a relay `normalizeRelayUrl` keeps, with the line as typed; null when it is\n * one. A host alone or another scheme (`relay.example.org`, `wss://…`) was meant as an https:// relay.\n */\nexport function relayUrlProblem(input: string): string | null {\n const line = input.trim();\n if (normalizeRelayUrl(line)) return null;\n const meant = looksLikeHost(line) || looksLikeHost(line.replace(/^[a-z][a-z\\d+.-]*:\\/\\//i, \"\"));\n return meant ? `Use an https:// relay address: ${line}` : `Not a relay address: ${line}`;\n}\n\n/** No space, and a dot after the first character, before the last one and before any `/` or `:`; linear, for a long pasted line. */\nfunction looksLikeHost(text: string): boolean {\n if (/\\s/.test(text)) return false;\n const slash = text.search(/[/:]/);\n const dot = text.indexOf(\".\", 1);\n return dot > 0 && dot < text.length - 1 && (slash < 0 || dot < slash);\n}\n\n/** A relay the breaker leaves alone for failing (`RelayBreaker`): nothing was asked of it now. */\nclass RelayLeftAloneError extends Error {}\n\n/**\n * A relay a put did not get an answer from. `sent` false: the request never left (its network cooling down after a\n * failure, or a connection that could not be made, `connectFailed`); true: it may have reached the relay.\n */\nclass RelayNoAnswerError extends Error {\n constructor(message: string, readonly sent: boolean) { super(message); }\n}\n\n/** What Node says of a connection it could not make: the request never left. A browser's TypeError says nothing either way. */\nconst CONNECT_FAILURES = new Set([\"ECONNREFUSED\", \"ENOTFOUND\", \"EAI_AGAIN\", \"EHOSTUNREACH\", \"ENETUNREACH\", \"ENETDOWN\", \"EHOSTDOWN\", \"EADDRNOTAVAIL\", \"UND_ERR_CONNECT_TIMEOUT\"]);\n\n/** A fetch that failed before its request left this device: Node's `cause.code` (each of an AggregateError's, for several addresses). */\nfunction connectFailed(error: unknown): boolean {\n const cause = (error as { cause?: unknown } | null)?.cause as { code?: unknown; errors?: unknown } | undefined;\n if (!cause || typeof cause !== \"object\") return false;\n if (Array.isArray(cause.errors) && cause.errors.length) return cause.errors.every((e) => CONNECT_FAILURES.has((e as { code?: unknown } | null)?.code as string));\n return CONNECT_FAILURES.has(cause.code as string);\n}\n\n/**\n * The error a publish ends with after a second round dated past a relay's later copy failed too: one that may have\n * stored the first round's packet still may, whatever the second round's relays said.\n */\nfunction laterRound(first: unknown, later: unknown): unknown {\n return publishedNowhere(later) && !publishedNowhere(first) ? new PublishFailedError((later as Error).message, true) : later;\n}\n\n/** A packet date no further ahead of this clock than readers take (`newerPacket`): one this client may date past. */\nfunction withinSkew(timestamp: bigint): boolean {\n return timestamp <= BigInt(Date.now() + PKARR_FUTURE_SKEW_MS) * 1000n;\n}\n\n/**\n * A read the relays failed (or left alone for failing before), when its caller has another path to ask\n * (`RelayTransport.resolve` with `keptOnFailure` false): `kept` is the newest packet the relays gave for the key before.\n */\nexport class RelaysFailedError extends Error {\n constructor(readonly kept: SignedPacket) { super(\"No Pkarr relay reachable\"); }\n}\n\nexport class RelayTransport implements PkarrTransport {\n private relays: string[];\n private readonly timeoutMs: number;\n private readonly fetchFn: typeof fetch;\n private readonly timeListeners = new Set<(time: ServerTime) => void>();\n private readonly lastTimestamp = new Map<string, bigint>();\n private readonly newest = new Map<string, SignedPacket>();\n /**\n * The latest time of any packet read under a key, whoever dated it: the next packet this client puts there is dated\n * past it (`nextTimestamp`). A key is not always one writer's with one clock: a group's lobby, beacon and knock\n * records are written by every member, an inviter warms its contact's key with an empty packet, and this device's\n * own clock may have been set back since it last wrote. A relay and the DHT keep only the packet dated latest, so\n * one dated by this clock alone, when it is behind, was refused (409) or silently never read, until this clock\n * caught up with the other one: minutes, or an hour. Only up to `PKARR_FUTURE_SKEW_MS` ahead of this clock\n * (`withinSkew`): a packet one holder of a shared key dated further ahead must not date every later one of this\n * device past it (past 64 bits, unsignable; else ahead of every reader's clock, never taken over one dated now).\n */\n private readonly seenTimestamp = new Map<string, bigint>();\n /**\n * The last packet this client put under a key that a relay took. A read the budget holds back answers the newer of\n * it and the last one read: a hub that wrote its own beacon entry since it last read the beacon must not see that\n * entry as old as the one it replaced (it would stop counting itself at its community's door until its next write).\n */\n private readonly written = new Map<string, SignedPacket>();\n private readonly coolingDown = new Map<string, number>();\n private readonly networkCooldown = new Map<string, number>();\n private cursor = 0;\n /** Per key, the relay that answered its last read: the next read of the key starts at the one after it (`resolve`). */\n private readonly lastReadFrom = new Map<string, string>();\n private readonly spent = new Map<string, number[]>();\n private readonly spentBackground = new Map<string, number[]>();\n /** Background writes on each relay in the last minute (`BACKGROUND_WRITES_SHARE`). */\n private readonly spentBackgroundWrites = new Map<string, number[]>();\n /** Groups' urgent reads on each relay in the last `GROUP_BURST_MS`: edges' reads for an answer apart (`ANSWER_READ_FIRST_MS`). */\n private readonly spentGroupUrgent = new Map<string, number[]>();\n private readonly spentAnswerUrgent = new Map<string, number[]>();\n /** Watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`WATCH_SHARE`). */\n private readonly spentWatch = new Map<string, number[]>();\n /** 1:1 chats' watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`CHAT_WATCH_SHARE`). */\n private readonly spentChatWatch = new Map<string, number[]>();\n /** Groups' reads past the limit on each relay in the last `GROUP_OVER_PACE_MS` (`GROUP_SIGNALING_ALLOWANCE_SHARE`). */\n private readonly spentGroupOver = new Map<string, number[]>();\n /** Group edges' signaling requests on each relay in the last minute: their floor (`GROUP_SIGNALING_ALLOWANCE_SHARE`). */\n private readonly spentGroupSignal = new Map<string, number[]>();\n /** Community members' ways back on each relay in the last minute: their allowance (`WAY_BACK_SHARE`). */\n private readonly spentWayBack = new Map<string, number[]>();\n /** Edges' reads for an answer that only their own allowance let through, on each relay in the last minute (`ANSWER_READ_ALLOWANCE`). */\n private readonly spentAnswerAllowance = new Map<string, number[]>();\n /** Per contact, its departed reads past the limit in the last minute, every relay together (`DEPARTED_READS`). */\n private readonly departedOver = new Map<string, number[]>();\n /** The awaited reads past the limit in the last minute, every invite and every relay together (`AWAITED_READS`). */\n private awaitedOver: number[] = [];\n /** When an awaited invite's read last asked: the departed reads leave it room for a minute (`AWAITED_READS`). */\n private awaitedAt = -Infinity;\n /**\n * Per key a group reads (not in the background), when a read of it last went out and when it last asked: whose turn\n * it is under the watch share (`WATCH_SHARE`) and while the groups' reads are rationed (`GROUP_RATION_WINDOW_MS`). And\n * per key a chat watches, whose turn it is under theirs (`CHAT_WATCH_SHARE`).\n */\n private readonly readTurns = new Map<string, { servedAt: number; askedAt: number; waiting: boolean; watch: boolean; lane: string; answer?: boolean }>();\n /** Per key read in turn (`isTurnRead`), when a read of it last went out and when it last asked (`READ_TURN_MS`). */\n private readonly keyTurns = new Map<string, { servedAt: number; askedAt: number; waiting: boolean; who: Asker }>();\n /** When `readTurns` and `keyTurns` last dropped their stale turns (`TURNS_PRUNE_MS`). */\n private readonly turnsPrunedAt = new Map<Map<string, unknown>, number>();\n /** Groups' reads (not background ones) on each relay in the last `GROUP_RATION_WINDOW_MS`. */\n private readonly spentGroupReads = new Map<string, number[]>();\n /** When a group's read last found each relay's minute full: its reads there are rationed for `GROUP_RATION_MS`. */\n private readonly groupsFullAt = new Map<string, number>();\n /** When a link's write was last refused on each relay (`chat <relay>`, `group <relay>`), while it waits for the budget. */\n private readonly writeWaiting = new Map<string, number>();\n /** Per relay, the keys whose edges' reads for an answer it last refused, and when, until one is read (`ANSWER_READ_FIRST_MS`). */\n private readonly answerReadWaiting = new Map<string, Map<string, number>>();\n /**\n * Per key a 1:1 chat asks for: when it last read urgently (for the next minute, groups leave it `CHAT_RESERVE` on\n * every relay) and when the budget last refused it on each relay (the same, on that relay). A read of the key at a\n * slow pace (the chat is live, or back in the background) drops it: `CHAT_RESERVE`. Per relay, the later of the two\n * for each key (`chatNeed`); `chatUrgentAt` keeps the urgent ones for a relay not asked yet.\n */\n private readonly chatNeeds = new Map<string, RecentKeys>();\n private readonly chatUrgentAt = new RecentKeys();\n /** When a link (a chat's or a group's) last asked urgently: background requests yield for `SIGNALING_WINDOW_MS`. */\n private urgentAt = -Infinity;\n /** Timestamp of the last packet sent to each relay, per key: the compare-and-swap value for the next one. */\n private readonly lastPut = new Map<string, bigint>();\n /** Per relay and key, the newest packet that relay held back for its budget while another relay took it (`catchUpLater`). */\n private readonly catchUp = new Map<string, { relay: string; key: string; payload: Uint8Array; timestamp: bigint; who: Asker }>();\n /** Per relay, how many packets wait in `catchUp` for it: background reads leave them their share (`heldFor`). */\n private readonly catchUpWaiting = new Map<string, number>();\n private catchUpTimer: ReturnType<typeof setTimeout> | null = null;\n /**\n * Per key whose reads the budget held back since its last read went out: when a request frees for it\n * (`readHeldBackFor`), how many times in a row, and since when (`READ_STARVED_MS`).\n */\n private readonly heldBack = new Map<string, { until: number; times: number; since: number }>();\n /** When the relays last answered a read of each key, for `FRESH_READ_MS`. */\n private readonly readAt = new Map<string, number>();\n private readonly freshReadMs: number;\n private readonly perMinute: number;\n /** `requestsPerMinute` was given: it bounds every relay, one with its own share (`RELAY_REQUESTS_PER_MINUTE`) too. */\n private readonly perMinuteGiven: boolean;\n private readonly backgroundPerMinute: number;\n private readonly backgroundWhileSignaling: number;\n private readonly breaker: RelayBreaker;\n /** The relay the last read was answered by. */\n private lastRelay: string | null = null;\n private readonly hedgeMs: number;\n /** Until when each relay found slow (`SLOW_MS`) goes after the others in a read (`readOrder`). */\n private readonly slowUntil = new Map<string, number>();\n /** Per relay, when each of this client's requests still waiting for its answer went out (`unanswering`). */\n private readonly waiting = new Map<string, Set<{ at: number }>>();\n /** When each relay last answered a request of this client, whatever it said (`unanswering`). */\n private readonly answeredAt = new Map<string, number>();\n /** Keys whose last read was answered 404: their next read hedges later (`HEDGE_MISSING_MS`). */\n private readonly missing = new Set<string>();\n private readonly listeners = new Set<(change?: DiscoveryChange) => void>();\n\n constructor(options: RelayTransportOptions = {}) {\n this.relays = [];\n this.setRelays(options.relays ?? DEFAULT_RELAYS);\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.fetchFn = options.fetch ?? ((...args) => fetch(...args));\n this.perMinute = options.requestsPerMinute ?? REQUESTS_PER_MINUTE;\n this.freshReadMs = options.freshReadMs ?? FRESH_READ_MS;\n this.hedgeMs = options.hedgeMs ?? HEDGE_MS;\n this.perMinuteGiven = options.requestsPerMinute !== undefined;\n this.backgroundPerMinute = this.perMinute === REQUESTS_PER_MINUTE ? BACKGROUND_REQUESTS_PER_MINUTE : Math.ceil(this.perMinute * 2 / 3);\n this.backgroundWhileSignaling = this.perMinute === REQUESTS_PER_MINUTE ? BACKGROUND_WHILE_SIGNALING : Math.ceil(this.perMinute / 6);\n // Read at a terminal too (a CLI one-shot writes it on stderr): \"tripped\" and \"left alone\" were the breaker's words.\n const log = options.log ?? ((line: string) => console.info(`ghostly: ${line}`));\n this.breaker = new RelayBreaker({\n ...options.breaker,\n onTrip: (relay, reason, forMs) => {\n log(`relay ${new URL(relay).host} ${reason === \"no answer\" ? \"did not answer\" : reason === \"slow\" ? \"answered too slowly\" : `failed (${reason})`}; asked again in ${Math.round(forMs / 1000)} s`);\n options.breaker?.onTrip?.(relay, reason, forMs);\n this.changed(\"tripped\");\n },\n onRecover: (relay) => {\n log(`relay ${new URL(relay).host} answers again`);\n options.breaker?.onRecover?.(relay);\n this.changed(\"recovered\");\n },\n });\n }\n\n /** How reads go and how each relay is doing, for the connection panel. */\n discovery(): DiscoveryStatus {\n const relays = this.breaker.health(this.relays).map((health) => {\n const limited = this.rateLimitedFor(health.relay);\n return health.state === \"ok\" && limited > 0 ? { ...health, state: \"throttled\" as const, until: Date.now() + limited, reason: \"rate limited (429)\" } : health;\n });\n return { path: this.lastRelay ? { via: \"relay\", relay: this.lastRelay } : null, relays };\n }\n\n /** Back online on some network: relays that failed (or rate limited this address) on the old one are asked again. */\n networkChanged(): void {\n this.breaker.reset();\n this.networkCooldown.clear();\n this.coolingDown.clear();\n this.slowUntil.clear();\n this.changed(\"recovered\");\n }\n\n /**\n * `PkarrTransport.forget`: the packets and dates this client kept under these keys go, on every relay (`written`,\n * `newest`, `lastTimestamp`, `seenTimestamp`, `lastPut`). A spare invite replaced unused left them here for its two keys\n * for good: an idle CLI daemon gained 8 keys an hour (343 in `written` and 690 `lastPut` entries after a day). The maps\n * that bound themselves (`readAt`, `lastReadFrom`, `heldBack`, `missing`, the turns) and the catch-ups, which go once\n * put, are left as they are. A later put under one of these keys goes as a key's first.\n */\n forget(keys: Iterable<string>): void {\n const gone = new Set(keys);\n if (gone.size === 0) return;\n for (const key of gone) for (const perKey of [this.lastTimestamp, this.seenTimestamp, this.newest, this.written]) perKey.delete(key);\n // Per relay and key (`${relay} ${key}`), on the relays set now and any set before.\n for (const slot of this.lastPut.keys()) if (gone.has(slot.slice(slot.lastIndexOf(\" \") + 1))) this.lastPut.delete(slot);\n }\n\n /** Called when a relay trips or recovers. */\n subscribe(listener: (change?: DiscoveryChange) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private changed(change: DiscoveryChange): void {\n for (const listener of this.listeners) try { listener(change); } catch { /* a listener that fails must not fail a request */ }\n }\n\n /** What the relay did, for its breaker. */\n private answered(relay: string, failure?: { kind: RelayFailure; reason: string }, method?: \"GET\" | \"PUT\"): void {\n if (failure) { this.breaker.failure(relay, failure.kind, failure.reason); return; }\n // It answered this kind of request: an earlier failure of it no longer keeps the next one back.\n if (method) this.networkCooldown.delete(`${method} ${relay}`);\n this.breaker.success(relay, this.relays);\n }\n\n setRelays(relays: string[]): void {\n const normalized = relays\n .map(normalizeRelayUrl)\n .filter((r): r is string => r !== null);\n this.relays = [...new Set(normalized)];\n }\n\n describe(): { protocol: string; relays: string[] } {\n return { protocol: \"Pkarr relays (HTTP) → Mainline DHT (BEP44)\", relays: [...this.relays] };\n }\n\n /**\n * Publishes to every relay. Peers may be configured with different relay\n * sets; writing everywhere keeps the overlap warm, the DHT covers the rest.\n * Returns once one relay took the packet: the others finish in the background.\n */\n async publish(identity: Identity, records: GhostRecord[], options: PkarrRequestOptions = {}): Promise<void> {\n if (this.relays.length === 0) throw new PublishFailedError(\"No Pkarr relays configured\", false);\n await this.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putEverywhere(key, payload, timestamp, options, conflict), options);\n }\n\n /**\n * The time the next packet under a key is dated: this clock's, and past every packet this client put or read there.\n * BEP44 sequence numbers must strictly increase, and the clock that dated the last one may not be this one's.\n */\n nextTimestamp(pubKeyZ32: string): bigint {\n const now = BigInt(Date.now()) * 1000n;\n const last = this.lastTimestamp.get(pubKeyZ32) ?? 0n, seen = this.seenTimestamp.get(pubKeyZ32) ?? 0n;\n const floor = last > seen ? last : seen;\n const timestamp = now > floor ? now : floor + 1n;\n this.lastTimestamp.set(pubKeyZ32, timestamp);\n return timestamp;\n }\n\n /**\n * Signs the records, dated by `nextTimestamp`, and hands the payload to `put` (the relays; the CLI adds the DHT).\n * When every relay's budget (or rate limit) holds this asker back, it throws that wait before signing anything\n * (`publishWait`): a daemon at its budget signed about 500 packets a minute that never went out. `elsewhere`: `put`\n * also takes the packet where no budget holds it back (the CLI's DHT), so it is signed whatever the relays say.\n * `put` calls `conflict` for a relay that answered 409: it holds a packet under this key dated at or after this one,\n * which this client has not read (an inviter's warm packet under the key it gave its contact, from a clock ahead of\n * this one). That packet is read from that relay, and the records go again dated just past it, once. Without this\n * the packet was refused until this device's clock passed the other one's, however long that took, and on a relay\n * that did take it, readers still preferred the later-dated empty packet of another relay. `read`: how to learn the\n * held packet's date where it is not a relay to ask (the CLI's DHT, whose nodes answer 302 for a later-dated packet).\n */\n async publishDated(identity: Identity, records: GhostRecord[],\n put: (pubKeyZ32: string, payload: Uint8Array, timestamp: bigint, conflict: (relay: string, read?: () => Promise<bigint | null>) => void) => Promise<void>,\n options: PkarrRequestOptions = {}, again = false, elsewhere = false): Promise<void> {\n const key = identity.pubKeyZ32;\n // Before the packet is signed and dated: a publish no relay takes now costs no signature, and moves no date on.\n if (!again && !elsewhere) {\n const held = this.publishWait(key, asker(options, true));\n if (held) throw new DiscoveryBudgetError(held.wait, `Publish held back on every relay: ${held.reasons.join(\"; \")}`);\n const refused = this.refusedEverywhere(key, asker(options, true));\n if (refused) throw refused;\n }\n const timestamp = this.nextTimestamp(key);\n let redated: Promise<boolean> | undefined;\n const conflict = (relay: string, read?: () => Promise<bigint | null>) => {\n if (again || redated) return;\n redated = (async () => {\n const held = read ? await read().catch(() => null) : await this.heldAt(relay, key, asker(options, true));\n // Not dated later than this one: the relay was still putting another packet. The caller tries again, as before.\n // Dated too far ahead to follow (`seenTimestamp`): that relay keeps it, the others take this one.\n if (held === null || held < timestamp || !withinSkew(held)) return false;\n traceLink(key, \"publish-redated\", { aheadMs: Number((held - timestamp) / 1000n), relay });\n // A later publication of this key took over meanwhile: it is dated past what was just read.\n if (this.lastTimestamp.get(key) !== timestamp) return true;\n await this.publishDated(identity, records, put, options, true, elsewhere);\n return true;\n })();\n redated.catch(() => {});\n };\n try { await put(key, createRelayPayload(identity, records, timestamp), timestamp, conflict); }\n catch (error) {\n // Refused everywhere, and somewhere for a later-dated packet: what the publication dated past it did is the answer.\n const pending = redated as Promise<boolean> | undefined;\n if (!pending || !(await pending.catch((later: unknown) => { throw laterRound(error, later); }))) throw error;\n }\n }\n\n /** `PkarrTransport.publishHeld`: `publishDated`'s check before signing, for a payload signed elsewhere in this process. */\n publishHeld(pubKeyZ32: string, options: PkarrRequestOptions = {}): DiscoveryBudgetError | null {\n if (this.relays.length === 0) return null;\n const held = this.publishWait(pubKeyZ32, asker(options, true));\n return held ? new DiscoveryBudgetError(held.wait, `Publish held back on every relay: ${held.reasons.join(\"; \")}`) : null;\n }\n\n /**\n * How long until some relay takes a publish of this asker, and why each holds it back; null when one would now. Walks the relays as `put` does,\n * without asking any: a relay the budget holds back gets its refused `take` (the asker's write then waits first in\n * line, as when `put` is refused), one rate limiting or throttling this address is a wait, one left alone for failing\n * is none. Null too when a relay fails another way (its network cooling down): the publish then goes, and fails, as\n * before, and when no relay is held back at all.\n */\n private publishWait(pubKeyZ32: string, who: Asker): { wait: number; reasons: string[] } | null {\n const probe = this.breaker.allDownProbe(this.relays);\n let wait = Infinity;\n const held: string[] = [], reasons: string[] = [];\n for (const relay of this.relays) {\n if (relay !== probe && this.networkCoolingDown(relay, \"PUT\")) return null;\n const limited = this.rateLimitedFor(relay);\n if (limited > 0) { wait = Math.min(wait, limited); reasons.push(`${relay}: Discovery relay is cooling down after a 429; retry shortly`); continue; }\n const blocked = relay === probe ? 0 : this.breaker.blockedFor(relay);\n if (blocked > 0) {\n if (this.breaker.blockedKind(relay) === \"throttled\") { wait = Math.min(wait, blocked); reasons.push(`${relay}: Discovery relay is throttling this address; retry shortly`); }\n else reasons.push(`${relay} is left alone after failing`);\n continue;\n }\n if (this.heldFor(relay, who, Date.now(), pubKeyZ32) <= 0) return null;\n held.push(relay);\n const left = this.heldFor(relay, who);\n wait = Math.min(wait, left);\n reasons.push(`${relay}: discovery budget reached; retry in ${Math.ceil(left / 1000)} s`);\n }\n if (wait === Infinity) return null;\n // Held back everywhere: refused as `put` would be, so what a refusal notes holds (this write goes first once a\n // request frees, a chat's need of its reserve). Only now: a publish another relay takes leaves no write waiting.\n for (const relay of held) this.take(relay, who, pubKeyZ32);\n return { wait, reasons };\n }\n\n /**\n * A publish that every relay would refuse now without being asked (its network cooling down, left alone after failing,\n * its rate limit or this asker's budget), and not as a wait alone (`publishWait` says those): the failure `putEverywhere`\n * would end in, in the same words, said before the packet is signed and dated. Null when some relay would be asked. With\n * every relay out of reach on a page that is online, each chat signed a packet every few seconds that went nowhere: ~58\n * a second at 300 chats (bug hunt, 2026-11-12).\n */\n private refusedEverywhere(pubKeyZ32: string, who: Asker): PublishFailedError | null {\n const probe = this.breaker.allDownProbe(this.relays);\n const now = Date.now();\n const reasons: string[] = [], held: string[] = [];\n for (const relay of this.relays) {\n const refused = this.refusal(relay, relay === probe);\n if (refused) { reasons.push(String(refused)); continue; }\n if (this.heldFor(relay, who, now, pubKeyZ32) <= 0) return null;\n held.push(relay);\n reasons.push(String(new DiscoveryBudgetError(this.heldFor(relay, who))));\n }\n // Refused by its budget, as `put` would be: this write goes first once a request frees.\n for (const relay of held) this.take(relay, who, pubKeyZ32);\n return new PublishFailedError(`Publish failed on every relay: ${reasons.join(\"; \")}`, false);\n }\n\n /** What `put` refuses a request to this relay with before its budget is asked; null when it gets that far. */\n private refusal(relay: string, probe: boolean): Error | null {\n if (!probe && this.networkCoolingDown(relay, \"PUT\")) return new RelayNoAnswerError(`${relay} did not answer a moment ago; retry shortly`, false);\n const limited = this.rateLimitedFor(relay);\n if (limited > 0) return new DiscoveryBudgetError(limited, \"Discovery relay is cooling down after a 429; retry shortly\");\n const blocked = probe ? 0 : this.breaker.blockedFor(relay);\n if (blocked > 0) {\n if (this.breaker.blockedKind(relay) === \"throttled\") return new DiscoveryBudgetError(blocked, \"Discovery relay is throttling this address; retry shortly\");\n return new RelayLeftAloneError(`${relay} is left alone after failing; asked again in ${Math.max(1, Math.ceil(this.breaker.askedAgainIn(relay, this.relays) / 1000))} s`);\n }\n return null;\n }\n\n /** One relay's packet for a key, read now: its time, kept for `nextTimestamp`. Null when it has none or does not answer. */\n private async heldAt(relay: string, pubKeyZ32: string, who: Asker): Promise<bigint | null> {\n if (!this.take(relay, who, pubKeyZ32)) return null;\n try {\n let payload: Uint8Array | undefined;\n const response = await this.request(`${relay}/${pubKeyZ32}`, { method: \"GET\" }, async (r, signal) => {\n if (r.ok && r.status !== 404) payload = await readRelayBody(r, signal);\n });\n if (!response.ok || !payload) return null;\n const packet = parseRelayPayload(pubKeyZ32, payload);\n this.sawTimestamp(pubKeyZ32, packet.timestampMicros);\n return packet.timestampMicros;\n } catch { return null; }\n }\n\n /** A packet under this key was read (on a relay, or by the CLI on the DHT): its time, for `nextTimestamp`. */\n sawTimestamp(pubKeyZ32: string, timestamp: bigint): void {\n if (withinSkew(timestamp) && timestamp > (this.seenTimestamp.get(pubKeyZ32) ?? 0n)) this.seenTimestamp.set(pubKeyZ32, timestamp);\n }\n\n /**\n * Puts a payload `publishDated` just signed, dated `timestamp`, on every relay. Its signature is not checked: it was\n * made here (`publishPayload` checks one signed elsewhere, to read its sequence number). `conflict`: as `publishDated`\n * gives it.\n */\n async putSigned(pubKeyZ32: string, payload: Uint8Array, timestamp: bigint, options: PkarrRequestOptions = {}, conflict?: (relay: string) => void): Promise<void> {\n if (this.relays.length === 0) throw new PublishFailedError(\"No Pkarr relays configured\", false);\n await this.putEverywhere(pubKeyZ32, payload, timestamp, options, conflict);\n }\n\n /**\n * Puts a payload signed elsewhere (a did:dht document), byte for byte, on every relay; one signed here says its date\n * (`signedAt`) and is not checked again. `conflict`: as `publishDated` gives it.\n */\n async publishPayload(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions = {}, conflict?: (relay: string) => void): Promise<void> {\n if (this.relays.length === 0) throw new PublishFailedError(\"No Pkarr relays configured\", false);\n const seq = options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;\n if (options.signedAt === undefined || !options.redate) return this.putEverywhere(pubKeyZ32, payload, seq, options, conflict);\n await this.putRedated(pubKeyZ32, payload, seq, options, PAYLOAD_REDATES);\n }\n\n /**\n * A payload every relay's budget held back while another path took it (the CLI's DHT): the publish is out, and each\n * relay gets it once its budget frees a request for the same asker (`catchUpLater`), unless a newer packet of the key\n * goes there first. Retried by the link instead, each try was signed and put on the DHT again (1-1.6 puts a minute per\n * chat at budget, not one per 4 min). `timestamp`: its date when signed here; read from the payload otherwise.\n */\n putLater(pubKeyZ32: string, payload: Uint8Array, timestamp: bigint | undefined, options: PkarrRequestOptions = {}): void {\n const at = timestamp ?? options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;\n try { this.written.set(pubKeyZ32, readOwnRelayPayload(pubKeyZ32, payload)); } catch { /* not a packet a read would take either */ }\n for (const relay of this.relays) this.catchUpLater(relay, pubKeyZ32, payload, at, asker(options, true));\n }\n\n /**\n * A payload signed in this process (a group edge's offer or answer, `CarriedTransport`) put on every relay, past what\n * a relay that answers 409 holds: that one is read, and the records go again at once, signed by `options.redate` dated\n * just past it, `left` times at most. A packet put here is the key's latest too: a publish dated here next\n * (`nextTimestamp`, the goodbye after the edge stops) goes past it. Before, the 409 failed the publish (or, when another\n * relay took it, left the relay's copy in place), the link tried again 4 s on with its clock's date, refused as long as\n * the relay's copy was later, and an edge started again in the same millisecond lost its new offer to its last one.\n */\n private async putRedated(key: string, payload: Uint8Array, timestamp: bigint, options: PkarrRequestOptions, left: number): Promise<void> {\n if (timestamp > (this.lastTimestamp.get(key) ?? 0n)) this.lastTimestamp.set(key, timestamp);\n let redated: Promise<boolean> | undefined;\n const conflict = (relay: string) => {\n if (left <= 0 || redated) return;\n redated = (async () => {\n const held = await this.heldAt(relay, key, asker(options, true));\n // Not dated at or after this one: the relay was still putting another packet. The caller tries again, as before.\n if (held === null || held < timestamp || !withinSkew(held)) return false;\n // A later packet of this key went out meanwhile: it is dated past this one, and is what the relays should hold.\n if (this.lastTimestamp.get(key) !== timestamp) return true;\n const again = options.redate!(held);\n if (!again) return true;\n traceLink(key, \"publish-redated\", { aheadMs: Number((held - timestamp) / 1000n), relay });\n await this.putRedated(key, again.payload, again.signedAt, { ...options, signedAt: again.signedAt }, left - 1);\n return true;\n })();\n redated.catch(() => {});\n };\n try { await this.putEverywhere(key, payload, timestamp, options, conflict); }\n catch (error) {\n const pending = redated as Promise<boolean> | undefined;\n if (!pending || !(await pending.catch((later: unknown) => { throw laterRound(error, later); }))) throw error;\n }\n }\n\n /**\n * Puts the packet on every relay and settles as soon as one of them took it. A relay that is slow to\n * answer (one that stores the packet and answers the PUT only at the timeout) must not hold a link's\n * presence, offer or answer back: the rest finish in the background, their outcomes still counted.\n * When no relay takes it, this waits for all of them to say why.\n */\n private putEverywhere(pubKeyZ32: string, payload: Uint8Array, timestamp: bigint, options: PkarrRequestOptions, conflict?: (relay: string) => void): Promise<void> {\n // A record read, changed and written back (a lobby, a knock record) is read from the relays the next time.\n this.readAt.delete(pubKeyZ32);\n // Published now: its next read is no longer one of a key nobody has (`HEDGE_MISSING_MS`).\n this.missing.delete(pubKeyZ32);\n const waitingBefore = new Map(this.writeWaiting);\n const writer = firstWriter(asker(options, true));\n // Out on one relay: the link will not try again, so a relay that refused it has no write to wait for.\n const noWriteWaits = () => {\n if (!writer) return;\n for (const relay of this.relays) {\n const key = `${writer} ${relay}`;\n if (this.writeWaiting.get(key) !== waitingBefore.get(key)) this.writeWaiting.delete(key);\n }\n };\n // Every relay left alone for failing: one of them is asked anyway, now and then (`allDownProbe`).\n const probe = this.breaker.allDownProbe(this.relays);\n // Whether the first relay whose budget took the packet took it too: each `put` takes its request before it awaits.\n let first: Promise<boolean> | undefined;\n // A group edge's offer or answer is on two relays, not on the one that took it: one that failed it (no answer, an\n // error of its own) gets it again once, as one its budget held back does, both on the edges' floor, not behind\n // background looks. A member reading the other relay found the edge's older offer (or none) until its next packet.\n const edgeSignal = isGroupSignal(asker(options, true));\n const failed = new Set<string>();\n // Each relay that surely does not hold the packet: not asked now, refused in an answer (a 4xx), or never reached.\n const nowhere = this.relays.map(() => false);\n const puts = this.relays.map(async (relay, i) => {\n const slot = `${relay} ${pubKeyZ32}`;\n const previous = this.lastPut.get(slot);\n this.lastPut.set(slot, timestamp);\n\n // A chat's packet another relay is taking, while chats need the relays: a copy here now would take a request their\n // reserve keeps (`spareHeldFor`). It comes later (`catchUpLater`), unless that relay does not take it. An app\n // opened with 30 contacts online wrote each offer to both relays, and the chats whose contact's offer or answer\n // came a few seconds later found both minutes spent: 11 of 30 were down past the first minute (2026-10-14).\n // That relay's answer is waited for `SLOW_MS` at most: one slow to say it took the packet (up to the 10 s\n // timeout) held the copy here, and a contact reading this relay found nothing, as long.\n if (first && isChat(asker(options, true)) && this.spareHeldFor(relay, Date.now()) > 0 && await answeredWithin(first, SLOW_MS)) {\n nowhere[i] = true;\n throw new DiscoveryBudgetError(Math.max(CATCH_UP_MIN_MS, this.spareHeldFor(relay, Date.now())));\n }\n // A relay refuses (428) to replace a packet whose DHT put is still in flight, unless told which\n // packet is being replaced. Links publish in bursts (a message, its ack, a signal), so say so.\n let response: Response;\n try {\n response = await this.put(relay, pubKeyZ32, payload, previous, asker(options, true), relay === probe, (ok) => { first ??= ok; });\n // 412: the relay never got `previous` (it was busy, or restarted). This client's packet is the one to replace, so insist.\n if (response.status === 412) response = await this.put(relay, pubKeyZ32, payload, undefined, asker(options, true));\n } catch (error) {\n if (!isDiscoveryBudgetError(error) && !(error instanceof RelayLeftAloneError)) failed.add(relay);\n nowhere[i] = isDiscoveryBudgetError(error) || error instanceof RelayLeftAloneError || (error instanceof RelayNoAnswerError && !error.sent);\n // An older packet of the key waiting for this relay (`catchUpLater`) waits on with this one in its place, as this\n // one asks (a chat's upkeep in the background). Dropped when the newer one was tried, a background write that the\n // budget held on every relay left the key with no copy waiting there: 10 of a daemon's 50 chats' packets never\n // reached a relay in 20 minutes. Kept as the older one asked, a daemon's 600 first packets at its start went as\n // chats' writes, and took every request for 10 minutes.\n if (this.catchUp.has(slot) && isDiscoveryBudgetError(error)) this.catchUpLater(relay, pubKeyZ32, payload, timestamp, asker(options, true));\n throw error;\n }\n // Out here: no older packet of the key waits for this relay any more. A newer one queued while this relay was slow\n // to answer stays (`catchUpLater`): dropped, the relay kept this older packet until the key's next publish.\n if (response.ok && (this.catchUp.get(slot)?.timestamp ?? 0n) <= timestamp) this.dropCatchUp(relay, pubKeyZ32);\n // The relay answered that it did not take it. A server error (5xx) says nothing of what it kept.\n nowhere[i] = response.status >= 400 && response.status < 500;\n if (response.status >= 500 || response.status === 428) failed.add(relay);\n // 409: this relay holds a packet under the key dated at or after this one (`publishDated` reads it and dates past it).\n if (response.status === 409) conflict?.(relay);\n // The relay's own rate limit: this packet did not go in, and goes once the relay says so.\n if (response.status === 429) throw new DiscoveryBudgetError(this.coolDown(relay, response), `${relay} responded 429; retry shortly`);\n if (!response.ok) throw new Error(`${relay} responded ${response.status}`);\n });\n const settled = Promise.allSettled(puts);\n\n return new Promise<void>((resolve, reject) => {\n let accepted = false;\n for (const put of puts) {\n put.then(() => {\n if (accepted) return;\n accepted = true;\n noWriteWaits();\n // Signed here (`publishDated`) or checked on the way in (`publishPayload`): not checked a third time.\n try { this.written.set(pubKeyZ32, readOwnRelayPayload(pubKeyZ32, payload)); } catch { /* not a packet a read would take either */ }\n resolve();\n }, () => { /* read from `settled` */ });\n }\n void settled.then((results) => {\n // A relay that finished after the first one took the packet may have been refused on its retry since.\n if (accepted) {\n noWriteWaits();\n // Its budget (or its rate limit) held it back there: that relay gets it once it frees a request (`catchUp`).\n results.forEach((r, i) => {\n if (r.status !== \"rejected\") return;\n if (isDiscoveryBudgetError(r.reason) || (edgeSignal && failed.has(this.relays[i]))) this.catchUpLater(this.relays[i], pubKeyZ32, payload, timestamp, edgeSignal ? asker(options, true) : CATCH_UP_ASKER);\n });\n return;\n }\n // Every relay held it back for its budget (this client's, or the relay's rate limit): a wait for the first\n // of them to free a request, not a failure.\n // So is a mix of relays held back and relays left alone for failing before (`RelayLeftAloneError`): nothing was\n // asked of those now, their outage was said when it began, and the packet goes once a held one frees a request.\n // Shown as a failure, it put \"Could not publish discovery: … budget reached …\" on a phone's group panel for\n // as long as the budget kept the other two relays waiting (2026-10-07).\n const held = results.map((r) => (r.status === \"rejected\" && isDiscoveryBudgetError(r.reason) ? r.reason : null));\n const leftAlone = (r: PromiseSettledResult<void>) => r.status === \"rejected\" && r.reason instanceof RelayLeftAloneError;\n const waits = held.filter((e): e is DiscoveryBudgetError => e !== null);\n const reasons = results.map((r) => (r.status === \"rejected\" ? String(r.reason) : \"\")).join(\"; \");\n if (waits.length === results.length) reject(new DiscoveryBudgetError(Math.min(...waits.map((e) => e.retryInMs)), `Publish held back on every relay: ${reasons}`));\n else if (waits.length && results.every((r, i) => held[i] !== null || leftAlone(r))) reject(new DiscoveryBudgetError(Math.min(...waits.map((e) => e.retryInMs)), `Publish held back on every relay not left alone: ${reasons}`));\n else reject(new PublishFailedError(`Publish failed on every relay: ${reasons}`, !nowhere.every(Boolean)));\n });\n });\n }\n\n /**\n * Public relays rate limit by IP (120 requests a minute at the time of\n * writing) and several peers may share one address, so a poll costs one\n * request: one relay is asked, the next one when this one fails, or when it\n * has not answered within `HEDGE_MS` (a hedge: the first good answer wins and\n * the other request is dropped). The newest validly signed packet seen so far\n * wins, which also covers a relay that is still serving an older cached copy.\n *\n * In turn per key: a key's next read starts at the relay after the one that answered its last read. A relay that\n * does not have a packet yet (a publish that reached only the other relay, one rate limited there) answers a key's\n * reads at most once in a row. With one turn for all keys, a link that read its peer between two other reads landed\n * on the same relay every time: a restarted member's offer, only on `pkarr.pubky.app`, went unread for 12 to 60 s\n * while the member at the other end read `pkarr.pubky.org` (bug hunt r5a, 2026-09-29). A relay found slow lately\n * (`SLOW_DEMOTE_MS`) goes after the others, whatever the turn.\n *\n * A hedge spends a second request, so it goes only where the budget has requests to spare (`hedgeRoom`), never for a\n * background read (nobody waits on it), and later for a key whose last read found nothing (`HEDGE_MISSING_MS`).\n *\n * `keptOnFailure` false: a read the relays failed throws `RelaysFailedError` with the packet they gave last, in place\n * of handing that back as their answer (a CLI asks the DHT then, `RelaysAndDht`).\n */\n async resolve(pubKeyZ32: string, options: PkarrRequestOptions = {}, keptOnFailure = true): Promise<SignedPacket | null> {\n if (this.relays.length === 0) throw new Error(\"No Pkarr relays configured\");\n // A chat reading its contact at a slow pace has nothing due: the reserve kept for it lapses (`CHAT_RESERVE`).\n if (options.background && !options.urgent && !options.group) this.chatNeedLapsed(pubKeyZ32);\n // Not one answered after now, the clock gone back since: its copy was not fresh for as long as the clock went back.\n const readAt = this.readAt.get(pubKeyZ32), age = readAt === undefined ? Infinity : Date.now() - readAt;\n if (age >= 0 && age < this.freshReadMs) return this.newest.get(pubKeyZ32) ?? null;\n\n const order = this.readOrder(pubKeyZ32);\n // Every relay left alone for failing: one of them is asked anyway, now and then (`allDownProbe`).\n const probe = this.breaker.allDownProbe(this.relays);\n // The soonest a relay passed over for its budget takes a request again, and whether one was down instead.\n let budgetWait = Infinity, down = false;\n const who = asker(options, false);\n const tried = new Set<string>();\n let hedgeAfter = options.background ? Infinity : this.missing.has(pubKeyZ32) ? Math.max(this.hedgeMs, HEDGE_MISSING_MS) : this.hedgeMs;\n\n /**\n * The next relay to ask, its request taken from its budget, or null. A hedge (`hedge`) goes only to a relay with\n * requests to spare; one passed over for that is still there if the relay asked fails.\n */\n const next = (hedge: boolean): string | null => {\n for (const relay of order) {\n if (tried.has(relay)) continue;\n if (relay !== probe && this.networkCoolingDown(relay, \"GET\")) { tried.add(relay); down = true; continue; }\n const limited = this.rateLimitedFor(relay);\n if (limited > 0) { tried.add(relay); budgetWait = Math.min(budgetWait, limited); continue; }\n // Its breaker is open: a relay throttling us is a wait, one failing is down. The others take its turn.\n const blocked = relay === probe ? 0 : this.breaker.blockedFor(relay);\n if (blocked > 0) {\n tried.add(relay);\n if (this.breaker.blockedKind(relay) === \"throttled\") budgetWait = Math.min(budgetWait, blocked); else down = true;\n continue;\n }\n // Asked before `take`, which notes a refusal (a chat's need, a waiting write): a hedge not sent is no refusal.\n if (hedge && (this.heldFor(relay, who, Date.now(), pubKeyZ32) > 0 || !this.hedgeRoom(relay))) continue;\n tried.add(relay);\n if (!this.take(relay, who, pubKeyZ32)) { budgetWait = Math.min(budgetWait, this.heldFor(relay, who, Date.now(), pubKeyZ32)); continue; }\n if (relay === probe) this.breaker.beginAllDown(relay); else this.breaker.begin(relay);\n return relay;\n }\n return null;\n };\n\n const asked = new Map<string, ReadAttempt>();\n let lastAsked = 0;\n const ask = (hedge: boolean): boolean => {\n const relay = next(hedge);\n if (!relay) return false;\n asked.set(relay, this.readFromRelay(relay, pubKeyZ32));\n lastAsked = Date.now();\n return true;\n };\n ask(false);\n\n let winner: { attempt: ReadAttempt; outcome: Extract<ReadOutcome, { kind: \"packet\" | \"missing\" }> } | null = null;\n while (asked.size > 0 && !winner) {\n const hedgeIn = hedgeAfter - (Date.now() - lastAsked);\n if (hedgeIn <= 0) {\n // No relay to spare a request for a hedge: this read waits for the relays it asked.\n if (!ask(true)) hedgeAfter = Infinity;\n continue;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const hedgeDue = hedgeIn === Infinity ? null : new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), hedgeIn); });\n const settled = await Promise.race([\n ...[...asked.values()].map((attempt) => attempt.done.then((outcome) => ({ attempt, outcome }))),\n ...(hedgeDue ? [hedgeDue] : []),\n ]);\n clearTimeout(timer);\n if (!settled) continue;\n const { attempt, outcome } = settled;\n asked.delete(attempt.relay);\n const relay = attempt.relay;\n if (outcome.kind === \"packet\" || outcome.kind === \"missing\") { winner = { attempt, outcome }; break; }\n if (outcome.kind === \"throttled\") {\n budgetWait = Math.min(budgetWait, this.coolDown(relay, outcome.response));\n this.answered(relay, { kind: \"throttled\", reason: \"rate limited (429)\" });\n } else if (outcome.kind === \"failed\") {\n // In a browser a rate-limited answer often arrives without CORS headers and\n // surfaces as a network error. Back off this operation and try the next relay.\n // Unlike an observable 429, this does not establish a relay-wide limit.\n this.networkCooldown.set(`GET ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);\n this.answered(relay, { kind: \"error\", reason: outcome.reason });\n down = true;\n }\n // A relay that failed is replaced at once, with no hedge delay.\n ask(false);\n }\n\n if (winner) {\n const { attempt, outcome } = winner, relay = attempt.relay;\n const took = Date.now() - attempt.started;\n if (outcome.kind === \"packet\") {\n this.sawTimestamp(pubKeyZ32, outcome.packet.timestampMicros);\n this.newest.set(pubKeyZ32, newerPacket(this.newest.get(pubKeyZ32), outcome.packet)!);\n this.missing.delete(pubKeyZ32);\n } else {\n this.missing.delete(pubKeyZ32);\n this.missing.add(pubKeyZ32);\n if (this.missing.size > READ_TURNS_KEPT) this.missing.delete(this.missing.values().next().value!);\n }\n if (took <= SLOW_MS) {\n this.answered(relay, undefined, \"GET\");\n this.slowUntil.delete(relay);\n } else {\n // It answered this kind of request: an earlier failure of it no longer keeps the next one back.\n this.networkCooldown.delete(`GET ${relay}`);\n // A slow packet counts against the relay; a slow 404 says nothing (every relay takes seconds to give one).\n if (outcome.kind === \"packet\") this.slow(relay);\n else this.breaker.cancel(relay);\n }\n // The relays still asked are dropped, after the winner's own outcome (a probe that answered is a relay to ask\n // again). One asked no later than the winner, which a relay beat with the packet, is slow. So is one beaten by a 404\n // while still silent past `HEDGE_MISSING_MS`, more than a relay takes to say 404: a relay that takes connections\n // and never answers was asked first in every read of a key nobody published yet, each one 6 s, and never tripped.\n for (const loser of asked.values()) {\n loser.controller.abort();\n if (loser.started <= attempt.started && (outcome.kind === \"packet\" || Date.now() - loser.started >= HEDGE_MISSING_MS)) this.slow(loser.relay);\n else this.breaker.cancel(loser.relay);\n }\n this.lastRelay = relay;\n this.answeredRead(pubKeyZ32);\n this.readFrom(pubKeyZ32, relay);\n return this.newest.get(pubKeyZ32) ?? null;\n }\n\n const resting = this.relays.every((r) => this.isCoolingDown(r, \"GET\") || this.breaker.blockedFor(r) > 0 || this.heldFor(r, who, Date.now(), pubKeyZ32) > 0);\n // Holding back is not an outage: report what is already known, this client's own writes included while only the\n // budget held the read (a relay that failed it says nothing of them: an inviter's placeholder under its contact's\n // key would hide the outage)…\n const known = down ? this.newest.get(pubKeyZ32) : newerPacket(this.newest.get(pubKeyZ32), this.written.get(pubKeyZ32));\n // A background read held back comes again at its own turn, not when the budget frees the next request.\n if (!down && budgetWait < Infinity) budgetWait = Math.max(budgetWait, this.backgroundTurnIn(pubKeyZ32, who, Date.now()));\n if (resting && known) {\n if (down && !keptOnFailure) throw new RelaysFailedError(known);\n if (!down && budgetWait < Infinity) this.heldBackUntil(pubKeyZ32, Date.now() + budgetWait);\n return known;\n }\n // …or, knowing nothing yet, that the read waits for the budget.\n if (!down && budgetWait < Infinity) {\n this.heldBackUntil(pubKeyZ32, Date.now() + budgetWait);\n throw new DiscoveryBudgetError(budgetWait);\n }\n throw new Error(\"No Pkarr relay reachable\");\n }\n\n /**\n * The order a key's read asks the relays in: in turn per key (see `resolve`), relays found slow lately or leaving a\n * request unanswered (`unanswering`) last. A relay\n * with a small share of its own (`RELAY_REQUESTS_PER_MINUTE` under `REQUESTS_PER_MINUTE`: pkarr.miguelmedeiros.dev's 5)\n * takes no turns: it comes after the others, for when they refuse, fail or are slow, unless every relay is one. In the\n * turn, it was spent in seconds and the relay after it took its turns too: pkarr.pubky.org got two reads in three and\n * pkarr.pubky.app, with twice its share, one. Its few requests are then left for writes, which go to every relay.\n */\n private readOrder(pubKeyZ32: string): string[] {\n const full = this.relays.filter((relay) => !((RELAY_REQUESTS_PER_MINUTE[relay] ?? Infinity) < REQUESTS_PER_MINUTE));\n const ring = full.length ? full : this.relays;\n const last = this.lastReadFrom.get(pubKeyZ32), lastAt = last === undefined ? -1 : this.relays.indexOf(last);\n // After the relay that answered last: the next one in the ring, from where that relay is in the list.\n const after = lastAt < 0 ? -1 : ring.findIndex((relay) => this.relays.indexOf(relay) > lastAt);\n const start = lastAt < 0 ? this.cursor++ : after < 0 ? 0 : after;\n const turn = [...ring.map((_, i) => ring[(start + i) % ring.length]), ...this.relays.filter((relay) => !ring.includes(relay))];\n const now = Date.now(), behind = (relay: string) => (this.slowUntil.get(relay) ?? 0) > now || this.unanswering(relay, now);\n return [...turn.filter((relay) => !behind(relay)), ...turn.filter(behind)];\n }\n\n /**\n * A request of this client has waited on the relay for `HEDGE_MS` and it has answered none since: it goes after the\n * others in a read (`readOrder`), at no cost of a request. A relay that took connections and never answered held a\n * fresh device's first pairing at its turn: the key's last read had found nothing (`HEDGE_MISSING_MS`), so the read\n * waited 6 s on it before asking the relay that had held the packet all along (8 s join to live, not 2.5 s).\n */\n private unanswering(relay: string, now: number): boolean {\n const since = this.answeredAt.get(relay) ?? -Infinity;\n for (const request of this.waiting.get(relay) ?? []) if (request.at > since && now - request.at >= this.hedgeMs) return true;\n return false;\n }\n\n /** One GET of a key at one relay, which `controller` drops. Never rejects: what happened is the outcome. */\n private readFromRelay(relay: string, pubKeyZ32: string): ReadAttempt {\n const controller = new AbortController(), started = Date.now();\n const done = (async (): Promise<ReadOutcome> => {\n let status = 0;\n try {\n let payload: Uint8Array | undefined;\n const response = await this.request(`${relay}/${pubKeyZ32}`, { method: \"GET\" }, async (r, signal) => {\n status = r.status;\n if (r.ok && r.status !== 404) payload = await readRelayBody(r, signal);\n }, controller.signal);\n status = response.status;\n if (response.status === 429) return { kind: \"throttled\", response };\n if (response.status === 404) return { kind: \"missing\" };\n if (!response.ok) throw new Error(`${relay} responded ${response.status}`);\n return { kind: \"packet\", packet: parseRelayPayload(pubKeyZ32, payload!) };\n } catch {\n if (controller.signal.aborted) return { kind: \"cancelled\" };\n return { kind: \"failed\", reason: status >= 200 && status < 300 ? \"invalid packet\" : status ? `HTTP ${status}` : \"no answer\" };\n }\n })();\n return { relay, controller, started, done };\n }\n\n /**\n * The relay was slow (`SLOW_MS`): it goes after the others for a while, and counts it against its breaker while\n * another relay is there to ask. With none, a slow answer beats no answer: it counts as one.\n */\n private slow(relay: string): void {\n this.slowUntil.set(relay, Date.now() + SLOW_DEMOTE_MS);\n const another = this.relays.some((r) => r !== relay && this.breaker.blockedFor(r) === 0 && !this.isCoolingDown(r, \"GET\"));\n if (another) this.breaker.failure(relay, \"error\", \"slow\");\n else this.breaker.success(relay, this.relays);\n }\n\n /**\n * A hedge may go to this relay: its minute has more requests left than what groups leave a chat (`reserveOf`), so\n * a second request for a read that already went out never takes one a pairing needs.\n */\n private hedgeRoom(relay: string): boolean {\n const now = Date.now();\n const recent = within(this.spent.get(relay) ?? [], now, 60_000).length;\n return recent < this.limitOf(relay) - this.reserveOf(relay);\n }\n\n readAnsweredAt(pubKeyZ32: string): number | undefined { return this.readAt.get(pubKeyZ32); }\n\n /** The last read of this key was answered 404 (`HEDGE_MISSING_MS`): a relay takes seconds to say so. */\n lastReadMissing(pubKeyZ32: string): boolean { return this.missing.has(pubKeyZ32); }\n\n readHeldBackFor(pubKeyZ32: string): number | undefined {\n const held = this.heldBack.get(pubKeyZ32);\n const left = held === undefined ? 0 : held.until - Date.now();\n // A hold that has run out is the past: the read that just ended was not held back (the relays went down after it).\n return left > 0 ? left : undefined;\n }\n\n private heldBackUntil(pubKeyZ32: string, until: number): void {\n const held = this.heldBack.get(pubKeyZ32), times = (held?.times ?? 0) + 1;\n this.heldBack.delete(pubKeyZ32);\n this.heldBack.set(pubKeyZ32, { until, times, since: held?.since ?? Date.now() });\n if (this.heldBack.size > READ_TURNS_KEPT) this.heldBack.delete(this.heldBack.keys().next().value!);\n }\n\n /** The relays answered a read of this key now; answers older than `FRESH_READ_MS` are dropped as the list grows. */\n private answeredRead(pubKeyZ32: string): void {\n const now = Date.now();\n this.heldBack.delete(pubKeyZ32);\n this.readAt.delete(pubKeyZ32);\n this.readAt.set(pubKeyZ32, now);\n // Oldest first: drop the stale ones from the front.\n if (this.readAt.size > 64) for (const [key, at] of this.readAt) { if (now - at < this.freshReadMs) break; this.readAt.delete(key); }\n }\n\n /** The relay that answered a key's read, for its next one; the keys read longest ago go past `READ_TURNS_KEPT`. */\n private readFrom(pubKeyZ32: string, relay: string): void {\n this.lastReadFrom.delete(pubKeyZ32);\n this.lastReadFrom.set(pubKeyZ32, relay);\n if (this.lastReadFrom.size > READ_TURNS_KEPT) this.lastReadFrom.delete(this.lastReadFrom.keys().next().value!);\n }\n\n /**\n * A relay whose budget (this client's, or its own rate limit) held a packet back that another relay took: it gets\n * that packet when it frees a request, as a background write (`who`: a group edge's offer or answer as its own, also\n * after that relay failed it). Only the newest per key and relay, until that relay takes this packet or a newer one (one\n * the budget holds there takes its place). Without this,\n * that relay kept the key's older packet for good, and an app that restarted and read it first found a contact's offer\n * long answered, answered it again, and waited on it (bug hunt r7a).\n */\n private catchUpLater(relay: string, key: string, payload: Uint8Array, timestamp: bigint, who = CATCH_UP_ASKER): void {\n const slot = `${relay} ${key}`;\n // A newer packet went to that relay (or was tried) since.\n if ((this.lastPut.get(slot) ?? 0n) > timestamp) return;\n const pending = this.catchUp.get(slot);\n if (pending && pending.timestamp >= timestamp) return;\n this.keepCatchUp(slot, { relay, key, payload, timestamp, who });\n this.scheduleCatchUp(CATCH_UP_MIN_MS);\n }\n\n private keepCatchUp(slot: string, item: { relay: string; key: string; payload: Uint8Array; timestamp: bigint; who: Asker }): void {\n if (!this.catchUp.has(slot)) this.catchUpWaiting.set(item.relay, (this.catchUpWaiting.get(item.relay) ?? 0) + 1);\n this.catchUp.set(slot, item);\n }\n\n private dropCatchUp(relay: string, key: string): void {\n if (!this.catchUp.delete(`${relay} ${key}`)) return;\n const left = (this.catchUpWaiting.get(relay) ?? 1) - 1;\n if (left > 0) this.catchUpWaiting.set(relay, left); else this.catchUpWaiting.delete(relay);\n }\n\n private scheduleCatchUp(inMs: number): void {\n if (this.catchUpTimer || this.catchUp.size === 0) return;\n this.catchUpTimer = setTimeout(() => { this.catchUpTimer = null; void this.runCatchUp(); }, inMs);\n }\n\n private async runCatchUp(): Promise<void> {\n let next = Infinity;\n for (const [slot, item] of [...this.catchUp]) {\n if (this.catchUp.get(slot) !== item) continue;\n const coolingDown = (this.networkCooldown.get(`PUT ${item.relay}`) ?? 0) - Date.now();\n const who: Asker = { ...item.who, catchUp: true };\n const wait = Math.max(this.heldFor(item.relay, who), this.rateLimitedFor(item.relay), this.breaker.blockedFor(item.relay), coolingDown);\n if (wait > 0) { next = Math.min(next, wait); continue; }\n this.dropCatchUp(item.relay, item.key);\n try {\n const response = await this.put(item.relay, item.key, item.payload, undefined, who);\n // The relay still putting an earlier packet (428) or rate limiting (429): again later, unless a newer one came.\n if ((response.status === 428 || response.status === 429) && !this.catchUp.has(slot)) { this.keepCatchUp(slot, item); next = Math.min(next, CATCH_UP_RETRY_MS); }\n } catch (error) {\n if (isDiscoveryBudgetError(error) && !this.catchUp.has(slot)) { this.keepCatchUp(slot, item); next = Math.min(next, error.retryInMs); }\n }\n }\n if (this.catchUp.size) this.scheduleCatchUp(Math.max(CATCH_UP_MIN_MS, next === Infinity ? CATCH_UP_RETRY_MS : next));\n }\n\n /** `sent`: told, once the budget took the request, whether the relay takes the packet (a 2xx). */\n private async put(relay: string, pubKeyZ32: string, payload: Uint8Array, replaces: bigint | undefined, who: Asker, probe = false, sent?: (ok: Promise<boolean>) => void): Promise<Response> {\n const refused = this.refusal(relay, probe);\n if (refused) throw refused;\n if (!this.take(relay, who, pubKeyZ32)) throw new DiscoveryBudgetError(this.heldFor(relay, who));\n if (probe) this.breaker.beginAllDown(relay); else this.breaker.begin(relay);\n const request = this.request(`${relay}/${pubKeyZ32}`, {\n method: \"PUT\",\n body: payload as BodyInit,\n headers: replaces === undefined ? undefined : { \"If-Match\": replaces.toString() },\n });\n sent?.(request.then((r) => r.ok, () => false));\n let response: Response;\n try { response = await request; } catch (error) {\n this.networkCooldown.set(`PUT ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);\n this.answered(relay, { kind: \"error\", reason: \"no answer\" });\n // Node's own words for it (\"TypeError: fetch failed\") named neither the relay nor what happened. A timeout or a\n // connection dropped on the way may have left the packet there; one never made did not.\n throw new RelayNoAnswerError(`${relay} did not answer`, !connectFailed(error));\n }\n // 409, 412 and 428 are the relay working as it should; its rate limit and its own errors count against it.\n if (response.status === 429) this.answered(relay, { kind: \"throttled\", reason: \"rate limited (429)\" });\n else if (response.status >= 500) this.answered(relay, { kind: \"error\", reason: `HTTP ${response.status}` });\n else this.answered(relay, undefined, \"PUT\");\n return response;\n }\n\n /**\n * Discovery reads and writes share a bounded per-relay request budget; background requests only part of it, and\n * groups leave a chat the budget refused its reserve. A link's write the budget refused goes before any read\n * once a request is free again.\n */\n private take(relay: string, who: Asker, key: string): boolean {\n const now = Date.now();\n const writer = firstWriter(who);\n // Asked, whether or not it gets a request now: the link is signaling, and a chat's needs its reserve from now on.\n if (who.urgent && !who.background) {\n this.urgentAt = now;\n if (isChat(who)) this.chatNeed(key, now);\n }\n if (isGroupRead(who) || isChatWatch(who)) this.readAsked(key, who, now);\n if (isTurnRead(who)) this.turnAsked(key, who, now);\n if (isAwaitedRead(who)) this.awaitedAt = now;\n if (this.heldFor(relay, who, now, key) > 0) {\n // The minute is full: the groups' reads are rationed from now on.\n if (isGroupRead(who) && (this.spent.get(relay)?.length ?? 0) >= this.limitOf(relay)) this.groupsFullAt.set(relay, now);\n if (isChat(who)) this.chatNeed(key, now, relay);\n if (writer) this.writeWaiting.set(`${writer} ${relay}`, now);\n if (isGroupAnswerRead(who)) {\n const waiting = this.answerReadWaiting.get(relay) ?? new Map<string, number>();\n this.answerReadWaiting.set(relay, waiting.set(key, now));\n }\n return false;\n }\n if (writer) this.writeWaiting.delete(`${writer} ${relay}`);\n if (isGroupAnswerRead(who)) this.answerReadWaiting.get(relay)?.delete(key);\n // A way back that only its allowance let through counts there alone: it takes nothing from anyone else's minute.\n if (isWayBack(who) && this.heldFor(relay, { ...who, back: false }, now, key, false) > 0) {\n this.spentWayBack.set(relay, [...(this.spentWayBack.get(relay) ?? []), now]);\n if (isGroupRead(who)) this.readTurns.set(key, { servedAt: now, askedAt: now, waiting: false, watch: false, lane: watchLane(who) });\n return true;\n }\n // So does an edge's read for its answer that only its own allowance let through (`ANSWER_READ_ALLOWANCE`).\n if (isGroupAnswerRead(who) && this.heldFor(relay, who, now, key, false, false) > 0) {\n this.spentAnswerAllowance.set(relay, [...(this.spentAnswerAllowance.get(relay) ?? []), now]);\n this.readTurns.set(key, { servedAt: now, askedAt: now, waiting: false, watch: false, lane: watchLane(who), answer: true });\n return true;\n }\n if (isGroupSignal(who) && !who.write && this.spent.get(relay)!.length >= this.limitOf(relay)) this.spentGroupOver.get(relay)!.push(now);\n if (isGroupSignal(who)) this.spentGroupSignal.get(relay)!.push(now);\n const departedOver = isDepartedRead(who) && this.spent.get(relay)!.length >= this.limitOf(relay);\n if (departedOver) this.overAdd(this.departedOver, key, now);\n if (isAwaitedRead(who) && this.spent.get(relay)!.length >= this.limitOf(relay)) this.awaitedOver = [...within(this.awaitedOver, now, 60_000), now];\n this.spent.get(relay)!.push(now);\n if (who.background) this.spentBackground.get(relay)!.push(now);\n if (who.background && who.write) this.spentBackgroundWrites.get(relay)!.push(now);\n if (isGroupUrgentRead(who) && isGroupAnswerRead(who)) this.spentAnswerUrgent.set(relay, [...(this.spentAnswerUrgent.get(relay) ?? []), now]);\n else if (isGroupUrgentRead(who)) this.spentGroupUrgent.get(relay)!.push(now);\n if (isWatch(who)) this.spentWatch.get(relay)!.push(now);\n if (isChatWatch(who) && !departedOver) this.spentChatWatch.get(relay)!.push(now);\n if (isGroupRead(who)) this.spentGroupReads.get(relay)!.push(now);\n if (isGroupRead(who) || isChatWatch(who)) this.readTurns.set(key, { servedAt: now, askedAt: now, waiting: false, watch: isWatch(who) || isChatWatch(who), lane: watchLane(who) });\n if (isTurnRead(who)) this.keyTurns.set(key, { servedAt: now, askedAt: now, waiting: false, who });\n return true;\n }\n\n /**\n * How long until this relay's budget takes this request, 0 when it would now: the oldest request of the minute over\n * a limit ages out, a chat's reserve lapses, or a waiting write has had its turn. Keeps the lists to the minute, oldest first.\n *\n * Who goes first: a chat's refused write holds back everything but chat writes; a group's refused write holds back\n * group reads and background requests, never a chat's. Background requests yield to a link that signals. A chat's\n * signaling goes over the limit by its allowance (`SIGNALING_ALLOWANCE_SHARE`), and so do a few of its reads of a\n * contact that just went away (`DEPARTED_READS`) or of an invite awaited (`AWAITED_READS`). `ownAllowance` false: what holds an edge's read for its answer\n * without its own allowance (`ANSWER_READ_ALLOWANCE`).\n */\n private heldFor(relay: string, who: Asker, now = Date.now(), key?: string, turns = true, ownAllowance = true): number {\n const recent = within(this.spent.get(relay) ?? [], now, 60_000);\n const recentBackground = within(this.spentBackground.get(relay) ?? [], now, 60_000);\n this.spent.set(relay, recent);\n this.spentBackground.set(relay, recentBackground);\n const recentBackgroundWrites = within(this.spentBackgroundWrites.get(relay) ?? [], now, 60_000);\n this.spentBackgroundWrites.set(relay, recentBackgroundWrites);\n // Until the `limit`-th newest request of the minute ages out; 0 while fewer than `limit` were made.\n const over = (list: number[], limit: number) => (list.length >= limit ? list[list.length - limit] + 60_000 - now : 0);\n const limit = this.limitOf(relay);\n // A chat's signaling may go over the minute by its allowance; its reads leave the last of it to a write.\n // A group edge's, for a member that may be back, by a smaller one, its reads one at a time past the limit.\n // A chat's read of a contact that just went away, past the limit: within the chat's allowance, a few per contact.\n // So is its read of an invite this side made while the joiner is due, a few for every invite together.\n const departed = isDepartedRead(who) && key !== undefined && recent.length >= limit && this.overReads(this.departedOver, key, now) < DEPARTED_READS;\n if (isAwaitedRead(who)) this.awaitedOver = within(this.awaitedOver, now, 60_000);\n const awaited = isAwaitedRead(who) && key !== undefined && recent.length >= limit && this.awaitedOver.length < AWAITED_READS;\n const share = isChatSignal(who) || departed || awaited ? SIGNALING_ALLOWANCE_SHARE : isGroupSignal(who) ? GROUP_SIGNALING_ALLOWANCE_SHARE : 0;\n let allowance = share ? Math.max(0, Math.floor(limit * share) - (who.write ? 0 : 1)) : 0;\n // The departed reads leave the last of it to an awaited invite's, while one is (`AWAITED_READS`).\n if (departed && now - this.awaitedAt < 60_000) allowance = Math.max(0, allowance - AWAITED_READS / 2);\n // The edges' signaling has its allowance whatever the chats spend: the limit and the chats' reserve wait for it.\n const groupSignaled = within(this.spentGroupSignal.get(relay) ?? [], now, 60_000);\n this.spentGroupSignal.set(relay, groupSignaled);\n const groupFloor = isGroupSignal(who) && groupSignaled.length < allowance;\n let wait = groupFloor ? 0 : over(recent, limit + allowance);\n const starved = key !== undefined && this.starved(key, who, now);\n const groupOver = within(this.spentGroupOver.get(relay) ?? [], now, GROUP_OVER_PACE_MS);\n this.spentGroupOver.set(relay, groupOver);\n if (isGroupSignal(who) && !who.write && recent.length >= limit && groupOver.length > 0) wait = Math.max(wait, groupOver[groupOver.length - 1] + GROUP_OVER_PACE_MS - now);\n // On a relay with a small share of its own (5), background requests keep to two thirds of it, as on a smaller\n // budget: they would otherwise take the whole minute there, and leave nothing for a link's write.\n const backgroundShare = Math.min(this.backgroundPerMinute, Math.ceil(limit * 2 / 3));\n const writesShare = Math.max(1, Math.floor(backgroundShare * BACKGROUND_WRITES_SHARE));\n // Packets this relay held back while another path took them (`catchUpLater`): background reads, starved ones too,\n // leave what is left of the background writes' share to them. Without it, a daemon whose 50 contacts were away\n // read them with every request the budget freed (each read starved in turn), and 35 of its 50 chats' packets never\n // reached the relays in 40 minutes, where the web app and the extension read them (bug hunt, 2026-11-06).\n const caughtUp = this.catchUpWaiting.get(relay) ?? 0;\n if (who.background && !who.write && caughtUp) {\n const writesLeft = writesShare - recentBackgroundWrites.length;\n if (writesLeft > 0) wait = Math.max(wait, over(recent, Math.max(1, limit - writesLeft)), over(recentBackground, Math.max(1, backgroundShare - writesLeft)));\n }\n // And another background write waits behind them, for about as long as they take at that share, a minute at most: a\n // link's upkeep tried again at every request that freed, and the same 30 chats took every one while the queue kept\n // the others'. One the DHT took joins the queue (`putLater`).\n if (who.background && who.write && !who.catchUp && caughtUp) wait = Math.max(wait, Math.min(CATCH_UP_BEHIND_MAX_MS, Math.ceil(caughtUp * 60_000 / writesShare)));\n if (who.background && !starved) {\n wait = Math.max(wait, over(recentBackground, backgroundShare));\n // Background writes leave the rest of that share to background reads (`BACKGROUND_WRITES_SHARE`).\n if (who.write) wait = Math.max(wait, over(recentBackgroundWrites, writesShare));\n // A link signaling: background takes a smaller share until it stops, or until enough of its own age out. A\n // community door's bell does not: the links it signals for are often the ones its last admission opened.\n const signaling = this.urgentAt + SIGNALING_WINDOW_MS - now;\n if (signaling > 0 && !who.door) wait = Math.max(wait, Math.min(signaling, over(recentBackground, Math.min(this.backgroundWhileSignaling, Math.ceil(limit / 6)))));\n }\n // Groups' urgent reads: their share of the minute spread over it (`GROUP_BURST_MS`).\n const burst = within(this.spentGroupUrgent.get(relay) ?? [], now, GROUP_BURST_MS);\n this.spentGroupUrgent.set(relay, burst);\n const answerBurst = within(this.spentAnswerUrgent.get(relay) ?? [], now, GROUP_BURST_MS);\n this.spentAnswerUrgent.set(relay, answerBurst);\n if (isGroupUrgentRead(who)) {\n const most = Math.max(GROUP_BURST_ONE_LINK, Math.floor(limit * GROUP_BURST_MS / 60_000));\n // An edge's read for its answer counts in a burst of its own: the others' (reads back after a restart) leave it be.\n const spent = isGroupAnswerRead(who) ? answerBurst : burst;\n if (spent.length >= most) wait = Math.max(wait, spent[spent.length - most] + GROUP_BURST_MS - now);\n }\n // Watch reads: their share, spread over the minute, the keys read longest ago first.\n const watched = within(this.spentWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);\n this.spentWatch.set(relay, watched);\n // A key's turn among the others (`TURN_WAIT_MS`): apart, as a way back waits it whatever its allowance.\n let turn = 0;\n if (isWatch(who)) {\n const most = Math.max(1, Math.ceil(limit * WATCH_SHARE * GROUP_RATION_WINDOW_MS / 60_000));\n if (watched.length >= most) wait = Math.max(wait, watched[watched.length - most] + GROUP_RATION_WINDOW_MS - now);\n if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;\n }\n // The chats' watch reads: theirs, the same way; not a departed read past the limit.\n const chatWatched = within(this.spentChatWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);\n this.spentChatWatch.set(relay, chatWatched);\n if (isChatWatch(who) && !departed) {\n const most = Math.max(1, Math.ceil(limit * CHAT_WATCH_SHARE * GROUP_RATION_WINDOW_MS / 60_000));\n if (chatWatched.length >= most) wait = Math.max(wait, chatWatched[chatWatched.length - most] + GROUP_RATION_WINDOW_MS - now);\n if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;\n }\n // The groups' reads after one found the minute full: spread over it, in turn.\n const rationed = within(this.spentGroupReads.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);\n this.spentGroupReads.set(relay, rationed);\n // Not a read past the limit within the groups' allowance: it takes nothing the ration spreads, and goes one at a time.\n const pastLimit = isGroupSignal(who) && recent.length >= limit;\n if (isGroupRead(who) && !pastLimit && now - (this.groupsFullAt.get(relay) ?? -Infinity) < GROUP_RATION_MS) {\n const most = Math.max(1, Math.ceil(limit * GROUP_RATION_WINDOW_MS / 60_000));\n if (rationed.length >= most) wait = Math.max(wait, rationed[rationed.length - most] + GROUP_RATION_WINDOW_MS - now);\n if (this.readsAhead(key, now, undefined, isGroupAnswerRead(who)) > 0) turn = TURN_WAIT_MS;\n }\n if ((who.group && !groupFloor) || who.background) {\n const reserved = this.chatReservedFor(relay, now);\n if (reserved > 0) wait = Math.max(wait, Math.min(reserved, over(recent, limit - this.chatReserveOf(relay, now))));\n }\n const writer = firstWriter(who);\n const waiting = (lane: \"chat\" | \"group\") => {\n const at = this.writeWaiting.get(`${lane} ${relay}`);\n return at !== undefined && now - at < WRITE_FIRST_MS ? at + WRITE_FIRST_MS - now : 0;\n };\n // A departed or awaited read past the limit takes no request a waiting write could have either (it is no signal).\n // Nor does a chat's read for a signal past it: an offer or answer has the allowance's last request, and any other\n // write waits for the limit. Held for one, a live chat back after a reload, next to an invite whose packet the spent\n // minute refused at every read, read its contact's answer only once the minute freed: 62 s, against 8 s (bug hunt,\n // 2026-11-07). A starved read goes before them (`READ_STARVED_MS`).\n const signalOver = isChatSignal(who) && !who.write && recent.length >= limit;\n if (writer !== \"chat\" && !departed && !awaited && !signalOver && !starved) wait = Math.max(wait, waiting(\"chat\"));\n // A read past the limit within the groups' allowance takes no request a waiting write could have (it is no signal).\n // An edge's read for its answer does not wait for one: the floor's other requests wait for it instead.\n if (((writer === null && who.group && !pastLimit && !isGroupAnswerRead(who)) || who.background) && !starved) wait = Math.max(wait, waiting(\"group\"));\n // The groups' other signaling waits for an edge's read for its answer the budget refused, for what that read could\n // take now (`ANSWER_READ_FIRST_MS`): not the floor's last request, which only a write takes.\n if (isGroupSignal(who) && !isGroupAnswerRead(who)) {\n const ahead = this.answerReadAhead(relay, now);\n if (ahead && this.heldFor(relay, ANSWER_READER, now, ahead.key, false, false) <= 0) wait = Math.max(wait, ahead.ms);\n }\n // In turn per key: a key read longer ago that is asking too goes first (`READ_TURN_MS`).\n if (turns && wait <= 0 && isTurnRead(who) && this.turnAhead(relay, key, who, now)) turn = TURN_WAIT_MS;\n // A community member's way back that all this holds goes within its own allowance (`WAY_BACK_SHARE`), past a turn\n // too: the key whose turn it is waits for the same. Not past a turn alone: a request is free, and that key takes it\n // first, a second, as for any group's read; the allowance stays for a full minute.\n if (wait > 0 && isWayBack(who) && this.wayBackLeft(relay, who, now) > 0) return 0;\n // So does an edge's read for its answer, within its own (`ANSWER_READ_ALLOWANCE`), one at a time.\n if (wait > 0 && ownAllowance && isGroupAnswerRead(who) && this.answerAllowanceFree(relay, now)) return 0;\n return Math.max(wait, turn, 0);\n }\n\n /**\n * The edges' reads for their answers may take their own allowance on this relay now (`ANSWER_READ_ALLOWANCE`): fewer\n * than it in the last minute, and none within `ANSWER_READ_SPACING_MS`. None where the groups have no allowance.\n */\n private answerAllowanceFree(relay: string, now: number): boolean {\n const spent = within(this.spentAnswerAllowance.get(relay) ?? [], now, 60_000);\n this.spentAnswerAllowance.set(relay, spent);\n const most = Math.min(ANSWER_READ_ALLOWANCE, Math.floor(this.limitOf(relay) * GROUP_SIGNALING_ALLOWANCE_SHARE));\n return spent.length < most && (spent.length === 0 || now - spent[spent.length - 1] >= ANSWER_READ_SPACING_MS);\n }\n\n /**\n * The edges' reads for their answers the budget refused on this relay within `ANSWER_READ_FIRST_MS`, still not read:\n * the key refused last, and how long the groups' other signaling waits for them there. Undefined when there is none.\n */\n private answerReadAhead(relay: string, now: number): { key: string; ms: number } | undefined {\n const waiting = this.answerReadWaiting.get(relay);\n if (!waiting) return undefined;\n let last: { key: string; at: number } | undefined;\n for (const [key, at] of waiting) {\n if (now - at >= ANSWER_READ_FIRST_MS) waiting.delete(key);\n else if (!last || at > last.at) last = { key, at };\n }\n return last && { key: last.key, ms: last.at + ANSWER_READ_FIRST_MS - now };\n }\n\n /** What is left of the community members' way back allowance on this relay (`WAY_BACK_SHARE`); its reads leave a write the last of it. */\n private wayBackLeft(relay: string, who: Asker, now: number): number {\n const spent = within(this.spentWayBack.get(relay) ?? [], now, 60_000);\n this.spentWayBack.set(relay, spent);\n return Math.floor(this.limitOf(relay) * WAY_BACK_SHARE) - (who.write ? 0 : 1) - spent.length;\n }\n\n /** A group's read of `key`, or a chat's watch read, asks: it waits for its turn from now on, unless it is taken (`readsAhead`). */\n private readAsked(key: string, who: Asker, now: number): void {\n this.pruneTurns(this.readTurns, now);\n const turn = this.readTurns.get(key);\n this.readTurns.set(key, { servedAt: turn && !staleTurn(turn, now) ? turn.servedAt : -Infinity, askedAt: now, waiting: true, watch: isWatch(who) || isChatWatch(who), lane: watchLane(who), answer: isGroupAnswerRead(who) });\n }\n\n /**\n * Keys a group reads, still asking (within `WATCH_TURN_MS`), that were read longer ago than `key`: a share keeps a\n * request for each. With `watchLane`, only watched keys the same other limits hold: one the groups' burst holds back\n * would keep a turn it cannot take. The chats' watched keys only in their own lane (`CHAT_WATCH_SHARE`). `answer`: an\n * edge's read for its answer, which waits only for the others' (`ANSWER_READ_FIRST_MS`).\n */\n private readsAhead(key: string | undefined, now: number, watchLane?: string, answer = false): number {\n const mine = key === undefined ? -Infinity : this.readTurns.get(key)?.servedAt ?? -Infinity;\n let ahead = 0;\n for (const [other, turn] of this.readTurns) {\n if (other === key || !turn.waiting || now - turn.askedAt >= WATCH_TURN_MS) continue;\n if (watchLane !== undefined ? !turn.watch || turn.lane !== watchLane : turn.lane === \"chat\") continue;\n if (answer && !turn.answer) continue;\n if (turn.servedAt < mine) ahead++;\n }\n return ahead;\n }\n\n /** A read of `key` that takes turns asks: it waits for its turn from now on, unless it is taken (`turnAhead`). */\n private turnAsked(key: string, who: Asker, now: number): void {\n this.pruneTurns(this.keyTurns, now);\n const turn = this.keyTurns.get(key);\n this.keyTurns.set(key, { servedAt: turn && !staleTurn(turn, now) ? turn.servedAt : -Infinity, askedAt: now, waiting: true, who });\n }\n\n /** Drops the turns asked and read over a minute ago, at most once in `TURNS_PRUNE_MS` (or when the clock went back). */\n private pruneTurns<T extends { servedAt: number; askedAt: number }>(turns: Map<string, T>, now: number): void {\n const prunedAt = this.turnsPrunedAt.get(turns) ?? -Infinity;\n if (Math.abs(now - prunedAt) < TURNS_PRUNE_MS) return;\n this.turnsPrunedAt.set(turns, now);\n // The clock went back: a turn read after now was read just now (`within`). Left after now, the keys read before the\n // step went last for as long as it, and those read since took every turn: 22 of 50 contacts away were not read in\n // the 15 minutes after an hour back.\n const back = now < prunedAt;\n for (const [key, turn] of turns) {\n if (back) { turn.servedAt = Math.min(turn.servedAt, now); turn.askedAt = Math.min(turn.askedAt, now); }\n if (staleTurn(turn, now)) turns.delete(key);\n }\n }\n\n /**\n * Whether a key read in turn longer ago than `key`, still asking, would take this relay's next request: one read in the\n * background for a background read, and a chat's that is starved (`READ_STARVED_MS`) for any. One asks again after\n * the budget held it back (a link's poll does, a one-off look does not), and keeps asking within `READ_TURN_MS` of its\n * last ask, or of when it was told the budget frees a request for it (`readHeldBackFor`).\n * One the budget holds back on its own account (a group's read, for the chats' reserve) keeps no turn: a group key\n * waiting for the chats held every chat's read back (CLI lab, 2026-10-13).\n */\n private turnAhead(relay: string, key: string | undefined, who: Asker, now: number): boolean {\n const mine = key === undefined ? -Infinity : this.keyTurns.get(key)?.servedAt ?? -Infinity;\n for (const [other, turn] of this.keyTurns) {\n const held = this.heldBack.get(other);\n if (other === key || !turn.waiting || turn.servedAt >= mine || !held || held.times < 2) continue;\n if (!(who.background && turn.who.background) && !this.starved(other, turn.who, now)) continue;\n if (now - Math.max(turn.askedAt, held.until) < READ_TURN_MS && this.heldFor(relay, turn.who, now, other, false) === 0) return true;\n }\n return false;\n }\n\n /**\n * How long until a background read of `key` the budget held back is likely to have its turn: the background reads of\n * keys ahead of it in turn (read longer ago, still asking; `turnAhead`), one after the other at the relays' background\n * share. Told only when the budget frees the next request, every held key asked again then, and lost it to the key\n * whose turn it was: a daemon whose 50 contacts were away asked about 600 times a minute for some 50 reads, and one\n * with 200 three times as often after four hours as after 15 minutes (bug hunts, 2026-11-06 and 2026-11-14).\n */\n private backgroundTurnIn(key: string, who: Asker, now: number): number {\n if (!who.background || !isTurnRead(who)) return 0;\n const mine = this.keyTurns.get(key);\n if (!mine) return 0;\n const since = (k: string) => this.heldBack.get(k)?.since ?? now;\n const mineSince = since(key);\n let ahead = 0, read = 0;\n for (const [other, turn] of this.keyTurns) {\n if (other !== key && turn.who.background && now - turn.servedAt < 60_000) read++;\n if (other === key || !turn.waiting || !turn.who.background || staleTurn(turn, now)) continue;\n // Read longer ago, or as long ago (never, or the clock's same millisecond) and held back longer; then by key.\n if (turn.servedAt < mine.servedAt || (turn.servedAt === mine.servedAt && (since(other) < mineSince || (since(other) === mineSince && other < key)))) ahead++;\n }\n if (ahead === 0) return 0;\n // As fast as the relays' background share reads, or as background keys were read in the last minute if faster (a key\n // held back long reads past the share, `READ_STARVED_MS`).\n const perMinute = this.relays.reduce((sum, relay) => sum + Math.min(this.backgroundPerMinute, Math.ceil(this.limitOf(relay) * 2 / 3)), 0);\n return Math.min(BACKGROUND_TURN_MAX_MS, Math.ceil(ahead * 60_000 / Math.max(1, perMinute, read)));\n }\n\n /** A 1:1 chat's read of `key` the budget has held back for `READ_STARVED_MS` without a break. */\n private starved(key: string, who: Asker, now: number): boolean {\n const since = this.heldBack.get(key)?.since;\n return !who.group && !who.write && !who.door && since !== undefined && now - since >= READ_STARVED_MS;\n }\n\n /** This key's departed reads past the limit in the last minute (`DEPARTED_READS`). */\n private overReads(over: Map<string, number[]>, key: string, now: number): number {\n const reads = within(over.get(key) ?? [], now, 60_000);\n if (reads.length) over.set(key, reads); else over.delete(key);\n return reads.length;\n }\n\n /** One more, the keys with none in the last minute dropped. */\n private overAdd(over: Map<string, number[]>, key: string, now: number): void {\n for (const [other, reads] of over) if (now - reads[reads.length - 1] >= 60_000) over.delete(other);\n over.set(key, [...(over.get(key) ?? []), now]);\n }\n\n /** A chat's request of `key` asked urgently (it needs every relay), or the budget refused it on `relay` (it needs that one). */\n private chatNeed(key: string, now: number, relay?: string): void {\n if (relay !== undefined) { this.chatNeedsOn(relay, now).set(key, now); return; }\n this.chatUrgentAt.set(key, now);\n for (const needs of this.chatNeeds.values()) needs.set(key, now);\n }\n\n /** The chats that need this relay: those a request of was refused there, and the urgent ones. */\n private chatNeedsOn(relay: string, now: number): RecentKeys {\n let needs = this.chatNeeds.get(relay);\n if (!needs) {\n this.chatNeeds.set(relay, needs = new RecentKeys());\n for (const [key, at] of this.chatUrgentAt.entries(now)) needs.set(key, at);\n }\n return needs;\n }\n\n /** The chat reading `key` has nothing due: it needs no relay any more. */\n private chatNeedLapsed(key: string): void {\n this.chatUrgentAt.delete(key);\n for (const needs of this.chatNeeds.values()) needs.delete(key);\n }\n\n /**\n * How long groups still leave a chat its reserve on this relay (`CHAT_RESERVE`); a chat's need a minute old goes.\n * Kept up to date as needs come and go (`RecentKeys`): walking them all for each request cost a daemon with 500\n * contacts away 2.7 s of CPU per 10 idle minutes (bug hunt, 2026-11-01).\n */\n private chatReservedFor(relay: string, now: number): number {\n return this.chatNeedsOn(relay, now).latest(now) + 60_000 - now;\n }\n\n /**\n * How long a chat's packet another relay already took waits for this one: while chats need the relays, a copy takes\n * none of the requests their reserve keeps (`chatReserveOf`), as a group's request does not. 0 when it goes now.\n */\n private spareHeldFor(relay: string, now: number): number {\n const reserved = this.chatReservedFor(relay, now);\n if (reserved <= 0) return 0;\n const recent = within(this.spent.get(relay) ?? [], now, 60_000);\n const keep = this.limitOf(relay) - this.chatReserveOf(relay, now);\n return recent.length >= keep ? Math.min(reserved, recent[recent.length - keep] + 60_000 - now) : 0;\n }\n\n /** Requests allowed to this relay a minute: this client's budget, or the relay's own share (`RELAY_REQUESTS_PER_MINUTE`). */\n private limitOf(relay: string): number {\n const share = RELAY_REQUESTS_PER_MINUTE[relay];\n if (share === undefined) return this.perMinute;\n return this.perMinuteGiven ? Math.min(this.perMinute, share) : share;\n }\n\n /** What the chats that need the relays keep on this relay (`CHAT_RESERVE_PER_CHAT`), never less than `reserveOf`. */\n private chatReserveOf(relay: string, now: number): number {\n const needing = this.chatNeedsOn(relay, now).size(now);\n return Math.max(this.reserveOf(relay), Math.min(needing * CHAT_RESERVE_PER_CHAT, Math.floor(this.limitOf(relay) * CHAT_RESERVE_MOST_SHARE)));\n }\n\n /** What groups leave a chat on this relay: `CHAT_RESERVE`, or a third of a smaller budget. */\n private reserveOf(relay: string): number {\n return Math.min(CHAT_RESERVE, Math.floor(this.limitOf(relay) / 3));\n }\n\n private isCoolingDown(relay: string, method: \"GET\" | \"PUT\"): boolean {\n return this.rateLimitedFor(relay) > 0 || this.networkCoolingDown(relay, method);\n }\n\n /** Left alone after failing at the network level. */\n private networkCoolingDown(relay: string, method: \"GET\" | \"PUT\"): boolean {\n return (this.networkCooldown.get(`${method} ${relay}`) ?? 0) > Date.now();\n }\n\n /** How much longer the relay asked (429) to be left alone; 0 when it did not. */\n private rateLimitedFor(relay: string): number {\n return Math.max(0, (this.coolingDown.get(relay) ?? 0) - Date.now());\n }\n\n /** Leaves the relay alone for as long as its 429 asks; returns that, in ms. */\n private coolDown(relay: string, response: Response): number {\n const retryAfter = Number.parseInt(response.headers.get(\"retry-after\") ?? \"\", 10);\n const seconds = Number.isFinite(retryAfter) ? Math.min(Math.max(retryAfter, 1), 120) : 15;\n this.coolingDown.set(relay, Date.now() + seconds * 1000);\n return seconds * 1000;\n }\n\n /**\n * One request under one time limit. `read` runs before the timer is cleared, so a body read there is bounded in\n * time as well: a relay that sends its headers and then trickles, or never ends, is given up on like one that\n * never answered.\n */\n /**\n * The relay's own time, when its answer says it and this runtime may read it: Node and the Desktop can, a browser\n * only when the relay exposes the header to other origins. Held against this device's clock (`ClockWatch`).\n */\n private serverTime(url: string, response: Response, sent: number): void {\n if (!this.timeListeners.size) return;\n let date = NaN;\n try {\n // An answer a cache kept says when it was made, not when it was served (`Age` says how long ago): not a clock.\n if (Number(response.headers.get(\"age\") ?? 0) > 0) return;\n date = Date.parse(response.headers.get(\"date\") ?? \"\");\n } catch { /* an answer with no headers to read */ }\n if (!Number.isFinite(date)) return;\n const time: ServerTime = { source: new URL(url).origin, date, sent, received: Date.now() };\n for (const listener of this.timeListeners) try { listener(time); } catch { /* a listener that fails must not fail a request */ }\n }\n\n onServerTime(listener: (time: ServerTime) => void): () => void {\n this.timeListeners.add(listener);\n return () => this.timeListeners.delete(listener);\n }\n\n /**\n * The turn record's read (WISP 06 § Publishing and reading): every relay, in parallel, `TURN_SOURCE_TIMEOUT_MS`\n * each. Unlike `resolve`, it does not stop at the first relay that answers, keeps nothing, and answers nothing from\n * memory. Each request counts in the relay's minute, so chats see it, but is never held back by it: a device may\n * not act before it has read its turn.\n */\n turnRead(pubKeyZ32: string, options: { timeoutMs?: number } = {}): Promise<TurnSourceAnswer[]> {\n const timeoutMs = Math.min(options.timeoutMs ?? TURN_SOURCE_TIMEOUT_MS, TURN_SOURCE_TIMEOUT_MS);\n return Promise.all(this.relays.map(async (relay): Promise<TurnSourceAnswer> => {\n try {\n let payload: Uint8Array | undefined;\n const read = async (r: Response, signal: AbortSignal) => { if (r.ok) payload = await readRelayBody(r, signal); };\n // A relay answers a plain GET from its cache while the packet's TTL lasts (five minutes): a record another\n // device put through another relay, or on the DHT itself, would not be seen. `NetworkOnly` makes it look.\n let response = await this.turnRequest(relay, `${pubKeyZ32}?policy=NetworkOnly`, { method: \"GET\" }, read, timeoutMs);\n // A relay from before that query refuses it (400): asked plainly, once, and its answer may be minutes old.\n const stale = response.status === 400;\n if (stale) response = await this.turnRequest(relay, pubKeyZ32, { method: \"GET\" }, read, timeoutMs);\n const age = stale ? { stale: true as const } : {};\n if (response.status === 404) {\n // The DHT holds an item under the key that is no signed packet: the relay names its sequence.\n const invalid = response.headers.get(INVALID_PACKET_SEQ_HEADER);\n return { source: relay, answered: true, payloads: [], ...age, ...(invalid && /^\\d{1,19}$/.test(invalid) ? { sequences: [invalid] } : {}) };\n }\n if (!response.ok || !payload) return { source: relay, answered: false, payloads: [], detail: `HTTP ${response.status}` };\n return { source: relay, answered: true, payloads: [payload], ...age };\n } catch (error) {\n return { source: relay, answered: false, payloads: [], detail: error instanceof Error ? error.message : String(error) };\n }\n }));\n }\n\n /**\n * The turn record's put: the bytes as given, to each relay `conditions` names, with `If-Match` on the sequence that\n * relay is known to hold (none where it held no record). Unlike `putEverywhere`, a relay that refuses (409, 412,\n * 428) is not asked again without the condition: its refusal is the answer, and every relay's answer is reported.\n */\n turnPut(pubKeyZ32: string, payload: Uint8Array, conditions: TurnConditions): Promise<TurnSourcePut[]> {\n const relays = this.relays.filter((relay) => conditions[relay] !== undefined);\n return Promise.all(relays.map(async (relay): Promise<TurnSourcePut> => {\n const replaces = conditions[relay];\n try {\n const response = await this.turnRequest(relay, pubKeyZ32, { method: \"PUT\", body: payload as BodyInit, headers: replaces === null ? undefined : { \"If-Match\": replaces } });\n if (response.ok) return { source: relay, outcome: \"stored\", detail: `HTTP ${response.status}` };\n return { source: relay, outcome: TURN_REFUSALS.includes(response.status) ? \"refused\" : \"failed\", detail: `HTTP ${response.status}` };\n } catch (error) {\n return { source: relay, outcome: \"failed\", detail: error instanceof Error ? error.message : String(error) };\n }\n }));\n }\n\n private async turnRequest(relay: string, path: string, init: RequestInit, read?: (response: Response, signal: AbortSignal) => Promise<void>, timeoutMs = TURN_SOURCE_TIMEOUT_MS): Promise<Response> {\n this.spent.get(relay)?.push(Date.now());\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const response = await this.fetchFn(`${relay}/${path}`, { ...init, cache: \"no-store\", signal: controller.signal });\n await read?.(response, controller.signal);\n return response;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** `cancel`: this client drops the request (a hedged read another relay answered first). */\n private async request(url: string, init: RequestInit, read?: (response: Response, signal: AbortSignal) => Promise<void>, cancel?: AbortSignal): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n const drop = () => controller.abort();\n cancel?.addEventListener(\"abort\", drop, { once: true });\n // The relay is the URL up to the key (`unanswering`).\n const relay = url.slice(0, url.lastIndexOf(\"/\")), request = { at: Date.now() };\n const waiting = this.waiting.get(relay) ?? new Set<{ at: number }>();\n this.waiting.set(relay, waiting.add(request));\n try {\n // Relays answer with `cache-control: max-age=300`; polling needs fresh data.\n const sent = Date.now();\n const response = await this.fetchFn(url, { ...init, cache: \"no-store\", signal: controller.signal });\n this.answeredAt.set(relay, Date.now());\n this.serverTime(url, response, sent);\n await read?.(response, controller.signal);\n return response;\n } finally {\n waiting.delete(request);\n clearTimeout(timer);\n cancel?.removeEventListener(\"abort\", drop);\n }\n }\n}\n\n/** What one relay did with a read (`readFromRelay`); `cancelled`: this client dropped it. */\ntype ReadOutcome =\n | { kind: \"packet\"; packet: SignedPacket }\n | { kind: \"missing\" }\n | { kind: \"throttled\"; response: Response }\n | { kind: \"failed\"; reason: string }\n | { kind: \"cancelled\" };\ninterface ReadAttempt { relay: string; controller: AbortController; started: number; done: Promise<ReadOutcome> }\n\n/**\n * A relay's answer body, at most RELAY_PAYLOAD_MAX_BYTES: refused on a larger `content-length` before anything is\n * read, and otherwise streamed with a running count, so a relay (a default one or one the person added, working or\n * compromised) cannot fill memory with a huge or endless body. Stops when `signal` aborts.\n */\nexport async function readRelayBody(response: Response, signal: AbortSignal, max = RELAY_PAYLOAD_MAX_BYTES): Promise<Uint8Array> {\n const tooLarge = () => new Error(`Relay answer is larger than ${max} bytes`);\n if (Number(response.headers.get(\"content-length\")) > max) { void response.body?.cancel().catch(() => {}); throw tooLarge(); }\n if (!response.body) return new Uint8Array(0);\n const reader = response.body.getReader();\n // The fetch aborts its own stream; this also stops a body that is not tied to the request's signal.\n const stop = () => { void reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", stop, { once: true });\n try {\n const chunks: Uint8Array[] = [];\n let length = 0;\n for (;;) {\n if (signal.aborted) throw new Error(\"Relay answer timed out\");\n const { done, value } = await reader.read();\n if (signal.aborted) throw new Error(\"Relay answer timed out\");\n if (done) break;\n length += value.byteLength;\n if (length > max) { stop(); throw tooLarge(); }\n chunks.push(value);\n }\n const body = new Uint8Array(length);\n let at = 0;\n for (const chunk of chunks) { body.set(chunk, at); at += chunk.byteLength; }\n return body;\n } finally {\n signal.removeEventListener(\"abort\", stop);\n }\n}\n"],"mappings":";;;;;;AA2FA,SAAgB,mBAAmB,WAA2B,OAA4C;CACxG,MAAM,UAA0B;EAC9B,UAAU,UAAU,SAAS,YAAY,UAAU,QAAQ,UAAU,SAAS;GAAE,GAAG;GAAS,GAAG;EAAM,CAAC;EACtG,UAAU,WAAW,YAAY,UAAU,QAAQ,WAAW;GAAE,GAAG;GAAS,GAAG;EAAM,CAAC;EACtF,gBAAgB,UAAU,SAAS;CACrC;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GAAE,KAAK,IAAI,OAAO,EAAE;GAAG,MAAM,MAAM;EAAY;EAC3E,OAAO;CACT,UAAU;EACR,OAAO,oBAAoB,SAAS,IAAI;CAC1C;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { l as toBase64Url, o as isZ32Key } from "./bytes-C1DNGY18.js";
2
- import { t as DEFAULT_RELAYS } from "./relay-Cjfmdec0.js";
2
+ import { t as DEFAULT_RELAYS } from "./relay-CHWg5hpZ.js";
3
3
  import { c as nip05RootKey, d as recordsFromWellKnown, f as recordsName, l as normalizeDomain, m as wellKnownUrl, n as decodeDnsResponse, o as encodeDnsQuery, p as txtValue, r as dnsProofName, s as isPublicAddress, t as DOMAIN_FILE_MAX_BYTES, u as recordsFromTxt } from "./domainProofs-BDNP1dIy.js";
4
4
  import { s as IdentityCheckUnavailable } from "./identityProofs-Cksc_K7_.js";
5
5
  import { sha256 } from "@noble/hashes/sha2.js";
@@ -967,4 +967,4 @@ async function verifiedAtprotoHandle(doc, options) {
967
967
  }
968
968
  export { normalizeAtprotoHandle as C, verifyAtprotoRecordProof as E, isAtprotoDid as S, AtprotoProofError as T, ATPROTO_PROOF_COLLECTION as _, verifiedAtprotoHandle as a, atprotoProofRkey as b, assertDomainRecord as c, chosenResolver as d, resolverById as f, ATPROTO_FULL_SCOPE as g, ATPROTO_DECLARED_SCOPE as h, resolveAtprotoHandle as i, assertNip05 as l, setPkarrRelaySource as m, plcDirectory as n, DOH_RESOLVERS as o, pkarrRelays as p, resolveAtprotoDid as r, DomainCheckError as s, assertPublicServer as t, assertPublicHost as u, ATPROTO_PROOF_SCOPE as v, shortAtprotoDid as w, checkAtprotoProofRecord as x, atprotoProofRecord as y };
969
969
 
970
- //# sourceMappingURL=resolve-CIc3KZMV.js.map
970
+ //# sourceMappingURL=resolve-B1upovPM.js.map