sigelo-contact 0.1.13 → 0.1.20

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 (51) hide show
  1. package/README.md +13 -10
  2. package/call.mjs +727 -0
  3. package/carrier.mjs +1204 -137
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +239 -43
  7. package/gen-carrier.mjs +4 -4
  8. package/gen-device.mjs +2 -2
  9. package/gen-envelope.mjs +3 -3
  10. package/gen-invite.mjs +3 -3
  11. package/gen-short.mjs +3 -3
  12. package/group.mjs +616 -0
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +24 -16
  16. package/package.json +49 -7
  17. package/page.mjs +1172 -70
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +125 -18
  20. package/prekeys.mjs +10 -2
  21. package/public.mjs +93 -0
  22. package/relays.mjs +1 -1
  23. package/restore.mjs +3 -3
  24. package/rtc-web.mjs +95 -0
  25. package/short.mjs +31 -3
  26. package/store.mjs +147 -12
  27. package/test-carrier.mjs +138 -21
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +157 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +413 -0
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +11 -8
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +169 -0
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +248 -0
  39. package/test-short.mjs +38 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +246 -0
  42. package/test-transfer.mjs +463 -0
  43. package/test-voice.mjs +158 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +800 -0
  46. package/transfer-node.mjs +449 -0
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +388 -0
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +65 -0
  51. package/words-lock.mjs +115 -0
package/carrier.mjs CHANGED
@@ -4,10 +4,17 @@
4
4
  // sees random topics and ciphertext; everything here that decides who someone is runs offline.
5
5
  //
6
6
  // const c = new Carrier({ identity, store, state, relay, endpoints, retentionDays, clock, onEvent, keep, transport, platform })
7
- // await c.invite({ name, ttl, short, relay, local }) → { code, did, relay, exp, short?, short_exp? } the answer topic is claimed first
7
+ // await c.invite({ name, ttl, short, relay, local, renew }) → { code, did, relay, exp, short?, short_exp?, renew? } the answer topic is claimed first
8
8
  // (local: at the next login, no session now);
9
9
  // short: the long code is also parked at the relay under a short one;
10
- // relay: the relay the code names and the short code is parked at (default: this agent's)
10
+ // relay: the relay the code names and the short code is parked at (default: this agent's);
11
+ // renew (with short): a one-person code that renews itself: once it is used, a fresh
12
+ // short code with the same name (numbered), ttl and relay is parked (store.mjs renew)
13
+ // await c.invitePublic({ name, ttl, cap, open, relay }) → { id, name, code: sgl2…, short: PUB-…, words, link, exp, relay, cap, open, did }:
14
+ // a public code (public.mjs, Pro only at the relay): many may use it, each a request
15
+ // (event public_request) approved by approvePublic(id) or refusePublic(id), or at
16
+ // once with open; setPublic(id|PUB code, { paused, cap }); cancelInvite(it): Revoke
17
+ // for all; publics() and contacts().publics: each with its requests waiting
11
18
  // await c.unpark(short, { relay }) → the long code parked under a short one, taken from the relay (one use);
12
19
  // relay: named, else relayForShort's (unparkFrom: { invite, relay })
13
20
  // await c.relayForShort(short, { relay }) → { relay, from }: where a short code is parked: 8 characters, shortRelay
@@ -16,13 +23,24 @@
16
23
  // await c.probeRelay(host) → { relay, ok, ms, retention_days, detail? }: does it answer (GET /relay.json, else /challenge)
17
24
  // await c.redeemGift(code) → { exp, months }: a gift code (PRO-K7F3-Q9ZP) redeemed at this agent's relay;
18
25
  // this identity is the operator whose pool is Pro until exp (relay/gifts.mjs)
19
- // await c.accept(code, { name, wait, relay }) → { status: 'connected' | 'waiting' | 'pending', … } a long code or a short one
26
+ // await c.accept(code, { name, wait, relay, words }) → { status: 'connected' | 'waiting' | 'waiting_approval' | 'pending', … } a long code, a short one,
27
+ // or a public one (PUB-…, its link, sgl2…; words: its page's four words, checked on the reply)
20
28
  // (refused after a short code was fetched: .long, keepLong); relay: where a
21
29
  // short code was parked, when not at this agent's relay (the inviter's --relay)
22
- // await c.cancelInvite(code) → { cancelled, name }: an unanswered invite of this agent's withdrawn
30
+ // await c.cancelInvite(code, { relay }) → { cancelled, name, short?, unparked?, detail? }: an unanswered invite of this agent's
31
+ // withdrawn, by its long code, its short code or the short code's hash; a short
32
+ // code parked is cancelled at the relay too (DELETE /park/<hash>, relay/park.mjs):
33
+ // unparked true once nobody can fetch it there, false with detail when the relay
34
+ // could not be told (an older relay, offline: it runs out there by itself, and an
35
+ // answer to it is refused here); a renewing code's series ends
23
36
  // c.rename(who, name) the owner's name for a contact (store.mjs rename) → { did, name }
24
- // c.contacts() → { contacts, invites, answers, failed } each contact with its four words (fingerprint),
25
- // pair id, chain, ours (an operator attestation of mine marks it), tier
37
+ // c.contacts() → { contacts, invites, answers, failed, renewing } invites: { name, exp, relay, short?, short_exp?, renew? },
38
+ // renewing: { id, name, used: [{ short, did, name, at }], error } per series;
39
+ // each contact with its four words (fingerprint),
40
+ // pair id, chain, ours (an operator attestation of mine marks it), tier, seen_upto
41
+ // (their newest seen receipt: my messages sealed at or before it were shown; null: none) and
42
+ // seen_peer (a receipt came: they read receipts), busy (their busy mark is on) and
43
+ // busy_peer (they take busy marks), tier
26
44
  // (store.mjs: own, friend, quiet) and tier_by, prekeys: its
27
45
  // bundle is here (false: messages wait for it), waiting: why they wait, or null;
28
46
  // failed: pairing_failed events (code_expired: an answer that outlived its code) until inbox
@@ -33,22 +51,47 @@
33
51
  // queued wait in files/.out (0600), the state names them; gone once sent or refused.
34
52
  // local (all three): no session, queued in the state file for a started carrier
35
53
  // of the same identity elsewhere (a watcher), which sends it at its next sync()
36
- // await c.inbox({ wait, tiers, local, paired }) → { messages, events, dropped, offline? }: all are taken (messages: those kept;
54
+ // await c.inbox({ wait, tiers, local, paired, from }) → { messages, events, dropped, offline? }: all are taken (messages: those kept;
37
55
  // tiers: only those from contacts of these tiers, the rest stay); local: no
38
56
  // session, the state file only (a started carrier elsewhere is connected);
39
- // paired: the wait also ends at a pairing (enrol.mjs)
57
+ // paired: the wait also ends at a pairing (enrol.mjs); from: that DID's only.
58
+ // The wait is the caller's: a session the relay ends early is logged in again
59
+ // at the pace backoff sets until then; ended: { code, detail, n }, the relay's
60
+ // last word when it ended one (n times) during this inbox
61
+ // Each message and file has an id (messageId), the same at every read
62
+ // await c.reply(id, content, { label, local }), c.replyFile(id, file, { local }) → as send, sendFile, to the sender of
63
+ // message id (kept RECEIVED_DAYS), with msg_id and delivery; c.replyStatus(id) →
64
+ // { msg_id, from, name, received, reply: { status: queued|published|refused, … } | null, fetched: null }
40
65
  // c.peek(), c.take(pick) the messages kept for inbox(), each with its sender's tier: read, or those
41
66
  // pick(message, tier) chooses taken; no session (a started carrier's owner)
42
67
  // c.history({ since }) → { messages }: what inbox() and take() gave out, again, from the local log
43
68
  // (`log`: x.inbox.log, pathsFor), received at or after since (unix seconds);
44
69
  // no session, nothing taken
45
70
  // c.setTier(who, tier) the owner's tier for a contact (store.mjs setTier) → { did, name, tier, ours }
71
+ // c.setPresence(who, allow) may that contact see whether this agent is online (store.mjs setPresence;
72
+ // off by default, own agents always) → { did, name, presence }; a started
73
+ // carrier applies it at once, another at its next round
46
74
  // c.presetTier(did, tier) the same for an original DID not yet a contact, filed when it pairs
47
75
  // c.takeLinks(), c.setLink(who, link) link.mjs's: the sigelo-link/1 messages received (never in inbox(), the log
48
76
  // or onEvent: a `link` event without content says one came), taken; a
49
77
  // contact's link record (store.mjs setLink)
78
+ // await c.seen(to, upto) a seen receipt (SEEN_LABEL, the header's "Seen receipts") to contact to: every message of
79
+ // theirs sealed at or before upto (their iat, unix seconds; 0: none yet) was shown → as send
80
+ // await c.busy(to, on, { local }) a busy mark (BUSY_LABEL, the header's "Busy marks") to contact to: on (a turn runs)
81
+ // or off → as send, or { status: 'skipped' } for a contact that never said it takes them
82
+ // await c.read(items, { local }) read marks: a seen receipt to each sender of these inbox items, once per message
83
+ // (own contacts always, others as the app does) → [{ to, upto, status | error }]
84
+ // c.takeGroups() group.mjs's: the sigelo-group/1 messages received (never in inbox(), the
85
+ // log or onEvent: a `group` event without content says one came), taken
86
+ // c.groupTier what this agent's relay told its last login of its group tier ($sigelo/notice
87
+ // "tier": { tier, groups: { max, members } }, event `group_tier`), or null
50
88
  // c.takeDevices() device.mjs's: the sigelo-device/1 messages received (never in inbox(), the
51
89
  // log or onEvent: a `device` event without content says one came), taken
90
+ // c.takeTransfers(), c.deliver(item) transfer-node.mjs's: the sigelo-transfer/0 messages received (never in inbox(),
91
+ // the log or onEvent: a `transfer` event without content says one came), taken;
92
+ // a file a transfer saved whole, as an inbox item (kept as #onFile keeps one)
93
+ // c.takeCalls() call.mjs's: the sigelo-call/0 messages received (never in inbox(), the log or
94
+ // onEvent: a `call` event without content says one came), taken
52
95
  // c.freshEpochs({ only, retire }) every session (or only's) afresh, as after a rotation (a snapshot's
53
96
  // state imported where the seat moved, devices.md §4.3) → the DIDs
54
97
  // c.answeredBy(nonce) the original DID that paired through this agent's code `nonce`, or null
@@ -61,6 +104,15 @@
61
104
  // c.lastError the error behind the last offline of inbox or forget (SIGELO_DEBUG)
62
105
  // c.clockOffset(), await c.checkClock() → { relay, offset, checked } | null: the relay's clock less this one's, seconds
63
106
  // await c.start(), c.sync(), c.stop() stay connected, reconnecting with backoff; events reach onEvent
107
+ // await c.tryNow({ confirmed }) the human's "Try now": a login at each relay in use not connected
108
+ // c.wake({ now }) a nudge from outside (the Android app's Stay connected: its alarm, the end of
109
+ // Doze): a started carrier retries, with its backoff, each relay in use that is
110
+ // down with no try already waiting; nothing else. now (a push wake): at once
111
+ // c.setPush(reg | null), c.pushStatus() the phone's UnifiedPush endpoint and keys registered at this agent's own relay
112
+ // (sigelo-push/0 on $sigelo/push, relay/push.mjs) at every login; null removes it
113
+ // started: 'user' | 'confirmed' (start, invite, accept, tryNow) a search the human started: past
114
+ // POW_SEARCHES a day it is never refused, it asks (pow_confirm),
115
+ // and 'confirmed' goes on; without it (automatic retries) the cap holds
64
116
  //
65
117
  // identity() → { sign, bundle }: the agent's signer for its current key (sign(body) → the SPEC §3
66
118
  // signature; sigelo-agent-keys.ts) and its SPEC §8 bundle, read again at every operation, so a
@@ -80,7 +132,7 @@
80
132
  // One connected carrier per identity: every process logs in with the identity's one MQTT client
81
133
  // id, so a second login takes the session from a started carrier (the files stay sound under the
82
134
  // lock; the started one reconnects with backoff). Beside one, use inbox and send with local: the
83
- // state file only (sigelo-agent's one-owner rule, adapters/moadim/WATCH.md).
135
+ // state file only (sigelo-agent's one-owner rule, apps/agent/WATCH.md).
84
136
  //
85
137
  // Transport (transport, or SIGELO_RELAY_TRANSPORT): "auto" (the default), 8883 for PROBE_MS, then
86
138
  // 443 for the rest of the process, so a network that lets only HTTPS out needs no setting; "mqtts",
@@ -191,6 +243,36 @@
191
243
  // hinted and proved again; asks for the same operators go at most every RESYNC. A contact
192
244
  // learns from the hints only which operator DIDs it guesses right (THREAT-MODEL §2.12). An
193
245
  // agent on an older version gets the hints as messages with that label. send refuses the label.
246
+ // - Seen receipts (label SEEN_LABEL, a message like any other, inside the envelope): {seen: n}, n the
247
+ // iat of the newest message of the contact's that the reader's app has shown (0: none yet). The
248
+ // sender reads its own messages sealed at or before n as seen. Taken here, never an inbox message,
249
+ // never logged; kept as the contact's seen_upto (the highest) and seen_peer (contacts()), with an
250
+ // event `seen`. The relay sees one more envelope, never which. Sent only through seen() (SEEN_SEND):
251
+ // what to send and when is the app's (apps/contact/page.mjs: one first receipt to a contact not
252
+ // known to read them, further ones only once one came back). A contact on an earlier version takes
253
+ // the first as a message with that label, and never sends one: its messages stay at one tick.
254
+ // Once paired, each side also sends one {seen: 0, name}: its display name (the "Names" below).
255
+ // Every receipt (the name's too) carries busy: true: this side takes busy marks (below).
256
+ // - Busy marks (label BUSY_LABEL, inside the envelope; 2026-11-19): {busy: true|false}, a hosted agent's "I am
257
+ // working on it" (sigelo-agent-host.ts): on at a turn's start and every 20 s while it runs, off before its reply.
258
+ // Taken here, never an inbox message, never logged, never an event `message`: the contact's busy_until (now +
259
+ // BUSY_TTL_S, 0 for off; any message or file of theirs ends it too), contacts() busy, an event `busy`. Sent
260
+ // only through busy() (BUSY_SEND), with expires now + BUSY_TTL_S (a stale one goes unsent), and only to a
261
+ // contact whose receipt said busy: true (busy_peer): an earlier version would show it as a message.
262
+ // - Presence (design/transfer.md §8 T0): a started carrier sets the will $sigelo/presence on its
263
+ // CONNECT and publishes, to each contact that may see it (store.mjs presenceOf: own agents
264
+ // always, others when the owner allowed them), one marker on presenceTopic(K, own original DID,
265
+ // contact's): a kind 6 frame under presenceKey(K, …), {v: "sigelo-presence/0", state: "online",
266
+ // since}. The relay (relay/presence.mjs) holds it, sends it at once to whoever subscribes, and
267
+ // replaces it with its own {"presence": "offline", "at"} when that session ends. A marker toward a
268
+ // contact no longer allowed is cleared (an empty publish, st.presence_out). Sealed by the
269
+ // pairing key, not as an envelope: an envelope is read once (its counter, its replay window), a
270
+ // marker again at every subscribe, and the relay's offline is written after the writer is gone;
271
+ // not signed, so a reader cannot show anyone else when this agent was online. A started
272
+ // carrier subscribes, at QoS 0, to each contact's marker toward it (a short session does not:
273
+ // it would forget it at once, and the subscribes draw on the relay's brake); what it reads is st.presence, which
274
+ // contacts() reports as online, online_since, last_seen, and forgets when the connection to that
275
+ // relay closes (a marker read is true only while the reader is connected).
194
276
  // - Mailboxes: an agent holds the topics of every ISO week from `retention` ago to AHEAD (7 days,
195
277
  // or its retention if shorter) ahead. The relay drops a publish to a topic nobody claimed (and
196
278
  // says no_reader), so next week's topic must be claimed before a contact writes in it while
@@ -218,11 +300,12 @@ import { sha256 } from '@noble/hashes/sha2.js';
218
300
  import { concatBytes, hexToBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
219
301
  import { canonicalize, commitmentOf, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
220
302
  import { KIND, acceptPrekeys, expire, header, open, pad, prekeysMissing, restartEpoch, send, session, unpad } from './envelope.mjs';
221
- import { answerId, buildAnswer, buildReply, checkAnswer, checkReply, checkRelay, inviteKeys, keyOf, makeInvite, parseInvite } from './invite.mjs';
303
+ import { PUBLIC_VERSION, admitAnswer, answerId, buildAnswer, buildReply, checkAnswer, checkReply, checkRelay, inviteKeys, keyOf, makeInvite, parseInvite, parsePublicCode, screenAnswer } from './invite.mjs';
304
+ import { PUBLIC_CAP, PUBLIC_TTL_MAX, REQUEST_TTL, SEEN_KEEP, checkCap, formatPub, isPub, joinerKeys, normalisePub, normaliseWords, publicHash, publicKeys, publicLink, readLink } from './public.mjs';
222
305
  import { MsgError, checkNow, fail, hex, isoWeek, pairId, signAs, topic } from './kdf.mjs';
223
306
  import { Prekeys, exact, kemDecapsulate, kemEncapsulate, kemKey } from './prekeys.mjs';
224
307
  import { Contacts, OPERATOR_CTX, TIERS } from './store.mjs';
225
- import { SHORT_TTL, codeHash, codeKind, fingerprint, formatShort, giftHash, makeShort, normaliseShort, relayTag, tagOf } from './short.mjs';
308
+ import { ENROL_TTL_MAX, SHORT_TTL, SHORT_TTL_MAX, SHORT_TTL_MIN, codeHash, codeKind, didWords, fingerprint, formatShort, giftHash, isEnrolCode, makeShort, normaliseShort, relayTag, stripEnrol, tagOf } from './short.mjs';
226
309
  import { REGISTRY_URL, RELEASE_DID, loadRegistry, readTable, remember, resolveTag } from './relays.mjs';
227
310
  import { FILE_LABEL, MAX_FILE, assemble, checkChunk, checkManifest, chunkHead, isManifest, safeName, splitFile } from './file.mjs';
228
311
  // Every file, lock, network and CPU call goes through a platform (design/apps.md §4.2): Node's by default.
@@ -239,6 +322,8 @@ export const OPERATOR_LABEL = 'sigelo-operator/0';
239
322
  export const LOGIN_V = 'sigelo-relay/0', TYP_LOGIN = 'relay-login';
240
323
  // RETENTION_DAYS: the relay's free tier (relay/allowance.mjs TIERS.free), when relay.json says nothing.
241
324
  export const RETENTION_DAYS = 14, RETENTION_MAX_DAYS = 90, DAY = 86400, SKEW = 300, AHEAD = 7 * DAY;
325
+ // Seconds before a renewing code that failed to renew is tried again (#renewDue).
326
+ export const RENEW_RETRY = 60;
242
327
  // The relay closes a connection whose SUBSCRIBE holds more topics (relay/mailbox.mjs MAX_TOPICS).
243
328
  const MAX_TOPICS = 128;
244
329
  // An invite topic holds 4 messages and 64 KB (relay/mailbox.mjs INVITE_BYTES); a bundle at most 64
@@ -251,17 +336,25 @@ export const INVITE_BYTES = 64 * 1024, MAX_ROTATIONS = 64;
251
336
  // one per rotation, and again at most hourly), and the last REFUSED_NOTICES refused after that
252
337
  // check are refused again unchecked (#onContactNotice).
253
338
  export const NOTICE_CHECKS = 4, REFUSED_NOTICES = 16;
254
- // A proof of work must be sent within the challenge's 300 s. Node on a phone-class ARM64 CPU
255
- // hashes ~180,000 a second (measured 2026-10-07): 22 bits take 23 s on average, 24 bits 92 s, 26
256
- // bits 6 minutes. A relay asking more than POW_MAX is refused rather than spun for, and the search
257
- // stops at POW_MS, before the challenge expires. Any host can be named by a stranger's code, so a
258
- // relay other than this agent's own (SIGELO_RELAY) gets the plan's normal 22 bits at most.
259
- export const POW_MAX = 26, POW_MAX_OTHER = 22, POW_MS = 280000;
339
+ // A proof of work (relay/pow.mjs, sigelo-relay-pow/1: Argon2id) must be sent within the
340
+ // challenge's 300 s. One evaluation at 64 MiB, 3 passes takes POW_EVAL_MS on a phone-class ARM64
341
+ // CPU (hash-wasm in Node or a Worker, a big core; measured 2026-11-13; 1.64 s on a little core):
342
+ // 6 bits take 31 s on average, 8 bits 2 minutes, 10 bits 8. A relay asking more than POW_MAX is
343
+ // refused rather than spun for, and the search stops at POW_MS, before the challenge expires. Any
344
+ // host can be named by a stranger's code, so a relay other than this agent's own (SIGELO_RELAY)
345
+ // gets the plan's normal 6 bits at most. POW_COST: the most a relay may ask one evaluation to cost
346
+ // (GET /challenge's `pow`); a cheaper one is computed as stated (it costs the relay only).
347
+ export const POW_MAX = 10, POW_MAX_OTHER = 6, POW_MS = 280000, POW_EVAL_MS = 485;
348
+ export const POW_V = 1, POW_COST = Object.freeze({ m: 65536, t: 3, p: 1 });
260
349
  // Searches at one relay in any 24 hours, each counted in the state file as it begins, found or not.
261
350
  // An honest relay asks once per identity, and again only if it forgot it. Without a count, a relay
262
351
  // that grants a proven login, closes, then refuses the next login's SUBSCRIBE `pow` had this client
263
352
  // search again at each reconnection, without end: success reset every other bound.
353
+ // The cap is for this client's AUTOMATIC retries only (design/profiles.md §6): a search the human
354
+ // started (`started: 'user'`) past it answers pow_confirm, and one confirmed (`'confirmed'`) goes.
264
355
  export const POW_SEARCHES = 3;
356
+ const ORDINAL = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth'];
357
+ const hhmmUtc = (t) => new Date(t * 1000).toISOString().slice(11, 16);
265
358
  // A delivery this process failed on this many times, its files sound each time, is dropped.
266
359
  const POISON_TRIES = 3;
267
360
  // Events kept for the next inbox(): pairings, rotations, failed pairings. The oldest go first.
@@ -271,17 +364,62 @@ const EVENTS_MAX = 1000, INBOX_MAX = 1000;
271
364
  // newest is kept whatever its size). Labels it never holds: enrolment's, one of which carries a key,
272
365
  // devices', and links' (a live invite code).
273
366
  export const LOG_MAX = 500, LOG_BYTES = 4 * 1024 * 1024;
274
- // Labels whose messages carry keys, device material or a live code (enrol, device, link): never logged.
275
- export const UNLOGGED = /^sigelo-(identity|enrol|device|link)\//;
367
+ // Labels whose messages carry keys, device material or a live code (enrol, device, link), and busy marks: never logged.
368
+ export const UNLOGGED = /^sigelo-(identity|enrol|device|link|transfer|busy)\//;
276
369
  // Links (link.mjs, sigelo-link/1): never an inbox message. Kept apart in the state (st.links, at most
277
370
  // LINKS_MAX, the oldest go) for link.mjs handle(), which takeLinks() them; sent only by link.mjs
278
371
  // (send's internal: LINK_SEND), so a caller's label (an MCP client's, a model's) cannot forge one.
279
372
  export const LINK_LABEL = 'sigelo-link/1', LINK_SEND = Symbol('sigelo-link send');
280
373
  const LINKS_MAX = 64;
374
+ // Groups (group.mjs, sigelo-group/1): the same, kept apart in st.groups (at most GROUPS_MAX) for
375
+ // group.mjs handle(), which checks the sender's inner signature and the roster; sent only with GROUP_SEND.
376
+ export const GROUP_LABEL = 'sigelo-group/1', GROUP_SEND = Symbol('sigelo-group send');
377
+ const GROUPS_MAX = 256;
281
378
  // Devices (device.mjs, sigelo-device/1): the same, kept apart in st.devices for sigelo-agent's
282
379
  // `device` verbs (takeDevices); sent only with DEVICE_SEND: one carries the operator's keys.
283
380
  export const DEVICE_LABEL = 'sigelo-device/1', DEVICE_SEND = Symbol('sigelo-device send');
284
381
  const DEVICES_MAX = 16;
382
+ // Transfers (transfer.mjs, sigelo-transfer/0): the introduction of a big file, sent direct or over Tor
383
+ // (design/transfer.md §3). The same: kept apart in st.transfers (at most TRANSFERS_MAX) for the transfer
384
+ // engine, never logged (an offer carries addresses, an onion message a client key); sent only with TRANSFER_SEND.
385
+ export const TRANSFER_LABEL = 'sigelo-transfer/0', TRANSFER_SEND = Symbol('sigelo-transfer send');
386
+ const TRANSFERS_MAX = 256;
387
+ // Calls (call.mjs, sigelo-call/0; design/calls.md §2): the signalling of a voice call. The same: kept apart in st.calls
388
+ // (at most CALLS_MAX) for the page's Line (page.mjs) or watch's answer, never logged (an offer carries addresses); sent
389
+ // only with CALL_SEND.
390
+ export const CALL_LABEL = 'sigelo-call/0', CALL_SEND = Symbol('sigelo-call send');
391
+ const CALLS_MAX = 64;
392
+ // Seen receipts (the header's): sent only with SEEN_SEND, never an inbox message.
393
+ export const SEEN_LABEL = 'sigelo-seen/0', SEEN_SEND = Symbol('sigelo-seen send');
394
+ // UnifiedPush (design/push.md, relay/push.mjs): the phone's endpoint and keys, registered with this agent's own
395
+ // relay over its session (setPush), where GET /challenge says the relay takes them.
396
+ export const PUSH_TOPIC = '$sigelo/push', PUSH_V = 'sigelo-push/0';
397
+ // Busy marks (the header's): sent only with BUSY_SEND, never an inbox message; one is good for BUSY_TTL_S seconds.
398
+ export const BUSY_LABEL = 'sigelo-busy/0', BUSY_SEND = Symbol('sigelo-busy send'), BUSY_TTL_S = 45;
399
+ // Names (0.1.17: "the system allocated some random text" for a new contact). Once paired, each side tells the other its
400
+ // display name (selfName) in a seen receipt {seen: 0, name}: an existing message older clients take as a receipt and
401
+ // whose extra member they ignore (no new label, no new typ). The receiver files the contact under it only while the
402
+ // contact's name was made up here (name_from "auto": an unnamed invite or accept, a public code's) or came from them
403
+ // before; a name the human gave or changed is never replaced. The name: at most THEIR_NAME_MAX characters, trimmed, no
404
+ // control or bidi characters, else ignored; one another contact holds gets " (2)", " (3)"….
405
+ export const THEIR_NAME_MAX = 40;
406
+ // Replies (0.1.17: "reply to messages"): a message that answers one names it in its label, re/<h>/<s|r>, h the first 16
407
+ // hex of SHA-256 over the quoted text, s when the sender quotes its own message, r the recipient's. The envelope's body is
408
+ // exact (envelope.mjs BODY): no member can be added, and a label is free text an older client shows as a tag. Each side
409
+ // finds the quoted message among its own by its text and its author; inbox() gives it as re: {sha, by: me | them}.
410
+ export const RE_LABEL = /^re\/([0-9a-f]{16})\/([sr])$/;
411
+ export const quoteHash = (text) => hex(sha256(utf8ToBytes(String(text)))).slice(0, 16);
412
+ /** The label of a reply to `text`, own: the sender's own message, else the recipient's. */
413
+ export const reLabel = (text, own) => `re/${quoteHash(text)}/${own ? 's' : 'r'}`;
414
+ /** A received message's label read as a reply: { sha, by: "them" (its sender quoted its own) | "me" }, or null. */
415
+ export const reOf = (label) => { const m = RE_LABEL.exec(typeof label === 'string' ? label : ''); return m ? { sha: m[1], by: m[2] === 's' ? 'them' : 'me' } : null; };
416
+ const NAME_BAD = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
417
+ /** A name as a peer sent it, for display: trimmed, control and bidi characters dropped, at most THEIR_NAME_MAX; else null. */
418
+ export function theirName(v) {
419
+ if (typeof v !== 'string') return null;
420
+ const t = [...v.replace(NAME_BAD, '').trim()].slice(0, THEIR_NAME_MAX).join('').trim();
421
+ return t === '' ? null : t;
422
+ }
285
423
  // Received files of one name and hash prefix kept side by side, at most (#onFile).
286
424
  const FILE_COPIES = 64;
287
425
  // A contact's folder of received files: its name as safeName keeps it, and 16 hex digits of the
@@ -312,17 +450,25 @@ const TICK = 3600 * 1000, BACKOFF = [1000, 60000];
312
450
  // A connection that held this long resets the backoff when it closes; a shorter one does not, so a
313
451
  // relay that accepts and closes at once is dialled ever more slowly, as one that refuses is.
314
452
  const STABLE_MS = 60000;
453
+ // A session the relay ended itself (its notice session_*: relay/auth.mjs endWith), or a login it
454
+ // turned away (rate, relay_full): the next session waits backoff[0], 2 × that, … up to backoff[1] ms
455
+ // after it (BACKOFF by default: 1 s … 60 s), kept in the state (st.relays[relay].ended) so a new process waits too (0.1.17: a
456
+ // temporary identity cut by the relay logged in again at once, 30 times a minute, until the rate
457
+ // refused it). Reset by a session this client ends itself, or one the relay held ENDED_LASTS ms.
458
+ const ENDED_LASTS = 300000;
459
+ const ENDED_RETRY = new Set(['rate', 'relay_full', 'connect', 'timeout']);
315
460
  // Login refusals no retry can fix.
316
- const PERMANENT = new Set(['password', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'challenge', 'relay', 'identity']);
461
+ const PERMANENT = new Set(['password', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'challenge', 'relay', 'identity', 'client_old']);
317
462
  // A refusal by one of these is this process failing, not a message: the delivery is not acknowledged.
318
463
  const INTERNAL = new Set(['lock', 'state', 'store', 'identity', 'time']);
319
464
  // The login checks relay/auth.mjs names on POST /check. Any other word from the relay is `connect`:
320
465
  // a check name decides what this client does next, so a relay cannot pick one.
321
- const LOGIN_CHECKS = new Set(['rate', 'password', 'challenge_unknown', 'challenge_expired', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'pow', 'relay_full']);
466
+ // client_old: a client of the dropped SHA-256 proof of work (relay/pow.mjs CLIENT_OLD); this one never is.
467
+ const LOGIN_CHECKS = new Set(['rate', 'password', 'challenge_unknown', 'challenge_expired', 'bundle', 'sig', 'retired_recovery', 'client_id', 'closed', 'pow', 'relay_full', 'client_old']);
322
468
  // Refusals of an invite reply that a later round may get past: the reply stays queued.
323
469
  const REPLY_RETRY = new Set(['rate', 'relay_full', 'quota_messages']);
324
470
  // $sigelo/notice codes that refuse the publish, or the SUBSCRIBE, in flight (relay-plan §3 "Errors").
325
- const PUBLISH_CODES = new Set(['too_large', 'quota_storage', 'quota_messages', 'rate', 'relay_full', 'pow', 'no_reader']);
471
+ const PUBLISH_CODES = new Set(['push', 'too_large', 'quota_storage', 'quota_messages', 'rate', 'relay_full', 'pow', 'no_reader', 'presence_taken', 'presence_will', 'presence_full', 'public_cap', 'public_paused', 'public_revoked', 'public_once']);
326
472
  // A contact's envelope this agent cannot open for want of its epoch asks the writer for a new epoch
327
473
  // by a fresh prekey bundle (RESYNC_CHECKS), at most once in this many seconds per contact after
328
474
  // the last such bundle: the check comes before any decryption, so a relay can make one up. A
@@ -375,6 +521,35 @@ const sameBytes = (a, b) => { if (a.length !== b.length) return false; for (let
375
521
  const utf8 = new TextDecoder('utf-8', { ignoreBOM: true });
376
522
  const textOf = (bytes) => utf8.decode(bytes);
377
523
  const randomId = () => hex(randomBytes(8));
524
+
525
+ // The message id (the agent task loop: a hook's SIGELO_MSG_ID, `reply --to`, MCP sigelo_reply): the
526
+ // same for one message wherever and however often it is read. A message: hex of the first 16 bytes of
527
+ // SHA-256 of the lines "sigelo-msg-id/0", the sender's original DID, the epoch id (hex) and the
528
+ // message number, both from the envelope's header (envelope.mjs "Layout"), which no two envelopes of
529
+ // one sender share. A file: of "sigelo-msg-id/0 file", the sender, the file's id (file.mjs). An item
530
+ // kept by an earlier version has none: then of "sigelo-msg-id/0 item" and the canonical JSON of what
531
+ // it holds {from, iat, received, label, content, path}, which do not change while it waits. Nothing
532
+ // of it goes on the wire.
533
+ export const MSG_ID = /^[0-9a-f]{32}$/;
534
+ const idOf = (...parts) => hex(sha256(utf8ToBytes(parts.join('\n'))).subarray(0, 16));
535
+ export function messageId(m) {
536
+ if (typeof m?.id === 'string' && MSG_ID.test(m.id)) return m.id;
537
+ const held = { from: m?.from ?? null, iat: m?.iat ?? null, received: m?.received ?? null, label: m?.label ?? null, content: m?.content ?? null, path: m?.path ?? null };
538
+ let text;
539
+ try { text = canonicalize(held); } catch { text = JSON.stringify(held); }
540
+ return idOf('sigelo-msg-id/0 item', text);
541
+ }
542
+ // What a reply needs of a message received (reply, replyStatus): its sender and when, and the last
543
+ // reply's ids and state, in the state file, RECEIVED_DAYS at most and the newest RECEIVED_MAX.
544
+ export const RECEIVED_DAYS = 30, RECEIVED_MAX = 2048;
545
+ function received(st, id, from, now) {
546
+ const r = (st.received ??= {});
547
+ r[id] ??= { from, ts: now };
548
+ for (const [k, v] of Object.entries(r)) if (!(v.ts > now - RECEIVED_DAYS * DAY)) delete r[k];
549
+ const keys = Object.keys(r);
550
+ if (keys.length > RECEIVED_MAX) for (const k of keys.sort((a, b) => r[a].ts - r[b].ts).slice(0, keys.length - RECEIVED_MAX)) delete r[k];
551
+ return r[id];
552
+ }
378
553
  const clientIdOf = (original) => 's' + hex(sha256(utf8ToBytes(original))).slice(0, 24);
379
554
  // Operators as hinted and proved: each with its attestation's expiry, so a renewal goes again.
380
555
  const opKey = (mine, ops) => [...ops].sort().map((d) => `${d} ${mine.exp.get(d)}`).join();
@@ -387,7 +562,15 @@ const theirPrekeys = (c, d, pair, now) => {
387
562
  // The four words of a pairing (short.mjs), from its pairing key as the store holds it (hex), or null.
388
563
  const wordsOf = (pairKey) => (typeof pairKey === 'string' ? fingerprint(pairId(hexToBytes(pairKey))) : null);
389
564
  // The refusals of POST /park this client names (relay/park.mjs, and the login's: auth.mjs).
390
- const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', ...LOGIN_CHECKS]);
565
+ const PARK_CHECKS = new Set(['park', 'park_taken', 'park_full', 'pow', 'public_pro', 'public_full', 'public_topic', ...LOGIN_CHECKS]);
566
+ // An accept's reply topic and key: a public code's are the joiner's own (public.mjs joinerKeys), else the code's.
567
+ const replyOf = (id, p) => (p.public ? joinerKeys(hexToBytes(p.secret), id) : inviteKeys(hexToBytes(p.secret)));
568
+ // An accept's answer topic: a public code's mailbox, else the code's invite topic.
569
+ const answerTopicOf = (p) => (p.public ? publicKeys(hexToBytes(p.secret)).answer_topic : inviteKeys(hexToBytes(p.secret)).answer_topic);
570
+ // A public code's state as contacts() and the page show it (requests without the answers they hold).
571
+ const publicView = (nonce, p, now) => ({ id: nonce, name: p.name, short: p.short, words: p.words, link: p.short ? publicLink(p.short, p.words) : null, exp: p.exp, relay: p.relay,
572
+ cap: p.cap, open: p.open, paused: p.paused, today: p.day === Math.floor(now / DAY) ? p.n : 0, chats: p.chats,
573
+ requests: Object.values(p.requests).map(({ id, did, current_did, words, received, exp }) => ({ id, did, current_did, words, received, exp })) });
391
574
  // The refusals of POST /gift this client names (relay/gifts.mjs, allowance.mjs, operator.mjs, and the login's).
392
575
  const GIFT_CHECKS = new Set(['gift', 'gift_member', 'gift_term', 'pow', ...LOGIN_CHECKS]);
393
576
 
@@ -552,6 +735,10 @@ export const operatorHint = (K, kind, from, op) => hex(hmac(sha256, K, utf8ToByt
552
735
  export const noticeKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-notice/0'), utf8ToBytes(`${from}\n${to}`), 32);
553
736
  /** The prekeys frame's key: HKDF-SHA256(K, salt "sigelo-prekeys/0", info = from ‖ "\n" ‖ to), original DIDs. */
554
737
  export const prekeysKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-prekeys/0'), utf8ToBytes(`${from}\n${to}`), 32);
738
+ /** Presence (the header's "Presence"): the topic from → to, and its marker's key; original DIDs. */
739
+ export const KIND_PRESENCE = 6, PRESENCE_V = 'sigelo-presence/0', PRESENCE_WILL = '$sigelo/presence';
740
+ export const presenceTopic = (K, from, to) => 'p/' + hex(hkdf(sha256, K, utf8ToBytes('sigelo-presence/0'), utf8ToBytes(`${from}\n${to}`), 16));
741
+ export const presenceKey = (K, from, to) => hkdf(sha256, K, utf8ToBytes('sigelo-presence-key/0'), utf8ToBytes(`${from}\n${to}`), 32);
555
742
 
556
743
  /** A kind 1, 2, 4 or 5 frame (the header's "Frames"). rng(24) gives the nonce: a parameter so a test fixes every byte. */
557
744
  export function seal(kind, key, t, value, rng = randomBytes) {
@@ -635,14 +822,27 @@ function recovers(c, bundle, fresh) {
635
822
  // ---------------------------------------------------------------- relay login (plan §3 "Login")
636
823
 
637
824
  /**
638
- * The first c (0, 1, 2, …) with SHA-256("sigelo-relay-pow/0\n" ‖ host ‖ original DID ‖ nonce ‖ c)
639
- * starting with `bits` zero bits (relay-plan §3 "Proof of work"), or null once Date.now() passes
640
- * `deadline`. pow: the platform's search (Node's yields to the event loop every 4,096 hashes, about
641
- * 20 ms on a phone, so the process's connections, keepalives and other identities carry on during
642
- * a search of minutes).
825
+ * GET /challenge's `pow` → its cost { m, t, p } when this client computes it: {v: 1, alg:
826
+ * "argon2id", m, t, p} with these keys only, 1 lane, and m (KiB) and t within POW_COST; else null.
827
+ */
828
+ export function powCost(fn) {
829
+ if (!exact(fn, ['v', 'alg', 'm', 't', 'p']) || fn.v !== POW_V || fn.alg !== 'argon2id' || fn.p !== 1) return null;
830
+ if (!Number.isInteger(fn.m) || fn.m < 8 || fn.m > POW_COST.m || !Number.isInteger(fn.t) || fn.t < 1 || fn.t > POW_COST.t) return null;
831
+ return { m: fn.m, t: fn.t, p: 1 };
832
+ }
833
+
834
+ /**
835
+ * The first c (0, 1, 2, …) with Argon2id(password = "sigelo-relay-pow/1\n" ‖ host ‖ original DID ‖
836
+ * nonce ‖ c, salt = SHA-256(nonce) cut to 16 bytes; cost's m KiB, t passes, 1 lane; 32 bytes)
837
+ * starting with `bits` zero bits (relay-plan §3 "Proof of work", relay/pow.mjs), or null once
838
+ * Date.now() passes `deadline`. 0 bits: "0", nothing evaluated. pow: the platform's search (Node's
839
+ * yields to the event loop after each evaluation, ~0.5 s on a phone, so the process's connections,
840
+ * keepalives and other identities carry on during a search of minutes); cost: powCost's.
643
841
  */
644
- export function solvePow(host, original, nonce, bits, deadline = Infinity, pow = nodePlatform.pow) {
645
- return pow(`sigelo-relay-pow/0\n${host}${original}${nonce}`, bits, { deadline });
842
+ export function solvePow(host, original, nonce, bits, deadline = Infinity, pow = nodePlatform.pow, cost = POW_COST, onProgress = undefined) {
843
+ if (bits === 0) return Promise.resolve('0');
844
+ const salt = sha256(utf8ToBytes(nonce)).subarray(0, 16);
845
+ return pow({ prefix: `sigelo-relay-pow/1\n${host}${original}${nonce}`, salt, ...cost }, bits, { deadline, ...(onProgress && { onProgress }) });
646
846
  }
647
847
 
648
848
  // The answer body is read as it arrives and cut off past HTTP_MAX, whatever Content-Length says:
@@ -704,7 +904,7 @@ const statusWhy = (r, what) => `the relay answered ${r.status} to ${what}${r.sta
704
904
  * is refused saying how the input was read, so a mistyped short code never reads "does not
705
905
  * start with sgl1". */
706
906
  export function readCode(text, now, how = 'long') {
707
- try { return parseInvite(text, now); } catch (e) {
907
+ try { return typeof text === 'string' && text.startsWith('sgl2') ? parsePublicCode(text, now) : parseInvite(text, now); } catch (e) {
708
908
  if (!(e instanceof MsgError) || !['code_checksum', 'code_length', 'code_version'].includes(e.check)) throw e;
709
909
  const as = how === 'parked' ? 'the long code the relay holds for this short code does not parse; ask the inviter for a new one'
710
910
  : `read as a long code (it starts sgl1, or has more than 12 characters; a short code has 8, like K7F3-Q9ZP, or 12): ${reason(e)}`;
@@ -725,6 +925,14 @@ export function keepLong(e, long) {
725
925
  // Whose quota a quota_storage refusal is (relay/allowance.mjs `side`), in this client's words: a
726
926
  // contact whose own queue is full, or whose operator's Pro lapsed, must not read as a broken relay.
727
927
  const QUOTA_SIDES = new Set(['reader', 'sender', 'relay']);
928
+ // The relay's "tier" notice (relay/allowance.mjs): {tier: free | pro, groups: {max, members}}, whole
929
+ // numbers within what a roster can hold (group.mjs LIMITS.pro.members), else ignored. → {tier, groups} | null.
930
+ const GROUP_MEMBERS_MAX = 64, GROUPS_TOLD_MAX = 10000;
931
+ export function groupTierOf(n) {
932
+ const g = n?.groups, whole = (x, lo, hi) => Number.isSafeInteger(x) && x >= lo && x <= hi;
933
+ if ((n?.tier !== 'free' && n?.tier !== 'pro') || g === null || typeof g !== 'object' || !whole(g.max, 0, GROUPS_TOLD_MAX) || !whole(g.members, 2, GROUP_MEMBERS_MAX)) return null;
934
+ return { tier: n.tier, groups: { max: g.max, members: g.members } };
935
+ }
728
936
  const quotaWhy = (r, name) => (r.code !== 'quota_storage' ? null
729
937
  : r.side === 'reader' ? `${name}'s side is over its storage quota (its queue is full, or its operator's Pro lapsed): nothing is wrong with your relay or your allowance; send again once ${name}'s agent has collected its messages (${relaySays(r.detail)})`
730
938
  : r.side === 'sender' ? `your network has used its share of this relay's free storage: send again once messages are collected or expire (${relaySays(r.detail)})` : null);
@@ -742,7 +950,7 @@ const rePairWhy = (c) => (c.re_pair === 'contact_recovery'
742
950
  // (`accept --name`): then that name. The inviter's `invite --name` names a new contact only: the
743
951
  // code may be answered by anyone, and a re-key code's name is the contact's own. → the contact.
744
952
  function renamed(store, c, entry) {
745
- if (entry.named === true && c.name !== entry.name) { c.name = entry.name; store.save(); }
953
+ if (entry.named === true && c.name !== entry.name) { c.name = store.freeName(entry.name, c.did); store.save(); }
746
954
  return c;
747
955
  }
748
956
 
@@ -814,10 +1022,12 @@ export function limitPackets(stream, max, cut) {
814
1022
 
815
1023
  // url: mqtts://, or wss:// (MQTT over WebSocket: through the HTTPS proxy when one applies, platform-node.mjs proxyFor;
816
1024
  // a frame over the largest packet, its fixed header included, refused by ws before it is held).
1025
+ // creds.will: the presence will of a started carrier (the header's "Presence").
817
1026
  function mqttConnect(platform, url, creds, link, onPacket, timeout = CONNECT_MS) {
818
1027
  return new Promise((resolve, reject) => {
819
1028
  const client = platform.mqtt(url, { protocolVersion: 4, clean: false, clientId: creds.clientId, username: creds.username, password: creds.password,
820
- reconnectPeriod: 0, connectTimeout: timeout, keepalive: 60, resubscribe: false, wsOptions: { maxPayload: MAX_PACKET + 5, perMessageDeflate: false } });
1029
+ reconnectPeriod: 0, connectTimeout: timeout, keepalive: 60, resubscribe: false, wsOptions: { maxPayload: MAX_PACKET + 5, perMessageDeflate: false },
1030
+ ...(creds.will && { will: creds.will }) });
821
1031
  link.client = client;
822
1032
  // connect() has built the socket and nothing has arrived yet. The cut is permanent at a relay
823
1033
  // other than this agent's own (#retry, accept): it would send the same packet again.
@@ -864,6 +1074,10 @@ class Link {
864
1074
  this.collect = null; this.lastIn = 0; this.since = Date.now(); this.tokens = RATE.burst; this.at = Date.now(); this.pow = false; this.closing = false;
865
1075
  this.abort = null; // rejects the PUBLISH or SUBSCRIBE in flight when the connection closes
866
1076
  this.cut = null; // the MsgError of limitPackets, once it cut the connection
1077
+ this.ended = null; // the relay's notice before it ended this session ({ code, detail }: relay/auth.mjs endWith)
1078
+ // Presence: the contacts' marker topics subscribed on this connection; this agent's markers
1079
+ // published on it (topic → its contact); when it connected (a marker's since); the will set.
1080
+ this.presenceIn = new Set(); this.presenceOut = new Map(); this.onlineAt = 0; this.will = false;
867
1081
  }
868
1082
  // Nothing delivered for QUIET ms since connecting: the relay's queue for this agent is drained.
869
1083
  get quiet() { return Date.now() - Math.max(this.lastIn, this.since) >= QUIET; }
@@ -885,12 +1099,21 @@ class Link {
885
1099
  export class Carrier {
886
1100
  #links = new Map(); #work = Promise.resolve(); #busy = 0; #lastWork = 0; #routes = new Map(); #results = new Map();
887
1101
  #claimed = new Set(); #refusedTopics = new Map(); #handshakes = new Map(); #soon = new Set();
888
- #started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #ask = false;
889
- #mineMemo = null; #clocks = new Map();
1102
+ #renewing = false;
1103
+ #started = false; #tick = null; #timers = new Map(); #attempts = new Map(); #connecting = new Set(); #powFails = new Map(); #powWaits = new Set(); #ask = false; #spare = new Map();
1104
+ #push = undefined; #pushState = { state: 'none' }; // setPush: undefined = never set (nothing sent), null = off
1105
+ #mineMemo = null; #clocks = new Map(); #selfName = () => null;
890
1106
 
891
1107
  constructor({ identity, store, state, relay = DEFAULT_RELAY, endpoints = {}, retentionDays, clock = () => Math.floor(Date.now() / 1000),
892
1108
  onEvent, keep, backoff = BACKOFF, tick = TICK, files, log, transport = 'auto', shortRelay = DEFAULT_RELAY, registry = REGISTRY_URL, registryPin = RELEASE_DID, relays, registryFile,
893
- platform = nodePlatform }) {
1109
+ platform = nodePlatform, selfName = null, enrolHash = null }) {
1110
+ // enrolHash: the enrolment code this (temporary) identity holds, as its park hash: its first login asks
1111
+ // GET /challenge?…&enrol=<hash>, and a relay states the base proof of work for it (relay/park.mjs enrolGrace).
1112
+ if (enrolHash !== null && !(typeof enrolHash === 'string' && /^[0-9a-f]{64}$/.test(enrolHash))) throw new TypeError('enrolHash: 64 hex (short.mjs codeHash), or null');
1113
+ this.enrolHash = enrolHash;
1114
+ // This side's display name, told to each new contact once paired (the header's "Names"): a string or a function → one, or null.
1115
+ if (selfName !== null && typeof selfName !== 'string' && typeof selfName !== 'function') throw new TypeError('selfName: a string, a function → a string or null, or null');
1116
+ this.#selfName = typeof selfName === 'function' ? selfName : () => selfName;
894
1117
  if (!TRANSPORTS.includes(transport)) throw new TypeError(`transport: ${TRANSPORTS.join(', ')}`);
895
1118
  // The platform (design/apps.md §4.2, platform-node.mjs): files, lock, network, proof of work.
896
1119
  if (typeof platform?.files?.read !== 'function' || typeof platform.transact !== 'function' || typeof platform.fetch !== 'function' || typeof platform.mqtt !== 'function'
@@ -1011,7 +1234,7 @@ export class Carrier {
1011
1234
  const gone = store.lapsed(now);
1012
1235
  for (const p of gone) {
1013
1236
  this.#emit(this.#note(st, now, { type: 'pairing_failed', did: p.code_did, name: p.name, code: 'code_expired',
1014
- detail: `the code from ${p.name} expired at ${new Date(p.exp * 1000).toISOString().replace('.000', '')} before the inviter's agent replied: ask the inviter for a new code` }));
1237
+ detail: p.public ? `${p.name} did not approve the request by ${new Date(p.exp * 1000).toISOString().replace('.000', '')} (a public code, 7 days): it has ended; try the code again later` : `the code from ${p.name} expired at ${new Date(p.exp * 1000).toISOString().replace('.000', '')} before the inviter's agent replied: ask the inviter for a new code` }));
1015
1238
  }
1016
1239
  return gone.length > 0;
1017
1240
  }
@@ -1087,6 +1310,14 @@ export class Carrier {
1087
1310
  #emit(ev) { try { this.onEvent(ev); } catch {} }
1088
1311
 
1089
1312
  // An event kept for the next inbox() as well: a CLI or MCP agent has no onEvent.
1313
+ // This side's name to a contact just paired (the header's "Names"), in its outbox: it goes with the next round.
1314
+ #tellName(st, did) {
1315
+ let n = null;
1316
+ try { n = theirName(this.#selfName()); } catch {}
1317
+ if (n === null) return;
1318
+ this.#entry(st, did).outbox.push({ id: randomId(), label: SEEN_LABEL, content: { seen: 0, name: n, busy: true } });
1319
+ }
1320
+
1090
1321
  #note(st, now, ev) {
1091
1322
  st.events.push({ ...ev, at: now });
1092
1323
  if (st.events.length > EVENTS_MAX) st.events.splice(0, st.events.length - EVENTS_MAX);
@@ -1121,8 +1352,9 @@ export class Carrier {
1121
1352
  #want({ now, me, store }, relay) {
1122
1353
  const out = [], seen = new Set();
1123
1354
  const add = (x) => { if (!seen.has(x.topic)) { seen.add(x.topic); out.push(x); } };
1355
+ for (const p of Object.values(store.s.publics ?? {})) if (p.relay === relay && p.exp > now) add({ topic: publicKeys(hexToBytes(p.secret)).answer_topic });
1124
1356
  for (const p of Object.values(store.s.invites)) if (p.relay === relay && p.exp > now) add({ topic: inviteKeys(hexToBytes(p.secret)).answer_topic });
1125
- for (const p of Object.values(store.s.accepts)) if (p.relay === relay && p.exp > now) add({ topic: inviteKeys(hexToBytes(p.secret)).reply_topic });
1357
+ for (const [id, p] of Object.entries(store.s.accepts)) if (p.relay === relay && p.exp > now) add({ topic: replyOf(id, p).reply_topic });
1126
1358
  // No new mailbox under a burned K (re_pair): those held run out at their time (#refresh).
1127
1359
  const contacts = this.#liveContacts(store, relay).filter((c) => !c.re_pair).map((c) => ({ did: c.did, K: hexToBytes(c.pair_key) }));
1128
1360
  const weeks = this.#weeks(now), at = Math.max(0, weeks.findIndex((w) => w.week === isoWeek(now)));
@@ -1137,8 +1369,10 @@ export class Carrier {
1137
1369
  this.#routes = this.#read(({ now, me, store }) => {
1138
1370
  const m = new Map(), wide = this.retention + 7 * DAY;
1139
1371
  for (const c of this.#liveContacts(store)) for (const w of this.#weeks(now, wide, wide)) m.set(topic(hexToBytes(c.pair_key), c.did, me.did, w.week), { type: 'peer', did: c.did });
1372
+ for (const c of this.#liveContacts(store)) m.set(presenceTopic(hexToBytes(c.pair_key), c.did, me.did), { type: 'presence', did: c.did });
1140
1373
  for (const [nonce, p] of Object.entries(store.s.invites)) m.set(inviteKeys(hexToBytes(p.secret)).answer_topic, { type: 'answer', nonce });
1141
- for (const [id, p] of Object.entries(store.s.accepts)) m.set(inviteKeys(hexToBytes(p.secret)).reply_topic, { type: 'reply', id });
1374
+ for (const [id, p] of Object.entries(store.s.accepts)) m.set(replyOf(id, p).reply_topic, { type: 'reply', id });
1375
+ for (const [nonce, p] of Object.entries(store.s.publics ?? {})) m.set(publicKeys(hexToBytes(p.secret)).answer_topic, { type: 'public', nonce });
1142
1376
  return m;
1143
1377
  });
1144
1378
  }
@@ -1147,7 +1381,7 @@ export class Carrier {
1147
1381
  return this.#read(({ now, store, st }) => {
1148
1382
  const s = store.load().s, r = new Set();
1149
1383
  for (const c of Object.values(s.contacts)) if (!c.revoked) r.add(c.relay);
1150
- for (const p of [...Object.values(s.invites), ...Object.values(s.accepts)]) if (p.exp > now) r.add(p.relay);
1384
+ for (const p of [...Object.values(s.invites), ...Object.values(s.accepts), ...Object.values(s.publics ?? {})]) if (p.exp > now) r.add(p.relay);
1151
1385
  for (const p of st.pending) r.add(p.relay);
1152
1386
  for (const [name, x] of Object.entries(st.relays)) if (Object.keys(x.claims ?? {}).length > 0) r.add(name);
1153
1387
  return [...r];
@@ -1184,9 +1418,12 @@ export class Carrier {
1184
1418
  if (!this.#routes.has(t)) this.#rebuildRoutes();
1185
1419
  route = this.#routes.get(t) ?? fail('route', 'a message on a topic this agent does not read');
1186
1420
  const events = this.#locked((ctx) => (route.type === 'peer' ? this.#onPeer(ctx, route.did, t, bytes)
1187
- : route.type === 'answer' ? this.#onAnswer(ctx, t, bytes) : this.#onReply(ctx, t, bytes)));
1421
+ : route.type === 'presence' ? this.#onPresence(ctx, route.did, t, bytes)
1422
+ : route.type === 'answer' ? this.#onAnswer(ctx, t, bytes) : route.type === 'public' ? this.#onPublic(ctx, route.nonce, t, bytes) : this.#onReply(ctx, t, bytes)));
1188
1423
  for (const e of events) this.#emit(e);
1424
+ if (route.type === 'answer') this.#renewSoon();
1189
1425
  } catch (e) {
1426
+ if (route?.type === 'answer') this.#renewSoon();
1190
1427
  if (e instanceof MsgError && !INTERNAL.has(e.check)) this.#drop(e.check, e.message, route);
1191
1428
  else if (!this.#undeliverable(t, bytes, e)) {
1192
1429
  this.#emit({ type: 'error', relay: link.relay, check: e.check ?? 'internal', detail: e.message });
@@ -1251,12 +1488,41 @@ export class Carrier {
1251
1488
  let n;
1252
1489
  try { n = parseBytes(bytes); } catch { return; }
1253
1490
  if (n === null || typeof n !== 'object' || typeof n.code !== 'string') return;
1491
+ // The relay's group tier for this login (relay/allowance.mjs "tier"): kept per relay in the state, refuses nothing.
1492
+ if (n.code === 'tier') {
1493
+ const g = groupTierOf(n);
1494
+ if (g) { try { this.#locked(({ st }) => { (st.group_tier ??= {})[link.relay] = g; }); } catch {} this.#emit({ type: 'group_tier', relay: link.relay, ...g }); }
1495
+ return;
1496
+ }
1254
1497
  const note = { code: n.code.slice(0, 64), detail: typeof n.detail === 'string' ? n.detail.slice(0, 200) : '', ...(QUOTA_SIDES.has(n.side) && { side: n.side }) };
1498
+ // Why the relay is about to end this session (relay/auth.mjs endWith): kept for #closed.
1499
+ if (note.code.startsWith('session_')) link.ended = { code: note.code, detail: note.detail };
1255
1500
  // id: the packet id of the PUBLISH a refusal names (#publish), kept out of events.
1256
1501
  if (link.collect) link.collect.push(Number.isSafeInteger(n.id) ? { ...note, id: n.id } : note);
1257
1502
  else this.#emit({ type: 'notice', relay: link.relay, ...note });
1258
1503
  }
1259
1504
 
1505
+ // A contact's presence marker toward this agent (the header's "Presence"): its sealed online, the
1506
+ // relay's offline, or nothing (cleared). → the presence event.
1507
+ #onPresence({ me, store, st }, did, t, bytes) {
1508
+ const c = store.lookup(did);
1509
+ if (!c || c.revoked || !c.pair_key) return [];
1510
+ const p = (st.presence ??= {});
1511
+ let e = null;
1512
+ if (bytes.length > 0 && bytes[0] === 0x7b) {
1513
+ let v;
1514
+ try { v = parseBytes(bytes); } catch (err) { fail('presence', `the relay's offline marker is not JSON: ${err.message}`); }
1515
+ if (!exact(v, ['at', 'presence']) || v.presence !== 'offline' || !Number.isSafeInteger(v.at) || v.at < 0) fail('presence', 'not the relay\'s {presence: "offline", at}');
1516
+ e = { online: false, since: null, last_seen: v.at };
1517
+ } else if (bytes.length > 0) {
1518
+ const v = unseal(KIND_PRESENCE, presenceKey(hexToBytes(c.pair_key), c.did, me.did), t, bytes);
1519
+ if (!exact(v, ['since', 'state', 'v']) || v.v !== PRESENCE_V || v.state !== 'online' || !Number.isSafeInteger(v.since) || v.since < 0) fail('presence', `not a ${PRESENCE_V} online marker`);
1520
+ e = { online: true, since: v.since, last_seen: null };
1521
+ }
1522
+ if (e) p[c.did] = { ...e, relay: c.relay }; else delete p[c.did];
1523
+ return [{ type: 'presence', did: c.did, name: c.name, online: e ? e.online : null, since: e?.since ?? null, last_seen: e?.last_seen ?? null }];
1524
+ }
1525
+
1260
1526
  // A contact's mailbox: an envelope (kind 0), its rotation notice (kind 4) or its prekeys (kind 5).
1261
1527
  #onPeer(ctx, did, t, bytes) {
1262
1528
  const { now, me, store, st } = ctx;
@@ -1308,6 +1574,51 @@ export class Carrier {
1308
1574
  l.push({ from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now });
1309
1575
  if (l.length > LINKS_MAX) { st.dropped.links_full = (st.dropped.links_full ?? 0) + l.length - LINKS_MAX; l.splice(0, l.length - LINKS_MAX); }
1310
1576
  events.push({ type: 'link', from: c.did, name: c.name });
1577
+ } else if (r.body.label === GROUP_LABEL) {
1578
+ // A group message (group.mjs): kept for handle(), never for inbox() nor onEvent's readers.
1579
+ const l = (st.groups ??= []);
1580
+ l.push({ from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now });
1581
+ if (l.length > GROUPS_MAX) { st.dropped.groups_full = (st.dropped.groups_full ?? 0) + l.length - GROUPS_MAX; l.splice(0, l.length - GROUPS_MAX); }
1582
+ events.push({ type: 'group', from: c.did, name: c.name });
1583
+ } else if (r.body.label === TRANSFER_LABEL) {
1584
+ // A transfer message (transfer-node.mjs): kept for the engine, never for inbox() nor onEvent's readers.
1585
+ const l = (st.transfers ??= []);
1586
+ l.push({ from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now });
1587
+ if (l.length > TRANSFERS_MAX) { st.dropped.transfers_full = (st.dropped.transfers_full ?? 0) + l.length - TRANSFERS_MAX; l.splice(0, l.length - TRANSFERS_MAX); }
1588
+ events.push({ type: 'transfer', from: c.did, name: c.name });
1589
+ } else if (r.body.label === CALL_LABEL) {
1590
+ // A call's signalling (call.mjs): kept for the page's Line, never for inbox() nor onEvent's readers.
1591
+ const l = (st.calls ??= []);
1592
+ l.push({ from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now });
1593
+ if (l.length > CALLS_MAX) { st.dropped.calls_full = (st.dropped.calls_full ?? 0) + l.length - CALLS_MAX; l.splice(0, l.length - CALLS_MAX); }
1594
+ events.push({ type: 'call', from: c.did, name: c.name });
1595
+ } else if (r.body.label === SEEN_LABEL) {
1596
+ // A seen receipt (the header's): the highest kept; one malformed is counted, never an inbox message.
1597
+ const n = r.body.content?.seen, nm = theirName(r.body.content?.name);
1598
+ // busy: true: they take busy marks (the header's "Busy marks").
1599
+ if (r.body.content?.busy === true) this.#entry(st, c.did).busy_peer = true;
1600
+ if (nm !== null) {
1601
+ const all = store.load().s.contacts, rec = all[c.did];
1602
+ if (rec && (rec.name_from === 'auto' || rec.name_from === 'them') && rec.name !== nm) {
1603
+ const taken = (x) => Object.values(all).some((y) => !y.revoked && y.did !== rec.did && y.name === x);
1604
+ let to = nm;
1605
+ for (let i = 2; taken(to) && i < 100; i++) to = `${nm} (${i})`;
1606
+ rec.name = to; rec.name_from = 'them'; store.save();
1607
+ events.push({ type: 'named', did: c.did, name: to });
1608
+ } else if (rec && rec.name_from === 'auto') { rec.name_from = 'them'; store.save(); }
1609
+ }
1610
+ // A name's receipt (seen 0) says nothing of what was shown.
1611
+ if (nm !== null && n === 0) { /* the name only */ } else if (!Number.isSafeInteger(n) || n < 0) { st.dropped.seen = (st.dropped.seen ?? 0) + 1; events.push({ type: 'dropped', check: 'seen', detail: 'a seen receipt without its time' }); } else {
1612
+ const e = this.#entry(st, c.did);
1613
+ e.seen_peer = true;
1614
+ e.seen_upto = Math.max(e.seen_upto ?? 0, n);
1615
+ events.push({ type: 'seen', from: c.did, name: c.name, upto: e.seen_upto });
1616
+ }
1617
+ } else if (r.body.label === BUSY_LABEL) {
1618
+ // A busy mark (the header's): good for BUSY_TTL_S, never an inbox message nor logged.
1619
+ const e = this.#entry(st, c.did), on = r.body.content?.busy === true;
1620
+ e.busy_until = on ? now + BUSY_TTL_S : 0;
1621
+ events.push({ type: 'busy', from: c.did, name: c.name, on });
1311
1622
  } else if (r.body.label === DEVICE_LABEL) {
1312
1623
  // A device message (device.mjs): kept for the `device` verbs, never for inbox() nor onEvent's readers.
1313
1624
  const l = (st.devices ??= []);
@@ -1317,7 +1628,11 @@ export class Carrier {
1317
1628
  } else {
1318
1629
  // last_resort: the epoch began on the last-resort prekey, which may serve many epochs: weaker
1319
1630
  // forward secrecy (plan §3 "Prekeys"), and routine for a while after a rotation (#next).
1320
- const m = { from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now, last_resort: r.last_resort };
1631
+ const id = idOf('sigelo-msg-id/0', c.did, r.epoch, r.n);
1632
+ const m = { id, from: c.did, name: c.name, current_did: r.body.from, label: r.body.label, content: r.body.content, iat: r.body.iat, received: now, last_resort: r.last_resort };
1633
+ received(st, id, c.did, now);
1634
+ // A message ends the contact's busy mark (its reply is here).
1635
+ this.#entry(st, c.did).busy_until = 0;
1321
1636
  // Plaintext at rest: kept only for inbox() (keep), and only so many (the header).
1322
1637
  if (this.keep) {
1323
1638
  st.inbox.push(m);
@@ -1449,8 +1764,11 @@ export class Carrier {
1449
1764
  delete st.files[key];
1450
1765
  files.remove(this.#partDir(key));
1451
1766
  if (path === null) return drop(new MsgError('file_exists', `${p.name}: ${FILE_COPIES} files of that name and hash are in ${dir} already; not saved`));
1452
- const item = { type: 'file', from: c.did, contact: c.name, current_did: r.body.from, label: FILE_LABEL, name: p.name, size: p.size, sha256: p.sha256, path,
1767
+ const id = idOf('sigelo-msg-id/0 file', c.did, p.id);
1768
+ const item = { type: 'file', id, from: c.did, contact: c.name, current_did: r.body.from, label: FILE_LABEL, name: p.name, size: p.size, sha256: p.sha256, path,
1453
1769
  iat: r.body.iat, received: now, last_resort: r.last_resort };
1770
+ received(st, id, c.did, now);
1771
+ this.#entry(st, c.did).busy_until = 0;
1454
1772
  // Kept for inbox() as a message is (#onPeer), and so many at most.
1455
1773
  if (this.keep) {
1456
1774
  st.inbox.push(item);
@@ -1679,6 +1997,7 @@ export class Carrier {
1679
1997
  throw e;
1680
1998
  }
1681
1999
  const c = store.lookup(res.did), K = hexToBytes(res.pair_key);
2000
+ if (p.auto && !before[c.did] && c.name === p.name) { c.name_from = 'auto'; store.save(); }
1682
2001
  // What checkAnswer replaced, put back if the reply cannot reach the answerer (#unpair).
1683
2002
  const undo = { contact: before[c.did] ?? null, peer: st.peers[c.did] ?? null };
1684
2003
  const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K });
@@ -1692,11 +2011,69 @@ export class Carrier {
1692
2011
  }
1693
2012
  st.peers[c.did] = { session: dumpSession(s), announced: me.current_did, known: me.current_did, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: now };
1694
2013
  this.#queue(st, { ...entry, bytes: frame });
2014
+ this.#tellName(st, c.did);
1695
2015
  // Who answered this code (answeredBy): saved with the pairing, whoever reads the paired event.
1696
2016
  for (const [x, a] of Object.entries(st.answered)) if (!(a.exp > now)) delete st.answered[x];
1697
2017
  st.answered[nonce] = { did: c.did, exp: p.exp + DAY };
2018
+ // A renewing code: who used it, for the state; the fresh one comes after this delivery (#renewDue).
2019
+ if (p.renew) store.renewUsed(p.renew, { short: p.short ?? null, did: c.did, name: c.name, at: now });
2020
+ this.#routes = new Map();
2021
+ return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), invite: nonce, ...(p.renew && { renew: p.renew }) })];
2022
+ }
2023
+
2024
+ // Alice: an answer to a public code of hers (public.mjs). Screened (invite.mjs screenAnswer), an
2025
+ // answer id seen before dropped (replay), the day's own cap kept, one waiting request per original
2026
+ // DID (a newer replaces it); then a request waiting for the owner's approval, or, with open (let
2027
+ // anyone in), approved at once. Nothing is written for an answer refused.
2028
+ #onPublic(ctx, nonce, t, bytes) {
2029
+ const { now, store, st } = ctx;
2030
+ store.hold();
2031
+ const p = store.load().s.publics?.[nonce];
2032
+ if (!p || p.exp <= now) fail('challenge_unknown', 'no public code of this agent reads this topic');
2033
+ const answer = unseal(KIND.invite_answer, publicKeys(hexToBytes(p.secret)).key, t, bytes);
2034
+ const sc = screenAnswer(answer, { nonce, exp: p.exp }, store, now);
2035
+ if (Object.hasOwn(p.seen, sc.answer_id)) fail('replay', 'an answer to the public code seen before: dropped');
2036
+ const today = Math.floor(now / DAY);
2037
+ if (p.day === today && p.n >= p.cap) fail('public_cap', `the public code took its ${p.cap} new chats today: dropped`);
2038
+ if (p.day !== today) { p.day = today; p.n = 0; }
2039
+ p.n++;
2040
+ p.seen[sc.answer_id] = now + SEEN_KEEP;
2041
+ for (const [id, q] of Object.entries(p.requests)) if (q.did === sc.did) delete p.requests[id];
2042
+ const req = { id: sc.answer_id, did: sc.did, current_did: sc.current_did, words: didWords(sc.did), received: now, exp: Math.min(p.exp, answer.iat + REQUEST_TTL), answer };
2043
+ if (p.open) { store.save(); return this.#approve(ctx, nonce, req); }
2044
+ p.requests[req.id] = req;
2045
+ store.save();
2046
+ return [this.#note(st, now, { type: 'public_request', public: nonce, id: req.id, did: req.did, words: req.words, name: p.name })];
2047
+ }
2048
+
2049
+ // Alice approves a request (or open approves it at once): the rest of the handshake, as
2050
+ // #onAnswer, the reply on the joiner's own topic (public.mjs joinerKeys). The contact is named
2051
+ // after the code (name-1, name-2, …) and marked via {public: nonce}: unchecked, nobody compared.
2052
+ #approve(ctx, nonce, req) {
2053
+ const { now, me, store, st } = ctx;
2054
+ store.hold();
2055
+ const p = store.load().s.publics[nonce], rk = joinerKeys(hexToBytes(p.secret), req.id);
2056
+ const before = structuredClone(store.load().s.contacts);
2057
+ let ct = null;
2058
+ const name = `${p.name ?? 'public'}-${p.chats + 1}`;
2059
+ const res = admitAnswer(req.answer, { nonce, exp: p.exp, secret: p.secret, name, relay: p.relay }, store, now, (pk) => { const k = kemEncapsulate(pk); ct = k.ct; return k.shared; }, { via: { public: nonce } });
2060
+ const c = store.lookup(res.did), K = hexToBytes(res.pair_key);
2061
+ if (!before[c.did] && c.name === name) { c.name_from = 'auto'; store.save(); }
2062
+ const undo = { contact: before[c.did] ?? null, peer: st.peers[c.did] ?? null };
2063
+ const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K });
2064
+ const prekeys = s.in.prekeys.issue({ current_did: me.current_did, sign: me.sign }, s.pair, now);
2065
+ const reply = buildReply({ answer_id: res.answer_id, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_ct: ct, prekeys });
2066
+ const frame = seal(KIND.invite_reply, rk.key, rk.reply_topic, reply);
2067
+ const entry = { relay: p.relay, topic: rk.reply_topic, kind: KIND.invite_reply, control: 'reply', peer: c.did, undo, needs: [topic(K, c.did, me.did, isoWeek(now))], exp: req.exp };
2068
+ delete p.requests[req.id];
2069
+ if (frame.length > INVITE_BYTES) return [this.#unpair(ctx, entry, { code: 'too_large', detail: `the reply is ${frame.length} bytes, more than an invite topic holds (${INVITE_BYTES}): this agent's chain is too long` })];
2070
+ p.chats++;
2071
+ store.save();
2072
+ st.peers[c.did] = { session: dumpSession(s), announced: me.current_did, known: me.current_did, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: now };
2073
+ this.#queue(st, { ...entry, bytes: frame });
2074
+ this.#tellName(st, c.did);
1698
2075
  this.#routes = new Map();
1699
- return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), invite: nonce })];
2076
+ return [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), public: nonce })];
1700
2077
  }
1701
2078
 
1702
2079
  // Alice: her reply will never reach the answerer (refused, too large, or its code expired while
@@ -1736,9 +2113,9 @@ export class Carrier {
1736
2113
  // kem_ct to the same K.
1737
2114
  #onReply({ now, me, store, st }, t, bytes) {
1738
2115
  store.hold();
1739
- const waiting = Object.entries(store.load().s.accepts).filter(([, x]) => inviteKeys(hexToBytes(x.secret)).reply_topic === t);
2116
+ const waiting = Object.entries(store.load().s.accepts).filter(([x, p]) => replyOf(x, p).reply_topic === t);
1740
2117
  if (waiting.length === 0) fail('challenge_unknown', 'no answer of this agent waits on this topic');
1741
- const keys = inviteKeys(hexToBytes(waiting[0][1].secret)), spend = (except) => {
2118
+ const keys = replyOf(waiting[0][0], waiting[0][1]), spend = (except) => {
1742
2119
  for (const [x] of waiting) if (x !== except) { try { store.take('accepts', x, now); } catch {} }
1743
2120
  };
1744
2121
  let reply, res, id = waiting[0][0];
@@ -1750,7 +2127,16 @@ export class Carrier {
1750
2127
  if (!waiting.some(([x]) => x === named)) fail('challenge_unknown', 'the reply names another answer than those whose topic it came on');
1751
2128
  id = named;
1752
2129
  }
2130
+ // A public code's inviter, checked against the four words its page published (accept --words).
2131
+ const p0 = waiting.find(([x]) => x === id)?.[1];
2132
+ if (p0?.words) {
2133
+ let original = null;
2134
+ try { original = verify(reply?.bundle, now).chain[0]; } catch {}
2135
+ if (original !== null && didWords(original) !== p0.words) fail('words', `the inviter's four words are "${didWords(original)}", not "${p0.words}" as given: this is not the code its page published; nothing was paired`);
2136
+ }
1753
2137
  res = checkReply(reply, store, now, (kemCt, sk) => kemDecapsulate(kemCt, hexToBytes(sk)));
2138
+ // Came by a public code: marked, checked when the words matched.
2139
+ if (p0?.public) { const rec = store.load().s.contacts[res.did]; if (rec) { rec.via = { public: true, words: p0.words ? 'checked' : null }; store.save(); } }
1754
2140
  } catch (e) {
1755
2141
  spend(null);
1756
2142
  store.commit();
@@ -1761,14 +2147,17 @@ export class Carrier {
1761
2147
  // An entry written before `as` was kept: unknown, so the notice goes (#next `first`).
1762
2148
  const answered = waiting.find(([x]) => x === id)[1], held = answered.as ?? null;
1763
2149
  const c = renamed(store, store.lookup(res.did), answered);
2150
+ if (!answered.named && c.name === answered.name && c.name_from === undefined && !res.rekeyed) { c.name_from = 'auto'; store.save(); }
1764
2151
  const s = session({ me: { did: me.did, current_did: me.current_did, sign: me.sign }, peer: c, K: hexToBytes(res.pair_key) });
1765
- const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key) })];
2152
+ const pub = answered.public ? { public: true, words_checked: Boolean(answered.words) } : {};
2153
+ const events = [this.#note(st, now, { type: 'paired', did: c.did, name: c.name, current_did: c.current_did, rekeyed: res.rekeyed, fingerprint: wordsOf(res.pair_key), ...pub })];
1766
2154
  try { acceptPrekeys(s, reply.prekeys, now); } catch (e) {
1767
2155
  if (!(e instanceof MsgError)) throw e;
1768
2156
  events.push({ type: 'dropped', check: e.check, detail: `the reply's prekeys: ${e.message}` });
1769
2157
  }
1770
2158
  st.peers[c.did] = { session: dumpSession(s), announced: held, known: held, outbox: st.peers[c.did]?.outbox ?? [], prekeys_resend: false, prekeys_iat: 0 };
1771
- for (const [x] of waiting) this.#handshakes.set(x, { contact: { name: c.name, did: c.did, current_did: c.current_did, fingerprint: wordsOf(res.pair_key) } });
2159
+ this.#tellName(st, c.did);
2160
+ for (const [x] of waiting) this.#handshakes.set(x, { contact: { name: c.name, did: c.did, current_did: c.current_did, fingerprint: wordsOf(res.pair_key), ...pub } });
1772
2161
  this.#routes = new Map();
1773
2162
  return events;
1774
2163
  }
@@ -1796,6 +2185,15 @@ export class Carrier {
1796
2185
  for (const c of this.#liveContacts(store, relay)) {
1797
2186
  const e = st.peers[c.did];
1798
2187
  if (!e) continue;
2188
+ // Past its expires (send): dropped unsent, waiting (no reader, no prekeys) or not.
2189
+ if (e.outbox.some((x) => x.exp !== undefined && x.exp <= now)) {
2190
+ e.outbox = e.outbox.filter((x) => {
2191
+ if (x.exp === undefined || x.exp > now) return true;
2192
+ this.#results.set(x.id, { code: 'expired', detail: `not sent before it expired (${x.exp})`, local: true });
2193
+ this.#replyMark(st, x.id, now, { code: 'expired', detail: `not sent before it expired (${x.exp})` });
2194
+ return false;
2195
+ });
2196
+ }
1799
2197
  if (absent(c.did)) {
1800
2198
  const detail = noReader(c.name);
1801
2199
  for (const item of e.outbox) this.#results.set(item.id, { code: null, queued: detail });
@@ -1841,6 +2239,7 @@ export class Carrier {
1841
2239
  // exited, and its agent was told it goes at a later connection.
1842
2240
  for (const item of e.outbox.splice(0)) {
1843
2241
  this.#results.set(item.id, { code: 're_pair', detail: rePairWhy(c), local: true });
2242
+ this.#replyMark(st, item.id, now, { code: 're_pair', detail: rePairWhy(c) });
1844
2243
  this.#emit(this.#note(st, now, { type: 'refused', id: item.id, peer: c.did, name: c.name, code: 're_pair', detail: rePairWhy(c) }));
1845
2244
  }
1846
2245
  continue;
@@ -1891,6 +2290,7 @@ export class Carrier {
1891
2290
  // Refused here, before sending (message_too_large, revoked): never reported as the relay's word.
1892
2291
  e.outbox.shift();
1893
2292
  this.#results.set(item.id, { code: err.check, detail: err.message, local: true });
2293
+ this.#replyMark(st, item.id, now, { code: err.check, detail: err.message });
1894
2294
  }
1895
2295
  }
1896
2296
  }
@@ -1949,11 +2349,11 @@ export class Carrier {
1949
2349
  // message as refused (its epoch restarted, its prekey put back, its contact marked absent).
1950
2350
  // Nothing leaves before the state that sent it is committed (platform.flush): an envelope whose
1951
2351
  // ratchet step a crash lost would be sent again under the same key, a replay at the reader.
1952
- async #publish(link, t, bytes) {
2352
+ async #publish(link, t, bytes, retain = false) {
1953
2353
  await this.platform.flush();
1954
2354
  link.collect = [];
1955
2355
  try {
1956
- const id = await link.request('PUBACK', (cb) => link.client.publish(t, bytes, { qos: 1 }, (err, packet) => (err ? cb(new MsgError('connect', err.message)) : cb(null, packet?.messageId))));
2356
+ const id = await link.request('PUBACK', (cb) => link.client.publish(t, bytes, { qos: 1, retain }, (err, packet) => (err ? cb(new MsgError('connect', err.message)) : cb(null, packet?.messageId))));
1957
2357
  const mine = (n) => PUBLISH_CODES.has(n.code) && (n.id === undefined || n.id === id);
1958
2358
  for (const n of link.collect) if (!mine(n)) this.#emit({ type: 'notice', relay: link.relay, code: n.code, detail: n.detail });
1959
2359
  return link.collect.find(mine) ?? null;
@@ -1976,14 +2376,20 @@ export class Carrier {
1976
2376
  this.#emit({ type: 'error', relay: link.relay, check: err.check ?? 'publish', detail: err.message });
1977
2377
  return;
1978
2378
  }
1979
- this.#locked((ctx) => { if (!(r && this.#refused(ctx, e, r))) ctx.st.pending = ctx.st.pending.filter((p) => p.id !== e.id); });
2379
+ this.#locked((ctx) => {
2380
+ if (r && this.#refused(ctx, e, r)) return;
2381
+ ctx.st.pending = ctx.st.pending.filter((p) => p.id !== e.id);
2382
+ // A reply's part: published, or refused; back in the outbox (no reader): still queued.
2383
+ if (e.kind === KIND.message && !(r?.code === 'no_reader' && e.item !== undefined)) this.#replyMark(ctx.st, e.id, ctx.now, r && { code: r.code, detail: r.detail });
2384
+ });
1980
2385
  if (r?.code === 'pow') { link.pow = true; link.closing = true; link.client.end(true); return; } // log in again, with the proof (#connect, #closed)
1981
2386
  if (r?.code === 'no_reader' && e.peer !== undefined && e.control !== 'reply') link.absent.add(e.peer);
1982
2387
  // A message the relay had no reader for is back in its outbox (#refused): queued, not refused.
1983
2388
  const back = r?.code === 'no_reader' && e.kind === KIND.message && e.item !== undefined;
1984
2389
  if (e.control === undefined || e.control === 'answer') this.#results.set(e.id, back ? { code: null, queued: noReader(this.#nameOf(e.peer)) } : r ?? { code: null }); // what a verb waits for
1985
- this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail }
1986
- : r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, ...(r.side && { side: r.side }), detail: r.detail } : { type: 'sent', id: e.id, peer: e.peer, control: e.control });
2390
+ const receipt = e.item?.label === SEEN_LABEL ? { receipt: true } : {};
2391
+ this.#emit(back ? { type: 'queued', id: e.id, peer: e.peer, code: r.code, detail: r.detail, ...receipt }
2392
+ : r ? { type: 'refused', id: e.id, peer: e.peer, control: e.control, code: r.code, ...(r.side && { side: r.side }), detail: r.detail, ...receipt } : { type: 'sent', id: e.id, peer: e.peer, control: e.control, ...receipt });
1987
2393
  // A refusal stops this round: what follows would be refused alike (a quota, the rate brake),
1988
2394
  // and a control frame would be queued again at once. The next round retries. A mailbox
1989
2395
  // nobody holds stops only what goes to that contact (absent, #next).
@@ -2067,9 +2473,108 @@ export class Carrier {
2067
2473
  // have stopped: a relay keeping messages longer than this agent thinks (a Pro reader run with
2068
2474
  // the free tier's retention) has then delivered them. #session ends with such a round.
2069
2475
  if (stale.length > 0 && link.quiet) await this.#unsubscribe(link, stale);
2476
+ if (!link.up) return;
2477
+ await this.#presence(link);
2478
+ if (!link.up) return;
2479
+ await this.#pushOut(link);
2070
2480
  await this.#flush(link);
2071
2481
  }
2072
2482
 
2483
+ // The push registration (setPush) at this agent's own relay, once per connection and again when it
2484
+ // changes: the JSON {v, endpoint, p256dh, auth}, or an empty payload (off). A relay that does not
2485
+ // say it takes them is sent nothing (state unsupported); a refusal is kept, not retried this connection.
2486
+ async #pushOut(link) {
2487
+ if (this.#push === undefined || !link.own) return;
2488
+ const bytes = this.#push === null ? '' : canonicalize({ v: PUSH_V, ...this.#push });
2489
+ if (link.pushSent === bytes) return;
2490
+ link.pushSent = bytes;
2491
+ if (!link.push) { this.#pushSays({ state: 'unsupported', relay: link.relay }); return; }
2492
+ await this.#throttle(link);
2493
+ const r = await this.#publish(link, PUSH_TOPIC, utf8ToBytes(bytes));
2494
+ if (r) { this.#emit({ type: 'notice', relay: link.relay, code: r.code, detail: r.detail }); this.#pushSays({ state: 'refused', relay: link.relay, code: r.code, detail: r.detail }); return; }
2495
+ this.#pushSays({ state: this.#push === null ? 'off' : 'registered', relay: link.relay, at: this.clock() });
2496
+ }
2497
+ #pushSays(x) { this.#pushState = x; this.#emit({ type: 'push', ...x }); }
2498
+
2499
+ /**
2500
+ * The phone's UnifiedPush registration for this agent's own relay (design/push.md, relay/push.mjs): { endpoint (https),
2501
+ * p256dh, auth (base64url) } to register, null to remove it there; sent at once when connected, else at the next login,
2502
+ * and again at every login. Never called: nothing is sent (a computer, the GTK app). → pushStatus().
2503
+ */
2504
+ setPush(reg) {
2505
+ if (reg !== null) {
2506
+ const fine = reg && typeof reg === 'object' && Object.keys(reg).sort().join() === 'auth,endpoint,p256dh'
2507
+ && typeof reg.endpoint === 'string' && /^https:\/\//.test(reg.endpoint) && reg.endpoint.length <= 1024 && [reg.p256dh, reg.auth].every((x) => typeof x === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(x));
2508
+ if (!fine) fail('push', 'a push registration is {endpoint: an https URL, p256dh, auth: base64url}, or null');
2509
+ reg = { endpoint: reg.endpoint, p256dh: reg.p256dh, auth: reg.auth };
2510
+ }
2511
+ const same = canonicalize(reg) === canonicalize(this.#push ?? null) && this.#push !== undefined;
2512
+ this.#push = reg;
2513
+ if (!same) {
2514
+ this.#pushState = { state: 'pending', relay: this.relay };
2515
+ if (this.#links.get(this.relay)?.up) this.#refreshSoon(this.relay);
2516
+ }
2517
+ return this.pushStatus();
2518
+ }
2519
+
2520
+ /** → { state: 'none' (never set) | 'pending' | 'registered' | 'off' | 'refused' | 'unsupported', relay?, at?, code?, detail? }. */
2521
+ pushStatus() { return { ...this.#pushState }; }
2522
+
2523
+ // Presence at one relay (the header's "Presence"): each contact's marker toward this agent read
2524
+ // (QoS 0: a marker is never queued); this agent's published toward those who may see it, once
2525
+ // per connection, by a started carrier only (its CONNECT set the will); cleared toward any other.
2526
+ // A refusal stops the round: the next round tries again.
2527
+ async #presence(link) {
2528
+ const { want, out, clear } = this.#read(({ now, me, store, st }) => {
2529
+ const cs = this.#liveContacts(store, link.relay).filter((c) => !c.re_pair);
2530
+ // Read by a started carrier only: what a session reads is forgotten when it closes (#closed),
2531
+ // so a short one (a CLI verb, an MCP call) would spend one subscribe per contact on the relay's
2532
+ // brake (allowance.mjs RATE.subscribe, 256 at once) for nothing, and verbs in quick succession
2533
+ // were refused rate.
2534
+ const want = link.will ? cs.map((c) => presenceTopic(hexToBytes(c.pair_key), c.did, me.did)) : [];
2535
+ const out = link.will ? cs.filter((c) => store.presenceOf(c, now) !== 'deny').map((c) => {
2536
+ const K = hexToBytes(c.pair_key), t = presenceTopic(K, me.did, c.did);
2537
+ return { did: c.did, topic: t, key: presenceKey(K, me.did, c.did) };
2538
+ }) : [];
2539
+ // Cleared: a marker toward a contact that may no longer see it, gone or denied (any session).
2540
+ const sees = new Set(cs.filter((c) => store.presenceOf(c, now) !== 'deny').map((c) => c.did));
2541
+ const clear = Object.entries(st.presence_out ?? {}).filter(([, x]) => x.relay === link.relay && !sees.has(x.did)).map(([t]) => t);
2542
+ return { want, out, clear };
2543
+ });
2544
+ const fresh = want.filter((t) => !link.presenceIn.has(t));
2545
+ for (let i = 0; i < fresh.length && link.up; i += MAX_TOPICS) {
2546
+ const chunk = fresh.slice(i, i + MAX_TOPICS);
2547
+ link.collect = [];
2548
+ let granted, notes;
2549
+ try {
2550
+ granted = await link.request('SUBACK', (cb) => link.client.subscribe(chunk, { qos: 0 }, (err, _subs, packet) =>
2551
+ (packet?.granted ? cb(null, packet.granted) : cb(new MsgError('connect', err?.message ?? 'no SUBACK')))));
2552
+ notes = link.collect;
2553
+ } finally { link.collect = null; }
2554
+ chunk.forEach((t, j) => { if (granted[j] !== 128) link.presenceIn.add(t); });
2555
+ for (const n of notes) this.#emit({ type: 'notice', relay: link.relay, ...n });
2556
+ if (notes.some((n) => n.code === 'rate')) return;
2557
+ }
2558
+ const note = (topic, x) => this.#locked(({ st }) => { const o = (st.presence_out ??= {}); if (x) o[topic] = x; else delete o[topic]; });
2559
+ for (const x of out) {
2560
+ if (!link.up) return;
2561
+ if (link.presenceOut.has(x.topic)) continue;
2562
+ await this.#throttle(link);
2563
+ const r = await this.#publish(link, x.topic, seal(KIND_PRESENCE, x.key, x.topic, { v: PRESENCE_V, state: 'online', since: link.onlineAt }), true);
2564
+ if (r) { this.#emit({ type: 'notice', relay: link.relay, code: r.code, detail: r.detail }); return; }
2565
+ link.presenceOut.set(x.topic, x.did);
2566
+ note(x.topic, { relay: link.relay, did: x.did });
2567
+ }
2568
+ for (const t of clear) {
2569
+ if (!link.up) return;
2570
+ await this.#throttle(link);
2571
+ const r = await this.#publish(link, t, new Uint8Array(0), true);
2572
+ if (r && r.code !== 'presence_taken') { this.#emit({ type: 'notice', relay: link.relay, code: r.code, detail: r.detail }); return; }
2573
+ link.presenceOut.delete(t);
2574
+ note(t, null);
2575
+ }
2576
+ }
2577
+
2073
2578
  // Work runs one item at a time, after the delivery that queued it is acknowledged: a SUBACK or
2074
2579
  // PUBACK it waits for is handled only once the packet before it is.
2075
2580
  #later(fn) {
@@ -2087,10 +2592,11 @@ export class Carrier {
2087
2592
  }
2088
2593
 
2089
2594
  // Until queued work is done and nothing has arrived for QUIET ms (and `until()` holds), or max ms.
2090
- async #idle({ max = DRAIN, until = null } = {}) {
2595
+ async #idle({ max = DRAIN, until = null, down = null } = {}) {
2091
2596
  const end = Date.now() + max;
2092
2597
  for (;;) {
2093
2598
  await this.#drain();
2599
+ if (down?.()) return;
2094
2600
  const last = Math.max(this.#lastWork, ...[...this.#links.values()].map((l) => l.lastIn));
2095
2601
  if (Date.now() - last >= QUIET && (!until || until())) return;
2096
2602
  if (Date.now() >= end) return;
@@ -2100,10 +2606,16 @@ export class Carrier {
2100
2606
 
2101
2607
  // ---- connections
2102
2608
 
2103
- async #credentials(relay, ep) {
2609
+ async #credentials(relay, ep, started) {
2610
+ // A login with a proof of work that a busy relay turned away "rate" before spending its nonce
2611
+ // (#dial; relay/pow.mjs): sent again as it is while that nonce lives, no search spent twice.
2612
+ const spare = this.#spare.get(relay);
2613
+ this.#spare.delete(relay);
2614
+ if (spare && spare.until > Date.now()) return spare;
2104
2615
  const { me, proven } = this.#read(({ me, st }) => ({ me, proven: st.relays[relay]?.proven === true }));
2105
2616
  const powMax = relay === this.relay ? POW_MAX : POW_MAX_OTHER;
2106
- const r = await http(this.platform, `${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}`);
2617
+ const issued = Date.now();
2618
+ const r = await http(this.platform, `${ep.http}/challenge?did=${encodeURIComponent(me.current_did)}${!proven && this.enrolHash ? `&enrol=${this.enrolHash}` : ''}`);
2107
2619
  this.#clockFrom(relay, r);
2108
2620
  if (r.status === 429) refuse('rate', `the relay ${relay} turned the login away: too many logins from this network (${relaySays(r.body?.error ?? r.body?.detail)}): ${retryIn(r, 'a minute')}, then try again`, r);
2109
2621
  // Any other status is no answer about this agent (nginx says 502 while the relay restarts):
@@ -2132,24 +2644,39 @@ export class Carrier {
2132
2644
  e.permanent = true;
2133
2645
  throw e;
2134
2646
  }
2647
+ // The function the relay states beside the bits: one this client does not compute is not
2648
+ // searched for (a relay of sigelo-relay-pow/0, SHA-256, or one asking more memory than POW_COST).
2649
+ const cost = bits === 0 ? POW_COST : powCost(r.body.pow);
2650
+ if (cost === null) {
2651
+ const e = new MsgError('pow', `the relay asks a proof of work this client does not compute (${JSON.stringify(r.body.pow ?? null).slice(0, 200)}); it computes {v: 1, alg: "argon2id"} at up to ${POW_COST.m} KiB, ${POW_COST.t} passes, 1 lane: update this client, or the relay`);
2652
+ e.permanent = true;
2653
+ throw e;
2654
+ }
2135
2655
  // A search of 0 bits costs nothing and is not counted.
2136
2656
  if (bits > 0) this.#locked(({ now, st }) => {
2137
2657
  const at = (st.relays[relay] ??= { proven: false, claims: {} }), recent = (at.searches ?? []).filter((t) => t > now - DAY);
2138
- if (recent.length >= POW_SEARCHES) {
2139
- // Permanent like the bits above: no backoff loop; the hourly round asks again (#retry).
2140
- const e = new MsgError('pow', `${recent.length} proof-of-work searches at ${relay} within 24 hours, the most this client spends: the next may begin after ${new Date((recent[0] + DAY) * 1000).toISOString()}; nothing is lost meanwhile, this client tries again then by itself (a search is spent once per identity, and again only when a login with it got no answer)`);
2141
- e.permanent = true;
2142
- throw e;
2658
+ if (recent.length >= POW_SEARCHES && started !== 'confirmed') {
2659
+ const next = recent[0] + DAY;
2660
+ // The human started it: never refused, asked once (the page: "Go on?"), then `confirmed`.
2661
+ if (started === 'user') {
2662
+ const nth = ORDINAL[recent.length] ?? `${recent.length + 1}th`;
2663
+ throw Object.assign(new MsgError('pow_confirm', `${nth[0].toUpperCase()}${nth.slice(1)} setup at this relay (${relay}) today, up to 2 minutes. Go on?`), { permanent: true, relay, next });
2664
+ }
2665
+ // Automatic: permanent like the bits above, no backoff loop; a timer tries again at `next` (#retry).
2666
+ const e = new MsgError('pow', `setup paused at ${relay}: ${recent.length} proof-of-work searches today, the most this client spends by itself. Next automatic try at ${hhmmUtc(next)} UTC (${new Date(next * 1000).toISOString()}); nothing is lost meanwhile, and a try you start goes now (a search is spent once per identity, and again only when a login with it got no answer)`);
2667
+ throw Object.assign(e, { permanent: true, relay, next });
2143
2668
  }
2144
2669
  at.searches = [...recent, now];
2145
2670
  });
2146
2671
  const t0 = Date.now();
2147
- if (bits > 0) this.#emit({ type: 'pow', relay, bits });
2148
- pow = await solvePow(relay, me.did, ch.nonce, bits, t0 + POW_MS, this.platform.pow) ?? fail('pow', `no ${bits}-bit proof of work found within the challenge's 5 minutes on this machine: try again, or later (the relay raises it under load)`);
2672
+ if (bits > 0) this.#emit({ type: 'pow', relay, bits, m: cost.m, t: cost.t });
2673
+ pow = await solvePow(relay, me.did, ch.nonce, bits, t0 + POW_MS, this.platform.pow, cost)
2674
+ ?? fail('pow', `no ${bits}-bit proof of work found within ${POW_MS / 1000} s on this machine (${2 ** bits} Argon2id evaluations on average, ~${Math.round((2 ** bits * POW_EVAL_MS * cost.m * cost.t) / (POW_COST.m * POW_COST.t) / 1000)} s on a phone): try again, or later (the relay raises it under load)`);
2149
2675
  if (bits > 0) this.#emit({ type: 'pow_done', relay, bits, ms: Date.now() - t0 });
2150
2676
  }
2151
2677
  const password = canonicalize({ v: LOGIN_V, nonce: ch.nonce, sig, bundle: loginBundle(me.bundle, relay), ...(pow !== undefined && { pow }) });
2152
- return { username: me.current_did, clientId: clientIdOf(me.did), password, pow };
2678
+ // until: this login's nonce is good till about then (#dial keeps it for a retry after "rate").
2679
+ return { username: me.current_did, clientId: clientIdOf(me.did), password, pow, until: issued + POW_MS, push: r.body?.push === PUSH_V };
2153
2680
  }
2154
2681
 
2155
2682
  // How long this agent's own relay keeps a message on the free tier (relay.json, plan §11), when
@@ -2167,6 +2694,8 @@ export class Carrier {
2167
2694
  }
2168
2695
 
2169
2696
  get retentionDays() { return this.retention / DAY; }
2697
+ /** The group tier this agent's relay told its last login ({tier, groups: {max, members}}), or null (group.mjs tierOf). */
2698
+ get groupTier() { try { return this.#read(({ st }) => st.group_tier?.[this.relay] ?? null); } catch { return null; } }
2170
2699
 
2171
2700
  // The relay's clock less this agent's (this.clock), in seconds, from an answer r of relay: its
2172
2701
  // Date header (whole seconds, so +0.5) taken as of the middle of the round trip.
@@ -2188,10 +2717,12 @@ export class Carrier {
2188
2717
  return this.clockOffset();
2189
2718
  }
2190
2719
 
2191
- async #dial(relay) {
2720
+ async #dial(relay, started) {
2192
2721
  const ep = endpointOf(relay, this.endpoints), link = new Link(relay, relay === this.relay);
2193
2722
  const info = link.own && this.#ask ? this.#relayInfo(ep) : null;
2194
- const creds = await this.#credentials(relay, ep);
2723
+ const creds = await this.#credentials(relay, ep, started);
2724
+ // A started carrier says it is online (the header's "Presence"): the relay says offline after.
2725
+ if (this.#started) { creds.will = { topic: PRESENCE_WILL, payload: 'offline', qos: 0, retain: false }; link.will = true; }
2195
2726
  await info;
2196
2727
  // The transport (the header's "Transport"): auto tries ep.mqtt for PROBE_MS, then the WebSocket
2197
2728
  // endpoint, and keeps to it for the rest of the process (FELL_BACK). Only a dial that got no
@@ -2208,18 +2739,25 @@ export class Carrier {
2208
2739
  if (n.accepted && creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[relay] ??= { proven: false, claims: {} }).proven = true; });
2209
2740
  return n;
2210
2741
  };
2211
- try { await mqttConnect(this.platform, url, creds, link, onPacket, probe ? PROBE_MS : CONNECT_MS); } catch (e) {
2212
- if (!probe || link.cut || typeof e.code === 'number') throw link.cut ?? await why(e);
2213
- url = await wsEndpoint(this.platform, ep);
2214
- try { await mqttConnect(this.platform, url, creds, link, onPacket); } catch (e2) { throw link.cut ?? await why(e2); }
2215
- FELL_BACK.set(ep.mqtt, url);
2216
- this.#emit({ type: 'transport', relay, transport: 'wss', detail: `${ep.mqtt} gave no CONNACK within ${PROBE_MS / 1000} s (${e.message}): MQTT over WebSocket at ${url} for the rest of this process` });
2742
+ try {
2743
+ try { await mqttConnect(this.platform, url, creds, link, onPacket, probe ? PROBE_MS : CONNECT_MS); } catch (e) {
2744
+ if (!probe || link.cut || typeof e.code === 'number') throw link.cut ?? await why(e);
2745
+ url = await wsEndpoint(this.platform, ep);
2746
+ try { await mqttConnect(this.platform, url, creds, link, onPacket); } catch (e2) { throw link.cut ?? await why(e2); }
2747
+ FELL_BACK.set(ep.mqtt, url);
2748
+ this.#emit({ type: 'transport', relay, transport: 'wss', detail: `${ep.mqtt} gave no CONNACK within ${PROBE_MS / 1000} s (${e.message}): MQTT over WebSocket at ${url} for the rest of this process` });
2749
+ }
2750
+ } catch (e) {
2751
+ // "rate" with a proof of work: the relay was checking as many proofs as it holds and refused
2752
+ // before spending the nonce (relay/pow.mjs), so this very login is good for the next try.
2753
+ if (e?.check === 'rate' && creds.pow !== undefined && creds.until > Date.now()) this.#spare.set(relay, creds);
2754
+ throw e;
2217
2755
  }
2218
2756
  // A close right after CONNACK (a cut in the same read) reached no listener of this connection.
2219
2757
  if (!link.client.connected) throw link.cut ?? new MsgError('connect', 'the relay closed the connection');
2220
2758
  // Deliveries are counted from here (quiet), not from before the login: a proof-of-work search
2221
2759
  // of seconds would read as a drained queue, and give up stale claims before what they hold came.
2222
- link.since = Date.now();
2760
+ link.since = Date.now(); link.onlineAt = this.clock(); link.push = creds.push === true;
2223
2761
  if (creds.pow !== undefined) this.#locked(({ st }) => { (st.relays[relay] ??= { proven: false, claims: {} }).proven = true; });
2224
2762
  link.client.on('error', () => {}); // a close follows
2225
2763
  link.client.on('close', () => this.#closed(link));
@@ -2229,11 +2767,11 @@ export class Carrier {
2229
2767
  return link;
2230
2768
  }
2231
2769
 
2232
- async #connect(relay) {
2770
+ async #connect(relay, started) {
2233
2771
  this.#connecting.add(relay);
2234
2772
  try {
2235
2773
  for (let attempt = 0; ; attempt++) {
2236
- const link = await this.#dial(relay);
2774
+ const link = await this.#dial(relay, started);
2237
2775
  this.#refreshSoon(relay);
2238
2776
  await this.#drain();
2239
2777
  if (link.up) return link;
@@ -2246,18 +2784,49 @@ export class Carrier {
2246
2784
 
2247
2785
  #closed(link) {
2248
2786
  link.abort?.(new MsgError('connect', 'the connection to the relay closed'));
2787
+ // What this connection read of the contacts' presence holds only while it is up.
2788
+ if (link.presenceIn.size > 0) {
2789
+ try {
2790
+ this.#locked(({ st }) => { for (const [d, e] of Object.entries(st.presence ?? {})) if (e.relay === link.relay) delete st.presence[d]; });
2791
+ } catch {}
2792
+ }
2249
2793
  if (this.#links.get(link.relay) === link) this.#links.delete(link.relay);
2250
2794
  this.#emit({ type: 'disconnected', relay: link.relay });
2251
2795
  if (Date.now() - link.since >= STABLE_MS) this.#attempts.delete(link.relay);
2796
+ // Logged in, then closed: by this client (it hung up), or by the relay (its notice says why).
2797
+ if (link.onlineAt > 0) this.#ended(link.relay, link.closing ? null : { ms: Date.now() - link.since, ...(link.ended ?? { code: 'session_ended', detail: 'the relay closed the connection' }) });
2252
2798
  if (!this.#started || this.#connecting.has(link.relay) || (link.closing && !link.pow)) return;
2253
2799
  if (link.cut?.permanent) {
2254
- this.#emit({ type: 'error', relay: link.relay, check: link.cut.check, detail: link.cut.message });
2800
+ this.#emit({ type: 'error', relay: link.relay, check: link.cut.check, detail: link.cut.message, ...(link.cut.next !== undefined && { next: link.cut.next }) });
2255
2801
  this.#abandon(link.relay, link.cut);
2256
2802
  } else this.#retry(link.relay);
2257
2803
  }
2258
2804
 
2259
- // Exponential backoff with jitter: first, 2 × first, … up to most.
2260
- #retry(relay, delay) {
2805
+ // The relay ended a session (why: { ms it lasted, code, detail }) or refused a login (why: { code,
2806
+ // detail }), or this client ended one itself (why null): the pace of the next login (backoff).
2807
+ #ended(relay, why) {
2808
+ try {
2809
+ this.#locked(({ st }) => {
2810
+ const r = (st.relays[relay] ??= { proven: false, claims: {} });
2811
+ if (why === null || (why.ms ?? 0) >= ENDED_LASTS) { delete r.ended; if (why === null) return; }
2812
+ r.ended = { n: Math.min(32, (r.ended?.n ?? 0) + 1), at: Date.now(), code: String(why.code).slice(0, 64), detail: String(why.detail ?? '').slice(0, 200) };
2813
+ });
2814
+ } catch {}
2815
+ }
2816
+ // Before a login to `relay`: the wait the last early ends ask (backoff), but never past `end` (ms).
2817
+ async #pace(relay, end = null) {
2818
+ let e = null;
2819
+ try { e = this.#read(({ st }) => st.relays[relay]?.ended ?? null); } catch {}
2820
+ if (!e || !(e.n > 0) || !Number.isFinite(e.at)) return;
2821
+ const [first, most] = this.backoff;
2822
+ const due = e.at + Math.min(most, first * 2 ** (e.n - 1));
2823
+ const ms = Math.min(due, end ?? due) - Date.now();
2824
+ if (ms > 0) await sleep(Math.min(ms, most));
2825
+ }
2826
+
2827
+ // Exponential backoff with jitter: first, 2 × first, … up to most. started: the first try's only
2828
+ // (start({ started })); every later one is automatic.
2829
+ #retry(relay, delay, started) {
2261
2830
  if (this.#timers.has(relay)) return;
2262
2831
  const n = (this.#attempts.get(relay) ?? 0) + 1, [first, most] = this.backoff;
2263
2832
  this.#attempts.set(relay, n);
@@ -2266,11 +2835,11 @@ export class Carrier {
2266
2835
  this.#timers.delete(relay);
2267
2836
  if (!this.#started || this.#links.get(relay)?.up || this.#connecting.has(relay)) return;
2268
2837
  try {
2269
- const link = await this.#connect(relay);
2838
+ const link = await this.#connect(relay, started);
2270
2839
  this.#powFails.delete(relay);
2271
2840
  if (!this.#started) await this.#hangUp(link); // stop() came while this connected
2272
2841
  } catch (e) {
2273
- this.#emit({ type: 'error', relay, check: e.check ?? 'connect', detail: e.message });
2842
+ this.#emit({ type: 'error', relay, check: e.check ?? 'connect', detail: e.message, ...(e.next !== undefined && { next: e.next }) });
2274
2843
  if (e.check === 'pow') this.#powFails.set(relay, (this.#powFails.get(relay) ?? 0) + 1);
2275
2844
  // A refusal no retry can fix, or proof of work failing twice (each try may cost POW_MS of
2276
2845
  // CPU), or POW_SEARCHES spent: no backoff loop here. The hourly round tries again while a
@@ -2278,10 +2847,21 @@ export class Carrier {
2278
2847
  // stranger's code sent there.
2279
2848
  if (PERMANENT.has(e.check) || e.permanent || this.#powFails.get(relay) >= 2) this.#abandon(relay, e);
2280
2849
  else this.#retry(relay);
2850
+ // The day's searches spent: the next automatic try at the time the refusal named, not later.
2851
+ if (e.check === 'pow' && e.next !== undefined && this.#started) this.#powWait(relay, e.next);
2281
2852
  }
2282
2853
  }, wait));
2283
2854
  }
2284
2855
 
2856
+ // A timer to `next` (unix seconds): the relay's next automatic try once the day's searches are
2857
+ // spent. The hourly round leaves it be (it holds the relay's timer); sync() and tryNow() clear it.
2858
+ #powWait(relay, next) {
2859
+ if (this.#timers.has(relay)) return;
2860
+ const ms = Math.min(2 ** 31 - 1, Math.max(1000, (next - this.clock()) * 1000 + 1000));
2861
+ this.#timers.set(relay, setTimeout(() => { this.#timers.delete(relay); this.#powWaits.delete(relay); this.#retry(relay, 0); }, ms));
2862
+ this.#powWaits.add(relay);
2863
+ }
2864
+
2285
2865
  // A relay other than this agent's own refuses it for good: the answers still waiting to go to it
2286
2866
  // are withdrawn, so no later round dials, for them, a host that a stranger's code named. An
2287
2867
  // answer the relay already holds stays: the inviter may pair and reply, and its secret is what
@@ -2293,7 +2873,7 @@ export class Carrier {
2293
2873
  this.#locked(({ now, store, st }) => {
2294
2874
  const waiting = new Set(st.pending.filter((x) => x.relay === relay && x.control === 'answer').map((x) => x.topic));
2295
2875
  for (const [id, p] of Object.entries(store.load().s.accepts)) {
2296
- if (p.relay !== relay || !waiting.has(inviteKeys(hexToBytes(p.secret)).answer_topic)) continue;
2876
+ if (p.relay !== relay || !waiting.has(answerTopicOf(p))) continue;
2297
2877
  store.take('accepts', id, now);
2298
2878
  this.#emit(this.#note(st, now, { type: 'pairing_failed', did: p.code_did, name: p.name, code: e.check ?? 'connect', detail: `the code's relay refused this agent: ${e.message}` }));
2299
2879
  }
@@ -2316,15 +2896,36 @@ export class Carrier {
2316
2896
 
2317
2897
  // Connects (or refreshes) each relay, waits for the round to settle, and hangs up again unless
2318
2898
  // started.
2319
- async #session(relays, idle = {}) {
2899
+ // A wait (idle.max) is the caller's: a session the relay ends early, or a login it turns away
2900
+ // after the first, is tried again at the backoff pace until that time, never returned early
2901
+ // (0.1.17: `inbox --wait 300` said "no message came within 300 s" after ~20 s). this.ended: the
2902
+ // relay's last word on a session it ended during this one ({ code, detail, n }), or null.
2903
+ async #session(relays, idle = {}, started) {
2320
2904
  const opened = [];
2321
2905
  this.#locked((ctx) => this.#expireKeys(ctx));
2906
+ const end = idle.max !== undefined && !this.#started ? Date.now() + idle.max : null;
2907
+ this.ended = null;
2322
2908
  try {
2323
- for (const r of relays) {
2324
- if (this.#links.get(r)?.up) this.#refreshSoon(r);
2325
- else opened.push(await this.#connect(r));
2909
+ for (let round = 0; ; round++) {
2910
+ for (const r of relays) {
2911
+ if (this.#links.get(r)?.up) { this.#refreshSoon(r); continue; }
2912
+ await this.#pace(r, end);
2913
+ if (end !== null && round > 0 && Date.now() >= end) continue;
2914
+ try { opened.push(await this.#connect(r, started)); } catch (e) {
2915
+ if (ENDED_RETRY.has(e.check)) this.#ended(r, { code: e.check, detail: e.message });
2916
+ // The first login fails the verb as it always did; one after the relay ended a session waits again.
2917
+ if (end === null || round === 0 || !ENDED_RETRY.has(e.check)) throw e;
2918
+ this.ended = { code: e.check, detail: e.message, n: (this.ended?.n ?? 0) + 1 };
2919
+ }
2920
+ }
2921
+ const down = () => relays.some((r) => !this.#links.get(r)?.up);
2922
+ await this.#idle(end === null ? idle : { ...idle, max: Math.max(0, end - Date.now()), down });
2923
+ if (end === null || Date.now() >= end || !down() || opened.some((l) => l.cut)) break;
2924
+ if (idle.until?.()) break;
2925
+ // The relay ended it: why, then the same wait on a new login.
2926
+ const gone = opened.filter((l) => !l.up && l.ended).at(-1)?.ended ?? { code: 'session_ended', detail: 'the relay closed the connection' };
2927
+ this.ended = { ...gone, n: (this.ended?.n ?? 0) + 1 };
2326
2928
  }
2327
- await this.#idle(idle);
2328
2929
  // One more round now that deliveries have stopped: claims past their time are given up
2329
2930
  // only then (#refresh), and a frame that waited for a claim goes.
2330
2931
  for (const r of relays) if (this.#links.get(r)?.up) this.#refreshSoon(r);
@@ -2342,16 +2943,32 @@ export class Carrier {
2342
2943
 
2343
2944
  // short: the long code is parked at the relay (POST /park, relay/park.mjs) under a short code
2344
2945
  // (short.mjs) for SHORT_TTL seconds, one fetch; refused, the invite is withdrawn as when its topic
2345
- // is. A login of its own: the relay checks that the parked code is this agent's.
2946
+ // is. A login of its own: the relay checks that the parked code is this agent's. ttl with short:
2947
+ // SHORT_TTL_MIN to SHORT_TTL_MAX seconds, the life of both codes (a slow agent's operator).
2346
2948
  // relay: the relay the code names (a company relay for colleagues, a public one for outsiders);
2347
2949
  // the short code is parked there, and the pairing talks over it.
2348
2950
  // local: no session: the code is made and kept only; its answer topic is claimed at this
2349
2951
  // identity's next login (a device added offline, device.mjs), so connect once before it answers.
2350
- async invite({ name, ttl, short = false, relay, local = false } = {}) {
2952
+ // renew: true begins a series of renewing codes (store.mjs renew); a series id continues one (#renewDue).
2953
+ // named: false when the caller made the name up (a placeholder): the contact takes the name the other side tells.
2954
+ // enrol: an enrolment code (enrol.mjs issue): parked with enrol: true (relay/park.mjs: up to ENROL_TTL_MAX,
2955
+ // fetched until the grant); an older relay that refuses the field gets a plain park, when ttl allows one.
2956
+ async invite({ name, ttl, short = false, relay, local = false, started, renew = false, named = name !== undefined, enrol = false } = {}) {
2351
2957
  const at = relay === undefined ? this.relay : relayArg(relay);
2958
+ if (enrol && (!short || renew !== false || local)) fail('invite', 'an enrolment code is a short code, parked once: not long, renewing or local');
2959
+ if (enrol && ttl !== undefined && (!Number.isSafeInteger(ttl) || ttl < SHORT_TTL_MIN || ttl > ENROL_TTL_MAX)) {
2960
+ fail('ttl', `an enrolment code lives ${SHORT_TTL_MIN} s to a day (${ENROL_TTL_MAX} s), not ${JSON.stringify(ttl)}`);
2961
+ }
2962
+ if (short && !enrol && ttl !== undefined && (!Number.isSafeInteger(ttl) || ttl < SHORT_TTL_MIN || ttl > SHORT_TTL_MAX)) {
2963
+ fail('ttl', `a short code lives ${SHORT_TTL_MIN} to ${SHORT_TTL_MAX} seconds (default ${SHORT_TTL}), not ${JSON.stringify(ttl)}; longer: the long code (invite --long --ttl)`);
2964
+ }
2965
+ if (renew !== false && (!short || local)) fail('invite', 'a code that renews itself is a short one, parked at the relay: not with --long or local');
2966
+ const series = renew === true ? randomId() : typeof renew === 'string' ? renew : null;
2352
2967
  const code = this.#locked(({ now, me, store }) => {
2353
2968
  const code = makeInvite({ did: me.current_did, relay: at, now, ...(ttl !== undefined && { ttl }) });
2354
- store.addInvite(code, name ?? `invite-${code.nonce.slice(1, 9)}`, now);
2969
+ store.addInvite(code, name ?? `invite-${code.nonce.slice(1, 9)}`, now, null,
2970
+ series === null ? null : { id: series, ...(renew === true && { start: { name: name ?? null, ttl: ttl ?? null, relay: relay === undefined ? null : at } }) });
2971
+ if (!named) { store.load().s.invites[code.nonce].auto = true; store.save(); }
2355
2972
  return code;
2356
2973
  });
2357
2974
  if (local) {
@@ -2361,33 +2978,73 @@ export class Carrier {
2361
2978
  // The answer topic is claimed before the code leaves: the relay drops what nobody reads.
2362
2979
  const t = inviteKeys(code.secret).answer_topic;
2363
2980
  try {
2364
- await this.#session([code.relay]);
2981
+ await this.#session([code.relay], {}, started);
2365
2982
  if (!this.#claimed.has(t)) {
2366
2983
  const r = this.#refusedTopics.get(t);
2367
2984
  fail(r?.code ?? 'subscribe', `the relay did not let this agent claim the invite's topic${r ? ` (${relaySays(r.detail)})` : ''}`);
2368
2985
  }
2369
2986
  if (!short) return { code: code.text, did: code.did, relay: code.relay, exp: code.exp };
2370
2987
  // Eight characters on the public relay; on any other, twelve: the last four its relay tag.
2371
- const s = makeShort(undefined, code.relay === this.shortRelay ? null : relayTag(code.relay)), exp = Math.min(checkNow(this.clock()) + SHORT_TTL, code.exp), ep = endpointOf(code.relay, this.endpoints);
2372
- const creds = await this.#credentials(code.relay, ep);
2373
- const r = await http(this.platform, `${ep.http}/park`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: codeHash(s), invite: code.text, exp }) });
2988
+ const s = makeShort(undefined, code.relay === this.shortRelay ? null : relayTag(code.relay)), exp = Math.min(checkNow(this.clock()) + (ttl ?? SHORT_TTL), code.exp), ep = endpointOf(code.relay, this.endpoints);
2989
+ const parkOnce = async (asEnrol) => {
2990
+ const creds = await this.#credentials(code.relay, ep, started);
2991
+ return http(this.platform, `${ep.http}/park`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: codeHash(s), invite: code.text, exp, ...(asEnrol && { enrol: true }) }) });
2992
+ };
2993
+ let r = await parkOnce(enrol);
2994
+ // An older relay (no enrolment codes) answers 400 to the field: parked as an invite (fetched once), within its hour.
2995
+ if (enrol && r.status === 400) {
2996
+ if (exp - checkNow(this.clock()) > SHORT_TTL_MAX) refuse('park', `the relay ${code.relay} keeps no enrolment code longer than an hour (an older relay): --ttl 1h or less`, r);
2997
+ r = await parkOnce(false);
2998
+ }
2374
2999
  const check = typeof r.body?.check === 'string' ? r.body.check : null;
2375
3000
  if (r.status === 429) refuse('rate', `the relay ${code.relay} parks no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}, or use the long code (invite --long)`, r);
2376
3001
  if ((r.status === 404 || r.status === 405) && check === null) refuse('park', `the relay ${code.relay} takes no short codes: use the long code (invite --long)`, r);
2377
3002
  if (r.status !== 200) refuse('connect', `${code.relay}: ${statusWhy(r, 'POST /park')}`, r);
2378
3003
  // exp is this machine's clock: one far off the relay's is refused (relay/park.mjs PARK_SKEW).
2379
- const clock = typeof r.body?.detail === 'string' && r.body.detail.startsWith('exp:') ? ': this machine\'s clock may be off (date -u), or use the long code (invite --long)' : '';
3004
+ // A ttl past 10 minutes at an older relay (PARK_TTL 600) is refused the same way.
3005
+ const clock = typeof r.body?.detail === 'string' && r.body.detail.startsWith('exp:')
3006
+ ? (ttl ?? SHORT_TTL) > SHORT_TTL ? `: this relay may keep short codes 10 minutes at most (an older relay): --ttl ${SHORT_TTL} or less, or the long code (invite --long --ttl ${ttl})`
3007
+ : ': this machine\'s clock may be off (date -u), or use the long code (invite --long)' : '';
2380
3008
  if (r.body?.ok !== true) refuse(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the short code (${relaySays(`${check}: ${r.body?.detail}`)})${clock}`, r);
2381
3009
  // The relay keeps the code until its own exp (park.mjs: at most SHORT_TTL by its clock), not
2382
3010
  // this machine's: that is the one shown. This machine's only when the relay names none.
2383
3011
  const held = Number.isSafeInteger(r.body.exp) && r.body.exp > 0 ? r.body.exp : exp;
2384
- return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: held };
3012
+ // Kept with the invite: a cancel by the short code finds it; a renewing series has its fresh code.
3013
+ this.#locked(({ store }) => { store.setShort(code.nonce, formatShort(s), held); if (series !== null && renew !== true) store.renewDone(series); });
3014
+ return { code: code.text, did: code.did, relay: code.relay, exp: code.exp, short: formatShort(s), short_exp: held, ...(series !== null && { renew: series }), ...(enrol && { enrol: r.body.enrol === true, short_hash: codeHash(s) }) };
2385
3015
  } catch (e) {
2386
- try { this.#locked(({ store }) => store.cancelInvite(code.nonce)); } catch {}
3016
+ // A renewal that failed leaves its series due (taken: store.mjs take), tried again (#renewDue).
3017
+ try { this.#locked(({ now, store }) => (series !== null && renew !== true ? store.take('invites', code.nonce, now) : store.cancelInvite(code.nonce))); } catch {}
2387
3018
  throw e;
2388
3019
  }
2389
3020
  }
2390
3021
 
3022
+ // Renewing codes (store.mjs renew): a code of a series taken (answered) leaves it due, and a fresh
3023
+ // short code is parked for it here, with the series' name (numbered), ttl and relay. Claimed under
3024
+ // the lock, so two processes of one identity park one code; a failure is tried again RENEW_RETRY
3025
+ // seconds later, its reason kept for the state. Run after a session that may have taken one
3026
+ // (inbox, sync), at start, at a started carrier's answer and each round; never inside the work
3027
+ // queue (#later), whose drain the invite's own session waits for.
3028
+ async #renewDue(started) {
3029
+ if (this.#renewing) return;
3030
+ try { if (this.#read(({ now, store }) => store.renewClaim(now, true)).length === 0) return; } catch { return; }
3031
+ this.#renewing = true;
3032
+ try {
3033
+ const due = this.#locked(({ now, store }) => store.renewClaim(now));
3034
+ for (const x of due) {
3035
+ try {
3036
+ await this.invite({ name: x.name === null ? undefined : `${x.name}-${x.n + 1}`, short: true, renew: x.id, started,
3037
+ ...(x.ttl !== null && { ttl: x.ttl }), ...(x.relay !== null && { relay: x.relay }) });
3038
+ } catch (e) { try { this.#locked(({ now, store }) => store.renewFailed(x.id, reason(e), now + RENEW_RETRY)); } catch {} }
3039
+ }
3040
+ } finally { this.#renewing = false; }
3041
+ }
3042
+ #renewSoon() {
3043
+ if (!this.#started || this.#renewing) return;
3044
+ const t = setTimeout(() => { if (this.#started) void this.#renewDue().catch(() => {}); }, 0);
3045
+ t.unref?.();
3046
+ }
3047
+
2391
3048
  // Where a short code is parked → { relay, from }: `relay` when named (the inviter's --relay; a
2392
3049
  // twelve-character code's tag must be its tag), else an eight-character code's shortRelay
2393
3050
  // (relay.sigelo.ai), else the host its relay tag resolves to (relays.mjs resolveTag): this agent's
@@ -2447,17 +3104,38 @@ export class Carrier {
2447
3104
  async unparkFrom(text, { relay } = {}) { return this.#unpark(text, relay); }
2448
3105
 
2449
3106
  async #unpark(text, relay) {
3107
+ text = stripEnrol(text);
2450
3108
  const { relay: at, from } = await this.relayForShort(text, { relay });
2451
3109
  const shown = formatShort(normaliseShort(text)), ep = endpointOf(at, this.endpoints);
2452
3110
  const r = await http(this.platform, `${ep.http}/park/${codeHash(text)}`);
2453
3111
  if (r.status === 429) refuse('rate', `the relay ${at} looks up no more short codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}, or ask for the long code (invite --long)`, r);
2454
3112
  if (r.status === 404 && r.body?.check === 'park_unknown') {
2455
- refuse('park_unknown', `short code ${shown}: no invite waits under it at ${at}. It expired (a short code lives 10 minutes), was used already (once only), or is mistyped; ask the inviter for a new one. If the inviter made it on another relay (invite --relay) with an older sigelo, accept it with --relay <that relay>, or ask for the long code (invite --long)`, r);
3113
+ refuse('park_unknown', `short code ${shown}: no invite waits under it at ${at}. It expired (a short code lives 10 minutes unless its inviter chose up to an hour), was used already (once only), or is mistyped; ask the inviter for a new one. If the inviter made it on another relay (invite --relay) with an older sigelo, accept it with --relay <that relay>, or ask for the long code (invite --long)`, r);
2456
3114
  }
2457
3115
  if (r.status === 404 || r.status === 405) refuse('park', `the relay ${at} takes no short codes: ask the inviter for the long code (invite --long)`, r);
2458
3116
  if (r.status !== 200) refuse('connect', `${at}: ${statusWhy(r, 'GET /park')}`, r);
2459
3117
  if (r.body?.ok !== true || typeof r.body.invite !== 'string') refuse('connect', `${at}: GET /park answered 200 without a parked code: try again later; SIGELO_DEBUG=1 shows the answer`, r);
2460
3118
  if (from === 'named' && tagOf(normaliseShort(text)) !== null) try { remember(this.relaysPath, at, this.platform.files); } catch {}
3119
+ // enrol: the relay parked it as an enrolment code (relay/park.mjs): init --enrol takes no other.
3120
+ return { invite: r.body.invite, relay: at, enrol: r.body.enrol === true };
3121
+ }
3122
+
3123
+ // The operator's grant has gone (enrol.mjs): its enrolment code spent at the relay that parks it
3124
+ // (DELETE /park/<hash>, the parker's login), so nobody fetches it again. Best effort → { unparked, … }.
3125
+ async unparkHash(hash, relay = this.relay) {
3126
+ if (typeof hash !== 'string' || !/^[0-9a-f]{64}$/.test(hash)) fail('park', 'a code hash: 64 hex');
3127
+ return this.#unparkCancel(relayArg(relay), hash);
3128
+ }
3129
+
3130
+ // A public code's long code: GET /park/<public hash> (relay/park.mjs), not spent there. → { invite, relay }.
3131
+ async #unparkPublic(text, relay) {
3132
+ const norm = normalisePub(text), shown = formatPub(norm);
3133
+ const { relay: at } = await this.relayForShort(norm, { relay });
3134
+ const r = await http(this.platform, `${endpointOf(at, this.endpoints).http}/park/${publicHash(text)}`);
3135
+ if (r.status === 429) refuse('rate', `the relay ${at} looks up no more public codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}, or use its sgl2 code`, r);
3136
+ if (r.status === 409 && r.body?.check === 'public_paused') refuse('public_paused', `${shown} is paused by its owner: try again later`, r);
3137
+ if (r.status === 404 && r.body?.check === 'park_unknown') refuse('park_unknown', `${shown}: no public code under it at ${at}: revoked, ended, or mistyped`, r);
3138
+ if (r.status !== 200 || r.body?.ok !== true || typeof r.body.invite !== 'string' || !r.body.invite.startsWith('sgl2')) refuse(r.status === 200 ? 'park' : 'connect', `${at}: ${r.status === 200 ? 'GET /park answered without a public code' : statusWhy(r, 'GET /park')}`, r);
2461
3139
  return { invite: r.body.invite, relay: at };
2462
3140
  }
2463
3141
 
@@ -2483,6 +3161,16 @@ export class Carrier {
2483
3161
  // relay: the relay a short code was parked at (unpark), and the one a code must name (a long
2484
3162
  // code names its own: one naming another is refused code_relay).
2485
3163
  async accept(text, opts = {}) {
3164
+ // An enrolment code (ENROL-…, short.mjs) is for init --enrol on a new machine: refused here before any
3165
+ // fetch, so it is not spent and its operator is never made a contact of this identity by it.
3166
+ if (isEnrolCode(typeof text === 'string' ? text : '')) fail('enrol_code', 'that is an enrol code: run init --enrol CODE (sigelo-agent init --enrol, or sigelo_enrol), on a machine with no identity yet');
3167
+ // A public code's link carries its code and the four words to check (public.mjs readLink).
3168
+ const link = readLink(typeof text === 'string' ? text.trim() : text);
3169
+ if (link) { text = link.code; opts = { ...opts, words: opts.words ?? link.words ?? undefined }; }
3170
+ if (isPub(text)) {
3171
+ const { invite, relay: at } = await this.#unparkPublic(text, opts.relay);
3172
+ return this.#answer(invite, 'parked', { ...opts, relay: at });
3173
+ }
2486
3174
  // Short or long by the input's shape, before either parser runs (short.mjs codeKind).
2487
3175
  const how = codeKind(text) === 'short' ? 'parked' : 'long';
2488
3176
  if (how !== 'parked') return this.#answer(text, how, opts);
@@ -2491,11 +3179,15 @@ export class Carrier {
2491
3179
  try { return await this.#answer(long, how, { ...opts, relay: at }); } catch (e) { throw keepLong(e, long); }
2492
3180
  }
2493
3181
 
2494
- async #answer(text, how, { name, wait = 10, tier, relay } = {}) {
3182
+ // words (a public code's): the inviter's four words as its page published them, checked on the reply.
3183
+ async #answer(text, how, { name, wait = 10, tier, relay, started, words } = {}) {
2495
3184
  if (tier !== undefined && !TIERS.includes(tier)) fail('tier', `a tier is ${TIERS.join(', ')}; not ${JSON.stringify(tier)}`);
2496
3185
  const named = relay === undefined ? undefined : relayArg(relay);
2497
- const { code, id, entry } = this.#locked(({ now, me, store, st }) => {
3186
+ const given = words === undefined || words === null ? null : normaliseWords(words);
3187
+ const { code, id, entry, reply, until } = this.#locked(({ now, me, store, st }) => {
2498
3188
  const code = readCode(text, now, how);
3189
+ const pub = code.version === PUBLIC_VERSION;
3190
+ if (given !== null && !pub) fail('words', 'four words are checked with a public code (PUB-…) only; compare a one-time code\'s words after pairing');
2499
3191
  if (named !== undefined && code.relay !== named) fail('code_relay', `the code names ${code.relay}, not ${named} (--relay): leave --relay out, or ask the inviter which relay it used`);
2500
3192
  // This agent's own relay, those its operator configured, and one it named (--relay) are the operator's choice.
2501
3193
  if (code.relay !== this.relay && code.relay !== named && !Object.hasOwn(this.endpoints ?? {}, code.relay) && !publicRelay(code.relay)) {
@@ -2507,16 +3199,19 @@ export class Carrier {
2507
3199
  if (known?.revoked && !(known.relink?.until > now)) fail('revoked', `${known.did} was revoked by this owner${known.ended ? ` (link ${known.ended.id} ended): a new link needs both operators to ask again` : ''}`);
2508
3200
  const k = kemKey();
2509
3201
  try {
2510
- const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null });
2511
- const keys = inviteKeys(code.secret), frame = seal(KIND.invite_answer, keys.key, keys.answer_topic, answer);
3202
+ const answer = buildAnswer({ code, identity: { sign: me.sign, genesis: me.genesis }, bundle: chainOf(me.bundle), kem_pk: k.pk, prekeys: null, ...(pub && { iat: now }) });
3203
+ const keys = pub ? publicKeys(code.secret) : inviteKeys(code.secret), frame = seal(KIND.invite_answer, keys.key, keys.answer_topic, answer);
2512
3204
  // Checked before anything is stored: the relay would refuse it (quota_storage).
2513
3205
  if (frame.length > INVITE_BYTES) fail('too_large', `the answer is ${frame.length} bytes, more than an invite topic holds (${INVITE_BYTES}): this agent's chain is too long`);
2514
3206
  const id = answerId(answer);
2515
3207
  // Unnamed: the code's DID's first digits ("z5esAbCd"), as operators shorten a DID. Named, the
2516
3208
  // name also replaces a known contact's on a re-pair (#onReply).
2517
- store.addAccept(code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined, tier ?? null);
2518
- const entry = this.#queue(st, { relay: code.relay, topic: keys.answer_topic, bytes: frame, kind: KIND.invite_answer, control: 'answer', needs: [keys.reply_topic], exp: code.exp });
2519
- return { code, id, entry: entry.id };
3209
+ // A public code's request lives REQUEST_TTL at most (its reply topic's life), on its own topic.
3210
+ const until = pub ? Math.min(code.exp, now + REQUEST_TTL) : code.exp, reply = pub ? joinerKeys(code.secret, id).reply_topic : keys.reply_topic;
3211
+ store.addAccept(pub ? { ...code, exp: until } : code, id, name ?? code.did.slice('did:sigelo:'.length, 'did:sigelo:'.length + 8), now, hex(k.secretKey), me.current_did, name !== undefined, tier ?? null,
3212
+ pub ? { public: true, ...(given !== null && { words: given }) } : {});
3213
+ const entry = this.#queue(st, { relay: code.relay, topic: keys.answer_topic, bytes: frame, kind: KIND.invite_answer, control: 'answer', needs: [reply], exp: until });
3214
+ return { code, id, entry: entry.id, reply, until };
2520
3215
  } finally { k.secretKey.fill(0); }
2521
3216
  });
2522
3217
  // Refused: the answer and the pending entry go, so no later connection sends or waits for them.
@@ -2526,10 +3221,9 @@ export class Carrier {
2526
3221
  };
2527
3222
  // Done early too once the reply topic or the answer is refused (a code answered before:
2528
3223
  // mailbox_taken), not after the whole wait.
2529
- const reply = inviteKeys(code.secret).reply_topic;
2530
3224
  // And once the code expires (#lapse): the answer is dead, so --wait does not run out first.
2531
- const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >= code.exp;
2532
- try { await this.#session([code.relay], { max: wait * 1000, until: settled }); } catch (e) {
3225
+ const settled = () => this.#handshakes.has(id) || this.#refusedTopics.has(reply) || Boolean(this.#results.get(entry)?.code) || this.clock() >= until;
3226
+ try { await this.#session([code.relay], { max: wait * 1000, until: settled }, started); } catch (e) {
2533
3227
  // A relay other than this agent's own that refuses it for good would be dialled again at
2534
3228
  // every connection, until the code expires, for an answer it never takes: and a stranger's
2535
3229
  // code names it. Withdrawn only while it waits to go: an answer the relay holds keeps its
@@ -2562,33 +3256,191 @@ export class Carrier {
2562
3256
  // The code expired during the wait: #lapse emitted pairing_failed (onEvent); the refusal says
2563
3257
  // it here, so the next inbox does not say it again. No long code to keep (keepLong): it is dead.
2564
3258
  const lapsed = this.#locked(({ now, store, st }) => {
2565
- if (now < code.exp) return null;
3259
+ if (now < until) return null;
2566
3260
  st.pending = st.pending.filter((p) => p.id !== entry); store.take('accepts', id, now);
2567
- const at = new Date(code.exp * 1000).toISOString().replace('.000', '');
3261
+ const at = new Date(until * 1000).toISOString().replace('.000', '');
2568
3262
  const i = st.events.findIndex((e) => e.type === 'pairing_failed' && e.code === 'code_expired' && e.did === code.did && e.detail?.includes(at));
2569
3263
  return i >= 0 ? st.events.splice(i, 1)[0].detail : `the code expired at ${at} before the inviter's agent replied: ask the inviter for a new code`;
2570
3264
  });
2571
3265
  if (lapsed) throw Object.assign(new MsgError('code_expired', lapsed), { lapsed: true });
3266
+ if (sent && code.version === PUBLIC_VERSION) return { status: 'waiting_approval', did: code.did, relay: code.relay, exp: until, words_given: given,
3267
+ detail: 'sent: the inviter accepts each new chat; if not within 7 days, this request ends (inbox then says so)' };
2572
3268
  if (!sent) return { status: 'pending', did: code.did, relay: code.relay, detail: 'the answer has not reached the relay yet: it goes at the next connection' };
2573
3269
  return { status: 'waiting', did: code.did, relay: code.relay, detail: 'answer delivered; the pairing completes when the inviter\'s agent next connects' };
2574
3270
  }
2575
3271
 
3272
+ // A public code (sigelo-public/0, design/public-invite.md): a version 2 long code parked at the
3273
+ // relay under a PUB code, for months (ttl up to PUBLIC_TTL_MAX), by an identity on Pro (the relay
3274
+ // refuses public_pro otherwise). Its answer topic is claimed first. cap: new chats a day (the
3275
+ // relay's and this agent's: PUBLIC_CAP); open: approved at once, no request (an agent service
3276
+ // with its own doorman). → { id, name, code, short, words, link, exp, relay, cap, open, did }.
3277
+ async invitePublic({ name, ttl = 183 * DAY, cap = PUBLIC_CAP, open = false, relay, started } = {}) {
3278
+ const at = relay === undefined ? this.relay : relayArg(relay);
3279
+ checkCap(cap);
3280
+ if (!Number.isSafeInteger(ttl) || ttl < DAY || ttl > PUBLIC_TTL_MAX) fail('ttl', `a public code lives a day to a year (${PUBLIC_TTL_MAX} s), not ${JSON.stringify(ttl)}`);
3281
+ if (name !== undefined && typeof name !== 'string') fail('name', 'a string');
3282
+ const { code, words } = this.#locked(({ now, me, store }) => {
3283
+ const code = makeInvite({ did: me.current_did, relay: at, now, ttl, version: PUBLIC_VERSION }), words = didWords(me.did);
3284
+ store.addPublic(code, { name: name ?? `public-${code.nonce.slice(1, 7)}`, cap, open, words }, now);
3285
+ return { code, words };
3286
+ });
3287
+ const drop = () => { try { this.#locked(({ store }) => store.dropPublic(code.nonce)); } catch {} this.#routes = new Map(); };
3288
+ const t = publicKeys(code.secret).answer_topic;
3289
+ try {
3290
+ this.#routes = new Map();
3291
+ await this.#session([at], {}, started);
3292
+ if (!this.#claimed.has(t)) {
3293
+ const r = this.#refusedTopics.get(t);
3294
+ fail(r?.code ?? 'subscribe', `the relay did not let this agent claim the public code's answer topic${r ? ` (${relaySays(r.detail)})` : ''}`);
3295
+ }
3296
+ const pub = formatPub(makeShort(undefined, at === this.shortRelay ? null : relayTag(at))), ep = endpointOf(at, this.endpoints);
3297
+ const creds = await this.#credentials(at, ep, started);
3298
+ const r = await http(this.platform, `${ep.http}/park`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, code_hash: publicHash(pub), invite: code.text, exp: code.exp, cap }) });
3299
+ const check = typeof r.body?.check === 'string' ? r.body.check : null;
3300
+ if (r.status === 429) refuse('rate', `the relay ${at} parks no more codes from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to an hour')}`, r);
3301
+ if ((r.status === 404 || r.status === 405) && check === null) refuse('park', `the relay ${at} takes no public codes`, r);
3302
+ if (r.status !== 200) refuse('connect', `${at}: ${statusWhy(r, 'POST /park')}`, r);
3303
+ if (check === 'public_pro') refuse('public_pro', `a public code comes with Pro: one allowance for all your agents (sigelo.io/pro.html; relay: ${relaySays(r.body?.detail)})`, r);
3304
+ if (r.body?.ok !== true) refuse(PARK_CHECKS.has(check) ? check : 'park', `the relay refused the public code (${relaySays(`${check}: ${r.body?.detail}`)})${check === 'park' ? ': an older relay takes no public codes' : ''}`, r);
3305
+ const held = Number.isSafeInteger(r.body.exp) && r.body.exp > 0 ? r.body.exp : code.exp;
3306
+ this.#locked(({ store }) => { const p = store.load().s.publics[code.nonce]; p.short = pub; store.save(); });
3307
+ const n = this.#read(({ store }) => store.load().s.publics[code.nonce].name);
3308
+ return { id: code.nonce, name: n, code: code.text, short: pub, words, link: publicLink(pub, words), exp: held, relay: at, cap, open: open === true, did: code.did };
3309
+ } catch (e) { drop(); throw e; }
3310
+ }
3311
+
3312
+ /** This agent's public codes, with their requests waiting: contacts().publics. */
3313
+ publics() { return this.#read(({ now, store }) => Object.entries(store.load().s.publics ?? {}).map(([n, p]) => publicView(n, p, now))); }
3314
+
3315
+ // The owner approves a request (by its id: the answer id), at once: the reply goes at this
3316
+ // session (queued if the relay cannot be reached). → { approved: true, did, name, fingerprint, queued? }.
3317
+ async approvePublic(id, { started } = {}) {
3318
+ let out;
3319
+ try {
3320
+ out = this.#locked((ctx) => {
3321
+ const f = ctx.store.findRequest(id) ?? fail('challenge_unknown', `no request waits with id ${JSON.stringify(id)}: approved, refused or ended`);
3322
+ if (f[2].exp <= ctx.now) fail('challenge_expired', 'this request is older than 7 days: the joiner\'s agent has given it up');
3323
+ return { relay: f[1].relay, events: this.#approve(ctx, f[0], f[2]) };
3324
+ });
3325
+ } catch (e) {
3326
+ // A request that cannot be approved (revoked since, too old) goes.
3327
+ if (e instanceof MsgError && e.check !== 'challenge_unknown' && !INTERNAL.has(e.check)) {
3328
+ try { this.#locked(({ store }) => { const f = store.findRequest(id); if (f) { delete f[1].requests[id]; store.save(); } }); } catch {}
3329
+ }
3330
+ throw e;
3331
+ }
3332
+ for (const e of out.events) this.#emit(e);
3333
+ const paired = out.events.find((e) => e.type === 'paired');
3334
+ if (!paired) { const f = out.events[0]; fail(f?.code ?? 'pairing', f?.detail ?? 'not paired'); }
3335
+ const base = { approved: true, did: paired.did, name: paired.name, fingerprint: paired.fingerprint };
3336
+ try { await this.#session([out.relay], {}, started); } catch (e) { return { ...base, queued: true, detail: `${reason(e)}: the reply goes at the next connection` }; }
3337
+ return base;
3338
+ }
3339
+
3340
+ /** The owner refuses a request: dropped, the joiner told nothing (its request ends after 7 days). */
3341
+ refusePublic(id) {
3342
+ return this.#locked(({ store }) => {
3343
+ const f = store.findRequest(id) ?? fail('challenge_unknown', `no request waits with id ${JSON.stringify(id)}`);
3344
+ delete f[1].requests[id];
3345
+ store.save();
3346
+ return { refused: true, did: f[2].did };
3347
+ });
3348
+ }
3349
+
3350
+ // Pause, Resume and the cap of a public code (its id, or its PUB code), at the relay (POST
3351
+ // /park/<hash>) and here. → the code's view.
3352
+ async setPublic(key, { paused, cap } = {}, { started } = {}) {
3353
+ if (paused !== undefined && typeof paused !== 'boolean') fail('paused', 'true or false');
3354
+ if (cap !== undefined) checkCap(cap);
3355
+ if (paused === undefined && cap === undefined) fail('public', 'paused or cap');
3356
+ const k = typeof key === 'string' && isPub(key) ? formatPub(normalisePub(key)) : key;
3357
+ const [nonce, p] = this.#read(({ store }) => store.findPublic(k)) ?? fail('challenge_unknown', 'no public code of this agent with this id or code');
3358
+ if (p.short === null) fail('challenge_unknown', 'this public code was never parked');
3359
+ const ep = endpointOf(p.relay, this.endpoints), creds = await this.#credentials(p.relay, ep, started);
3360
+ const r = await http(this.platform, `${ep.http}/park/${publicHash(p.short)}`, { method: 'POST', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password, ...(paused !== undefined && { paused }), ...(cap !== undefined && { cap }) }) });
3361
+ if (r.status === 429) refuse('rate', `the relay ${p.relay} takes no more requests from this network for now (${relaySays(r.body?.detail)}): ${retryIn(r, 'up to 10 minutes')}`, r);
3362
+ if (r.status === 404 && r.body?.check === 'park_unknown') refuse('park_unknown', `the relay ${p.relay} holds no such public code of yours (revoked or ended)`, r);
3363
+ if (r.status !== 200 || r.body?.ok !== true) refuse(typeof r.body?.check === 'string' ? r.body.check : 'connect', `${p.relay}: ${r.status === 200 ? relaySays(`${r.body?.check}: ${r.body?.detail}`) : statusWhy(r, 'POST /park/<hash>')}`, r);
3364
+ return this.#locked(({ now, store }) => {
3365
+ const q = store.load().s.publics[nonce];
3366
+ q.paused = r.body.paused === true; q.cap = r.body.cap ?? q.cap;
3367
+ store.save();
3368
+ return publicView(nonce, q, now);
3369
+ });
3370
+ }
3371
+
2576
3372
  // An invite this agent made and nobody has answered, withdrawn: code, its long code (invite's
2577
- // `code`). Its answer topic is given up at the next round; a short code parked for it leads to
2578
- // nothing. → { cancelled: true, name }.
2579
- async cancelInvite(code) {
2580
- const { relay, name } = this.#locked(({ now, store }) => {
2581
- const c = readCode(code, now), p = store.load().s.invites[c.nonce];
2582
- store.cancelInvite(c.nonce);
2583
- return { relay: c.relay, name: p.name };
3373
+ // `code`), its short code, or the short code's hash (64 hex digits). Its answer topic is given up
3374
+ // at the next round; the short code parked for it is cancelled at the relay (DELETE /park/<hash>,
3375
+ // relay/park.mjs: a tombstone until its exp), at `relay` when named, else where it was parked. A
3376
+ // relay that cannot be told (older, offline, rate) leaves it to run out there: it leads to nothing,
3377
+ // the invite being gone here. A short code or hash this agent keeps no invite for (made on another
3378
+ // device of this identity) is cancelled at the relay only. A renewing code's series ends with it.
3379
+ // → { cancelled: true, name, short?, unparked?, detail? }.
3380
+ async cancelInvite(code, { relay: named, started } = {}) {
3381
+ const text = stripEnrol(typeof code === 'string' ? code.trim() : '');
3382
+ // A public code (its id, PUB code, sgl2 code or hash): Revoke for all (public.mjs).
3383
+ const pkey = isPub(text) ? formatPub(normalisePub(text)) : text.startsWith('sgl2') ? (() => { try { return parsePublicCode(text, checkNow(this.clock())).nonce; } catch { return null; } })() : text;
3384
+ const pub = pkey ? this.#read(({ store }) => store.findPublic(pkey, (sh) => publicHash(sh))) : null;
3385
+ if (pub) return this.#revokePublic(pub[0], pub[1], started);
3386
+ const hash = /^[0-9a-f]{64}$/.test(text) ? text : null, kind = hash !== null ? 'hash' : codeKind(text);
3387
+ const short = kind === 'short' ? formatShort(normaliseShort(text)) : null;
3388
+ const found = this.#locked(({ now, store }) => {
3389
+ const inv = store.load().s.invites;
3390
+ const nonce = kind === 'long' ? readCode(text, now).nonce
3391
+ : Object.keys(inv).find((n) => typeof inv[n].short === 'string' && (short !== null ? inv[n].short === short : codeHash(inv[n].short) === hash));
3392
+ if (nonce === undefined) return null;
3393
+ const p = inv[nonce] ?? fail('challenge_unknown', 'no pending invite with this nonce');
3394
+ store.cancelInvite(nonce);
3395
+ return { name: p.name, relay: p.relay, short: p.short ?? null, short_exp: p.short_exp ?? 0, now };
2584
3396
  });
3397
+ if (found) {
3398
+ this.#routes = new Map();
3399
+ if (this.#links.get(found.relay)?.up) this.#refreshSoon(found.relay);
3400
+ }
3401
+ const shown = found?.short ?? short;
3402
+ if (shown === null && hash === null) return { cancelled: true, name: found.name };
3403
+ if (found && !(found.short_exp > found.now)) return { cancelled: true, name: found.name, short: found.short, unparked: true };
3404
+ const at = named !== undefined ? relayArg(named) : found ? found.relay : short !== null ? (await this.relayForShort(short)).relay : this.relay;
3405
+ const r = await this.#unparkCancel(at, hash ?? codeHash(shown), started);
3406
+ if (!found && !r.unparked) throw new MsgError(r.check ?? 'challenge_unknown', r.detail);
3407
+ if (!found && r.gone) fail('challenge_unknown', `${shown ?? 'that hash'}: no code of yours waits at ${at} (used, run out, or made elsewhere)`);
3408
+ return { cancelled: true, name: found?.name ?? null, ...(shown !== null && { short: shown }), unparked: r.unparked, ...(r.detail && { detail: r.detail }) };
3409
+ }
3410
+
3411
+ // Revoke for all: the relay's tombstone (DELETE /park/<hash>), then the code goes here with its
3412
+ // waiting requests, and its answer topic is given up at the next round. Pairings made stay.
3413
+ async #revokePublic(nonce, p, started) {
3414
+ const r = p.short !== null ? await this.#unparkCancel(p.relay, publicHash(p.short), started) : { unparked: true };
3415
+ this.#locked(({ store }) => store.dropPublic(nonce));
2585
3416
  this.#routes = new Map();
2586
- if (this.#links.get(relay)?.up) this.#refreshSoon(relay);
2587
- return { cancelled: true, name };
3417
+ if (this.#links.get(p.relay)?.up) this.#refreshSoon(p.relay);
3418
+ return { cancelled: true, name: p.name, public: true, ...(p.short && { short: p.short }), unparked: r.unparked, ...(r.detail && { detail: r.detail }) };
3419
+ }
3420
+
3421
+ // DELETE /park/<hash> with a login of its own (as invite's POST /park). → { unparked, gone?, check?, detail? };
3422
+ // never throws: the invite is gone here whatever the relay says.
3423
+ async #unparkCancel(relay, hash, started) {
3424
+ try {
3425
+ const ep = endpointOf(relay, this.endpoints), creds = await this.#credentials(relay, ep, started);
3426
+ const r = await http(this.platform, `${ep.http}/park/${hash}`, { method: 'DELETE', body: JSON.stringify({ username: creds.username, client_id: creds.clientId, password: creds.password }) });
3427
+ const check = typeof r.body?.check === 'string' ? r.body.check : null;
3428
+ if (r.status === 200 && r.body?.ok === true) return { unparked: true };
3429
+ // Nobody can fetch it there: run out, or used and run out.
3430
+ if (r.status === 404 && check === 'park_unknown') return { unparked: true, gone: true };
3431
+ const later = 'it runs out there by itself; any answer to it is refused here';
3432
+ if ((r.status === 404 || r.status === 405) && check === null) return { unparked: false, check: 'park', detail: `the relay ${relay} cannot cancel a short code (an older relay): ${later}` };
3433
+ if (r.status === 429) return { unparked: false, check: 'rate', detail: `the relay ${relay} takes no more short-code requests from this network for now (${relaySays(r.body?.detail)}): ${later}` };
3434
+ return { unparked: false, check: check ?? 'connect', detail: `the relay ${relay} did not cancel the short code (${r.status === 200 ? relaySays(`${check}: ${r.body?.detail}`) : statusWhy(r, 'DELETE /park')}): ${later}` };
3435
+ } catch (e) {
3436
+ return { unparked: false, check: e.check ?? 'connect', detail: `${reason(e)}: the short code runs out at the relay by itself; any answer to it is refused here` };
3437
+ }
2588
3438
  }
2589
3439
 
2590
3440
  /** The owner renames a contact (a name or any DID of its chain; store.mjs rename) → { did, name }. */
2591
3441
  rename(who, name) { return this.#locked(({ store }) => store.rename(who, name)); }
3442
+ /** This side's display name as it is told to new contacts (the header's "Names"), or null. */
3443
+ selfName() { try { return theirName(this.#selfName()); } catch { return null; } }
2592
3444
 
2593
3445
  contacts() {
2594
3446
  return this.#read(({ now, store, st }) => {
@@ -2598,18 +3450,30 @@ export class Carrier {
2598
3450
  const e = st.peers[c.did], pair = c.revoked || !c.pair_key ? null : pairId(hexToBytes(c.pair_key));
2599
3451
  return { name: c.name, did: c.did, current_did: c.current_did, chain: c.chain, revoked: c.revoked, relay: c.relay, queued: e?.outbox.length ?? 0,
2600
3452
  re_pair: c.re_pair ?? null, fingerprint: c.revoked ? null : wordsOf(c.pair_key), pair, ours: store.oursOf(c, now), tier: store.tierOf(c, now), tier_by: c.tier_by ?? null,
2601
- prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null, link: c.link ?? null };
3453
+ prekeys: pair !== null && theirPrekeys(c, e?.session, pair, now), waiting: e?.waiting ?? null, link: c.link ?? null,
3454
+ // Presence (the header's): what this contact sees of mine, and theirs as read now (null: not known).
3455
+ presence: store.presenceOf(c, now), online: st.presence?.[c.did]?.online ?? null, online_since: st.presence?.[c.did]?.since ?? null, last_seen: st.presence?.[c.did]?.last_seen ?? null,
3456
+ seen_upto: e?.seen_upto ?? null, seen_peer: e?.seen_peer === true,
3457
+ busy: (e?.busy_until ?? 0) > now, busy_peer: e?.busy_peer === true, via: c.via ?? null, name_from: c.name_from ?? null };
2602
3458
  }),
2603
- invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay })),
3459
+ invites: Object.values(s.invites).filter((p) => p.exp > now).map((p) => ({ name: p.name, exp: p.exp, relay: p.relay,
3460
+ ...(typeof p.short === 'string' && { short: p.short, short_exp: p.short_exp }), ...(p.renew && { renew: p.renew }) })),
3461
+ // Renewing codes (store.mjs renew): each series, its codes used, and why its last renewal failed (null: none).
3462
+ renewing: Object.entries(s.renew ?? {}).map(([id, x]) => ({ id, name: x.name, used: x.used, error: x.error ?? null })),
2604
3463
  answers: Object.values(s.accepts).filter((p) => p.exp > now).map((p) => ({ name: p.name, did: p.code_did, exp: p.exp, relay: p.relay })),
3464
+ // Public codes of mine (public.mjs), with the requests waiting for approval.
3465
+ publics: Object.entries(s.publics ?? {}).filter(([, p]) => p.exp > now).map(([n, p]) => publicView(n, p, now)),
2605
3466
  // Pairings that failed since the last inbox, which takes them as events.
2606
3467
  failed: st.events.filter((e) => e.type === 'pairing_failed').map(({ name, did, code, detail, at }) => ({ name, did, code, detail, at })),
2607
3468
  };
2608
3469
  });
2609
3470
  }
2610
3471
 
2611
- async send(to, content, { label = '', local = false, internal } = {}) {
2612
- const [r] = await this.#sendAll(to, [content], label, false, local, internal);
3472
+ // expires (unix seconds, optional): past it the message is dropped from the outbox unsent (refused
3473
+ // `expired`): a remote control's request or pushed state is worth minutes (apps/contact/control.mjs TTL).
3474
+ async send(to, content, { label = '', local = false, internal, expires } = {}) {
3475
+ if (expires !== undefined && !Number.isSafeInteger(expires)) fail('body', 'expires: unix seconds');
3476
+ const [r] = await this.#sendAll(to, [content], label, false, local, internal, expires);
2613
3477
  // side: whose quota a quota_storage is (relay/allowance.mjs), on the error too.
2614
3478
  if (r.status === 'refused') throw Object.assign(new MsgError(r.code, `refused (${r.detail})`), r.side && { side: r.side });
2615
3479
  return r;
@@ -2620,12 +3484,63 @@ export class Carrier {
2620
3484
  // the contact's claim on the topic; queued: it goes at the next connection.
2621
3485
  async sendAll(to, contents, { label = '', local = false } = {}) { return this.#sendAll(to, contents, label, false, local); }
2622
3486
 
3487
+ // A seen receipt (the header's "Seen receipts"): every message of to's sealed at or before upto was shown.
3488
+ async seen(to, upto, { local = false } = {}) {
3489
+ if (!Number.isSafeInteger(upto) || upto < 0) fail('body', 'upto: unix seconds, 0 for none yet');
3490
+ return this.send(to, { seen: upto, busy: true }, { label: SEEN_LABEL, local, internal: SEEN_SEND });
3491
+ }
3492
+
3493
+ // A busy mark (the header's "Busy marks"): on, a turn runs for to; off, it ended. Only to a contact that
3494
+ // said it takes them (busy_peer), else { status: 'skipped' }; unsent past BUSY_TTL_S.
3495
+ async busy(to, on, { local = false } = {}) {
3496
+ const peer = this.#read(({ store, st }) => st.peers[this.#resolve(store, to).did]?.busy_peer === true);
3497
+ if (!peer) return { status: 'skipped', to, detail: 'this contact never said it takes busy marks' };
3498
+ return this.send(to, { busy: on === true }, { label: BUSY_LABEL, local, internal: BUSY_SEND, expires: this.clock() + BUSY_TTL_S });
3499
+ }
3500
+
3501
+ // Read marks (the header's "Seen receipts", 0.1.19): an agent's reader took these items (inbox, the MCP, a hook,
3502
+ // a host turn), so their senders get a seen receipt, by code, never the agent's own. Per contact the newest iat of
3503
+ // its direct messages (group items and ones without iat: none); once per message (the state's read_sent). An own
3504
+ // contact (its tier) always; anyone else as the app does: a first one, more only once theirs came (seen_peer).
3505
+ // → [{ to, upto, status | error }], one per receipt sent; local: queued for a started carrier elsewhere.
3506
+ async read(items, { local = false } = {}) {
3507
+ const due = this.#locked(({ now, store, st }) => {
3508
+ const tiers = store.tiers(now), newest = new Map(), out = [];
3509
+ for (const m of Array.isArray(items) ? items : []) {
3510
+ if (m === null || typeof m !== 'object' || typeof m.from !== 'string' || m.group !== undefined || !Number.isSafeInteger(m.iat) || m.iat <= 0) continue;
3511
+ newest.set(m.from, Math.max(newest.get(m.from) ?? 0, m.iat));
3512
+ }
3513
+ for (const [from, upto] of newest) {
3514
+ let c = null;
3515
+ try { c = store.lookup(from); } catch {}
3516
+ if (!c || c.revoked) continue;
3517
+ const e = this.#entry(st, c.did);
3518
+ if (upto <= (e.read_sent ?? 0)) continue;
3519
+ if (tiers.get(c.did) !== 'own' && !e.seen_peer && e.read_told) continue;
3520
+ e.read_sent = upto; e.read_told = true;
3521
+ out.push({ to: c.did, upto });
3522
+ }
3523
+ return out;
3524
+ });
3525
+ const r = [];
3526
+ for (const x of due) {
3527
+ try { r.push({ ...x, status: (await this.seen(x.to, x.upto, { local }))?.status ?? null }); } catch (e) { r.push({ ...x, error: e.message }); }
3528
+ }
3529
+ return r;
3530
+ }
3531
+
2623
3532
  // spool: every content after the first waits on disk (#spool), as a file's chunks do. local: queued
2624
3533
  // only, for the started carrier of this identity in another process (inbox's local, for sending).
2625
- async #sendAll(to, contents, label, spool, local = false, internal = null) {
3534
+ // replyTo: the id of a message received (reply): its record keeps these ids, queued, in the same lock.
3535
+ async #sendAll(to, contents, label, spool, local = false, internal = null, expires = undefined, replyTo = null) {
2626
3536
  if (typeof label !== 'string') fail('body', 'label must be a string');
2627
3537
  if (label === LABEL_PREKEYS || label === OPERATOR_LABEL) fail('body', `the label ${JSON.stringify(label)} is the carrier's own`);
2628
3538
  if (label.startsWith('sigelo-link/') && internal !== LINK_SEND) fail('body', `the label ${JSON.stringify(label)} is the link handler's own (sigelo-agent link)`);
3539
+ if (label.startsWith('sigelo-group/') && internal !== GROUP_SEND) fail('body', `the label ${JSON.stringify(label)} is the group handler's own (sigelo-agent group send)`);
3540
+ if (label.startsWith('sigelo-transfer/') && internal !== TRANSFER_SEND) fail('body', `the label ${JSON.stringify(label)} is the transfer engine's own (sigelo-agent transfer)`);
3541
+ if (label.startsWith('sigelo-call/') && internal !== CALL_SEND) fail('body', `the label ${JSON.stringify(label)} is the calls' own (the page's call screen)`);
3542
+ if (label.startsWith('sigelo-seen/') && internal !== SEEN_SEND) fail('body', `the label ${JSON.stringify(label)} is the seen receipts' own`);
3543
+ if (label.startsWith('sigelo-busy/') && internal !== BUSY_SEND) fail('body', `the label ${JSON.stringify(label)} is the busy marks' own`);
2629
3544
  if (label.startsWith('sigelo-device/') && internal !== DEVICE_SEND) fail('body', `the label ${JSON.stringify(label)} is the device verbs' own (sigelo-agent device)`);
2630
3545
  if (!Array.isArray(contents) || contents.length === 0) fail('body', 'at least one message');
2631
3546
  for (const content of contents) {
@@ -2648,13 +3563,14 @@ export class Carrier {
2648
3563
  }
2649
3564
  });
2650
3565
  }
2651
- const { ids, c } = this.#locked(({ store, st }) => {
3566
+ const { ids, c } = this.#locked(({ now, store, st }) => {
2652
3567
  const c = this.#resolve(store, to), outbox = this.#entry(st, c.did).outbox;
2653
3568
  const ids = contents.map((content, i) => {
2654
3569
  const id = randomId();
2655
- if (spool && i > 0) { this.#spool(id, content); outbox.push({ id, label, spool: true }); } else outbox.push({ id, label, content });
3570
+ if (spool && i > 0) { this.#spool(id, content); outbox.push({ id, label, spool: true }); } else outbox.push({ id, label, content, ...(expires !== undefined && { exp: expires }) });
2656
3571
  return id;
2657
3572
  });
3573
+ if (replyTo !== null) received(st, replyTo, c.did, now).reply = { ids, wait: ids, status: 'queued', queued: now, label, ...(spool && { file: contents[0]?.name ?? null }) };
2658
3574
  return { ids, c };
2659
3575
  });
2660
3576
  if (local) return ids.map((id) => ({ status: 'queued', id, to: c.did, name: c.name, detail: 'kept for the process that holds this identity\'s relay session: it sends it' }));
@@ -2676,7 +3592,8 @@ export class Carrier {
2676
3592
  // refused, so a confused or misled agent cannot send its key (platform openPath). file: a path, or
2677
3593
  // { bytes, name } (a page's file: no path to check). A refusal of any part throws as send does:
2678
3594
  // the contact gets no file, and what came of it there goes at its retention.
2679
- async sendFile(to, file, { local = false } = {}) {
3595
+ async sendFile(to, file, { local = false } = {}) { return this.#sendFile(to, file, local, null); }
3596
+ async #sendFile(to, file, local, replyTo) {
2680
3597
  let bytes, leaf, what;
2681
3598
  if (typeof file === 'string') {
2682
3599
  if (file === '') fail('file', 'a file path is required');
@@ -2689,7 +3606,7 @@ export class Carrier {
2689
3606
  } else fail('file', 'a file path is required');
2690
3607
  if (bytes.length > MAX_FILE) fail('file_too_large', `${what} is ${bytes.length} bytes, at most ${MAX_FILE} (8 MiB) a file`);
2691
3608
  const { manifest, chunks } = splitFile(bytes, leaf);
2692
- const results = await this.#sendAll(to, [manifest, ...chunks], FILE_LABEL, true, local);
3609
+ const results = await this.#sendAll(to, [manifest, ...chunks], FILE_LABEL, true, local, null, undefined, replyTo);
2693
3610
  const refused = results.find((x) => x.status === 'refused'), queued = results.find((x) => x.status === 'queued');
2694
3611
  if (refused) fail(refused.code, `refused (${refused.detail}): ${manifest.name} did not go whole; send it again once that is settled`);
2695
3612
  const { id, name, size, sha256: sum, chunks: n } = manifest;
@@ -2697,16 +3614,93 @@ export class Carrier {
2697
3614
  ...(queued && { detail: queued.detail }) };
2698
3615
  }
2699
3616
 
3617
+ // ---- the agent task loop (apps/agent/WATCH.md "Accept now, reply later"): a message taken
3618
+ // now (a hook that spooled it, watch --spool) is answered later by its id (messageId), to its sender.
3619
+
3620
+ // The record of a message received, by id: the state's (RECEIVED_DAYS), else one still in the inbox
3621
+ // or in the log (an item kept by an earlier version, id derived), filed now. → the record, or throws msg_unknown.
3622
+ #receivedFor(id) {
3623
+ if (typeof id !== 'string' || !MSG_ID.test(id)) {
3624
+ fail(/^[0-9a-f]{16}\.[0-9a-f]{16}$/.test(String(id)) ? 'msg_group' : 'msg_id', /\./.test(String(id))
3625
+ ? `${JSON.stringify(id)} is a group message's id: answer in the group (sigelo-agent group send <group> <text> --re <mid>)`
3626
+ : `a message id is 32 hex digits (SIGELO_MSG_ID, an inbox item's id), not ${JSON.stringify(id)}`);
3627
+ }
3628
+ const known = this.#read(({ st }) => st.received?.[id] ?? st.inbox.find((m) => messageId(m) === id) ?? null)
3629
+ ?? this.history().messages.find((m) => messageId(m) === id) ?? null;
3630
+ if (known === null) fail('msg_unknown', `no message ${id} here: unknown, or received more than ${RECEIVED_DAYS} days ago`);
3631
+ return this.#locked(({ now, st }) => received(st, id, known.from, Number.isSafeInteger(known.ts) ? known.ts : known.received ?? now));
3632
+ }
3633
+
3634
+ /** A text (or any content send takes) to the sender of message `id` → send's result, with msg_id and delivery (replyStatus). */
3635
+ async reply(id, content, { label = 'reply', local = false } = {}) {
3636
+ const rec = this.#receivedFor(id);
3637
+ const [r] = await this.#sendAll(rec.from, [content], label, false, local, null, undefined, id);
3638
+ if (r.status === 'refused') throw Object.assign(new MsgError(r.code, `refused (${r.detail})`), r.side && { side: r.side });
3639
+ return { ...r, msg_id: id, delivery: this.replyStatus(id).reply };
3640
+ }
3641
+
3642
+ /** The label of a reply quoting received message `id` (a text): re/<h>/r (the header's "Replies"). */
3643
+ quote(id) {
3644
+ this.#receivedFor(id);
3645
+ const m = this.#read(({ st }) => st.inbox.find((x) => messageId(x) === id)) ?? this.history().messages.find((x) => messageId(x) === id);
3646
+ if (!m || typeof m.content !== 'string') fail('msg_unknown', `message ${id} is not a text here to quote (a file, or gone from the log)`);
3647
+ return reLabel(m.content, false);
3648
+ }
3649
+
3650
+ /** A file, as sendFile, to the sender of message `id` → sendFile's result, with msg_id and delivery. */
3651
+ async replyFile(id, file, { local = false } = {}) {
3652
+ const rec = this.#receivedFor(id);
3653
+ const r = await this.#sendFile(rec.from, file, local, id);
3654
+ return { ...r, msg_id: id, delivery: this.replyStatus(id).reply };
3655
+ }
3656
+
3657
+ /**
3658
+ * What is known of message `id` and the last reply to it → { msg_id, from, name, received, reply, fetched }.
3659
+ * reply: null, or { status: queued (here, not yet at the relay) | published (the relay holds it in the
3660
+ * contact's mailbox) | refused, queued_at, published_at, code, detail, parts, label, file? }. fetched:
3661
+ * always null: sigelo/0 has no read receipt, the relay does not tell the sender. contact: its presence
3662
+ * as this agent sees it ({online, last_seen}, when the contact lets it see), a hint only.
3663
+ */
3664
+ replyStatus(id) {
3665
+ this.#receivedFor(id);
3666
+ return this.#read(({ store, st }) => {
3667
+ const rec = st.received[id], c = store.lookup(rec.from), r = rec.reply ?? null, p = st.presence?.[rec.from];
3668
+ return {
3669
+ msg_id: id, from: rec.from, name: c?.name ?? null, received: rec.ts,
3670
+ reply: r && { status: r.status, queued_at: r.queued, published_at: r.published ?? null, code: r.code ?? null, detail: r.detail ?? null, parts: r.ids.length, label: r.label,
3671
+ ...(r.file !== undefined && { file: r.file }) },
3672
+ fetched: null,
3673
+ ...(p && { contact: { online: p.online, last_seen: p.last_seen ?? null } }),
3674
+ };
3675
+ });
3676
+ }
3677
+
3678
+ // A reply's part `id` went (published), or the relay or this carrier refused it: its record says so.
3679
+ #replyMark(st, id, now, refused = null) {
3680
+ for (const rec of Object.values(st.received ?? {})) {
3681
+ const r = rec.reply;
3682
+ if (!r?.wait?.includes(id)) continue;
3683
+ if (refused) Object.assign(r, { status: 'refused', code: refused.code, detail: refused.detail, wait: [] });
3684
+ else {
3685
+ r.wait = r.wait.filter((x) => x !== id);
3686
+ if (r.wait.length === 0 && r.status === 'queued') Object.assign(r, { status: 'published', published: now });
3687
+ }
3688
+ return;
3689
+ }
3690
+ }
3691
+
2700
3692
  // tiers: only messages from contacts of these tiers are taken (and waited for); the rest stay for a
2701
3693
  // later inbox. Events are all taken. local: no session: what the state file holds, waited for by
2702
3694
  // reading it again, for a reader beside a started carrier of the same identity (a watcher), which
2703
- // a session here would disconnect.
2704
- async inbox({ wait = 0, tiers, local = false, paired = false } = {}) {
3695
+ // a session here would disconnect. from: only that contact's messages (its original DID), the
3696
+ // rest stay (MCP sigelo_wait_for_message).
3697
+ async inbox({ wait = 0, tiers, local = false, paired = false, from } = {}) {
2705
3698
  const want = tiers === undefined ? null : new Set(tiers);
2706
3699
  if (want && ![...want].every((t) => TIERS.includes(t))) fail('tier', `tiers: some of ${TIERS.join(', ')}`);
2707
- const picks = (store, now) => { const t = want && store.tiers(now); return (m) => !want || want.has(t.get(m.from) ?? 'friend'); };
2708
- const ready = () => this.#read(({ now, store, st }) => st.inbox.some(picks(store, now)) || (st.links?.length ?? 0) > 0 || (st.devices?.length ?? 0) > 0 || st.events.some((e) => e.type === 'pairing_failed' || (paired && e.type === 'paired')));
2709
- let offline = null;
3700
+ if (from !== undefined && typeof from !== 'string') fail('body', 'from: a contact\'s DID');
3701
+ const picks = (store, now) => { const t = want && store.tiers(now); return (m) => (from === undefined || m.from === from) && (!want || want.has(t.get(m.from) ?? 'friend')); };
3702
+ const ready = () => this.#read(({ now, store, st }) => st.inbox.some(picks(store, now)) || (st.links?.length ?? 0) > 0 || (st.groups?.length ?? 0) > 0 || (st.devices?.length ?? 0) > 0 || st.events.some((e) => e.type === 'pairing_failed' || (paired && e.type === 'paired')));
3703
+ let offline = null, ended = null;
2710
3704
  if (local) {
2711
3705
  for (const end = Date.now() + wait * 1000; Date.now() < end && !ready();) await sleep(250);
2712
3706
  } else {
@@ -2716,12 +3710,15 @@ export class Carrier {
2716
3710
  try {
2717
3711
  await this.#session(relays, wait > 0 ? { max: wait * 1000, until: ready } : {});
2718
3712
  } catch (e) { this.lastError = e; offline = e instanceof MsgError ? e.message : `connect: ${e.message}`; }
3713
+ ended = this.ended;
3714
+ // A renewing code this session took: its fresh one now, before the events go out.
3715
+ if (offline === null) await this.#renewDue();
2719
3716
  }
2720
3717
  return this.#locked(({ now, store, st }) => {
2721
3718
  this.#sweepFiles(st, now);
2722
3719
  const pick = picks(store, now), messages = st.inbox.filter(pick);
2723
3720
  this.#logOut(messages);
2724
- const out = { messages, events: st.events, dropped: st.dropped, ...(offline && { offline }) };
3721
+ const out = { messages: messages.map((m) => (reOf(m?.label) ? { ...m, re: reOf(m.label) } : m)), events: st.events, dropped: st.dropped, ...(offline && { offline }), ...(ended && { ended }) };
2725
3722
  st.inbox = st.inbox.filter((m) => !pick(m)); st.events = []; st.dropped = {};
2726
3723
  return out;
2727
3724
  });
@@ -2759,11 +3756,32 @@ export class Carrier {
2759
3756
  }
2760
3757
 
2761
3758
  setTier(who, tier) { return this.#locked(({ now, store }) => store.setTier(who, tier, now)); }
3759
+ setPresence(who, allow) {
3760
+ const r = this.#locked(({ now, store }) => { const x = store.setPresence(who, allow, now); return { ...x, relay: store.lookup(x.did)?.relay }; });
3761
+ if (r.relay && this.#links.get(r.relay)?.up) this.#refreshSoon(r.relay);
3762
+ return { did: r.did, name: r.name, presence: r.presence };
3763
+ }
2762
3764
  // The owner's tier for an original DID before it is a contact (an enrolled worker): store.mjs presetTier.
2763
3765
  presetTier(did, tier) { return this.#locked(({ now, store }) => store.presetTier(did, tier, now)); }
2764
3766
  // Links (link.mjs): the link messages received, taken; a contact's link record set (null: dropped).
2765
3767
  takeLinks() { return this.#locked(({ st }) => { const l = st.links ?? []; st.links = []; return l; }); }
3768
+ takeGroups() { return this.#locked(({ st }) => { const l = st.groups ?? []; st.groups = []; return l; }); }
2766
3769
  takeDevices() { return this.#locked(({ st }) => { const l = st.devices ?? []; st.devices = []; return l; }); }
3770
+ // pick(message) → take it (default all); the rest stay for a later take (an engine's).
3771
+ takeCalls(pick = () => true) { return this.#locked(({ st }) => { const l = st.calls ?? [], took = l.filter((m) => pick(m)); st.calls = l.filter((m) => !took.includes(m)); return took; }); }
3772
+ takeTransfers(pick = () => true) { return this.#locked(({ st }) => { const l = st.transfers ?? [], took = l.filter((m) => pick(m)); st.transfers = l.filter((m) => !took.includes(m)); return took; }); }
3773
+ // A file a transfer saved whole (transfer-node.mjs): an inbox item as #onFile makes one, kept for
3774
+ // inbox() (keep) and handed to onEvent. item: { type: 'file', from, contact, name, size, sha256, path, … }.
3775
+ deliver(item) {
3776
+ const it = { ...item, received: item.received ?? this.#read(({ now }) => now) };
3777
+ this.#locked(({ st }) => {
3778
+ if (!this.keep) return;
3779
+ st.inbox.push(it);
3780
+ if (st.inbox.length > INBOX_MAX) { const n = st.inbox.length - INBOX_MAX; st.inbox.splice(0, n); st.dropped.inbox_full = (st.dropped.inbox_full ?? 0) + n; }
3781
+ });
3782
+ this.#emit(it);
3783
+ return it;
3784
+ }
2767
3785
  // A copy of this state may have sent and received after it was taken (devices.md §4.3: the seat
2768
3786
  // moved, the state came in a snapshot). Every session with `only`'s contacts (default: all live)
2769
3787
  // starts afresh, as after a rotation: the outgoing epoch ends, the contact's one-time prekeys
@@ -2828,18 +3846,23 @@ export class Carrier {
2828
3846
 
2829
3847
  // ---- staying connected
2830
3848
 
2831
- async start() {
3849
+ /** started: 'user' when the human opened this (the page's start): its first login asks past the cap (pow_confirm). */
3850
+ async start({ started } = {}) {
2832
3851
  if (this.#started) return;
2833
3852
  this.#started = true;
2834
- for (const r of this.#relaysInUse()) this.#retry(r, 0);
3853
+ for (const r of this.#relaysInUse()) this.#retry(r, 0, started);
2835
3854
  this.#tick = setInterval(() => this.#round(), this.tick);
2836
3855
  this.#tick.unref?.();
3856
+ this.#renewSoon();
2837
3857
  }
2838
3858
 
2839
- #round() {
3859
+ // force (sync, the caller's): a relay waiting for its next automatic try (#powWait) is tried now too.
3860
+ #round(force = false) {
2840
3861
  this.#later(() => this.#locked((ctx) => this.#expireKeys(ctx)));
3862
+ this.#renewSoon();
2841
3863
  for (const l of this.#links.values()) l.absent.clear(); // an absent contact may be back: try once more
2842
3864
  for (const r of this.#relaysInUse()) {
3865
+ if (force) this.#unwait(r);
2843
3866
  if (this.#links.get(r)?.up) this.#refreshSoon(r);
2844
3867
  else if (!this.#timers.has(r) && !this.#connecting.has(r)) this.#retry(r, 0);
2845
3868
  }
@@ -2847,8 +3870,51 @@ export class Carrier {
2847
3870
 
2848
3871
  /** One round now (claims for a new week, queued messages), then wait as `inbox` does. */
2849
3872
  async sync({ wait = 0 } = {}) {
2850
- if (this.#started) { this.#round(); await this.#idle({ max: Math.max(DRAIN, wait * 1000) }); return; }
3873
+ if (this.#started) { this.#round(true); await this.#idle({ max: Math.max(DRAIN, wait * 1000) }); await this.#renewDue(); return; }
2851
3874
  await this.#session(this.#relaysInUse(), { max: Math.max(DRAIN, wait * 1000) });
3875
+ await this.#renewDue();
3876
+ }
3877
+
3878
+ #unwait(relay) {
3879
+ if (!this.#powWaits.delete(relay)) return;
3880
+ clearTimeout(this.#timers.get(relay));
3881
+ this.#timers.delete(relay);
3882
+ }
3883
+
3884
+ /** A nudge from outside (the phone woke): each relay in use down and not already waiting, a retry with the backoff; automatic (no proof-of-work confirmation). */
3885
+ // now (a push wake: mail waits at the relay): at once, past a backoff's wait already set.
3886
+ wake({ now = false } = {}) {
3887
+ if (!this.#started) return;
3888
+ for (const r of this.#relaysInUse()) {
3889
+ if (this.#links.get(r)?.up || this.#connecting.has(r)) continue;
3890
+ if (now && this.#timers.has(r) && !this.#powWaits.has(r)) { clearTimeout(this.#timers.get(r)); this.#timers.delete(r); }
3891
+ if (!this.#timers.has(r)) this.#retry(r, now ? 0 : undefined);
3892
+ }
3893
+ }
3894
+
3895
+ /**
3896
+ * The human's "Try now" (design/profiles.md §6): a login now at each relay in use that is not
3897
+ * connected, as a search they started: past the day's POW_SEARCHES it throws pow_confirm, and
3898
+ * { confirmed: true } goes on. → { tried: [relays] }; throws as the login does.
3899
+ */
3900
+ async tryNow({ confirmed = false } = {}) {
3901
+ const started = confirmed ? 'confirmed' : 'user', todo = this.#relaysInUse().filter((r) => !this.#links.get(r)?.up && !this.#connecting.has(r));
3902
+ for (const r of todo) {
3903
+ this.#unwait(r);
3904
+ clearTimeout(this.#timers.get(r));
3905
+ this.#timers.delete(r);
3906
+ this.#powFails.delete(r);
3907
+ this.#attempts.delete(r);
3908
+ }
3909
+ if (!this.#started) { await this.#session(todo, {}, started); return { tried: todo }; }
3910
+ for (const r of todo) {
3911
+ try { await this.#connect(r, started); } catch (e) {
3912
+ this.#emit({ type: 'error', relay: r, check: e.check ?? 'connect', detail: e.message, ...(e.next !== undefined && { next: e.next }) });
3913
+ if (!(PERMANENT.has(e.check) || e.permanent)) this.#retry(r);
3914
+ throw e;
3915
+ }
3916
+ }
3917
+ return { tried: todo };
2852
3918
  }
2853
3919
 
2854
3920
  async stop() {
@@ -2856,6 +3922,7 @@ export class Carrier {
2856
3922
  clearInterval(this.#tick);
2857
3923
  for (const t of this.#timers.values()) clearTimeout(t);
2858
3924
  this.#timers.clear();
3925
+ this.#powWaits.clear();
2859
3926
  await this.#drain();
2860
3927
  for (const link of [...this.#links.values()]) await this.#hangUp(link);
2861
3928
  }