sigelo-contact 0.1.14 → 0.1.21

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 +831 -0
  3. package/carrier.mjs +1013 -112
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +214 -35
  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 +28 -9
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +1 -1
  16. package/package.json +34 -7
  17. package/page.mjs +1018 -81
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +110 -13
  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 +109 -0
  25. package/short.mjs +19 -3
  26. package/store.mjs +126 -10
  27. package/test-carrier.mjs +121 -18
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +123 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +48 -7
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +6 -6
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +5 -5
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +323 -0
  39. package/test-short.mjs +35 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +313 -0
  42. package/test-transfer.mjs +51 -11
  43. package/test-voice.mjs +161 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +858 -0
  46. package/transfer-node.mjs +254 -641
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +25 -6
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +70 -0
  51. package/words-lock.mjs +25 -10
package/page.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: MIT
2
- // The page's routes over one carrier (adapters/moadim/UI-API.md), shared by `sigelo-agent ui`
3
- // (adapters/moadim/sigelo-agent-ui.ts: HTTP on 127.0.0.1) and the self-contained app (apps/web/router.mjs:
2
+ // The page's routes over one carrier (apps/agent/UI-API.md), shared by `sigelo-agent ui`
3
+ // (apps/agent/sigelo-agent-ui.ts: HTTP on 127.0.0.1) and the self-contained app (apps/web/router.mjs:
4
4
  // in the page). One route table, one JSON: what is the same everywhere is here; what one host has
5
5
  // and the other has not (the agents' directory, devices, the seat, the HTTP and LAN listeners)
6
6
  // comes in as hooks or as routes the host adds.
@@ -12,6 +12,7 @@
12
12
  // await p.start(), await p.halt() timers, the carrier's session, the first drain; halt: timers off, links done (then carrier.stop())
13
13
  // p.serial(fn), p.refuse(status, check, message), p.contactOf(did), p.cleanName(v, what), p.record(r), p.seen(did),
14
14
  // p.data, p.saveData(), p.live, p.recs, p.onChange(fn) for the host's own routes and its banners
15
+ // p.line the calls' Line (call.mjs): the host's Hang up from outside the page (a notification)
15
16
  //
16
17
  // store: the page's two files, the host's way: readHistory() → text | null, append(line) (a JSON
17
18
  // line and "\n"), clearHistory(), readData() → text | null, writeData(text). The history is every
@@ -25,7 +26,7 @@
25
26
  // confirm(name, match) → whether one was pending } (relay controls whose four words wait: the
26
27
  // Controls card; routes in no remote scope, so never asked over the relay or the LAN).
27
28
  //
28
- // Groups (adapters/moadim/GROUPS.md, design/groups.md §5): groups: group.mjs (the module) and groupsFile
29
+ // Groups (apps/agent/GROUPS.md, design/groups.md §5): groups: group.mjs (the module) and groupsFile
29
30
  // (groupsPath of the identity). Each drain hands the carrier's group messages to group.mjs handle(), here
30
31
  // in code: without it the page never takes a roster, carries a copy on or files a message. The page's
31
32
  // own marks in data: gread (gid → the newest item shown: {mid, at}), gnotices (a stranger added, the
@@ -42,38 +43,247 @@
42
43
  // derived from K (enrol.mjs `verified`) is words-checked here at once; the words stay to see, and the
43
44
  // optional switch (`confirm_words`) holds the key until "They match" (POST /api/agents/enrol-words).
44
45
  //
45
- // Transfers (adapters/moadim/TRANSFER.md, contact/transfer-node.mjs): hooks.transfers, where the host
46
- // moves big files ({ lib: transfer-node.mjs, make(carrier, onEvent) → its Engine }; Node only, until the
47
- // WebView's platform.rtc): the page owns the session, so its engine answers offers and moves the bytes;
48
- // the /api/transfers* routes; none without the hook (404 route).
46
+ // Keeper (UI-API.md "Keeper"): hooks.computer, where this profile is paired to a computer that runs the keeper:
47
+ // { name() → its name, call(method, path, body?) → { status, body } }. /api/keeper* go there; a limit is a
48
+ // policy-change signed here with this identity (the computer relays it, POST /api/keeper/policy). None: elsewhere.
49
+ //
50
+ // Transfers (apps/agent/TRANSFER.md, design/transfer.md §10): hooks.transfers, where the host moves big
51
+ // files ({ lib, identity, make(carrier, onEvent, { compared }) → its Engine; lib: transfer-node.mjs on a
52
+ // computer (a file by its path), transfer-web.mjs's in the phone app (a file picked: doc), which also gives
53
+ // pick(), photo({ keepLocation }), open(saved) and url(doc) }): the page owns the session, so its engine
54
+ // answers offers and moves the bytes; the /api/transfers* routes; none without the hook (404 route).
55
+ // compared(did): the contact's four words were compared here (the accept rule). A photo (PHOTO_LABEL,
56
+ // photo.mjs): its preview goes as one message (a group's: the msg's photo) beside the manifest; the chat
57
+ // shows it at once, then the full file by the transfer whose manifest has its sha256. A voice message (VOICE_LABEL,
58
+ // voice.mjs) goes the same way, its fields as the message and the recording as the file, where the host records
59
+ // (hooks.transfers.rec: write(rec, offset, bytes), keep(rec, name) → { doc } | { path }, read(saved) → bytes).
60
+ //
61
+ // Calls (UI-API.md "Calls", design/calls.md, call.mjs): one Line over this carrier, always; the media is the page's (ui.js's
62
+ // Phone), which reaches it by /api/calls*. hooks.calls, where the host has a shell: { alert({on, id, did, name}) the ring
63
+ // (the phone app: ringtone, vibration, a heads-up; the seam the push build wires to a full-screen ring), audio({on, id,
64
+ // name}) the call's audio mode (CallService), speaker(on), mic(), micSettings() }. "Can call me" (decision 2026-11-17):
65
+ // data.calls[did] true | false, else the default: off for a quiet contact, else data.settings.calls (default on).
66
+ // A call's chat line is a history record { kind: in | out, label CALL_LABEL, text "Call · 3:12" | "Missed call" | …,
67
+ // call: { id, state, secs } }; only a missed one counts as unread (a call taken or made here was seen).
68
+ // "Always relay my media" (design/calls.md §6, UI-API.md "Settings"): data.settings.relay_media, per profile (default
69
+ // off); SIGELO_ICE_POLICY=relay in the host's environment says the same. On: GET /api/calls/turn answers policy
70
+ // "relay" and the transfer engine is given it (relayMedia): every WebRTC lane only through the relay's TURN.
49
71
  //
50
72
  // Proof of work (design/profiles.md §6): what the human starts here (the page's start, a code, an
51
73
  // answer, "Try now") passes the carrier's `started: 'user'`; past the day's three the route answers
52
74
  // 409 pow_confirm, and the same call with `pow_confirmed: true` goes on. The carrier's automatic
53
75
  // retries stay capped: state's me.pow_capped {relay, next} says when the next one is.
54
76
  //
77
+ // Seen receipts (UI-API.md "Seen receipts", carrier.mjs's header): a message of mine is `seen` once the contact's
78
+ // newest receipt (contacts' seen_upto) is at or after the time I sent it. A contact's messages shown (GET /api/messages)
79
+ // send one receipt, the newest iat shown, unless data.settings.seen is false: to a contact that sent one (it reads
80
+ // them), or a first one to a contact not known to (an earlier version takes it as a message once, then hears no more;
81
+ // never to my own agents, which read none);
82
+ // the first receipt from a contact is answered once (a 0 when receipts are off), so both sides know. data.seen: each
83
+ // contact's {sent, told}. Chat defaults (data.settings): new_tier and new_presence, given to a contact at its pairing;
84
+ // notify (all chats) and data.notify (a chat: contact DID or gid → false) for the notifications.
85
+ //
86
+ // The Wallet settings (UI-API.md "Wallet", design/ux1/notes.md "Decided"): per profile, in data.settings: wallet (the
87
+ // switch, default off), prices (a local price, opt-in, default off) and currency (one of CURRENCIES). Read in state's
88
+ // me.wallet by every form of the page. This page holds no wallet: GET /api/wallet answers where: "none", its other
89
+ // wallet routes 409 wallet_none ("This phone has no wallet yet"); `sigelo-agent ui` answers them with the computer's.
90
+ //
91
+ // Pictures (UI-API.md "Pictures", design/ux1/notes.md "Decided"): store.readPicture(name) → bytes | null and
92
+ // store.writePicture(name, bytes | null), the host's (beside the page's data, 0600, on a computer; the profile's storage
93
+ // on the phone). data.pics: key → {type, rev, at} for 'me' (this identity's own), 'l:<did or gid>' (a local one for a
94
+ // contact or a group: wins) and 't:<did>' (the one a contact sent). Mine travels as one more body inside the
95
+ // end-to-end envelope (label PICTURE_LABEL: {type, data} or {remove: true}), never to the relay in the clear, and only to
96
+ // a contact known to read it: its seen receipt came (seen_peer) or its own picture did (data.pic_peer). An earlier
97
+ // version never gets one; data.pic_sent: what each contact has. A received one is checked (JPEG or WebP, at most
98
+ // PICTURE_MAX bytes), kept as t:<did>, never in the history.
99
+ //
100
+ // Signed statements (UI-API.md "Signed statements"): a text signed with this identity's key, portable: the text, a line
101
+ // naming the signer's four words, and `sigelo-statement/0 <base64url of JCS {body, sig, bundle}>`; body {v, typ:
102
+ // "statement", did (the signing key's DID), iat, text}, sig over "sigelo\n" ‖ JCS(body) (SPEC §3), bundle the chain only
103
+ // (genesis and rotations: no attestation, binding or issuer travels with it). Checked offline against that bundle
104
+ // (SPEC §9): the chain, the DID in it, the signature. In a chat: a message labelled STATEMENT_LABEL whose text is the
105
+ // portable form (an earlier version shows the text as it is). No protocol object: a chat-layer body.
106
+ //
107
+ // A hosted agent's approval and question (apps/agent sigelo-agent-host.ts "Approvals"): APPROVAL_LABEL {code, tool,
108
+ // summary, exp, text}, QUESTION_LABEL {question, options?, text}; checked (promptOf), kept as `approval` / `question`
109
+ // beside a one-line text; the page's buttons answer with a reply's text (`yes CODE`, an option). Malformed: shown as data.
110
+ //
111
+ // A hosted agent's settings (UI-API.md "Agent settings"; sigelo-agent-host.ts): HOST_CAPS_LABEL {fields: [{key, value,
112
+ // options: [{value, label}], off?, next?}], note?}, sent only to a page whose receipts said host: true (carrier.mjs
113
+ // host_peer); checked (capsOf: keys model, effort, permissionMode; others dropped), kept as data.host[did], never in the
114
+ // history; the contact's `host`. POST /api/host/set sends HOST_SET_LABEL {key, value} (a choice it offered) and marks it
115
+ // next until the agent says again. A HOST_SET_LABEL that reaches a page: dropped (a page hosts nothing).
116
+ //
117
+ // The public invite (UI-API.md "Public invite"): a public code (sigelo-public/0, carrier.mjs invitePublic), PUB-…
118
+ // with the four words and a link, for 1, 6 or 12 months, Pro only, kept in the contact store; each use a request to
119
+ // approve (/api/public/approve, /refuse) unless open; Pause and the cap: /api/public/set; Stop for good (Revoke for
120
+ // all): /api/invite/cancel {id}. An earlier version's 7-day long code (data.public) runs out as an ordinary invite.
121
+ //
122
+ // Codes that renew themselves (UI-API.md "Renewing codes"): POST /api/invite renew, a short person code that the
123
+ // carrier replaces with a fresh one once it is used (store.mjs renew, in the contact store). Its id here is "r" + the
124
+ // series id, the same after a restart; state's pending invite is the current code, `renew: true`, `used` the codes
125
+ // used. Cancel (/api/invite/cancel, an id or a short code) cancels at the relay too (carrier.mjs cancelInvite) and
126
+ // ends the series.
127
+ //
55
128
  // The relay setting (UI-API.md "Settings"): the relay new codes name, kept in data.settings.relay.
56
129
  // Precedence: relayFixed (the host's environment: SIGELO_RELAY, or a relay the host was given) wins,
57
130
  // then the setting, then relay.sigelo.ai. The carrier is made with the setting; a change applies at
58
131
  // once to new codes (invite names it) and becomes the carrier's own relay at the next start. Codes
59
132
  // to accept never read it: a 12-character code names its relay by its tag, an 8-character one is
60
133
  // relay.sigelo.ai's (the carrier's relayForShort).
61
- import { bytesToHex, randomBytes } from '@noble/hashes/utils.js';
62
- import { DEFAULT_RELAY } from './carrier.mjs';
134
+ import { sha256 } from '@noble/hashes/sha2.js';
135
+ import { bytesToHex, randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
136
+ import { canonicalize, did as didOf, parseBytes, verify, verifySig } from 'sigelo';
137
+ import { CALL_LABEL, CALL_SEND, DEFAULT_RELAY, KINDS, POW_COST, POW_EVAL_MS, RE_LABEL, quoteHash, reLabel } from './carrier.mjs';
138
+ import { Line, callRoutes, policyOf, stunOf } from './call.mjs';
139
+ import { signAs } from './kdf.mjs';
63
140
  import * as E from './enrol.mjs';
64
141
  import { checkRelay } from './invite.mjs';
65
142
  import { didWords } from './short.mjs';
143
+ import { FILE_LABEL } from './file.mjs';
144
+ import { PHOTO_LABEL, checkPhoto } from './photo.mjs';
145
+ import { VOICE_LABEL, VOICE_SIZE_MAX, checkVoice } from './voice.mjs';
146
+
147
+ // The tiers a new contact may be given at its pairing (Settings → Chats: new people's messages).
148
+ const TIER_NEW = new Set(['own', 'friend', 'quiet']);
149
+ export const CURRENCIES = ['EUR', 'USD', 'GBP', 'CHF', 'RON', 'JPY', 'CAD', 'AUD', 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'BRL', 'INR'];
66
150
 
67
151
  const DAY = 86400, TAG_MAX = 20, NAME_MAX = 64, TEXT_MAX = 100_000;
68
152
  // An agent's name: a contact name and, placed here, a file name (sigelo.<name>.local.json), as `enrol --name` takes it.
69
153
  const AGENT_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
70
154
  const goodRelay = (h) => { try { checkRelay(h); return true; } catch { return false; } };
71
155
  const nowS = () => Math.floor(Date.now() / 1000);
156
+ /** The limits a policy-change sets (apps/keeper/policychange.ts SETTABLE). */
157
+ const KEEPER_FIELDS = ['per_tx_max', 'per_period_max', 'period_seconds', 'rate_per_minute', 'approval_above', 'max_delegates', 'allow', 'paused'];
72
158
  const hexOf = (n) => bytesToHex(randomBytes(n));
73
159
  // A short change mark of a string (FNV-1a, 32 bits): not a check of anything, only "something changed".
74
160
  const hashOf = (t) => { let x = 0x811c9dc5; for (let i = 0; i < t.length; i++) { x ^= t.charCodeAt(i); x = Math.imul(x, 0x01000193) >>> 0; } return x.toString(36); };
75
161
  export const refuse = (status, check, message) => { throw Object.assign(new Error(message), { check, status }); };
76
162
 
163
+ // ---- pictures and signed statements (the header's)
164
+ export const PICTURE_LABEL = 'sigelo-picture/0', STATEMENT_LABEL = 'sigelo-statement/0', PICTURE_MAX = 64 * 1024, STATEMENT_MAX = 10_000;
165
+ const PICTURE_TYPES = new Set(['image/jpeg', 'image/webp']);
166
+ /** A received file the page reads whole to save it (GET /api/files/data): at most this. */
167
+ export const FILE_DATA_MAX = 64 * 2 ** 20;
168
+ const b64 = (bytes) => { let t = ''; for (let i = 0; i < bytes.length; i += 0x8000) t += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(t); };
169
+ const unb64 = (t) => Uint8Array.from(atob(t), (c) => c.charCodeAt(0));
170
+ const b64url = (bytes) => b64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
171
+ const unb64url = (t) => unb64(t.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (t.length % 4)) % 4));
172
+ /** A picture as it comes (POST /api/picture, a contact's body): its bytes, or a refusal (400 picture). */
173
+ export function pictureBytes(type, data) {
174
+ if (!PICTURE_TYPES.has(type)) refuse(400, 'picture', 'type: image/jpeg or image/webp');
175
+ if (typeof data !== 'string' || data.length > Math.ceil(PICTURE_MAX / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) refuse(400, 'picture', `data: base64 of at most ${PICTURE_MAX / 1024} KB`);
176
+ const b = unb64(data);
177
+ if (b.length === 0 || b.length > PICTURE_MAX) refuse(400, 'picture', `a picture of at most ${PICTURE_MAX / 1024} KB (256 pixels is plenty)`);
178
+ const jpeg = b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff, webp = b.length > 12 && String.fromCharCode(...b.subarray(0, 4)) === 'RIFF' && String.fromCharCode(...b.subarray(8, 12)) === 'WEBP';
179
+ if ((type === 'image/jpeg' && !jpeg) || (type === 'image/webp' && !webp)) refuse(400, 'picture', `not a ${type === 'image/jpeg' ? 'JPEG' : 'WebP'} picture`);
180
+ return b;
181
+ }
182
+ export const APPROVAL_LABEL = 'sigelo-approval/0', QUESTION_LABEL = 'sigelo-question/0';
183
+ /** A received approval or question's content: {key, value, text} (value checked, text its one line), or null (not one, or malformed). */
184
+ export function promptOf(label, c) {
185
+ if (typeof c !== 'object' || c === null || Array.isArray(c)) return null;
186
+ const str = (v, max) => typeof v === 'string' && v.length <= max, one = (v) => v.replace(/\s+/g, ' ').trim();
187
+ if (label === APPROVAL_LABEL) {
188
+ if (!str(c.code, 4) || !/^[A-Za-z0-9]{4}$/.test(c.code) || !str(c.tool, 200) || !str(c.summary, 1000) || !Number.isSafeInteger(c.exp)) return null;
189
+ const value = { code: c.code.toUpperCase(), tool: one(c.tool), summary: one(c.summary), exp: c.exp };
190
+ return { key: 'approval', value, text: `approval ${value.code}: ${value.tool}: ${value.summary} (yes ${value.code} / no ${value.code})` };
191
+ }
192
+ if (label === QUESTION_LABEL) {
193
+ if (!str(c.question, 4000) || (c.options !== undefined && (!Array.isArray(c.options) || c.options.length > 20 || !c.options.every((o) => str(o, 200) && o.trim() !== '')))) return null;
194
+ const value = { question: c.question, ...(c.options?.length && { options: c.options }) };
195
+ return { key: 'question', value, text: `question: ${c.question}${value.options ? `\n${value.options.map((o, i) => ` ${i + 1}) ${o}`).join('\n')}` : ''}` };
196
+ }
197
+ return null;
198
+ }
199
+ export const HOST_CAPS_LABEL = 'sigelo-host-caps/0', HOST_SET_LABEL = 'sigelo-host-set/0';
200
+ const HOST_KEYS = new Set(['model', 'effort', 'permissionMode']);
201
+ /** A hosted agent's settings as it announced them → {fields, note?} (a key not known here dropped), or null (malformed). */
202
+ export function capsOf(c) {
203
+ if (typeof c !== 'object' || c === null || Array.isArray(c) || !Array.isArray(c.fields) || c.fields.length > 16) return null;
204
+ const str = (v, max) => typeof v === 'string' && v.length <= max, fields = [];
205
+ for (const f of c.fields) {
206
+ if (typeof f !== 'object' || f === null || !str(f.key, 40) || !str(f.value, 200) || !Array.isArray(f.options) || f.options.length > 100
207
+ || !f.options.every((o) => typeof o === 'object' && o !== null && str(o.value, 200) && str(o.label, 80))
208
+ || (f.off !== undefined && !str(f.off, 120)) || (f.next !== undefined && !str(f.next, 200))) return null;
209
+ if (!HOST_KEYS.has(f.key) || fields.some((x) => x.key === f.key)) continue;
210
+ fields.push({ key: f.key, value: f.value, options: f.options.map((o) => ({ value: o.value, label: o.label })), ...(f.off !== undefined && { off: f.off }), ...(f.next !== undefined && { next: f.next }) });
211
+ }
212
+ if (c.note !== undefined && !str(c.note, 120)) return null;
213
+ return { fields, ...(c.note !== undefined && { note: c.note }) };
214
+ }
215
+ const chainOnly = (b) => ({ v: 'sigelo/0', typ: 'bundle', genesis: b.genesis, rotations: b.rotations ?? [], bindings: [], attestations: [], issuers: [] });
216
+ const SIGNED_LINE = /\n-- Signed with sigelo by [a-z]+ [a-z]+ [a-z]+ [a-z]+\. Check it in the sigelo app\.\s*$/;
217
+ /** A statement signed now by identity id ({sign | secret, bundle}, the carrier's): → its portable text. */
218
+ export function signStatement(id, text, now) {
219
+ if (typeof text !== 'string' || text.trim() === '' || text.length > STATEMENT_MAX) refuse(400, 'body', `text: 1 to ${STATEMENT_MAX} characters`);
220
+ const bundle = chainOnly(id.bundle), r = verify(bundle, now);
221
+ const body = { v: STATEMENT_LABEL, typ: 'statement', did: r.did, iat: now, text: text.trim() };
222
+ const blob = { body, sig: signAs(id, body), bundle };
223
+ return `${body.text}\n-- Signed with sigelo by ${didWords(r.chain[0])}. Check it in the sigelo app.\n${STATEMENT_LABEL} ${b64url(utf8ToBytes(canonicalize(blob)))}`;
224
+ }
225
+ /**
226
+ * A statement's portable text checked offline (SPEC §9 on its bundle, then the signature by the key of the DID it names):
227
+ * → {valid: true, text, iat, did, original, chain, current, created, edited} or {valid: false, check, message}. edited: the
228
+ * text shown above the signature differs from the one signed (the signed one is what counts).
229
+ */
230
+ export function checkStatement(portable, now) {
231
+ const no = (check, message) => ({ valid: false, check, message });
232
+ const t = String(portable ?? '').replace(/\r\n?/g, '\n');
233
+ const m = /(?:^|\n)sigelo-statement\/0\s+([A-Za-z0-9_\-\s]+?)\s*$/.exec(t);
234
+ if (!m) return no('statement_format', 'No sigelo signature in this text: paste all of it, the last line too.');
235
+ let blob;
236
+ try { blob = parseBytes(unb64url(m[1].replace(/\s+/g, ''))); } catch { return no('statement_format', 'The signature line is cut or changed: paste all of it.'); }
237
+ const keys = (o) => (o && typeof o === 'object' && !Array.isArray(o) ? Object.keys(o).sort().join() : '');
238
+ const { body, sig, bundle } = blob ?? {};
239
+ if (keys(blob) !== 'body,bundle,sig' || keys(body) !== 'did,iat,text,typ,v' || body.v !== STATEMENT_LABEL || body.typ !== 'statement' || typeof body.did !== 'string'
240
+ || !Number.isSafeInteger(body.iat) || body.iat < 0 || typeof body.text !== 'string' || body.text.length > STATEMENT_MAX || typeof sig !== 'string') {
241
+ return no('statement_format', 'Not a sigelo signed message.');
242
+ }
243
+ let r;
244
+ try { r = verify(bundle, now); } catch (e) { return no('statement_identity', `The identity it carries does not verify (${e.message}).`); }
245
+ const g = [bundle.genesis, ...bundle.rotations.map((x) => x.next_genesis)].find((x) => { try { return didOf(x) === body.did; } catch { return false; } });
246
+ if (!g || !r.chain.includes(body.did)) return no('statement_identity', 'The key that signed it is not in the identity it carries.');
247
+ if (!verifySig(g.key, body, sig)) return no('statement_sig', 'The text or its signature was changed after it was signed.');
248
+ if (body.iat > now + 300) return no('statement_time', 'It says it was signed in the future: the signer\'s clock is wrong, or it was changed.');
249
+ const shown = t.slice(0, m.index).replace(SIGNED_LINE, '').trim();
250
+ return { valid: true, text: body.text, iat: body.iat, did: body.did, original: r.chain[0], chain: r.chain, current: r.did === body.did, created: bundle.genesis.created ?? null,
251
+ edited: shown !== '' && shown !== body.text.trim() };
252
+ }
253
+
254
+ // ---- search (UI-API.md "Search"): a substring of the texts this device holds, case and accents folded. Each code point is
255
+ // folded alone (NFD, marks dropped, lower case) so that a hit in the folded text maps back to the text as written: at[i]
256
+ // is where the folded character i came from (at[f.length]: the end).
257
+ /** t folded for search → { f, at }. */
258
+ export function foldMap(t) {
259
+ let f = '';
260
+ const at = [];
261
+ for (let i = 0; i < t.length;) {
262
+ const cp = t.codePointAt(i), x = String.fromCodePoint(cp).normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
263
+ for (let k = 0; k < x.length; k++) at.push(i);
264
+ f += x; i += cp > 0xffff ? 2 : 1;
265
+ }
266
+ at.push(t.length);
267
+ return { f, at };
268
+ }
269
+ export const SNIPPET_MAX = 120;
270
+ /**
271
+ * The first hit of want (folded already) in t → { snippet, mark: [from, to] } or null: at most SNIPPET_MAX characters
272
+ * around the hit (… where cut, line breaks as spaces), mark the hit's place in the snippet (cut at its end if long).
273
+ */
274
+ export function matchIn(t, want) {
275
+ const { f, at } = foldMap(t), i = f.indexOf(want);
276
+ if (i < 0 || want === '') return null;
277
+ const s = at[i], e = at[i + want.length];
278
+ let from = Math.max(0, Math.min(s - 40, t.length - (SNIPPET_MAX - 1)));
279
+ if (/[\udc00-\udfff]/.test(t[from] ?? '')) from++;
280
+ let to = Math.min(t.length, from + SNIPPET_MAX - (from > 0 ? 1 : 0));
281
+ if (to < t.length) to--;
282
+ if (/[\ud800-\udbff]/.test(t[to - 1] ?? '')) to--;
283
+ const pre = from > 0 ? '…' : '', body = t.slice(from, to).replace(/[\r\n\t]/g, ' ');
284
+ return { snippet: pre + body + (to < t.length ? '…' : ''), mark: [s - from + pre.length, Math.min(e, to) - from + pre.length] };
285
+ }
286
+
77
287
  export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, groupsFile = null, enrolFile = null, codeKind, unlogged, store, hooks = {}, relayFixed = null }) {
78
288
  const defer = hooks.defer ?? ((f) => setTimeout(f, 0));
79
289
  const every = hooks.every ?? ((f, ms) => { const t = setInterval(f, ms); t.unref?.(); return t; });
@@ -103,13 +313,23 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
103
313
  };
104
314
  let data;
105
315
  try { data = JSON.parse(store.readData() ?? 'null') ?? {}; } catch { data = {}; }
106
- for (const k of ['tags', 'checked', 'read', 'controls', 'settings', 'gread']) data[k] ??= {};
316
+ for (const k of ['tags', 'checked', 'read', 'controls', 'settings', 'gread', 'seen', 'notify', 'kind', 'pics', 'pic_sent', 'pic_peer', 'host']) data[k] ??= {};
107
317
  data.gnotices ??= [];
108
318
  delete data.waiting; // kept by an earlier page; the carrier says it now (contacts: prekeys, waiting)
109
319
  const saveData = () => store.writeData(JSON.stringify(data));
110
320
 
111
321
  // ---- live status, not kept
112
322
  const live = { online: new Set(), pow: null, powDone: null, error: null, seatGone: null, powCapped: null, powConfirm: null };
323
+ // The last login's failure and the day's cap, kept (data.offline) so that the "Not connected" card says why after a restart
324
+ // too; gone once connected. A cap whose next try has passed is not brought back.
325
+ if (typeof data.offline?.error === 'string') live.error = data.offline.error;
326
+ if (Number.isSafeInteger(data.offline?.pow_capped?.next) && data.offline.pow_capped.next > nowS()) live.powCapped = { relay: String(data.offline.pow_capped.relay), next: data.offline.pow_capped.next };
327
+ const keepOffline = () => {
328
+ const was = JSON.stringify(data.offline ?? null), now = live.error === null && live.powCapped === null ? null : { error: live.error, pow_capped: live.powCapped };
329
+ if (JSON.stringify(now) === was) return;
330
+ if (now === null) delete data.offline; else data.offline = now;
331
+ try { saveData(); } catch {}
332
+ };
113
333
  // A call the human made: past the day's searches it asks (pow_confirm) unless they said go on.
114
334
  const startedBy = (b) => (b?.['pow_confirmed'] === true ? 'confirmed' : 'user');
115
335
  // Writes, one at a time. Once the seat went to another device, every write is refused.
@@ -117,6 +337,8 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
117
337
  const gone = (fn) => () => (live.seatGone !== null ? refuse(409, 'seat_elsewhere', `the seat went to ${live.seatGone}: this page no longer logs in as you`) : fn());
118
338
  const serial = (f0) => { const fn = gone(f0); const p = chain.then(fn, fn); chain = p.catch(() => {}); return p; };
119
339
  const invites = new Map();
340
+ // An earlier version's public invite (the header's): an ordinary long invite now, until it runs out.
341
+ if (data.public?.id) { invites.set(data.public.id, { ...data.public }); delete data.public; }
120
342
  let devices = null;
121
343
  // Enrolments this page issued (agents, below): id (the code's nonce) → { id, worker, name, short, code, exp, relay, tier,
122
344
  // state: code | words | sending | enrolled | expired | failed, words, temp, did, original, check?, detail? }.
@@ -125,16 +347,49 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
125
347
  // What the carrier's inbox() hands over, as every client takes it: messages and the events it
126
348
  // keeps (pairings, failures, rotations), into the history. Taken at once after any event, and
127
349
  // every minute for what no event announced.
128
- let draining = null, again = false;
350
+ let draining = null, again = false, drainedOnline = 0; // drainedOnline: when a drain last ended while connected (ms)
129
351
  function take(b) {
130
352
  // A linked contact's messages carry the link (id, purpose): data, shown beside them.
131
353
  for (const m of (L.labelled ? L.labelled(carrier, b.messages) : b.messages)) {
132
354
  // Enrolment and device messages carry keys or codes: never in the history (the device rounds take them).
133
355
  if (typeof m['label'] === 'string' && unlogged.test(m['label'])) { if (!holdAgent(m)) devices?.hold(m); continue; }
134
356
  if (hidden({ did: m['from'], name: m['name'] })) continue;
357
+ // A contact's own picture (the header's "Pictures"): kept apart, never in the history.
358
+ if (m['label'] === PICTURE_LABEL) { takePicture(m); continue; }
359
+ // A hosted agent's settings (the header's): kept apart, never in the history; a setting sent here, dropped.
360
+ if (m['label'] === HOST_CAPS_LABEL) { const h = capsOf(m['content']); if (h) { data.host[String(m['from'])] = { ...h, at: nowS() }; saveData(); changed(); } continue; }
361
+ if (m['label'] === HOST_SET_LABEL) continue;
362
+ // A photo's preview (photo.mjs): into the chat at once, the full file by its transfer.
363
+ if (m['label'] === PHOTO_LABEL) {
364
+ let ph = null;
365
+ try { ph = checkPhoto(m['content']); } catch (e) { record({ kind: 'event', type: 'dropped', did: m['from'], name: m['name'], code: 'photo', detail: e.message }); continue; }
366
+ record({ kind: 'in', did: m['from'], name: m['name'], text: 'Photo', label: PHOTO_LABEL, photo: ph, ...(Number.isSafeInteger(m['iat']) && { iat: m['iat'] }) });
367
+ continue;
368
+ }
369
+ // A voice message (voice.mjs): its bubble at once, the recording by its transfer.
370
+ if (m['label'] === VOICE_LABEL) {
371
+ let vo = null;
372
+ try { vo = checkVoice(m['content']); } catch (e) { record({ kind: 'event', type: 'dropped', did: m['from'], name: m['name'], code: 'voice', detail: e.message }); continue; }
373
+ record({ kind: 'in', did: m['from'], name: m['name'], text: 'Voice message', label: VOICE_LABEL, voice: vo, ...(Number.isSafeInteger(m['iat']) && { iat: m['iat'] }) });
374
+ continue;
375
+ }
135
376
  const link = m['link'] ? { link: m['link'] } : {};
136
- if (m['type'] === 'file') record({ kind: 'in', did: m['from'], name: m['contact'], label: m['label'], text: `file ${String(m['name'])} (${String(m['size'])} bytes), saved at ${String(m['path'])}`, ...link });
137
- else record({ kind: 'in', did: m['from'], name: m['name'], text: m['content'], label: m['label'], ...link });
377
+ // iat: the sender's time of it, what a seen receipt names (Seen receipts, above).
378
+ const iat = Number.isSafeInteger(m['iat']) ? { iat: m['iat'] } : {};
379
+ if (m['type'] === 'file') {
380
+ // (0.1.19) The lane it came by, for the bubble: a transfer's (direct, tor), else the relay (sigelo-file/0), which also
381
+ // ends a transfer of the same file from them that is still open here (Engine.superseded: no ghost left active).
382
+ const lane = m['transfer'] ? (m['via'] ?? null) : 'relay';
383
+ if (!m['transfer']) { try { transfers?.engine.superseded?.(m); } catch {} }
384
+ record({ kind: 'in', did: m['from'], name: m['contact'], label: m['label'], text: `file ${String(m['name'])} (${String(m['size'])} bytes), saved at ${String(m['path'])}`,
385
+ file: { name: String(m['name']), size: Number(m['size']), sha256: String(m['sha256'] ?? ''), via: lane, transfer: m['transfer'] ?? null },
386
+ ...(typeof m['path'] === 'string' && { saved: m['path'] }), ...iat, ...link }); // saved: where GET /api/files/data reads it, never parsed from the text
387
+ }
388
+ else {
389
+ // A hosted agent's approval or question (promptOf): its fields beside a one-line text, which a reply quotes.
390
+ const pr = promptOf(m['label'], m['content']);
391
+ record({ kind: 'in', did: m['from'], name: m['name'], text: pr ? pr.text : m['content'], label: m['label'], ...(pr && { [pr.key]: pr.value }), ...iat, ...link });
392
+ }
138
393
  }
139
394
  const named = new Set();
140
395
  for (const e of b.events) {
@@ -142,13 +397,19 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
142
397
  if (hidden({ did: d, name: e['name'] })) continue;
143
398
  switch (e.type) {
144
399
  case 'paired': {
145
- const inv = [...invites.values()].find((x) => x.name === e['name'] && !x.paired);
146
- if (inv && d) inv.paired = d;
400
+ // A renewing code stays current (its next code shows in its place): never "paired" itself.
401
+ const inv = e['renew'] ? invites.get(`r${String(e['renew'])}`) : [...invites.values()].find((x) => x.name === e['name'] && !x.paired && !x.renew);
402
+ if (inv && d && !inv.renew) inv.paired = d;
147
403
  record({ kind: 'event', type: 'paired', did: d, name: e['name'] });
404
+ if (d) newContact(d, inv);
148
405
  break;
149
406
  }
150
407
  // A refusal of one of my messages (it has an id) is its status, from onEvent.
151
408
  case 'refused': if (e['id'] === undefined) record({ kind: 'event', type: 'refused', did: d, name: e['name'], code: e['code'], detail: e['detail'] }); break;
409
+ // A pairing request to a public code of mine (carrier.mjs #onPublic): its words, to approve or refuse.
410
+ case 'public_request':
411
+ record({ kind: 'event', type: 'public_request', did: d, name: e['name'], detail: `a new chat asks to start by your public code (${String(e['words'])})` });
412
+ break;
152
413
  case 'pairing_failed': case 're_pair': case 'rotated': case 'dropped':
153
414
  if (e.type === 'dropped') named.add(String(e['check']));
154
415
  record({ kind: 'event', type: e.type, did: d, name: e['name'], code: e['code'] ?? e['check'], detail: e['detail'] });
@@ -161,7 +422,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
161
422
  if (draining) { again = true; return draining; }
162
423
  draining = (async () => {
163
424
  try {
164
- do { again = false; take(await carrier.inbox({ local: true })); await groupRound(); } while (again);
425
+ do { again = false; const t0 = Date.now(), up = live.online.size > 0; take(await carrier.inbox({ local: true })); callRound(); await groupRound(); if (up && live.online.size > 0) drainedOnline = t0; } while (again);
165
426
  // Device messages: wiped answers, a standby asking for the seat (it goes, and this page stops logging in as you).
166
427
  if (live.seatGone === null && hooks.deviceRound) {
167
428
  const r = await hooks.deviceRound();
@@ -186,12 +447,13 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
186
447
  };
187
448
  const onEvent = (e) => {
188
449
  if (e.type === 'transfer') defer(() => void transfers?.engine.kick());
450
+ if (e.type === 'call') { defer(callRound); return; }
189
451
  if (e.type === 'link' || e.type === 'paired') defer(() => void linkRound());
190
452
  try {
191
453
  const d = e['did'] ?? e['from'] ?? e['peer'];
192
454
  switch (e.type) {
193
455
  case 'sent': case 'queued': case 'refused': {
194
- if (e['control'] !== undefined) break;
456
+ if (e['control'] !== undefined || e['receipt'] === true) break;
195
457
  // Before send returns, its own result says the same: only later ones are recorded.
196
458
  const st = e.type, i = e['id'];
197
459
  if (i && outById.has(i)) { record({ kind: 'status', id: i, status: st, code: e['code'], detail: e['detail'] }); break; }
@@ -201,21 +463,27 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
201
463
  if (st === 'refused' && !i) soon();
202
464
  break;
203
465
  }
204
- case 'pow': live.pow = { bits: Number(e['bits']), since: Date.now() }; break;
466
+ case 'pow': live.pow = { bits: Number(e['bits']), m: Number(e['m'] ?? POW_COST.m), t: Number(e['t'] ?? POW_COST.t), since: Date.now() }; break;
205
467
  case 'pow_done': live.pow = null; live.powDone = Number(e['ms']); break;
206
468
  case 'connected':
207
469
  live.online.add(String(e['relay'])); live.error = null; void checkClock();
208
470
  if (live.powCapped?.relay === e['relay']) live.powCapped = null;
209
471
  if (live.powConfirm?.relay === e['relay']) live.powConfirm = null;
472
+ keepOffline();
210
473
  break;
211
474
  case 'disconnected': live.online.delete(String(e['relay'])); break;
212
475
  case 'error':
213
- live.error = `${e['check']}: ${e['detail']}`;
476
+ // A detail that names itself ("proof of work: …", the platform's) is said as it is.
477
+ live.error = /^proof of work: /.test(String(e['detail'])) ? String(e['detail']) : `${e['check']}: ${e['detail']}`;
214
478
  // The day's searches spent: when the next automatic try is, and "Try now" (POST /api/pow/try).
215
479
  if (e['check'] === 'pow' && Number.isSafeInteger(e['next'])) live.powCapped = { relay: String(e['relay']), next: e['next'] };
216
480
  if (e['check'] === 'pow_confirm') live.powConfirm = { relay: String(e['relay']), detail: String(e['detail']).replace(/^pow_confirm: /, '') };
481
+ keepOffline();
217
482
  break;
218
- case 'notice': case 'presence': case 'group_tier': break; // presence, the group tier: the state says it, nothing to take
483
+ case 'notice': case 'presence': case 'group_tier': case 'busy': break; // presence, the group tier, a busy mark: the state says it, nothing to take
484
+ case 'seen': defer(() => { receipt(String(e['from']), true); picturesDue(); }); break;
485
+ // A new contact told its name (carrier.mjs "Names"): my groups that list it under the made-up one are sent again.
486
+ case 'named': if (G && groupsFile) defer(() => serial(() => G.refreshNames({ carrier, file: groupsFile, did: String(e['did']) })).catch(() => {})); break; // the contact's receipt: contacts() has it; answered once; it reads pictures
219
487
  default: soon();
220
488
  }
221
489
  } catch (err) { live.error = `history: ${err.message}`; }
@@ -230,37 +498,169 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
230
498
  }
231
499
  changed();
232
500
  };
233
- const transfers = hooks.transfers ? { lib: hooks.transfers.lib, engine: hooks.transfers.make(carrier, onTransfer) } : null;
501
+ // The accept rule's "words compared": the pairing's words as the human checked them here (Chats → the four words).
502
+ const compared = (did) => { const x = carrier.contacts().contacts.find((c) => c.did === did); return Boolean(x && x.pair !== null && x.pair !== undefined && data.checked?.[did] === x.pair); };
503
+ // "Always relay my media" (the header's): the setting, or SIGELO_ICE_POLICY=relay where the host has an environment.
504
+ const relayMedia = () => policyOf(data.settings.relay_media === true, globalThis.process?.env?.SIGELO_ICE_POLICY);
505
+ const transfers = hooks.transfers ? { lib: hooks.transfers.lib, engine: hooks.transfers.make(carrier, onTransfer, { compared, policy: relayMedia }) } : null;
506
+ // ---- calls (the header's): the Line, its messages taken from the carrier at each `call` event and each drain.
507
+ data.calls ??= {};
508
+ const liveContact = (d) => carrier.contacts().contacts.find((c) => c.did === d && !c.revoked) ?? null;
509
+ const canCall = (c) => (typeof data.calls[c.did] === 'boolean' ? data.calls[c.did] : c.tier === 'quiet' ? false : data.settings.calls !== false);
510
+ // Calls are between people (design/calls.md §1): a contact this page takes for an agent (its kind, as the chat list
511
+ // shows it: the human's choice, else my agent, a worker, a group's agent) is never rung from here and never rings here.
512
+ const personOf = (c) => {
513
+ const agent = (hooks.agents?.() ?? []).find((a) => a.did !== undefined && c.chain?.includes(a.did));
514
+ return kindOf(c, agent?.mine ?? null, rosterAgents()).kind === 'person';
515
+ };
516
+ const CH = hooks.calls ?? {};
517
+ const line = new Line({
518
+ send: (to, content) => carrier.send(to, content, { label: CALL_LABEL, internal: CALL_SEND, local: false }),
519
+ contact: liveContact, allowed: canCall, person: personOf,
520
+ refused: ({ did, check }) => record({ kind: 'event', type: 'dropped', did, name: liveContact(did)?.name ?? null, code: check, detail: 'a call from an agent: refused (calls are between people)' }),
521
+ shares: (c) => c.presence === 'allow' || c.presence === 'own', me: () => hooks.me().original,
522
+ line: ({ did, dir, text, call }) => { record({ kind: dir, did, name: liveContact(did)?.name ?? null, text, label: CALL_LABEL, call }); },
523
+ alert: (x) => { try { CH.alert?.(x); } catch {} },
524
+ audio: (x) => { try { void Promise.resolve(CH.audio?.(x)).catch(() => {}); } catch {} },
525
+ changed: () => changed(),
526
+ });
527
+ const callRound = () => { try { for (const m of carrier.takeCalls()) line.receive(m); } catch (err) { live.error = `calls: ${err.message}`; } };
234
528
  // The relay new codes name, as the precedence says.
235
529
  const newCodes = () => relayFixed ?? kept() ?? DEFAULT_RELAY;
236
- const settings = () => ({ relay: kept() ?? DEFAULT_RELAY, default: DEFAULT_RELAY, fixed: relayFixed, in_use: carrier.relay });
530
+ // added: the relays taken here by name (Settings → Relay → Another relay), newest first, so that one stays in the list once another is in use.
531
+ const ADDED_MAX = 5;
532
+ const added = () => (Array.isArray(data.settings.relays) ? data.settings.relays.filter((x) => typeof x === 'string' && goodRelay(x)) : []);
533
+ const settings = () => ({ relay: kept() ?? DEFAULT_RELAY, default: DEFAULT_RELAY, fixed: relayFixed, in_use: carrier.relay, added: added() });
237
534
  async function checkClock() { try { await carrier.checkClock(); } catch {} }
238
535
  const seen = (d) => { let at = null; for (const r of recs) if (r.did === d && (r.kind === 'in' || r.kind === 'event')) at = r.at; return at; };
536
+ // ---- seen receipts and the chat defaults (the header's)
537
+ const receiptsOn = () => data.settings.seen !== false;
538
+ // The newest of a contact's messages shown (their iat), 0 when none.
539
+ const shownUpto = (d) => { let t = 0; const read = data.read[d] ?? 0; for (const r of recs) if (r.kind === 'in' && r.did === d && r.n <= read && Number.isSafeInteger(r.iat) && r.iat > t) t = r.iat; return t; };
540
+ // A receipt to contact d when one is due; answer: the contact's first receipt came (say that this side reads them too).
541
+ function receipt(d, answer = false) {
542
+ try {
543
+ const x = carrier.contacts().contacts.find((c) => c.did === d && !c.revoked);
544
+ // My own agents read none (no app shows them ticks): only once one sent a receipt.
545
+ if (!x || hidden(x) || (x.ours && !x.seen_peer)) return;
546
+ const s = (data.seen[d] ??= { sent: 0, told: false }), upto = receiptsOn() ? shownUpto(d) : 0;
547
+ const due = receiptsOn() && upto > s.sent && (x.seen_peer || !s.told);
548
+ if (!due && !(answer && !s.told)) return;
549
+ if (receiptsOn()) s.sent = Math.max(s.sent, upto);
550
+ s.told = true; saveData();
551
+ void serial(() => carrier.seen(d, upto)).catch(() => {});
552
+ } catch {}
553
+ }
554
+ // A message of mine: seen once the contact's newest receipt is at or after when it went (at: taken before the send).
555
+ const statusOf = (r, upto) => (r.kind === 'out' && r.status === 'sent' && Number.isSafeInteger(upto) && r.at <= upto ? 'seen' : r.status ?? null);
556
+ // A contact just paired: the chat defaults (a tier the human did not choose at accept, presence), and a group code's group.
557
+ function newContact(d, inv) {
558
+ try {
559
+ const x = carrier.contacts().contacts.find((c) => c.did === d && !c.revoked);
560
+ // An introduced contact (link.mjs) keeps the tier its introduction gave; my own agents theirs.
561
+ if (!x || x.link) return;
562
+ const t = data.settings.new_tier;
563
+ if (TIER_NEW.has(t) && t !== x.tier && !x.ours && x.tier_by !== 'owner') carrier.setTier(d, t);
564
+ if (data.settings.new_presence === true && x.presence === 'deny') carrier.setPresence(d, true);
565
+ } catch {}
566
+ if (inv?.group && G && groupsFile) {
567
+ const gid = inv.group;
568
+ defer(() => void serial(() => G.add({ carrier, file: groupsFile, group: gid, members: [d], humans: [d] })).then(() => changed(), (err) => { gnote({ type: 'group', why: 'refused', check: err.check ?? 'group', count: 1 }); saveData(); changed(); }));
569
+ }
570
+ }
571
+ const notifyOf = (chat) => data.notify[chat] !== false;
572
+ // The public invite as the state shows it (carrier.mjs publicView): the first public code of mine, or null.
573
+ const publicInvite = (c) => c.publics?.[0] ?? null;
574
+ const walletSet = () => ({ wallet: data.settings.wallet === true, prices: data.settings.prices === true, currency: CURRENCIES.includes(data.settings.currency) ? data.settings.currency : null });
575
+ const settingsAll = () => ({ ...settings(), seen_receipts: receiptsOn(), notify: data.settings.notify !== false,
576
+ new_tier: TIER_NEW.has(data.settings.new_tier) ? data.settings.new_tier : 'friend', new_presence: data.settings.new_presence === true, calls: data.settings.calls !== false,
577
+ relay_media: relayMedia() === 'relay', ...walletSet() });
578
+
579
+ // ---- pictures (the header's): mine to the contacts that read them, theirs kept, a local one beside
580
+ const picFile = (key) => (key === 'me' ? 'me' : `${key[0]}-${bytesToHex(sha256(utf8ToBytes(key.slice(2)))).slice(0, 16)}`);
581
+ const picRev = (key) => data.pics[key]?.rev ?? null;
582
+ const picOf = (id) => (id === 'me' ? 'me' : data.pics[`l:${id}`] ? `l:${id}` : data.pics[`t:${id}`] ? `t:${id}` : null);
583
+ const picSave = (key, type, bytes) => {
584
+ store.writePicture(picFile(key), bytes);
585
+ data.pics[key] = { type, rev: `${hashOf(b64(bytes))}${bytes.length.toString(36)}`, at: nowS() };
586
+ };
587
+ const picDrop = (key) => { if (!data.pics[key]) return false; store.writePicture(picFile(key), null); delete data.pics[key]; return true; };
588
+ // Mine to each contact known to read pictures that does not have this one (or its removal) yet: one body each.
589
+ let picturing = false;
590
+ function picturesDue() {
591
+ if (picturing || !store.writePicture || live.seatGone !== null) return;
592
+ const rev = picRev('me') ?? '';
593
+ const due = carrier.contacts().contacts.filter((x) => !x.revoked && !hidden(x) && (x.seen_peer || data.pic_peer[x.did]) && (data.pic_sent[x.did] ?? '') !== rev);
594
+ if (!due.length) return;
595
+ picturing = true;
596
+ const bytes = rev ? store.readPicture(picFile('me')) : null;
597
+ const content = bytes ? { type: data.pics.me.type, data: b64(bytes) } : { remove: true };
598
+ void serial(async () => {
599
+ for (const x of due) {
600
+ try { const [r] = await carrier.sendAll(x.did, [content], { label: PICTURE_LABEL }); if (r.status !== 'refused') data.pic_sent[x.did] = rev; } catch (e) { if (/queued/.test(e.message)) data.pic_sent[x.did] = rev; }
601
+ }
602
+ saveData();
603
+ }).catch(() => {}).finally(() => { picturing = false; if ((picRev('me') ?? '') !== rev) picturesDue(); });
604
+ }
605
+ // A contact's picture (or its removal): checked, kept as t:<did>; it reads pictures, so mine goes too.
606
+ function takePicture(m) {
607
+ const d = String(m['from']), v = m['content'];
608
+ try {
609
+ if (v?.remove === true) picDrop(`t:${d}`);
610
+ else picSave(`t:${d}`, v?.type, pictureBytes(v?.type, v?.data));
611
+ data.pic_peer[d] = true; saveData();
612
+ defer(() => picturesDue());
613
+ } catch (e) { record({ kind: 'event', type: 'dropped', did: d, name: m['name'], code: 'picture', detail: e.message }); }
614
+ }
615
+
239
616
  let timers = [];
240
617
  async function start() {
241
618
  void checkClock();
242
619
  timers = [every(() => void checkClock(), 600_000), every(() => void drain().then(() => linkRound()), 60_000)];
620
+ // The enrolments from before this start (the pending file): their requests held, a failed identity sent again.
621
+ try { await look(); } catch {}
243
622
  await carrier.start({ started: 'user' });
244
623
  await drain();
245
624
  void linkRound();
625
+ picturesDue();
246
626
  void transfers?.engine.kick();
247
627
  }
248
628
  async function halt() {
249
629
  for (const t of timers) clearInterval(t);
250
630
  await linking.catch(() => {});
251
631
  await transfers?.engine.close().catch(() => {});
632
+ line.close();
252
633
  }
253
634
 
254
635
 
255
636
  // ---- agents: the operator's workers (keeper `workers`), enrolled by a one-time code from this page
256
637
  const K = hooks.keeper ?? null;
638
+ // The computer this profile is paired to, for the keeper (design/agent-wallet-page.md §4): { name() → its name,
639
+ // call(method, path, body?) → { status, body } } (its page over the control, scope all), or none.
640
+ const PC = hooks.computer ?? null;
641
+ const viaPc = async (method, path, body) => {
642
+ let r;
643
+ try { r = await PC.call(method, path, body); } catch (e) { return refuse(409, 'keeper_computer', `${PC.name()} isn't answering (${e?.message ?? 'no answer'}). Its keeper is set there.`); }
644
+ if (r.status !== 200) return refuse(r.status, r.body?.error?.check ?? 'keeper_computer', r.body?.error?.message ?? `${PC.name()} answered ${r.status}`);
645
+ return r.body;
646
+ };
257
647
  const pend = (fn) => E.pending(enrolFile, nowS(), fn, carrier.platform);
258
648
  const LIVE = new Set(['code', 'words', 'sending']);
649
+ // The pending file's enrolments as look() last read them (alive, not done): id → { temp, i, name, needs_send }. They outlive
650
+ // the page (a restart forgets `enrolling`): a request from their temporary DID is still answered, and an identity whose
651
+ // send failed (needs_send, enrol.mjs) still goes again, at agentRound.
652
+ let issuedLive = new Map();
653
+ const needsSend = () => [...issuedLive.values()].some((f) => f.needs_send);
259
654
  function enrolHidden(x) {
260
655
  for (const e of enrolling.values()) {
261
656
  if (x.did !== undefined && x.did !== null && (x.did === e.temp || (LIVE.has(e.state) && carrier.answeredBy(e.id) === x.did))) return true;
262
657
  if (x.name === `${e.name} (enrolling)` && LIVE.has(e.state)) return true;
263
658
  }
659
+ // After a restart (0.1.16: the temporary identity showed in Chats with a chat and Pay): the pending file's enrolments.
660
+ for (const [id, f] of issuedLive) {
661
+ if (x.did !== undefined && x.did !== null && (x.did === f.temp || carrier.answeredBy(id) === x.did)) return true;
662
+ if (x.name === `${f.name ?? `worker ${f.i}`} (enrolling)`) return true;
663
+ }
264
664
  return false;
265
665
  }
266
666
  // An enrolment request from the DID that answered one of this page's codes: kept for agentRound, not the devices'.
@@ -269,18 +669,32 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
269
669
  for (const e of enrolling.values()) {
270
670
  if (LIVE.has(e.state) && (e.temp === m['from'] || carrier.answeredBy(e.id) === m['from'])) { agentHeld.push(m); return true; }
271
671
  }
672
+ for (const [id, f] of issuedLive) if (f.temp === m['from'] || carrier.answeredBy(id) === m['from']) { agentHeld.push(m); return true; }
272
673
  return false;
273
674
  }
274
- const agentsBusy = () => agentHeld.length > 0 || [...enrolling.values()].some((e) => LIVE.has(e.state));
675
+ const agentsBusy = () => agentHeld.length > 0 || needsSend() || [...enrolling.values()].some((e) => LIVE.has(e.state));
275
676
  const keeperOr = async () => (K ? await K.read() : null) ?? refuse(400, 'keeper', 'no keeper root here: your 25 words make it (sigelo-agent keeper --from-words on a computer; in the app, Create or Restore from seed)');
276
677
  const seatHere = () => { const st = hooks.seat?.(); if (st && st.here === false) refuse(409, 'seat_elsewhere', `the seat is with ${st.holder}: agents are enrolled there (DEVICES.md)`); };
277
678
  const pub = (e) => ({ id: e.id, state: e.state, code: e.state === 'code' ? e.short : null, exp: e.exp, relay: e.relay, words: e.words ?? null,
278
- confirm_words: e.confirmWords === true, words_ok: e.wordsOk ?? null, verified: e.verified === true,
679
+ confirm_words: e.confirmWords === true, words_ok: e.wordsOk ?? null, verified: e.verified === true, needs_send: issuedLive.get(e.id)?.needs_send === true,
279
680
  command: e.state === 'code' ? `${e.relay !== DEFAULT_RELAY ? `SIGELO_RELAY=${e.relay} ` : ''}sigelo-agent init --enrol ${e.short}` : null, ...(e.check !== undefined && { check: e.check, detail: e.detail ?? null }) });
280
681
  // Who answered each code (its four words), codes dead unanswered (the index free again), enrolments done.
281
682
  async function look() {
282
683
  if (!enrolFile) return;
283
- const t = nowS(), issued = pend((st) => Object.fromEntries(Object.entries(st.issued).map(([id, e]) => [id, { done: e.done ?? null }])));
684
+ const t = nowS(), issued = pend((st) => Object.fromEntries(Object.entries(st.issued).map(([id, e]) => [id, { done: e.done ?? null, temp: e.temp ?? null, i: e.i, name: e.name ?? null, needs_send: e.needs_send !== undefined,
685
+ page: e.page ?? null, confirm_words: e.confirm_words === true, words_ok: e.words_ok ?? null, did: e.did, original: e.original, relay: e.relay, sent: e.sent_at !== undefined, held: e.held !== undefined,
686
+ told: e.temp && st.told?.[e.temp] ? { check: st.told[e.temp].check, detail: st.told[e.temp].detail ?? '' } : null }])));
687
+ issuedLive = new Map(Object.entries(issued).filter(([, f]) => !f.done));
688
+ // This page's enrolments come back from the pending file after a restart (0.1.17: an app killed in the background
689
+ // forgot them: the four words never showed and the request was never answered): the code, the words, the answer.
690
+ for (const [id, f] of issuedLive) {
691
+ if (enrolling.has(id) || !f.page) continue;
692
+ const by = f.temp ?? carrier.answeredBy(id);
693
+ enrolling.set(id, { id, worker: f.i, name: f.name, short: f.page.short, code: f.page.short, exp: f.page.short_exp, relay: f.relay, tier: f.page.tier ?? 'own',
694
+ state: f.sent || f.needs_send ? 'sending' : by ? 'words' : 'code', did: f.did, original: f.original, confirmWords: f.confirm_words, ...(f.words_ok !== null && { wordsOk: f.words_ok }),
695
+ ...(by && { temp: by, words: carrier.contacts().contacts.find((x) => x.did === by)?.fingerprint ?? null }) });
696
+ changed();
697
+ }
284
698
  for (const e of enrolling.values()) {
285
699
  if (!LIVE.has(e.state)) continue;
286
700
  const f = issued[e.id];
@@ -292,7 +706,9 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
292
706
  e.temp = by; e.state = 'words';
293
707
  e.words = carrier.contacts().contacts.find((x) => x.did === by)?.fingerprint ?? null;
294
708
  changed();
295
- } else if (t > e.exp + 30) {
709
+ } else if (t > e.exp + 30 && drainedOnline > (e.exp + 30) * 1000) {
710
+ // Run out, and read: only once a drain while online came after its end, so an answer the relay held while
711
+ // this page was away (in the background, reconnecting) is taken first (0.1.17: it was dropped as expired).
296
712
  e.state = 'expired';
297
713
  pend((st) => { delete st.issued[e.id]; });
298
714
  try { await carrier.cancelInvite(e.code); } catch {}
@@ -305,20 +721,22 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
305
721
  async function agentRound() {
306
722
  await look();
307
723
  const pass = agentHeld.splice(0);
308
- if (!pass.length && ![...enrolling.values()].some((e) => e.state === 'words' || e.state === 'sending')) return;
724
+ if (!pass.length && !needsSend() && ![...issuedLive.values()].some((f) => f.held) && ![...enrolling.values()].some((e) => e.state === 'words' || e.state === 'sending')) return;
309
725
  const k = await K?.read();
310
726
  if (!k) return;
311
727
  const root = await K.root(k);
312
728
  // The carrier as enrolment sees it: its inbox is what the page kept apart.
313
729
  const proxy = new Proxy(carrier, { get: (x, p) => (p === 'inbox' ? async () => ({ messages: pass.splice(0), events: [], dropped: {} }) : typeof x[p] === 'function' ? x[p].bind(x) : x[p]) });
314
730
  // The optional switch: the key waits for "They match" (null: not yet, the request kept for the next round).
315
- const confirm = async (o) => { if (!o.ask) return true; const e = enrolling.get(o.id); if (e && !e.words) e.words = o.words; return e?.wordsOk ?? null; };
731
+ const confirm = async (o) => { if (!o.ask) return true; const e = enrolling.get(o.id); if (e && !e.words) e.words = o.words; return e?.wordsOk ?? issuedLive.get(o.id)?.words_ok ?? null; };
316
732
  let res;
317
733
  try { res = await E.complete({ carrier: proxy, file: enrolFile, keeper: root, wait: 0, confirm }); } finally { root.K.fill(0); }
318
- agentHeld.push(...(res.held ?? []));
734
+ // Held requests stay in the pending file (enrol.mjs "A request held"): the next round takes them again.
735
+ await look(); // needs_send as enrol.mjs left it
319
736
  for (const d of res.delivered) { const e = enrolling.get(d.id); if (e) e.state = 'sending'; }
320
- for (const x of res.refused) {
321
- const e = [...enrolling.values()].find((y) => y.temp !== undefined && y.temp === x.from);
737
+ // What the machine is told (enrol.mjs toldFor: its words, no DID), shown here the same.
738
+ for (const x of [...res.refused.map((y) => ({ to: y.from, check: y.check, detail: E.toldFor(y.check, y.detail) })), ...res.told]) {
739
+ const e = [...enrolling.values()].find((y) => y.temp !== undefined && y.temp === x.to);
322
740
  if (e) Object.assign(e, { check: x.check, detail: x.detail });
323
741
  }
324
742
  for (const p of res.placed) {
@@ -336,18 +754,41 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
336
754
  };
337
755
  // The contact holding a worker's original DID, live, or null.
338
756
  const contactOfWorker = (w) => carrier.contacts().contacts.find((x) => !x.revoked && x.chain.includes(w.original)) ?? null;
757
+ // A contact's kind (UI-API.md "Kinds"): person, agent or desk (a support desk). The human's choice (POST /api/kind,
758
+ // data.kind) wins; else what the contact said of itself once paired (carrier.mjs "Kinds": kind_peer agent or desk);
759
+ // else an agent when the page knows it is one (my agent: ours by its operator attestation, on this machine, or a
760
+ // worker of my keeper root; a member a group roster names an agent); else a person.
761
+ let workerDids = new Set();
762
+ const rosterAgents = () => {
763
+ try { return new Set(G && groupsFile && carrier.platform.files.read(groupsFile) !== null ? G.list({ carrier, file: groupsFile }).flatMap((g) => g.members.filter((m) => m.role === 'agent').map((m) => m.did)) : []); } catch { return new Set(); }
764
+ };
765
+ const kindOf = (x, mine, roles) => {
766
+ const set = data.kind[x.did];
767
+ if (KINDS.includes(set)) return { kind: set, kind_set: true };
768
+ if (x.kind_peer === 'agent' || x.kind_peer === 'desk') return { kind: x.kind_peer, kind_set: false };
769
+ const agent = x.ours === true || mine !== null || x.chain.some((d) => workerDids.has(d) || roles.has(d));
770
+ return { kind: agent ? 'agent' : 'person', kind_set: false };
771
+ };
772
+ const orphan = (n) => {
773
+ const hit = [...issuedLive].find(([, f]) => f.i === n);
774
+ return hit ? { id: hit[0], state: hit[1].needs_send ? 'sending' : 'waiting', code: null, exp: null, relay: null, words: null, confirm_words: false, words_ok: null, verified: false, needs_send: hit[1].needs_send, command: null,
775
+ ...(hit[1].told && { check: hit[1].told.check, detail: hit[1].told.detail }) } : null;
776
+ };
339
777
  async function workers() {
340
778
  const k = K ? await K.read() : null, st = hooks.seat?.() ?? null, seat = st ? (st.here ? 'here' : 'elsewhere') : null;
341
779
  if (!k) return { keeper: false, seat, workers: [] };
342
780
  await look();
343
781
  const local = hooks.agents?.() ?? [], waiting = enrolFile ? pend((x) => Object.values(x.issued).filter((e) => !e.done).map((e) => e.i)) : [];
782
+ workerDids = new Set(Object.values(k.workers).filter((w) => w.revoked === undefined).map((w) => w.original));
344
783
  const rows = Object.entries(k.workers).map(([i, w]) => {
345
784
  const n = Number(i), c = contactOfWorker(w), here = local.find((a) => a.did === w.original), e = [...enrolling.values()].filter((x) => x.worker === n).at(-1);
346
785
  const status = w.revoked !== undefined ? 'revoked' : c || here ? 'enrolled' : (e && LIVE.has(e.state)) || waiting.includes(n) ? 'pending' : 'unplaced';
347
- return { worker: n, name: w.name, did: c?.current_did ?? w.did, original: w.original, rank: w.rank ?? null, placed: w.placed, at: w.at, status, revoked: w.revoked ?? null,
786
+ return { worker: n, name: w.name, did: c?.current_did ?? w.did, original: w.original, words: didWords(w.original), rank: w.rank ?? null, placed: w.placed, at: w.at, status, revoked: w.revoked ?? null,
348
787
  seen: c ? seen(c.did) : null, tier: c?.tier ?? null, contact: c?.did ?? null, local: here?.name ?? null,
349
788
  online: c?.online ?? null, last_seen: c?.last_seen ?? null,
350
- attested_until: here?.mine?.exp ?? w.until ?? w.attestation?.body?.exp ?? null, enrolling: e && e.state !== 'expired' ? pub(e) : null };
789
+ attested_until: here?.mine?.exp ?? w.until ?? w.attestation?.body?.exp ?? null,
790
+ // Not in this page's memory (made before a restart): what the pending file says, sending again or waiting for the machine.
791
+ enrolling: e && e.state !== 'expired' ? pub(e) : status === 'pending' ? orphan(n) : null };
351
792
  }).sort((a, b) => a.worker - b.worker);
352
793
  return { keeper: true, seat, workers: rows };
353
794
  }
@@ -355,7 +796,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
355
796
  // ---- reads
356
797
  const textOf = (v) => (typeof v === 'string' ? v : JSON.stringify(v));
357
798
  function state(since) {
358
- const t = nowS(), c = carrier.contacts(), local = hooks.agents?.() ?? [], clock = carrier.clockOffset();
799
+ const t = nowS(), c = carrier.contacts(), local = hooks.agents?.() ?? [], clock = carrier.clockOffset(), roles = rosterAgents();
359
800
  const live_ = c.contacts.filter((x) => !x.revoked && !hidden(x)).map((x) => {
360
801
  const pair = x.pair, agent = local.find((a) => a.did !== undefined && x.chain.includes(a.did));
361
802
  const mine = agent?.mine ?? null;
@@ -368,43 +809,67 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
368
809
  const last = msgs.at(-1), read = data.read[x.did] ?? 0;
369
810
  const queued = msgs.filter((r) => r.kind === 'out' && r.status === 'queued');
370
811
  return {
371
- did: x.did, name: x.name, current_did: x.current_did, relay: x.relay, re_pair: x.re_pair, words: x.fingerprint, pair,
812
+ did: x.did, name: x.name, name_from: x.name_from ?? null, current_did: x.current_did, relay: x.relay, re_pair: x.re_pair, words: x.fingerprint, pair,
372
813
  words_checked: pair !== null && data.checked[x.did] === pair, tags: data.tags[x.did] ?? [],
373
- local: agent?.name ?? null, mine, unread: msgs.filter((r) => r.kind === 'in' && r.n > read).length,
374
- last: last ? { dir: last.kind, text: textOf(last.text).slice(0, 200), at: last.at, status: last.status ?? null } : null,
814
+ // Came by a public code (carrier.mjs via): mine ({public: id}, nobody compared) or theirs ({public: true, words}).
815
+ via: x.via ?? null,
816
+ local: agent?.name ?? null, mine, unread: msgs.filter((r) => r.kind === 'in' && r.n > read && (!r.call || r.call.state === 'missed')).length,
817
+ last: last ? { dir: last.kind, text: textOf(last.text).slice(0, 200), at: last.at, status: statusOf(last, x.seen_upto), ...(last.call && { call: last.call.state }) } : null,
818
+ notify: notifyOf(x.did), seen_upto: x.seen_upto ?? null,
819
+ // A busy mark (carrier.mjs "Busy marks"): their agent works on a turn; the chat's wheel, never a message.
820
+ busy: x.busy === true, busy_n: x.busy === true ? (x.busy_n ?? 1) : 0,
821
+ // A hosted agent's settings (the header's), as it last said them; null: it never did.
822
+ host: data.host[x.did] ?? null,
823
+ picture: picRev(picOf(x.did) ?? ''), picture_local: data.pics[`l:${x.did}`] !== undefined,
375
824
  waiting, not_collected: queued.length, queued: x.queued,
376
825
  status: x.re_pair ? 'pair_again' : waiting ? 'waiting' : queued.length ? 'not_collected' : 'ok', ours: x.ours === true || mine !== null, tier,
377
826
  link: x.link ? { id: x.link.id, purpose: x.link.purpose, linked_by: x.link.linked_by, expires: x.link.expires ?? null } : null,
378
827
  // Presence (carrier.mjs): theirs as read now (online true, false, null: not known), and what they see of mine.
379
828
  online: x.online ?? null, online_since: x.online_since ?? null, last_seen: x.last_seen ?? null, presence: x.presence ?? 'deny',
829
+ // Calls: may it ring here ("Can call me"), and whether that is my choice for it or the default.
830
+ can_call: canCall(x), can_call_set: typeof data.calls[x.did] === 'boolean',
831
+ ...kindOf(x, mine, roles),
380
832
  };
381
833
  });
382
834
  // Mine: ours by key, whatever the tier (an own agent set to friend is still mine), or tier own.
383
835
  const isMine = (x) => x.ours || x.tier === 'own';
384
836
  const mineGroup = live_.filter(isMine), rest = live_.filter((x) => !isMine(x));
385
837
  const pendingInvites = c.invites.filter((p) => !hidden(p)).map((p) => {
838
+ if (p.renew) {
839
+ // A renewing code: the current one of its series, wherever it was made (the long code only for the first, made here).
840
+ const ours = invites.get(`r${p.renew}`), x = c.renewing?.find((y) => y.id === p.renew);
841
+ return { name: p.name, exp: p.exp, relay: p.relay, id: `r${p.renew}`, short: p.short ?? null, short_exp: p.short_exp ?? null, code: ours?.short === p.short ? ours.code : null, group: null,
842
+ renew: true, used: (x?.used ?? []).map((u) => ({ short: u.short, name: u.name, did: u.did, at: u.at })), renew_error: x?.error ?? null };
843
+ }
386
844
  const ours = [...invites.values()].find((x) => x.name === p.name);
387
- return { name: p.name, exp: p.exp, relay: p.relay, ...(ours && { id: ours.id, short: ours.short ?? null, short_exp: ours.short_exp ?? null, code: ours.code }) };
845
+ return { name: p.name, exp: p.exp, relay: p.relay, ...(ours && { id: ours.id, short: ours.short ?? null, short_exp: ours.short_exp ?? null, code: ours.code, group: ours.group ?? null }) };
388
846
  });
389
847
  const paired = [...invites.values()].filter((x) => x.paired).map((x) => ({ id: x.id, name: x.name, paired: x.paired }));
390
848
  const failed = recs.filter((r) => r.kind === 'event' && r.type === 'pairing_failed' && r.at > t - DAY).slice(-5).map((r) => ({ name: r.name, did: r.did, code: r.code, detail: r.detail, at: r.at }));
391
849
  const m = hooks.me();
392
850
  return {
393
851
  seq, now: t,
852
+ // Enrolments whose four words wait for the human (this page's): said on every tab, not only on Agents (0.1.17).
853
+ enrol_words: [...enrolling.values()].filter((e) => e.state === 'words' && e.confirmWords && e.wordsOk === undefined && e.words).map((e) => ({ id: e.id, name: e.name })),
394
854
  me: {
395
855
  did: m.did, relay: carrier.relay, online: live.online.has(carrier.relay), clock_offset: clock?.offset ?? null, clock_checked: clock?.checked ?? null,
396
856
  retention_days: carrier.retentionDays, error: live.error, pow_done_ms: live.powDone,
397
857
  // The seat (DEVICES.md): null without one; here false = another device logs in as you: the page shows a banner.
398
858
  seat: hooks.seat?.() ?? null,
399
- pow: live.pow && { bits: live.pow.bits, elapsed_s: Math.round((Date.now() - live.pow.since) / 1000), expected_s: Math.ceil(2 ** live.pow.bits / 180000) },
859
+ pow: live.pow && { bits: live.pow.bits, elapsed_s: Math.round((Date.now() - live.pow.since) / 1000), expected_s: Math.ceil((2 ** live.pow.bits * POW_EVAL_MS * (live.pow.m * live.pow.t) / (POW_COST.m * POW_COST.t)) / 1000) },
400
860
  pow_capped: live.powCapped, pow_confirm: live.powConfirm,
861
+ // Wallet (Settings → Wallet): the switch and the price choice, for every scope of a control.
862
+ wallet: (({ wallet, prices, currency }) => ({ on: wallet, prices, currency }))(walletSet()),
863
+ picture: picRev('me'),
401
864
  },
402
865
  groups: { mine: mineGroup, contacts: rest },
403
866
  // Chat groups (GROUPS.md): the tab's badge and its notices; the list is GET /api/groups.
404
867
  chats: chatsState(),
405
- pending: { invites: pendingInvites, paired, answers: c.answers, failed },
868
+ pending: { invites: pendingInvites, paired, answers: c.answers, failed, public: publicInvite(c), publics: c.publics ?? [] },
406
869
  introductions: introductions(c.contacts),
407
870
  transfers: transferCounts(),
871
+ // The live call (GET /api/calls has the rest), or null: the page's call screen and its poll.
872
+ call: (({ id, did, name, dir, state } = {}) => (id ? { id, did, name, dir, state } : null))(line.view() ?? undefined),
408
873
  events: recs.filter((r) => r.kind === 'event' && r.n > since).slice(-50),
409
874
  };
410
875
  }
@@ -414,7 +879,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
414
879
  if (carrier.platform.files.read(linksFile) === null) return [];
415
880
  try {
416
881
  return L.list({ carrier, file: linksFile }).received.filter((x) => !x.answer && cs.find((c) => c.did === x.from)?.tier !== 'quiet')
417
- .map((x) => ({ id: x.id, from: x.from, name: x.name ?? x.from, purpose: x.purpose }));
882
+ .map((x) => ({ id: x.id, from: x.from, name: x.name ?? x.from, purpose: x.purpose, peer_name: x.peer_name ?? null }));
418
883
  } catch { return []; }
419
884
  }
420
885
 
@@ -460,7 +925,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
460
925
  return gs.map((g) => {
461
926
  const items = ['member', 'frozen'].includes(g.status) ? G.history({ carrier, file: groupsFile, group: g.gid }) : [];
462
927
  const last = items.at(-1);
463
- return { ...g, unread: unreadIn(g.gid, items), quiet: brakeQuiet(g),
928
+ return { ...g, unread: unreadIn(g.gid, items), quiet: brakeQuiet(g), notify: notifyOf(g.gid), picture: picRev(`l:${g.gid}`),
464
929
  last: last ? { name: last.mine ? null : last.name, text: textOf(last.content).slice(0, 200), at: last.received ?? last.iat, mine: last.mine === true } : null };
465
930
  });
466
931
  }
@@ -487,6 +952,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
487
952
  }
488
953
  }
489
954
  const gid = (b) => (typeof b['group'] === 'string' && b['group'] !== '' ? b['group'] : refuse(400, 'body', 'group: its gid'));
955
+ const isGroup = (x) => { try { return typeof x === 'string' && /^[0-9a-f]{32}$/.test(x) && Boolean(G && groupsFile && carrier.platform.files.read(groupsFile) !== null && G.list({ carrier, file: groupsFile }).some((g) => g.gid === x)); } catch { return false; } };
490
956
  const dids = (v, what, need = true) => {
491
957
  if (v === undefined && !need) return [];
492
958
  if (!Array.isArray(v) || (need && v.length === 0) || v.length > 64 || v.some((x) => typeof x !== 'string' || x === '')) refuse(400, 'body', `${what}: a list of contact DIDs`);
@@ -502,11 +968,12 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
502
968
  // Read: the page has shown them.
503
969
  if (last && data.gread[g]?.mid !== last.mid) { data.gread[g] = { mid: last.mid, at: last.received ?? last.iat }; saveData(); }
504
970
  return { group: { ...one, unread: 0 }, messages: items.slice(-200).map((i) => ({ mid: i.mid, re: i.re ?? null, from: i.from, name: i.name, role: i.role, tier: i.tier ?? null, mine: i.mine === true,
505
- operator: i.operator === true, note: i.note ?? null, text: textOf(i.content), mentions: i.mentions ?? [], mentioned: i.mentioned === true, via: i.via ?? null, at: i.received ?? i.iat })) };
971
+ operator: i.operator === true, note: i.note ?? null, text: textOf(i.content), mentions: i.mentions ?? [], mentioned: i.mentioned === true, via: i.via ?? null, photo: i.photo ?? null, ...(i.voice && { voice: i.voice }), at: i.received ?? i.iat })) };
506
972
  }),
507
973
  'POST /api/groups/create': (b) => serial(() => groupCall(async () => {
508
974
  const brake = b['brake'];
509
975
  return gout(await G.create({ carrier, file: groupsFile, name: b['name'], members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false), ...(brake !== undefined && brake !== null && { brake }),
976
+ ...(carrier.selfName() !== null && { selfName: carrier.selfName() }),
510
977
  ...(typeof b['role'] === 'string' && { role: b['role'] }) }));
511
978
  })),
512
979
  'POST /api/groups/add': (b) => serial(() => groupCall(async () => gout(await G.add({ carrier, file: groupsFile, group: gid(b), members: dids(b['members'], 'members'), humans: dids(b['humans'], 'humans', false) })))),
@@ -552,9 +1019,70 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
552
1019
  }
553
1020
  async function forget(c) {
554
1021
  const r = await carrier.forget(c.did);
555
- delete data.tags[c.did]; delete data.checked[c.did]; saveData();
1022
+ delete data.tags[c.did]; delete data.checked[c.did]; delete data.kind[c.did];
1023
+ if (store.writePicture) { picDrop(`l:${c.did}`); picDrop(`t:${c.did}`); }
1024
+ delete data.pic_sent[c.did]; delete data.pic_peer[c.did]; saveData();
556
1025
  return { forgotten: c.did, offline: r.offline ?? null };
557
1026
  }
1027
+ // Who signed a statement, as this page knows them: me, a contact (its chain holds the signing key), or nobody known.
1028
+ function signerOf(v) {
1029
+ const m = hooks.me();
1030
+ if (v.original === m.original && m.chain.includes(v.did)) return { kind: 'me', did: m.original, name: null, words_checked: true };
1031
+ const c = carrier.contacts().contacts.find((x) => !x.revoked && !hidden(x) && x.did === v.original && x.chain.includes(v.did));
1032
+ return c ? { kind: 'contact', did: c.did, name: c.name, words_checked: c.pair !== null && data.checked[c.did] === c.pair } : { kind: 'unknown', did: v.original, name: null, words_checked: false };
1033
+ }
1034
+ const checked = (v) => (v.valid ? { ...v, words: didWords(v.original), by: signerOf(v) } : v);
1035
+ // A statement in a chat (the bubble's "Signed by … · check"): checked once per message, kept for the page's life.
1036
+ const statements = new Map();
1037
+ function statementOf(r) {
1038
+ let v = statements.get(r.n);
1039
+ if (!v) { v = checkStatement(textOf(r.text), nowS()); statements.set(r.n, v); }
1040
+ const w = checked(v);
1041
+ return w.valid ? { valid: true, by: w.by, words: w.words, text: w.text, iat: w.iat } : { valid: false, check: w.check };
1042
+ }
1043
+ // POST /api/invite {public: true, months?, cap?, open?, name?}: a public code (the header's), Pro only (public_pro → 402).
1044
+ async function publicRoute(b) {
1045
+ const months = b['months'] ?? 6, cap = b['cap'] ?? 50;
1046
+ if (![1, 6, 12].includes(months)) refuse(400, 'body', 'months: 1, 6 or 12');
1047
+ if (!Number.isSafeInteger(cap) || cap < 1 || cap > 500) refuse(400, 'body', 'cap: new chats a day, 1 to 500');
1048
+ if (b['open'] !== undefined && typeof b['open'] !== 'boolean') refuse(400, 'body', 'open: true (let anyone in) or false (approve each, the default)');
1049
+ if (b['long'] !== undefined || b['group'] !== undefined || b['renew'] !== undefined || b['ttl'] !== undefined) refuse(400, 'body', 'public: with months, cap, open and name only');
1050
+ const name = b['name'] === undefined || b['name'] === '' ? undefined : cleanName(b['name'], 'name'), at = newCodes();
1051
+ const r = await carrier.invitePublic({ ...(name !== undefined && { name }), ttl: months === 12 ? 366 * DAY : months * 30 * DAY, cap, open: b['open'] === true, ...(at !== carrier.relay && { relay: at }), started: startedBy(b) })
1052
+ .catch((e) => { if (e.check === 'public_pro') e.status = 402; return Promise.reject(e); });
1053
+ changed();
1054
+ return { ...r, public: true };
1055
+ }
1056
+ // GET /api/search (UI-API.md "Search"): the contacts' histories (texts and signed messages; photos, voice and files are
1057
+ // not text) and the groups' (G.history, as GET /api/groups/history reads it), newest first. A read of what is here only:
1058
+ // no carrier call, no read mark, no receipt.
1059
+ const searchText = (r) => (r.label === STATEMENT_LABEL ? textOf(r.text).replace(/(?:^|\n)sigelo-statement\/0\s[\s\S]*$/, '').replace(SIGNED_LINE, '') : textOf(r.text));
1060
+ function search(q) {
1061
+ const want = foldMap(String(q.get('q') ?? '').trim()).f;
1062
+ if ([...want].length < 2) refuse(400, 'query', 'q: at least 2 characters');
1063
+ const lim = q.get('limit') === null ? 50 : Number(q.get('limit'));
1064
+ if (!Number.isSafeInteger(lim) || lim < 1 || lim > 200) refuse(400, 'body', 'limit: 1 to 200');
1065
+ const one = q.get('contact'), grp = q.get('group'), hits = [];
1066
+ if (one !== null && grp !== null) refuse(400, 'body', 'contact or group, not both');
1067
+ const hit = (base, t) => { const m = matchIn(t, want); if (m) hits.push({ ...base, text: t.slice(0, 1000), ...m }); };
1068
+ if (grp === null) {
1069
+ const by = new Map((one !== null ? [contactOf(one)] : carrier.contacts().contacts.filter((x) => !x.revoked && !hidden(x))).map((c) => [c.did, c]));
1070
+ for (const r of recs) {
1071
+ if ((r.kind !== 'in' && r.kind !== 'out') || !by.has(r.did) || r.photo || r.voice || r.file || [PHOTO_LABEL, VOICE_LABEL, FILE_LABEL].includes(r.label)) continue;
1072
+ hit({ chat: r.did, kind: 'contact', name: by.get(r.did).name, n: r.n, dir: r.kind, at: r.at }, searchText(r));
1073
+ }
1074
+ }
1075
+ if (one === null) {
1076
+ const gs = G && groupsFile && carrier.platform.files.read(groupsFile) !== null ? G.list({ carrier, file: groupsFile }).filter((g) => grp === null || g.gid === grp) : [];
1077
+ if (grp !== null && !gs.length) refuse(404, 'group_unknown', `no group ${grp} here`);
1078
+ for (const g of gs) {
1079
+ let items = [];
1080
+ try { items = G.history({ carrier, file: groupsFile, group: g.gid }); } catch {}
1081
+ for (const i of items) if (!i.photo && !i.voice) hit({ chat: g.gid, kind: 'group', name: g.name, n: i.mid, dir: i.mine ? 'out' : 'in', at: i.received ?? i.iat }, textOf(i.content));
1082
+ }
1083
+ }
1084
+ return { hits: hits.reverse().sort((a, b) => b.at - a.at).slice(0, lim) };
1085
+ }
558
1086
  const routes = {
559
1087
  'GET /api/state': async (_, q) => { if (draining) await draining; return state(Number(q.get('since') ?? 0) || 0); },
560
1088
  'GET /api/me': () => {
@@ -562,20 +1090,119 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
562
1090
  return { did: m.did, original: m.original, words: didWords(m.original), chain: m.chain, identity_file: i.identity_file, recovery: i.recovery, key: i.key, relay: carrier.relay, retention_days: carrier.retentionDays, erase: i.erase,
563
1091
  ...(i.restored && { restored: i.restored }) };
564
1092
  },
1093
+ // Pictures (the header's): of=me (mine), a contact's DID or a group's gid (the one shown: a local one, else theirs).
1094
+ 'GET /api/picture': (_, q) => {
1095
+ const of = q.get('of') ?? '';
1096
+ if (of !== 'me' && !isGroup(of)) contactOf(of);
1097
+ const key = picOf(of), bytes = key && data.pics[key] ? store.readPicture?.(picFile(key)) ?? null : null;
1098
+ if (!bytes) refuse(404, 'picture_none', 'no picture: the initial or the mark shows');
1099
+ return { of, type: data.pics[key].type, data: b64(bytes), rev: data.pics[key].rev, local: key.startsWith('l:') };
1100
+ },
1101
+ 'POST /api/picture': (b) => serial(async () => {
1102
+ if (!store.writePicture) refuse(404, 'route', 'no pictures here');
1103
+ const of = b['of'];
1104
+ if (typeof of !== 'string' || of === '') refuse(400, 'body', 'of: me, a contact\'s DID or a group\'s gid');
1105
+ const id = of === 'me' ? 'me' : isGroup(of) ? of : contactOf(of).did, key = id === 'me' ? 'me' : `l:${id}`;
1106
+ if (b['remove'] === true) picDrop(key);
1107
+ else picSave(key, b['type'], pictureBytes(b['type'], b['data']));
1108
+ saveData();
1109
+ if (id === 'me') picturesDue();
1110
+ changed();
1111
+ const now_ = picOf(id);
1112
+ return { of: id, picture: now_ ? picRev(now_) : null, local: now_?.startsWith('l:') ?? false };
1113
+ }),
1114
+ // Signed statements (the header's): sign a text with this identity's key; check one, offline.
1115
+ 'POST /api/statement/sign': (b) => serial(async () => {
1116
+ const statement = signStatement(carrier.identity(), b['text'], nowS());
1117
+ return { statement, ...checked(checkStatement(statement, nowS())) };
1118
+ }),
1119
+ 'POST /api/statement/check': async (b) => {
1120
+ if (typeof b['statement'] !== 'string' || b['statement'].length > 4 * TEXT_MAX) refuse(400, 'body', 'statement: the signed text, as it was shared');
1121
+ return checked(checkStatement(b['statement'], nowS()));
1122
+ },
1123
+ // Proof of age (Me → Proof of age): what this identity's own bundle shows of its age, checked (SPEC §9): the day its
1124
+ // genesis names (its own word) and each attestation a world signed, with when.
1125
+ 'GET /api/attestations': () => {
1126
+ const bundle = carrier.identity().bundle, r = verify(bundle, nowS());
1127
+ const list = Object.entries(r.attestations ?? {}).flatMap(([iss, bodies]) => bodies.map((x) => ({ iss, ctx: x.ctx, iat: x.iat, exp: x.exp, admission: x.admission, claims: x.claims ?? {} })));
1128
+ return { created: bundle.genesis.created ?? null, attestations: list.sort((a, c) => a.iat - c.iat), rejected: r.rejected?.attestations ?? 0 };
1129
+ },
565
1130
  'POST /api/invite': (b) => serial(async () => {
566
- const name = b['name'] === undefined || b['name'] === '' ? `contact-${hexOf(2)}` : cleanName(b['name'], 'name');
567
- const at = newCodes();
568
- const r = await carrier.invite({ name, short: b['long'] !== true, ...(at !== carrier.relay && { relay: at }), started: startedBy(b) });
569
- const inv = { id: hexOf(6), name, code: r.code, exp: r.exp, ...(r.short !== undefined && { short: r.short, short_exp: r.short_exp }) };
1131
+ if (b['public'] === true) return publicRoute(b);
1132
+ const pub = false, ttl = b['ttl'];
1133
+ const name = b['name'] === undefined || b['name'] === '' ? `${pub ? 'public' : 'contact'}-${hexOf(2)}` : cleanName(b['name'], 'name');
1134
+ const at = newCodes(), group = b['group'];
1135
+ // A long code's life (the public invite): an hour to 7 days; the short code lives 10 minutes whatever.
1136
+ if (ttl !== undefined && (b['long'] !== true || !Number.isSafeInteger(ttl) || ttl < 3600 || ttl > 7 * DAY)) refuse(400, 'body', 'ttl: with long, 3600 to 604800 seconds (an hour to 7 days)');
1137
+ if (b['public'] !== undefined && b['public'] !== false) refuse(400, 'body', 'public: true or false');
1138
+ // A person code that renews itself: short, for one person at a time (no long, public or group code).
1139
+ const renew = b['renew'] === true;
1140
+ if (b['renew'] !== undefined && (typeof b['renew'] !== 'boolean' || (renew && (b['long'] === true || pub || group !== undefined)))) refuse(400, 'body', 'renew: true, a short person code (not long, public or a group code)');
1141
+ // A group code (Add people): whoever pairs through it is added to that group of mine, as a person.
1142
+ if (group !== undefined) {
1143
+ const g = typeof group === 'string' && G && groupsFile ? G.list({ carrier, file: groupsFile }).find((x) => x.gid === group) : null;
1144
+ if (!g) refuse(404, 'group_unknown', `no group ${String(group)} here`);
1145
+ if (!g.mine || g.status !== 'member') refuse(409, 'group_creator', `only ${g.creator_name ?? 'its creator'} adds people to ${g.name}`);
1146
+ }
1147
+ // Unnamed: the made-up name gives way to the one the contact tells once paired (carrier.mjs "Names").
1148
+ const r = await carrier.invite({ name, named: !(b['name'] === undefined || b['name'] === ''), short: b['long'] !== true, ...(ttl !== undefined && { ttl }), ...(at !== carrier.relay && { relay: at }), ...(renew && { renew: true }), started: startedBy(b) });
1149
+ const inv = { id: r.renew ? `r${r.renew}` : hexOf(6), name, code: r.code, exp: r.exp, ...(r.short !== undefined && { short: r.short, short_exp: r.short_exp }), ...(group !== undefined && { group }), ...(pub && { public: true }), ...(r.renew && { renew: true }) };
570
1150
  invites.set(inv.id, inv);
571
1151
  changed();
572
1152
  return { ...inv, relay: r.relay };
573
1153
  }),
574
1154
  'POST /api/invite/cancel': (b) => serial(async () => {
575
- const inv = invites.get(String(b['id'])) ?? refuse(404, 'invite', 'no such invite');
576
- await carrier.cancelInvite(inv.code);
1155
+ // By its short code (a code this page did not make: the CLI's, a renewal), at the carrier and the relay.
1156
+ if (b['id'] === undefined && typeof b['code'] === 'string' && b['code'].trim() !== '') {
1157
+ const r = await carrier.cancelInvite(b['code'].trim()).catch((e) => (e.check === 'challenge_unknown' ? refuse(404, 'invite', 'no such invite') : Promise.reject(e)));
1158
+ for (const x of [...invites.values()]) if (x.short === r.short || (r.name !== null && x.name === r.name)) invites.delete(x.id);
1159
+ changed();
1160
+ return { cancelled: true, ...(r.unparked !== undefined && { unparked: r.unparked }), ...(r.detail && { detail: r.detail }) };
1161
+ }
1162
+ const id = String(b['id']);
1163
+ // A renewing code: its series' current code, wherever it was made; cancelling it ends the series.
1164
+ if (id.startsWith('r')) {
1165
+ const cur = carrier.contacts().invites.find((x) => `r${x.renew}` === id);
1166
+ invites.delete(id);
1167
+ if (!cur) refuse(404, 'invite', 'no such invite');
1168
+ const r = cur.short ? await carrier.cancelInvite(cur.short) : { unparked: undefined };
1169
+ changed();
1170
+ return { cancelled: true, ...(r.unparked !== undefined && { unparked: r.unparked }), ...(r.detail && { detail: r.detail }) };
1171
+ }
1172
+ // A public code of mine (its id): Revoke for all.
1173
+ if (carrier.publics().some((x) => x.id === id)) {
1174
+ const r = await carrier.cancelInvite(id);
1175
+ changed();
1176
+ return { cancelled: true, public: true, unparked: r.unparked, ...(r.detail && { detail: r.detail }) };
1177
+ }
1178
+ const inv = invites.get(id) ?? refuse(404, 'invite', 'no such invite');
1179
+ let r = {};
1180
+ try { r = await carrier.cancelInvite(inv.code); } catch (e) { if (!inv.public) throw e; }
577
1181
  invites.delete(inv.id);
578
- return { cancelled: true };
1182
+ changed();
1183
+ return { cancelled: true, ...(r.unparked !== undefined && { unparked: r.unparked }), ...(r.detail && { detail: r.detail }) };
1184
+ }),
1185
+ // A public code's requests and settings (UI-API.md "Public invite").
1186
+ 'POST /api/public/approve': (b) => serial(async () => {
1187
+ if (typeof b['id'] !== 'string') refuse(400, 'body', 'id: a request\'s id (pending.public.requests[].id)');
1188
+ const r = await carrier.approvePublic(b['id'], { started: startedBy(b) }).catch((e) => (e.check === 'challenge_unknown' ? refuse(404, 'request', e.message) : Promise.reject(e)));
1189
+ changed();
1190
+ return r;
1191
+ }),
1192
+ 'POST /api/public/refuse': (b) => serial(async () => {
1193
+ if (typeof b['id'] !== 'string') refuse(400, 'body', 'id: a request\'s id');
1194
+ try { const r = carrier.refusePublic(b['id']); changed(); return r; } catch (e) { if (e.check === 'challenge_unknown') refuse(404, 'request', e.message); throw e; }
1195
+ }),
1196
+ 'POST /api/public/set': (b) => serial(async () => {
1197
+ const id = b['id'] ?? carrier.publics()[0]?.id;
1198
+ if (typeof id !== 'string') refuse(404, 'public', 'no public code here');
1199
+ if (b['paused'] !== undefined && typeof b['paused'] !== 'boolean') refuse(400, 'body', 'paused: true or false');
1200
+ if (b['cap'] !== undefined && (!Number.isSafeInteger(b['cap']) || b['cap'] < 1 || b['cap'] > 500)) refuse(400, 'body', 'cap: new chats a day, 1 to 500');
1201
+ if (b['paused'] === undefined && b['cap'] === undefined) refuse(400, 'body', 'paused and/or cap');
1202
+ const r = await carrier.setPublic(id, { ...(b['paused'] !== undefined && { paused: b['paused'] }), ...(b['cap'] !== undefined && { cap: b['cap'] }) }, { started: startedBy(b) })
1203
+ .catch((e) => (e.check === 'challenge_unknown' ? refuse(404, 'public', e.message) : Promise.reject(e)));
1204
+ changed();
1205
+ return r;
579
1206
  }),
580
1207
  'POST /api/accept': (b) => serial(async () => {
581
1208
  if (typeof b['code'] !== 'string' || b['code'].trim() === '') refuse(400, 'body', 'code: the short code (K7F3-Q9ZP) or the long one (sgl1…)');
@@ -584,7 +1211,10 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
584
1211
  // friend or quiet, the human's choice; own is detected, never asked (store.mjs tiers).
585
1212
  const tier = b['tier'];
586
1213
  if (tier !== undefined && tier !== 'friend' && tier !== 'quiet') refuse(400, 'body', 'tier: friend or quiet');
587
- const r = await carrier.accept(code, { ...(name !== undefined && { name }), wait: 10, ...(tier !== undefined && { tier }), started: startedBy(b) });
1214
+ // words: a public code's four words, as its page printed them (checked on the reply).
1215
+ if (b['words'] !== undefined && (typeof b['words'] !== 'string' || b['words'].trim() === '')) refuse(400, 'body', 'words: the four words beside a public code');
1216
+ const words = typeof b['words'] === 'string' ? b['words'] : undefined;
1217
+ const r = await carrier.accept(code, { ...(name !== undefined && { name }), wait: 10, ...(tier !== undefined && { tier }), ...(words !== undefined && { words }), started: startedBy(b) });
588
1218
  const now = r.contact ? carrier.contacts().contacts.find((x) => x.did === r.contact.did) : undefined;
589
1219
  return r.contact ? { status: r.status, contact: { ...r.contact, pair: now?.pair ?? null, tier: now?.tier ?? null } }
590
1220
  : { ...r, exp: carrier.contacts().answers.find((x) => x.did === r.did)?.exp ?? null };
@@ -609,6 +1239,55 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
609
1239
  if (typeof allow !== 'boolean') refuse(400, 'body', 'allow: true or false');
610
1240
  try { return carrier.setPresence(c.did, allow); } catch (e) { if (e.check === 'presence_own') e.status = 409; throw e; }
611
1241
  }),
1242
+ // A hosted agent's setting (the header's): one of the choices it offered; it applies it at its next turn.
1243
+ 'POST /api/host/set': (b) => serial(async () => {
1244
+ const c = contactOf(b['contact']), h = data.host[c.did], key = b['key'], value = b['value'];
1245
+ if (!h) refuse(409, 'host_none', 'this contact has not said what can be set');
1246
+ const f = h.fields.find((x) => x.key === key) ?? refuse(400, 'body', `key: one of ${h.fields.map((x) => x.key).join(', ')}`);
1247
+ if (f.off !== undefined) refuse(409, 'host_off', f.off);
1248
+ if (typeof value !== 'string' || !f.options.some((o) => o.value === value)) refuse(400, 'body', 'value: one of its choices');
1249
+ const r = await carrier.send(c.did, { key, value }, { label: HOST_SET_LABEL });
1250
+ // Waiting for its next turn until the agent says again.
1251
+ if (value === f.value) delete f.next; else f.next = value;
1252
+ delete h.note;
1253
+ saveData(); changed();
1254
+ return { did: c.did, host: h, status: r.status };
1255
+ }),
1256
+ // A contact's kind, the human's choice (Chat settings → "This is"): person, agent, desk, or null (the page decides again).
1257
+ 'POST /api/kind': (b) => serial(async () => {
1258
+ const c = contactOf(b['contact']), k = b['kind'];
1259
+ if (!KINDS.includes(k) && k !== null) refuse(400, 'body', 'kind: person, agent, desk, or null (automatic)');
1260
+ if (k === null) delete data.kind[c.did]; else data.kind[c.did] = k;
1261
+ saveData(); changed();
1262
+ return { did: c.did, kind: kindOf(c, null, rosterAgents()).kind, kind_set: k !== null };
1263
+ }),
1264
+ // The keeper's settings and payment requests (UI-API.md "Keeper"): `sigelo-agent ui` answers them where the
1265
+ // keeper runs. Here, with hooks.computer (a computer of this operator paired to this profile, scope all;
1266
+ // design/agent-wallet-page.md §4), they go to that computer, and a limit is changed by a policy-change this
1267
+ // page signs with its own identity: the computer carries it to its keeper and cannot alter it. Without one:
1268
+ // elsewhere, and the writes are refused keeper_elsewhere.
1269
+ 'GET /api/keeper': async () => {
1270
+ if (!PC) return { state: 'elsewhere', via: null };
1271
+ try { return { ...(await viaPc('GET', '/api/keeper')), via: { computer: PC.name() } }; } catch (e) { return { state: 'elsewhere', via: { computer: PC.name(), error: e.message } }; }
1272
+ },
1273
+ 'POST /api/keeper/agent': async (b) => {
1274
+ if (!PC) return refuse(409, 'keeper_elsewhere', 'Set this on the computer that runs the keeper.');
1275
+ const v = await viaPc('GET', '/api/keeper'), ks = Array.isArray(v.keepers) ? v.keepers : [];
1276
+ const k = ks.find((x) => x.id === b['keeper']) ?? (b['keeper'] === undefined && ks.length === 1 ? ks[0] : null) ?? refuse(404, 'keeper_unknown', `no keeper ${JSON.stringify(b['keeper'])} on ${PC.name()}`);
1277
+ if (typeof b['agent'] !== 'string') refuse(400, 'body', 'agent: its name in the keeper');
1278
+ const set = Object.fromEntries(KEEPER_FIELDS.filter((f) => b[f] !== undefined).map((f) => [f, b[f]]));
1279
+ if (Object.keys(set).length === 0) refuse(400, 'body', `one of ${KEEPER_FIELDS.join(', ')}`);
1280
+ const t = nowS(), body = { v: 'sigelo/0', typ: 'policy-change', keeper: k.did, net: k.net, agent: b['agent'], set, nonce: hexOf(16), iat: t, exp: t + 300 };
1281
+ const idn = carrier.identity();
1282
+ return viaPc('POST', '/api/keeper/policy', { keeper: k.id, change: { body, sig: signAs(idn, body), bundle: idn.bundle } });
1283
+ },
1284
+ ...Object.fromEntries(['approvers', 'approve', 'refuse', 'restart'].map((r) => [`POST /api/keeper/${r}`, (b) => (PC ? viaPc('POST', `/api/keeper/${r}`, b) : refuse(409, 'keeper_elsewhere', 'Set this on the computer that runs the keeper.'))])),
1285
+ 'POST /api/keeper/policy': (b) => (PC ? viaPc('POST', '/api/keeper/policy', b) : refuse(409, 'keeper_elsewhere', 'Set this on the computer that runs the keeper.')),
1286
+ // The wallet (UI-API.md "Wallet"): none in this page; `sigelo-agent ui` answers these with the computer's.
1287
+ 'GET /api/wallet': () => ({ on: data.settings.wallet === true, where: 'none' }),
1288
+ 'GET /api/price': () => ({ on: false, currency: walletSet().currency }),
1289
+ ...Object.fromEntries(['GET /api/wallet/history', 'GET /api/wallet/tx', 'GET /api/wallet/services', 'GET /api/wallet/nodes', 'POST /api/wallet/sync', 'POST /api/wallet/receive', 'POST /api/wallet/label',
1290
+ 'POST /api/wallet/review', 'POST /api/wallet/send', 'POST /api/wallet/service', 'POST /api/wallet/node'].map((r) => [r, () => refuse(409, 'wallet_none', 'This phone has no wallet yet: use the computer\'s page.')])),
612
1291
  'POST /api/tag': (b) => serial(async () => {
613
1292
  const c = contactOf(b['contact']), tags = b['tags'];
614
1293
  if (!Array.isArray(tags) || tags.length > 8) refuse(400, 'body', 'tags: a list of at most 8');
@@ -619,39 +1298,98 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
619
1298
  }),
620
1299
  'POST /api/forget': (b) => serial(async () => forget(contactOf(b['contact']))),
621
1300
  'POST /api/send': (b) => serial(async () => {
622
- const c = contactOf(b['to']), text = b['text'];
1301
+ const c = contactOf(b['to']), st = b['statement'];
1302
+ // A signed statement (the header's): its portable text, labelled, checked before it goes.
1303
+ if (st !== undefined && (typeof st !== 'string' || !checkStatement(st, nowS()).valid)) refuse(400, 'statement', 'statement: the portable text of a valid signed statement (POST /api/statement/check)');
1304
+ // re: the n of a message of this chat that this one answers (carrier.mjs "Replies"): its label quotes it.
1305
+ const re = b['re'];
1306
+ if (re !== undefined && (st !== undefined || !Number.isSafeInteger(re))) refuse(400, 'body', 're: the n of a message of this chat (not with a statement)');
1307
+ const quoted = re === undefined ? null : recs.find((r) => (r.kind === 'in' || r.kind === 'out') && r.did === c.did && r.n === re && typeof r.text === 'string') ?? refuse(404, 'message', 'no such message in this chat to answer');
1308
+ const text = st ?? b['text'], label = st !== undefined ? STATEMENT_LABEL : quoted ? reLabel(quoted.text, quoted.kind === 'out') : '';
623
1309
  if (typeof text !== 'string' || text.trim() === '' || text.length > TEXT_MAX) refuse(400, 'body', `text: 1 to ${TEXT_MAX} characters`);
1310
+ // at: before it is sealed, so a receipt naming its iat covers it (statusOf).
1311
+ const at = nowS(), lab = label ? { label } : {};
624
1312
  let r;
625
- try { [r] = await carrier.sendAll(c.did, [text], { label: '' }); } catch (e) {
1313
+ try { [r] = await carrier.sendAll(c.did, [text], { label }); } catch (e) {
626
1314
  // The session failed: the message stays queued in the carrier and goes at a later connection.
627
1315
  if (!/queued/.test(e.message)) throw e;
628
- return record({ kind: 'out', did: c.did, id: null, text, status: 'queued', code: e.check, detail: e.message });
1316
+ return record({ kind: 'out', did: c.did, id: null, text, status: 'queued', code: e.check, detail: e.message, at, ...lab });
629
1317
  }
630
- return record({ kind: 'out', did: c.did, id: r.id, text, status: r.status, code: r.code, detail: r.detail });
1318
+ return record({ kind: 'out', did: c.did, id: r.id, text, status: r.status, code: r.code, detail: r.detail, at, ...lab });
631
1319
  }),
1320
+ 'GET /api/search': (_, q) => search(q),
632
1321
  'GET /api/messages': (_, q) => {
633
- const d = contactOf(q.get('contact')).did, since = Number(q.get('since') ?? 0) || 0;
1322
+ const x = contactOf(q.get('contact')), d = x.did, since = Number(q.get('since') ?? 0) || 0;
634
1323
  const msgs = recs.filter((r) => (r.kind === 'in' || r.kind === 'out') && r.did === d && r.n > since).slice(-200);
635
- // Read: the page has shown them.
1324
+ // A reply's quote (carrier.mjs "Replies"): the message it names, found among this chat's by its text and author.
1325
+ const all = recs.filter((r) => (r.kind === 'in' || r.kind === 'out') && r.did === d);
1326
+ const reOf = (r) => {
1327
+ const m = RE_LABEL.exec(r.label ?? '');
1328
+ if (!m) return null;
1329
+ const kind = (r.kind === 'out') === (m[2] === 's') ? 'out' : 'in';
1330
+ const q = all.filter((x) => x.n < r.n && x.kind === kind && typeof x.text === 'string' && quoteHash(x.text) === m[1]).at(-1);
1331
+ return { n: q?.n ?? null, dir: kind, text: q ? q.text.split('\n')[0].slice(0, 120) : null };
1332
+ };
1333
+ // Read: the page has shown them; a seen receipt when one is due (the header's).
636
1334
  if ((data.read[d] ?? 0) < seq) { data.read[d] = seq; saveData(); }
637
- return { seq, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, text: textOf(r.text), label: r.label ?? '', status: r.status ?? null, code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null })) };
1335
+ receipt(d);
1336
+ return { seq, messages: msgs.map((r) => ({ n: r.n, dir: r.kind, at: r.at, iat: r.iat ?? null, text: textOf(r.text), label: r.label ?? '', status: statusOf(r, x.seen_upto), code: r.code ?? null, detail: r.detail ?? null, link: r.link ?? null,
1337
+ ...(RE_LABEL.test(r.label ?? '') && { re: reOf(r) }),
1338
+ ...(r.label === STATEMENT_LABEL && { statement: statementOf(r) }), ...(r.photo && { photo: r.photo }), ...(r.voice && { voice: r.voice }), ...(r.file && { file: r.file }), ...(r.call && { call: r.call }),
1339
+ ...(r.approval && { approval: r.approval }), ...(r.question && { question: r.question }) })) };
638
1340
  },
639
1341
  'POST /api/sync': () => serial(async () => { await carrier.sync(); return { synced: true }; }),
640
- 'POST /api/history/clear': () => serial(async () => {
1342
+ 'POST /api/history/clear': (b) => serial(async () => {
1343
+ // One chat (contact: its messages go, the rest stays, written again), or all of it.
1344
+ if (b['contact'] !== undefined) {
1345
+ const d = contactOf(b['contact']).did, keep = recs.filter((r) => !((r.kind === 'in' || r.kind === 'out') && r.did === d));
1346
+ store.clearHistory();
1347
+ for (const r of keep) store.append(JSON.stringify(r) + '\n');
1348
+ recs.length = 0; outById.clear();
1349
+ for (const r of keep) { recs.push(r); if (r.kind === 'out' && r.id) outById.set(r.id, r); }
1350
+ changed();
1351
+ return { cleared: true, contact: d };
1352
+ }
641
1353
  store.clearHistory(); recs.length = 0; outById.clear(); data.read = {}; saveData();
642
1354
  changed();
643
1355
  return { cleared: true };
644
1356
  }),
1357
+ // Notifications for one chat (a contact's DID or a group's gid): on (the default) or off.
1358
+ 'POST /api/notify': (b) => serial(async () => {
1359
+ const chat = b['chat'], on = b['on'];
1360
+ if (typeof on !== 'boolean') refuse(400, 'body', 'on: true or false');
1361
+ const isGroup = typeof chat === 'string' && G && groupsFile && G.list({ carrier, file: groupsFile }).some((g) => g.gid === chat);
1362
+ const id = isGroup ? chat : contactOf(chat).did;
1363
+ if (on) delete data.notify[id]; else data.notify[id] = false;
1364
+ saveData(); changed();
1365
+ return { chat: id, notify: on };
1366
+ }),
645
1367
  // Settings: the relay new codes name (above). relay: a host[:port], or "" / null for relay.sigelo.ai.
646
- 'GET /api/settings': () => settings(),
1368
+ 'GET /api/settings': () => settingsAll(),
1369
+ // Any of: relay, seen_receipts, notify, new_tier, new_presence (Settings → Chats); wallet, prices, currency (Settings → Wallet); each checked before any is kept.
647
1370
  'POST /api/settings': (b) => serial(async () => {
648
- const v = b['relay'];
649
- if (v === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default');
650
- if (v === null || v === '' || v === DEFAULT_RELAY) delete data.settings.relay;
651
- else if (typeof v === 'string' && goodRelay(v.trim().toLowerCase())) data.settings.relay = v.trim().toLowerCase();
1371
+ const v = b['relay'], flags = ['seen_receipts', 'notify', 'new_presence', 'wallet', 'prices', 'calls', 'relay_media'].filter((k) => b[k] !== undefined), t = b['new_tier'], cur = b['currency'];
1372
+ if (v === undefined && flags.length === 0 && t === undefined && cur === undefined) refuse(400, 'body', 'relay: a host[:port], or "" for the default (or seen_receipts, notify, new_tier, new_presence, wallet, prices, currency, calls, relay_media)');
1373
+ for (const k of flags) if (typeof b[k] !== 'boolean') refuse(400, 'body', `${k}: true or false`);
1374
+ if (t !== undefined && !TIER_NEW.has(t)) refuse(400, 'body', 'new_tier: own, friend or quiet');
1375
+ if (cur !== undefined && cur !== null && !CURRENCIES.includes(cur)) refuse(400, 'body', `currency: one of ${CURRENCIES.join(', ')}`);
1376
+ if (v === undefined) {} else if (v === null || v === '' || v === DEFAULT_RELAY) delete data.settings.relay;
1377
+ else if (typeof v === 'string' && goodRelay(v.trim().toLowerCase())) {
1378
+ data.settings.relay = v.trim().toLowerCase();
1379
+ data.settings.relays = [data.settings.relay, ...added().filter((x) => x !== data.settings.relay)].slice(0, ADDED_MAX);
1380
+ }
652
1381
  else refuse(400, 'body', `relay: a host name, as relay.example.org (a port after a colon if not the usual)`);
1382
+ if (b['seen_receipts'] !== undefined) data.settings.seen = b['seen_receipts'];
1383
+ if (b['notify'] !== undefined) data.settings.notify = b['notify'];
1384
+ if (b['new_presence'] !== undefined) data.settings.new_presence = b['new_presence'];
1385
+ if (b['calls'] !== undefined) data.settings.calls = b['calls'];
1386
+ if (b['relay_media'] !== undefined) data.settings.relay_media = b['relay_media'];
1387
+ if (t !== undefined) data.settings.new_tier = t;
1388
+ if (b['wallet'] !== undefined) data.settings.wallet = b['wallet'];
1389
+ if (b['prices'] !== undefined) data.settings.prices = b['prices'];
1390
+ if (cur !== undefined) { if (cur === null) delete data.settings.currency; else data.settings.currency = cur; }
653
1391
  saveData(); changed();
654
- return settings();
1392
+ return settingsAll();
655
1393
  }),
656
1394
  // The signed registry's relays (sigelo.ai/relays.json, verified; fetched at most once a day): the page's picker.
657
1395
  'GET /api/relays': async () => ({ relays: await carrier.registryRelays() }),
@@ -666,7 +1404,9 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
666
1404
  'POST /api/agents/enrol-code': (b) => serial(async () => {
667
1405
  seatHere();
668
1406
  if (!enrolFile) refuse(404, 'route', 'no enrolment here');
669
- const name = b['name'], tier = b['tier'], relay = b['relay'], words = b['confirm_words'], label = b['operator_name'];
1407
+ const name = b['name'], tier = b['tier'], relay = b['relay'], words = b['confirm_words'], label = b['operator_name'], ttl = b['ttl'];
1408
+ // The code's life the app picked (enrol --ttl's): 10 minutes (the default), an hour or a day.
1409
+ if (ttl !== undefined && ![600, 3600, 86400].includes(ttl)) refuse(400, 'body', 'ttl: 600, 3600 or 86400 seconds (10 minutes, an hour, a day)');
670
1410
  if (typeof name !== 'string' || !AGENT_NAME.test(name)) refuse(400, 'body', 'name: lowercase letters, digits, _ and -, at most 64');
671
1411
  if (words !== undefined && typeof words !== 'boolean') refuse(400, 'body', 'confirm_words: true or false (default false: checked by its DID)');
672
1412
  if (label !== undefined && label !== null && label !== '' && E.operatorLabel(label) === null) refuse(400, 'body', 'operator_name: how the agent files you, 1 to 64 characters');
@@ -680,13 +1420,16 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
680
1420
  const root = await K.root(k);
681
1421
  let r;
682
1422
  try {
683
- r = await E.issue({ carrier, file: enrolFile, i, n: 0, name, keeper: root, relay: at, started: startedBy(b), confirmWords: words === true,
1423
+ r = await E.issue({ carrier, file: enrolFile, i, n: 0, name, keeper: root, relay: at, started: startedBy(b), confirmWords: words === true, ...(ttl !== undefined && { ttl }),
684
1424
  ...(typeof label === 'string' && label !== '' && { operatorName: label }) });
685
1425
  } finally { root.K.fill(0); }
686
- const until = pend((x) => x.issued[r.id]?.attestation?.body?.exp ?? null);
1426
+ // What this page shows of it, kept with the enrolment so a restart brings the code screen back (look()).
1427
+ // The code as an agent is given it: ENROL-K7F3-Q9ZP (enrol.mjs enrol_code), so it is never taken for a pairing code.
1428
+ const shown = r.enrol_code ?? r.short;
1429
+ const until = pend((x) => { const y = x.issued[r.id]; if (y) y.page = { short: shown, short_exp: r.short_exp, tier: tier ?? 'own' }; return y?.attestation?.body?.exp ?? null; });
687
1430
  await K.update((x) => { x.workers[i] = { name, n: 0, did: r.did, original: r.original, placed: 'remote', at: nowS(), ...(until && { until }) }; });
688
1431
  if (tier === 'friend' || tier === 'quiet') carrier.presetTier(r.original, tier);
689
- const e = { id: r.id, worker: i, name, short: r.short, code: r.code, exp: r.short_exp, relay: r.relay, tier: tier ?? 'own', state: 'code', did: r.did, original: r.original, confirmWords: words === true };
1432
+ const e = { id: r.id, worker: i, name, short: shown, code: shown, exp: r.short_exp, relay: r.relay, tier: tier ?? 'own', state: 'code', did: r.did, original: r.original, confirmWords: words === true };
690
1433
  enrolling.set(e.id, e);
691
1434
  changed();
692
1435
  return { worker: i, name, did: r.did, original: r.original, tier: e.tier, ...pub(e) };
@@ -697,6 +1440,7 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
697
1440
  if (typeof b['match'] !== 'boolean') refuse(400, 'body', 'match: true (the agent\'s machine shows the same four words) or false');
698
1441
  if (!LIVE.has(e.state)) refuse(409, 'enrol_state', `this enrolment is ${e.state}`);
699
1442
  e.wordsOk = b['match'];
1443
+ pend((x) => { if (x.issued[e.id]) x.issued[e.id].words_ok = b['match']; });
700
1444
  await agentRound();
701
1445
  if (!b['match']) {
702
1446
  pend((x) => { delete x.issued[e.id]; });
@@ -710,9 +1454,37 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
710
1454
  // "Try now" (design/profiles.md §6): the automatic tries paused for the day; the human's goes now.
711
1455
  'POST /api/pow/try': (b) => serial(async () => {
712
1456
  const r = await carrier.tryNow({ confirmed: b['pow_confirmed'] === true });
713
- live.powCapped = null; live.powConfirm = null; changed();
1457
+ live.powCapped = null; live.powConfirm = null; keepOffline(); changed();
714
1458
  return r;
715
1459
  }),
1460
+ // Cancel an enrolment in any state before it is done (0.1.17: a stale "k (enrolling)" could not be removed): the
1461
+ // pending entry dropped, the temporary contact forgotten, the code withdrawn. Its worker leaves the roster (the
1462
+ // index free again), or is marked revoked once its key may have gone (sent once, or being sent).
1463
+ 'POST /api/agents/cancel': (b) => serial(async () => {
1464
+ seatHere();
1465
+ if (!enrolFile) refuse(404, 'route', 'no enrolment here');
1466
+ const id = String(b['id'] ?? ''), e = enrolling.get(id);
1467
+ await look();
1468
+ const f = pend((x) => { const y = x.issued[id]; if (y) delete x.issued[id]; if (y?.temp && x.told) delete x.told[y.temp]; return y ?? null; });
1469
+ if (!f && !(e && LIVE.has(e.state))) refuse(404, 'enrol', 'no such enrolment pending here (done, expired or cancelled)');
1470
+ if (f?.done) refuse(409, 'enrol_state', 'this enrolment is done: revoke the agent instead');
1471
+ if (e?.state === 'code') { try { await carrier.cancelInvite(e.code); } catch {} }
1472
+ const temp = e?.temp ?? f?.temp ?? carrier.answeredBy(id);
1473
+ if (temp) { try { await carrier.forget(temp); } catch {} }
1474
+ const i = e?.worker ?? f?.i, keyWent = f?.sent_at !== undefined || f?.needs_send !== undefined || e?.state === 'sending', t = nowS();
1475
+ let revoked = null;
1476
+ if (Number.isSafeInteger(i)) {
1477
+ await K?.update((k) => {
1478
+ const w = k.workers[i];
1479
+ if (!w || w.placed !== 'remote' || w.revoked !== undefined) return;
1480
+ if (keyWent) { w.revoked = t; revoked = t; } else delete k.workers[i];
1481
+ });
1482
+ }
1483
+ if (e) Object.assign(e, { state: 'failed', check: 'cancelled', detail: 'Cancelled: the code no longer works and nothing more is sent.' });
1484
+ await look();
1485
+ changed();
1486
+ return { id, worker: i ?? null, cancelled: true, revoked, forgot: temp ?? null };
1487
+ }),
716
1488
  'POST /api/agents/revoke': (b) => serial(async () => {
717
1489
  seatHere();
718
1490
  const k = await keeperOr(), i = b['worker'], w = workerOf(k, i);
@@ -729,6 +1501,12 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
729
1501
  return { worker: i, name: w.name, cancelled: true, revoked: null, forgot: null };
730
1502
  }
731
1503
  if (e && LIVE.has(e.state)) { pend((x) => { delete x.issued[e.id]; }); e.state = 'failed'; e.check = 'revoked'; if (e.temp) { try { await carrier.forget(e.temp); } catch {} } }
1504
+ // One made before a restart (only the pending file knows it): dropped too, its temporary contact forgotten.
1505
+ for (const [id, f] of [...issuedLive].filter(([, y]) => y.i === i)) {
1506
+ pend((x) => { delete x.issued[id]; });
1507
+ const temp = f.temp ?? carrier.answeredBy(id);
1508
+ if (temp) { try { await carrier.forget(temp); } catch {} }
1509
+ }
732
1510
  const c = contactOfWorker(w);
733
1511
  if (c) await carrier.forget(c.did);
734
1512
  const t = nowS();
@@ -803,7 +1581,51 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
803
1581
  },
804
1582
  };
805
1583
  // Transfers: the routes exist only where the host moves files (hooks.transfers).
806
- if (transfers) Object.assign(routes, transferRoutes({ X: transfers.lib, engine: transfers.engine, carrier, identity: hooks.transfers.identity, serial, contactOf, changed }));
1584
+ // Calls (UI-API.md "Calls"): the Line's routes; a person present, never an agent (agents calling: later). Every write is
1585
+ // refused once the seat went to another device (it would log in as you beside it).
1586
+ const callRouteSet = callRoutes({
1587
+ line, contactOf: (v) => { const x = contactOf(v); return liveContact(x.did) ?? refuse(404, 'not_contact', 'not a contact'); },
1588
+ callable: (c) => {
1589
+ if (!personOf(c)) return { check: 'call_agent', message: 'calls are between people: no calls to or from an agent' };
1590
+ if (c.re_pair) return { check: 'call_pairing', message: 'pair again first' };
1591
+ if (c.online !== true) return { check: 'call_offline', message: `${c.name} is not online now` };
1592
+ return true;
1593
+ },
1594
+ stun: (c) => stunOf(carrier.relay, c?.relay),
1595
+ turn: () => (globalThis.process?.env?.SIGELO_TURN === 'off' ? null : carrier.turnServer?.() ?? null), // SIGELO_TURN=off: STUN alone (the transfer engine reads it too)
1596
+ policy: relayMedia,
1597
+ can: { speaker: typeof CH.speaker === 'function', mic: typeof CH.mic === 'function', ring: typeof CH.alert === 'function' },
1598
+ hooks: { speaker: CH.speaker, mic: CH.mic, micSettings: CH.micSettings },
1599
+ allow: (c, on) => { if (on === null) delete data.calls[c.did]; else data.calls[c.did] = on; saveData(); changed(); },
1600
+ allowOf: (c) => canCall(c),
1601
+ });
1602
+ for (const [k, f] of Object.entries(callRouteSet)) routes[k] = k.startsWith('POST ') ? (b, q) => gone(() => f(b, q))() : f;
1603
+ // A file received (2026-11-25, the bubble's "Save to Downloads"): its bytes, for the page to put where the owner takes it
1604
+ // from (the Android app: Downloads, through the shell's MediaStore; a tab or a computer's page: a download). By its chat
1605
+ // message (n) or its transfer (id); only a file under this identity's received files, at most FILE_DATA_MAX. Never remote.
1606
+ routes['GET /api/files/data'] = (_, q) => {
1607
+ let path = null, name = null, size = 0;
1608
+ const n = q.get('n'), id = q.get('id');
1609
+ if (n !== null) {
1610
+ const k = Number(n), r = Number.isSafeInteger(k) ? recs.find((x) => x.n === k && x.kind === 'in' && x.file) : undefined;
1611
+ if (!r) refuse(404, 'file_unknown', 'no file received in that message');
1612
+ ({ name, size } = r.file);
1613
+ path = typeof r.saved === 'string' ? r.saved : null; // a field kept at receipt (the text holds the sender's file name)
1614
+ } else if (id !== null) {
1615
+ if (!transfers) refuse(404, 'transfer_unknown', 'no transfers here');
1616
+ if (!/^[0-9a-f]{32}$/.test(id)) refuse(400, 'body', 'id: a transfer id (32 hex digits)');
1617
+ const r = transfers.lib.list({ carrier, identity: hooks.transfers.identity }).in.find((x) => x.id === id && x.state === 'done') ?? refuse(404, 'transfer_unknown', 'no file received by that transfer');
1618
+ ({ name, size } = r); path = r.saved ?? null;
1619
+ } else refuse(400, 'body', 'n: a chat message, or id: a transfer');
1620
+ if (typeof path === 'string' && path.startsWith('content:')) refuse(409, 'in_downloads', `${name} is in Downloads already`);
1621
+ const base = carrier.filesDir, rel = typeof path === 'string' && path.startsWith(`${base}/`) ? path.slice(base.length + 1) : null;
1622
+ if (rel === null || rel.startsWith('.') || rel.split('/').includes('..')) refuse(404, 'file_unknown', 'not a file received here');
1623
+ if (size > FILE_DATA_MAX) refuse(409, 'file_too_large', `${name} is over ${FILE_DATA_MAX / 2 ** 20} MiB: open it where it was saved`);
1624
+ const bytes = carrier.platform.files.read(path) ?? refuse(404, 'file_gone', `${name} is not here any more`);
1625
+ if (bytes.length > FILE_DATA_MAX) refuse(409, 'file_too_large', `${name} is over ${FILE_DATA_MAX / 2 ** 20} MiB: open it where it was saved`);
1626
+ return { name, size: bytes.length, data: b64(bytes) };
1627
+ };
1628
+ if (transfers) Object.assign(routes, transferRoutes({ X: transfers.lib, engine: transfers.engine, host: hooks.transfers, carrier, identity: hooks.transfers.identity, serial, contactOf, changed, record, groups: G && groupsFile ? { G, file: groupsFile, list: groupsList } : null }));
807
1629
  if (G) Object.assign(routes, groupRoutes);
808
1630
  // One handler for every listener: the route's answer as [status, JSON value].
809
1631
  async function dispatch(method, url, b) {
@@ -814,18 +1636,18 @@ export function makePage({ makeCarrier, link: L, linksFile, groups: G = null, gr
814
1636
  }
815
1637
  }
816
1638
  return {
817
- carrier, routes, dispatch, start, halt, serial, refuse, contactOf, cleanName, record, seen, data, saveData, live, recs, linkRound, drain,
1639
+ carrier, routes, dispatch, start, halt, serial, refuse, contactOf, cleanName, record, seen, data, saveData, live, recs, linkRound, drain, line,
818
1640
  setDevices: (d) => { devices = d; },
819
1641
  onChange: (f) => { watchers.add(f); return () => watchers.delete(f); },
820
1642
  };
821
1643
  }
822
1644
 
823
- // ---- transfers (UI-API.md "Transfers"): the verbs of contact/transfer-node.mjs over the page's session.
1645
+ // ---- transfers (UI-API.md "Transfers"): the verbs of apps/contact/transfer-node.mjs over the page's session.
824
1646
  // Refusals by check: unknown → 404; usage → 400; direct_ask, disk_full, transfer_state and the rest → 409.
825
- function transferRoutes({ X, engine, carrier, identity, serial, contactOf, changed }) {
1647
+ function transferRoutes({ X, engine, host, carrier, identity, serial, contactOf, changed, record, groups }) {
826
1648
  const call = async (fn) => {
827
1649
  try { const r = await fn(); changed(); return r; } catch (e) {
828
- if (e.check !== undefined && e.status === undefined) e.status = ['transfer_unknown', 'not_contact'].includes(e.check) ? 404 : ['usage', 'body'].includes(e.check) ? 400 : 409;
1650
+ if (e.check !== undefined && e.status === undefined) e.status = ['transfer_unknown', 'not_contact', 'group_unknown'].includes(e.check) ? 404 : ['usage', 'body', 'photo'].includes(e.check) ? 400 : 409;
829
1651
  throw e;
830
1652
  }
831
1653
  };
@@ -833,22 +1655,135 @@ function transferRoutes({ X, engine, carrier, identity, serial, contactOf, chang
833
1655
  const directOf = (b) => (b['direct'] === undefined ? undefined : typeof b['direct'] === 'boolean' ? b['direct'] : refuse(400, 'body', 'direct: true or false'));
834
1656
  const viaOf = (b) => (b['via'] === undefined || b['via'] === 'auto' || b['via'] === 'tor' ? b['via'] : refuse(400, 'body', 'via: auto or tor'));
835
1657
  const strip = ({ file: _f, ...r }) => r;
836
- const settings = async () => ({ ...X.settings({ identity }), tor_daemon: await X.torCaps(X.torConfig()), direct_available: (await X.loadRtc()) !== null });
1658
+ const docs = typeof host.pick === 'function';
1659
+ const settings = async () => ({ ...X.settings({ identity }), tor_daemon: await X.torCaps(X.torConfig()), direct_available: (await X.loadRtc()) !== null,
1660
+ pick: docs, camera: typeof host.photo === 'function', open: typeof host.open === 'function', voice: typeof host.rec?.keep === 'function', mic: typeof host.mic === 'function' });
1661
+ // A file to send: a path on this computer, or a doc picked on this phone (never both, each where it is).
1662
+ const sourceOf = (b) => {
1663
+ if (docs) return typeof b['doc'] === 'string' && b['doc'] !== '' ? { doc: b['doc'] } : refuse(400, 'body', 'doc: a file picked on this phone (POST /api/transfers/pick or /photo)');
1664
+ return typeof b['path'] === 'string' && b['path'] !== '' ? { path: b['path'] } : refuse(400, 'body', 'path: a file on this computer');
1665
+ };
1666
+ // A photo's preview from the page (downscaled there): {type, data, w, h}; the file's sha256, size and name are the manifest's.
1667
+ const shotOf = (b) => {
1668
+ const p = b['photo'];
1669
+ if (p === undefined) return null;
1670
+ if (typeof p !== 'object' || p === null || Array.isArray(p)) refuse(400, 'photo', 'photo: {type, data, w, h}');
1671
+ return { type: p['type'], data: p['data'], w: p['w'], h: p['h'] };
1672
+ };
1673
+ const full = (shot, f, name) => { try { return checkPhoto({ ...shot, sha256: f.whole, size: f.size, name }); } catch (e) { e.status = 400; throw e; } };
1674
+ // A voice message (voice.mjs): the recording sent in pieces first (POST /api/transfers/voice-part, rec), then send
1675
+ // {rec, voice: {name, type, duration_s, waveform?}}: the host keeps it as a file, which goes as a photo's full file does.
1676
+ const recOf = (b) => (typeof b['rec'] === 'string' && /^[0-9a-f]{32}$/.test(b['rec']) ? b['rec'] : refuse(400, 'body', 'rec: a recording id (32 hex digits)'));
1677
+ const voiceOf = (b) => {
1678
+ const v = b['voice'];
1679
+ if (v === undefined) return null;
1680
+ if (typeof v !== 'object' || v === null || Array.isArray(v) || b['rec'] === undefined || !host.rec) refuse(400, 'voice', 'voice: {name, type, duration_s, waveform?} with rec, where this host records');
1681
+ const x = { name: v['name'], type: v['type'], duration_s: v['duration_s'], ...(v['waveform'] !== undefined && { waveform: v['waveform'] }) };
1682
+ try { checkVoice({ ...x, sha256: '0'.repeat(64), size: 1 }); } catch (e) { e.status = 400; throw e; }
1683
+ return x;
1684
+ };
1685
+ const fullVoice = (vo, f, name) => { try { return checkVoice({ ...vo, sha256: f.whole, size: f.size, name }); } catch (e) { e.status = 400; throw e; } };
1686
+ const AUDIO = { webm: 'audio/webm', ogg: 'audio/ogg', m4a: 'audio/mp4' };
837
1687
  return {
838
1688
  'GET /api/transfers': () => X.list({ carrier, identity, engine }),
839
1689
  'POST /api/transfers/send': (b) => serial(() => call(async () => {
840
- if (typeof b['path'] !== 'string' || b['path'] === '') refuse(400, 'body', 'path: a file on this computer');
841
- const c = contactOf(b['to']), d = directOf(b), via = viaOf(b);
842
- const r = await X.send({ carrier, identity, to: c.did, path: b['path'], ...(via && { via }), ...(d !== undefined && { direct: d }) });
1690
+ const vo = voiceOf(b), src = vo ? await host.rec.keep(recOf(b), vo.name) : sourceOf(b), d = directOf(b), via = viaOf(b), shot = shotOf(b);
1691
+ if (shot) { const p = { ...shot, sha256: '0'.repeat(64), size: 0, name: 'x' }; try { checkPhoto(p); } catch (e) { e.status = 400; throw e; } }
1692
+ // A group (design §10.3): one transfer per member paired with; the preview (or a line naming the file) as one group message.
1693
+ if (b['group'] !== undefined) {
1694
+ if (!groups) refuse(404, 'route', 'no groups here');
1695
+ const g = groups.list().find((x) => x.gid === b['group']) ?? refuse(404, 'group_unknown', `no group ${String(b['group'])} here`);
1696
+ const f = await X.prepare({ carrier, identity, ...src });
1697
+ const fan = await X.fanOut({ carrier, identity, members: g.members.filter((m) => !m.me).map((m) => ({ did: m.did, name: m.name, contact: m.contact })), f, ...(d !== undefined && { direct: d }), ...(via && { via }), group: g.gid });
1698
+ const name = fan.sent[0] ? X.list({ carrier, identity }).out.find((r) => r.id === fan.sent[0].id)?.name ?? f.name : f.name;
1699
+ const msg = await groups.G.send({ carrier, file: groups.file, group: g.gid, text: shot ? 'Photo' : vo ? 'Voice message' : `File: ${name}`, ...(shot && { photo: full(shot, f, name) }), ...(vo && { voice: fullVoice(vo, f, name) }) });
1700
+ void engine.kick();
1701
+ return { group: g.gid, mid: msg.mid, sha256: f.whole, name, size: f.size, sent: fan.sent, unpaired: fan.unpaired, failed: fan.failed };
1702
+ }
1703
+ const c = contactOf(b['to']);
1704
+ const f = await X.prepare({ carrier, identity, ...src });
1705
+ const r = await X.sendTo({ carrier, identity, to: c.did, f, ...(via && { via }), ...(d !== undefined && { direct: d }) });
843
1706
  void engine.kick();
1707
+ if (shot) {
1708
+ // The preview beside the manifest: one more end-to-end message, into this chat at once.
1709
+ const ph = full(shot, f, r.name), at = Math.floor(Date.now() / 1000);
1710
+ let x = null;
1711
+ try { [x] = await carrier.sendAll(c.did, [ph], { label: PHOTO_LABEL }); } catch (e) { if (!/queued/.test(e.message)) throw e; }
1712
+ record({ kind: 'out', did: c.did, id: x?.id ?? null, text: 'Photo', label: PHOTO_LABEL, photo: ph, status: x?.status ?? 'queued', code: x?.code, detail: x?.detail, at });
1713
+ }
1714
+ if (!shot && !vo) {
1715
+ // (0.1.19) Any other file: its own bubble in this chat (name, size; the lane and state from its transfer), kept in the history.
1716
+ record({ kind: 'out', did: c.did, id: null, text: `File: ${r.name}`, label: FILE_LABEL, file: { name: r.name, size: r.size, sha256: r.sha256, via: null, transfer: r.id }, status: 'sent', at: Math.floor(Date.now() / 1000) });
1717
+ }
1718
+ if (vo) {
1719
+ // The voice message beside the manifest, as a photo's preview goes.
1720
+ const v = fullVoice(vo, f, r.name), at = Math.floor(Date.now() / 1000);
1721
+ let x = null;
1722
+ try { [x] = await carrier.sendAll(c.did, [v], { label: VOICE_LABEL }); } catch (e) { if (!/queued/.test(e.message)) throw e; }
1723
+ record({ kind: 'out', did: c.did, id: x?.id ?? null, text: 'Voice message', label: VOICE_LABEL, voice: v, status: x?.status ?? 'queued', code: x?.code, detail: x?.detail, at });
1724
+ }
844
1725
  return strip(r);
845
1726
  })),
1727
+ // The phone's own: a file picked (the system's picker), a photo taken (the system's camera), a file that landed opened.
1728
+ // images: the picker shows pictures only (the composer's Photo). multiple (2026-11-25): several at once → { docs: [...] },
1729
+ // each then sent as its own transfer (POST /api/transfers/send per doc, in order).
1730
+ ...(docs && { 'POST /api/transfers/pick': (b) => serial(async () => {
1731
+ const multiple = b?.['multiple'] === true, x = await host.pick({ images: b?.['images'] === true, ...(multiple && { multiple: true }) });
1732
+ if (!multiple || x === null || x === undefined) return x ?? { cancelled: true };
1733
+ const list = Array.isArray(x) ? x : [x];
1734
+ return list.length ? { docs: list } : { cancelled: true };
1735
+ }) }),
1736
+ // The microphone asked of the shell before the page records (Android: RECORD_AUDIO at the first); none elsewhere.
1737
+ // Refused once, never asked again (the shell remembers): mic-settings opens the app's settings page instead.
1738
+ ...(typeof host.mic === 'function' && { 'POST /api/transfers/mic': async () => ({ granted: await host.mic() }) }),
1739
+ ...(typeof host.micSettings === 'function' && { 'POST /api/transfers/mic-settings': async () => { await host.micSettings(); return { opened: true }; } }),
1740
+ ...(typeof host.photo === 'function' && { 'POST /api/transfers/photo': () => serial(async () => (await host.photo({ keepLocation: X.settings({ identity }).keep_location })) ?? { cancelled: true }) }),
1741
+ // A recording's pieces (at most 128 KiB each, in order): into the host's file for it, kept until send names it.
1742
+ ...(host.rec && { 'POST /api/transfers/voice-part': (b) => serial(async () => {
1743
+ const rec = recOf(b), off = b['offset'], data = b['data'];
1744
+ if (!Number.isSafeInteger(off) || off < 0 || off > VOICE_SIZE_MAX) refuse(400, 'body', 'offset: bytes from the start');
1745
+ if (typeof data !== 'string' || data === '' || data.length > Math.ceil((128 * 1024) / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) refuse(400, 'body', 'data: base64 of 1 byte to 128 KiB');
1746
+ const bytes = unb64(data);
1747
+ if (off + bytes.length > VOICE_SIZE_MAX) refuse(400, 'voice', `a voice message is at most ${VOICE_SIZE_MAX / 2 ** 20} MiB`);
1748
+ await host.rec.write(rec, off, bytes);
1749
+ return { rec, size: off + bytes.length };
1750
+ }) }),
1751
+ // A voice message's recording that landed here, to play: {id, type, data (base64)}.
1752
+ ...(host.rec && { 'GET /api/transfers/audio': (_, q) => call(async () => {
1753
+ const id = idOf({ id: q.get('id') }), r = X.list({ carrier, identity }).in.find((x) => x.id === id) ?? refuse(404, 'transfer_unknown', 'no such file here');
1754
+ if (r.state !== 'done' || !r.saved) refuse(409, 'transfer_state', `${r.name} has not landed yet`);
1755
+ if (r.size > VOICE_SIZE_MAX) refuse(409, 'voice', 'too large for a voice message');
1756
+ const bytes = await host.rec.read(r.saved);
1757
+ return { id, type: AUDIO[/\.([a-z0-9]+)$/i.exec(r.name)?.[1]?.toLowerCase() ?? ''] ?? 'application/octet-stream', data: b64(bytes) };
1758
+ }) }),
1759
+ ...(typeof host.open === 'function' && { 'POST /api/transfers/open': (b) => call(async () => {
1760
+ const id = idOf(b), L = X.list({ carrier, identity });
1761
+ // (0.1.19) A file I sent: the one picked (the record keeps it; the list leaves it out).
1762
+ if (L.out.some((x) => x.id === id)) {
1763
+ const f = engine.st((s) => (s.out[id] ? { ...s.out[id] } : null));
1764
+ if (!f?.file) refuse(409, 'transfer_state', 'that file is not on this device any more');
1765
+ await host.open(f.file, f.name);
1766
+ return { opened: id };
1767
+ }
1768
+ const r = L.in.find((x) => x.id === id) ?? refuse(404, 'transfer_unknown', 'no such file here');
1769
+ if (r.state !== 'done' || !r.saved) refuse(409, 'transfer_state', `${r.name} has not landed yet`);
1770
+ await host.open(r.saved, r.name);
1771
+ return { opened: r.id };
1772
+ }) }),
1773
+ 'POST /api/transfers/auto': (b) => serial(() => call(async () => {
1774
+ const mb = b['mb'];
1775
+ if (mb !== null && (typeof mb !== 'number' || !Number.isFinite(mb))) refuse(400, 'body', 'mb: a size in MB (0: always ask), or null: the default');
1776
+ return X.setAuto({ carrier, identity, contact: contactOf(b['contact']).did, mb });
1777
+ })),
846
1778
  'POST /api/transfers/accept': (b) => serial(() => call(async () => {
847
1779
  const d = directOf(b), via = viaOf(b), r = X.accept({ carrier, identity, id: idOf(b), ...(via && { via }), ...(d !== undefined && { direct: d }) });
848
1780
  void engine.kick();
849
1781
  return r;
850
1782
  })),
851
- 'POST /api/transfers/resume': (b) => serial(() => call(async () => { const r = X.accept({ carrier, identity, id: idOf(b), ...(directOf(b) !== undefined && { direct: directOf(b) }) }); void engine.kick(); return r; })),
1783
+ 'POST /api/transfers/resume': (b) => serial(() => call(async () => { const r = (X.resume ?? X.accept)({ carrier, identity, id: idOf(b), ...(directOf(b) !== undefined && { direct: directOf(b) }) }); void engine.kick(); return r; })),
1784
+ // (0.1.19) The sender's choices on a file that did not go: over the relay lane (at most 8 MiB), or offered afresh.
1785
+ 'POST /api/transfers/relay': (b) => serial(() => call(async () => strip(await engine.relay(idOf(b), { manual: true })))),
1786
+ 'POST /api/transfers/retry': (b) => serial(() => call(async () => { const r = strip(await X.retry({ carrier, identity, id: idOf(b), engine })); void engine.kick(); return r; })),
852
1787
  'POST /api/transfers/decline': (b) => serial(() => call(async () => X.decline({ carrier, identity, id: idOf(b) }))),
853
1788
  'POST /api/transfers/cancel': (b) => serial(() => call(async () => strip(await X.cancel({ carrier, identity, id: idOf(b), engine })))),
854
1789
  'POST /api/transfers/forget': (b) => serial(() => call(async () => strip(X.forget({ carrier, identity, id: idOf(b), engine })))),
@@ -861,6 +1796,8 @@ function transferRoutes({ X, engine, carrier, identity, serial, contactOf, chang
861
1796
  const patch = {};
862
1797
  if (b['tor'] !== undefined) { if (typeof b['tor'] !== 'boolean') refuse(400, 'body', 'tor: true or false'); patch.tor = b['tor']; }
863
1798
  if (b['prefer'] !== undefined) { if (b['prefer'] !== 'fast' && b['prefer'] !== 'private') refuse(400, 'body', 'prefer: fast or private'); patch.prefer = b['prefer']; }
1799
+ if (b['auto_mb'] !== undefined) { if (typeof b['auto_mb'] !== 'number' || !Number.isFinite(b['auto_mb']) || b['auto_mb'] < 0) refuse(400, 'body', 'auto_mb: a size in MB, 0: always ask'); patch.auto_mb = b['auto_mb']; }
1800
+ if (b['keep_location'] !== undefined) { if (typeof b['keep_location'] !== 'boolean') refuse(400, 'body', 'keep_location: true or false'); patch.keep_location = b['keep_location']; }
864
1801
  X.settings({ identity, patch });
865
1802
  return settings();
866
1803
  })),