@peer2peer/cli 0.0.0-stage → 0.1.1

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 (111) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +370 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +368 -0
  6. package/dist/app.js +1181 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +660 -0
  12. package/dist/cli.js +1787 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +159 -0
  16. package/dist/config.js +294 -0
  17. package/dist/doctor.d.ts +113 -0
  18. package/dist/doctor.js +930 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +38 -0
  22. package/dist/ext-host.js +293 -0
  23. package/dist/extensions.d.ts +487 -0
  24. package/dist/extensions.js +406 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/graph-memory.d.ts +107 -0
  30. package/dist/graph-memory.js +393 -0
  31. package/dist/history.d.ts +155 -0
  32. package/dist/history.js +697 -0
  33. package/dist/identity.d.ts +239 -0
  34. package/dist/identity.js +759 -0
  35. package/dist/inbound.d.ts +32 -0
  36. package/dist/inbound.js +261 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +14 -0
  39. package/dist/ix-local.d.ts +76 -0
  40. package/dist/ix-local.js +203 -0
  41. package/dist/join-answers.d.ts +49 -0
  42. package/dist/join-answers.js +149 -0
  43. package/dist/outbox.d.ts +109 -0
  44. package/dist/outbox.js +337 -0
  45. package/dist/pretty.d.ts +100 -0
  46. package/dist/pretty.js +256 -0
  47. package/dist/procstart.d.ts +1 -0
  48. package/dist/procstart.js +66 -0
  49. package/dist/progress.d.ts +30 -0
  50. package/dist/progress.js +78 -0
  51. package/dist/projects.d.ts +491 -0
  52. package/dist/projects.js +1383 -0
  53. package/dist/prompt/picker.d.ts +64 -0
  54. package/dist/prompt/picker.js +152 -0
  55. package/dist/prompt/tty.d.ts +29 -0
  56. package/dist/prompt/tty.js +122 -0
  57. package/dist/readonly.d.ts +20 -0
  58. package/dist/readonly.js +50 -0
  59. package/dist/receipts.d.ts +99 -0
  60. package/dist/receipts.js +182 -0
  61. package/dist/relay-client.d.ts +277 -0
  62. package/dist/relay-client.js +873 -0
  63. package/dist/relay-info.d.ts +24 -0
  64. package/dist/relay-info.js +53 -0
  65. package/dist/rotation.d.ts +402 -0
  66. package/dist/rotation.js +2054 -0
  67. package/dist/running.d.ts +5 -0
  68. package/dist/running.js +74 -0
  69. package/dist/sessions.d.ts +355 -0
  70. package/dist/sessions.js +1247 -0
  71. package/dist/shortcode.d.ts +149 -0
  72. package/dist/shortcode.js +465 -0
  73. package/dist/social.d.ts +139 -0
  74. package/dist/social.js +485 -0
  75. package/dist/state.d.ts +509 -0
  76. package/dist/state.js +220 -0
  77. package/dist/stdin.d.ts +17 -0
  78. package/dist/stdin.js +46 -0
  79. package/dist/sync.d.ts +77 -0
  80. package/dist/sync.js +375 -0
  81. package/dist/transient.d.ts +1 -0
  82. package/dist/transient.js +28 -0
  83. package/dist/trust.d.ts +37 -0
  84. package/dist/trust.js +134 -0
  85. package/dist/tty-confirm.d.ts +2 -0
  86. package/dist/tty-confirm.js +53 -0
  87. package/dist/tui/command.d.ts +20 -0
  88. package/dist/tui/command.js +70 -0
  89. package/dist/tui/frame.d.ts +43 -0
  90. package/dist/tui/frame.js +111 -0
  91. package/dist/tui/model.d.ts +221 -0
  92. package/dist/tui/model.js +259 -0
  93. package/dist/tui/sanitize.d.ts +13 -0
  94. package/dist/tui/sanitize.js +151 -0
  95. package/dist/tui/terminal.d.ts +88 -0
  96. package/dist/tui/terminal.js +354 -0
  97. package/dist/tui/tui.d.ts +78 -0
  98. package/dist/tui/tui.js +612 -0
  99. package/dist/tui/view.d.ts +4 -0
  100. package/dist/tui/view.js +358 -0
  101. package/dist/unknown-kinds.d.ts +12 -0
  102. package/dist/unknown-kinds.js +66 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +5 -0
  105. package/dist/want-pow.d.ts +12 -0
  106. package/dist/want-pow.js +46 -0
  107. package/dist/watch.d.ts +35 -0
  108. package/dist/watch.js +331 -0
  109. package/dist/xstate.d.ts +125 -0
  110. package/dist/xstate.js +422 -0
  111. package/package.json +60 -4
@@ -0,0 +1,697 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Message history (`p2p history`, docs/concepts.md "Message history"): what this device sent and
4
+ // received, kept so the person (and each session, for its own messages) can look back. Local only:
5
+ // nothing new goes to a relay or a peer, and nothing on the wire changes.
6
+ //
7
+ // - What is kept: messages in (p2p.message events, once each: the copy logged for a session that
8
+ // ended is not kept twice) and out (`p2p send`, the TUI, the front ends' sends), and extension
9
+ // kinds as their one-line fallback (never the body). Statuses, rosters and control events aren't.
10
+ // - Where: `<home>/cli/history.json` (the index) and `<home>/cli/history-<n>.json` (segments of at
11
+ // most SEGMENT_BYTES), each sealed with ChaCha20-Poly1305 under a key derived from
12
+ // `<home>/cli/history.key` (32 random bytes, 0600, made exclusively like the person token), with
13
+ // the document's name as associated data, so no plaintext is on disk and no segment can be
14
+ // swapped for another. There is no OS keychain backend yet (docs/roadmap.md): the key sits next
15
+ // to the device keys, with the same 0600 posture. It keeps the text out of backups, indexers and
16
+ // a grep of the home; it does not stop malware running as you (docs/security/threat-model.md).
17
+ // - Bounded: older than `history.retentionDays` (config.json, default 30) or past
18
+ // `history.maxBytes` (default 8 MiB of records), the oldest go, pruned on every write.
19
+ // `history.enabled: false` (or P2P_HISTORY=0) records nothing more; `p2p history --clear`
20
+ // deletes everything, the key included, and the messages in the event log (events.json).
21
+ // A record's `at` is when it arrived here (`sentAt`: the sender's clock), so a sender can't
22
+ // backdate one. A document that can't be opened is set aside (history.bad-*), never swept
23
+ // silently or overwritten. Writes are copy-on-write (see "Writing"), so a crash loses at most
24
+ // what was being written, and an older segment put back is never taken back in.
25
+ // - Who reads it (assertHistoryReader):
26
+ // the person's own view (no --session, or session `tui`: messages to the person, to no
27
+ // session, or from `p2p tui` / a terminal send): only the person, by the same gate as the
28
+ // other person-only commands (their front end's token, or outside any agent's session their
29
+ // "yes" on the controlling terminal; refused inside an agent's session);
30
+ // one session's (`--session <sid>`): its front end (the token), for a session a front end
31
+ // registered, and only records made since its binding began (projects.ts `since`), while the
32
+ // session was in projects it is still bound to (a record kept with no binding is UNBOUND: the
33
+ // person's only), so a session id bound anew never sees the earlier one's history.
34
+ // Without the token, only the person at their own terminal, as above.
35
+ // - Peer text stays untrusted: kept as received, sanitized for a terminal on the way out, and
36
+ // framed as the peer's data by the front ends that show it to a model.
37
+ import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from "node:crypto";
38
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
39
+ import { join } from "node:path";
40
+ import { b64uDecode, b64uEncode, loadCircle, sanitizePeerText } from "@peer2peer/core/v3";
41
+ import { readFileConfig } from "./config.js";
42
+ import { CliError } from "./errors.js";
43
+ import { agentContext, assertPersonForWidening, PERSON_SESSION, sessionBinding } from "./projects.js";
44
+ /** Kept this long by default (config.json `history.retentionDays`). */
45
+ export const HISTORY_RETENTION_DAYS = 30;
46
+ export const HISTORY_RETENTION_MIN_DAYS = 1;
47
+ export const HISTORY_RETENTION_MAX_DAYS = 365;
48
+ /** At most this many bytes of records by default (config.json `history.maxBytes`). */
49
+ export const HISTORY_MAX_BYTES = 8 * 1024 * 1024;
50
+ export const HISTORY_MIN_BYTES = 64 * 1024;
51
+ export const HISTORY_MAX_BYTES_CAP = 64 * 1024 * 1024;
52
+ /** A segment is closed past this many bytes of records (each write rewrites only the newest). */
53
+ export const SEGMENT_BYTES = 256 * 1024;
54
+ /** One record's text is at most this long (a message is at most 24 KiB anyway). */
55
+ export const MAX_RECORD_TEXT = 24 * 1024;
56
+ /** `p2p history` lists at most this many by default, the newest. */
57
+ export const HISTORY_LIST_DEFAULT = 50;
58
+ export const HISTORY_LIST_MAX = 1000;
59
+ const INDEX = "history";
60
+ const KEY_INFO = "p2p/v3/history/v1";
61
+ const AAD_PREFIX = "p2p/v3/history/v1|";
62
+ /** What config.json and P2P_HISTORY say (out-of-range values are clamped; a broken config.json: the defaults). */
63
+ export function historySettings(app) {
64
+ let cfg = {};
65
+ try {
66
+ const h = readFileConfig(app.home).history;
67
+ if (h && typeof h === "object" && !Array.isArray(h))
68
+ cfg = h;
69
+ }
70
+ catch {
71
+ // the defaults
72
+ }
73
+ const env = app.env.P2P_HISTORY?.trim().toLowerCase();
74
+ const enabled = env === "0" || env === "false" ? false : env === "1" || env === "true" ? true : cfg.enabled !== false;
75
+ const num = (v, d, lo, hi) => (typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, Math.floor(v))) : d);
76
+ return {
77
+ enabled,
78
+ retentionDays: num(cfg.retentionDays, HISTORY_RETENTION_DAYS, HISTORY_RETENTION_MIN_DAYS, HISTORY_RETENTION_MAX_DAYS),
79
+ maxBytes: num(cfg.maxBytes, HISTORY_MAX_BYTES, HISTORY_MIN_BYTES, HISTORY_MAX_BYTES_CAP),
80
+ };
81
+ }
82
+ // ---------------------------------------------------------------------------
83
+ // Sealing
84
+ export function historyKeyFile(home) {
85
+ return join(home, "cli", "history.key");
86
+ }
87
+ const KEY_RE = /^[A-Za-z0-9_-]{43}$/;
88
+ function readKey(home) {
89
+ try {
90
+ const t = readFileSync(historyKeyFile(home), "utf8").trim();
91
+ return KEY_RE.test(t) ? Buffer.from(hkdfSync("sha256", b64uDecode(t, 32), new Uint8Array(0), new TextEncoder().encode(KEY_INFO), 32)) : undefined;
92
+ }
93
+ catch {
94
+ return undefined;
95
+ }
96
+ }
97
+ /** The history key, made once (exclusively, 0600, in the CLI's own folder). */
98
+ function historyKey(home, create) {
99
+ const have = readKey(home);
100
+ if (have || !create)
101
+ return have;
102
+ mkdirSync(join(home, "cli"), { recursive: true, mode: 0o700 });
103
+ try {
104
+ writeFileSync(historyKeyFile(home), b64uEncode(new Uint8Array(randomBytes(32))), { mode: 0o600, flag: "wx" });
105
+ }
106
+ catch {
107
+ // made meanwhile by another process (or something is in the way: then nothing is recorded)
108
+ }
109
+ return readKey(home);
110
+ }
111
+ function seal(key, name, value) {
112
+ const nonce = randomBytes(12);
113
+ const pt = Buffer.from(JSON.stringify(value), "utf8");
114
+ const c = createCipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 });
115
+ c.setAAD(Buffer.from(AAD_PREFIX + name, "utf8"), { plaintextLength: pt.length });
116
+ const ct = Buffer.concat([c.update(pt), c.final(), c.getAuthTag()]);
117
+ return { v: 1, alg: "c20p1305", n: b64uEncode(new Uint8Array(nonce)), c: b64uEncode(new Uint8Array(ct)) };
118
+ }
119
+ /** The value sealed in `doc`, or undefined (missing, altered, swapped, or sealed under another key). */
120
+ function open(key, name, doc) {
121
+ const s = doc;
122
+ if (!s || s.v !== 1 || s.alg !== "c20p1305" || typeof s.n !== "string" || typeof s.c !== "string")
123
+ return undefined;
124
+ try {
125
+ const nonce = Buffer.from(b64uDecode(s.n, 12));
126
+ const raw = Buffer.from(b64uDecode(s.c));
127
+ if (raw.length < 16)
128
+ return undefined;
129
+ const d = createDecipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 });
130
+ d.setAAD(Buffer.from(AAD_PREFIX + name, "utf8"), { plaintextLength: raw.length - 16 });
131
+ d.setAuthTag(raw.subarray(raw.length - 16));
132
+ const pt = Buffer.concat([d.update(raw.subarray(0, raw.length - 16)), d.final()]);
133
+ return JSON.parse(pt.toString("utf8"));
134
+ }
135
+ catch {
136
+ return undefined;
137
+ }
138
+ }
139
+ // ---------------------------------------------------------------------------
140
+ // Writing
141
+ //
142
+ // Copy-on-write, so a crash at any point leaves a history that opens with nothing lost but what was
143
+ // being written: a segment's new version goes under a fresh name (`history-<next>`, numbers never
144
+ // reused), then the index, then its copy (MARK), then the old version is removed.
145
+ //
146
+ // - The index names each live segment with a hash of the sealed document, and `next`, the lowest
147
+ // number never used. A segment the index doesn't name is adopted only when its number is at or
148
+ // above `next` (written after the index: a crash before the index was) and it opens; if it says
149
+ // it `replaces` a listed segment, that one is dropped. Below `next` it is an old version (pruned,
150
+ // or superseded) put back or left behind: removed, never adopted. So a restored segment brings no
151
+ // older copy back.
152
+ // - The index can't be opened: its copy (MARK, sealed under its own name) stands in. Neither can:
153
+ // nothing older is trusted, and every segment is set aside. History starts again.
154
+ const recBytes = (r) => Buffer.byteLength(JSON.stringify(r), "utf8");
155
+ const docHash = (doc) => createHash("sha256").update(JSON.stringify(doc), "utf8").digest("base64url").slice(0, 22);
156
+ const segNum = (name) => Number(name.slice("history-".length));
157
+ /** The index's copy: what stands in when the index itself can't be opened. */
158
+ const MARK = "history-mark";
159
+ /** At most this many set-aside files are kept (each also goes once it is past retention). */
160
+ export const MAX_QUARANTINED = 16;
161
+ const QUARANTINE_RE = /^history\.bad-(\d{13})-[\w.-]{1,40}\.json$/;
162
+ /** Segment documents on disk (`<home>/cli/history-<n>.json`), whatever the index says, oldest first. */
163
+ function segmentNames(app) {
164
+ try {
165
+ return readdirSync(join(app.state.dir, "cli"))
166
+ .map((f) => /^(history-\d{1,9})\.json$/.exec(f)?.[1])
167
+ .filter((x) => x !== undefined)
168
+ .sort((a, b) => segNum(a) - segNum(b));
169
+ }
170
+ catch {
171
+ return [];
172
+ }
173
+ }
174
+ /**
175
+ * A history document that can't be read or opened (altered, sealed under another key, not JSON):
176
+ * moved aside to `history.bad-<ms>-<name>.json`, never silently deleted or overwritten, and said
177
+ * once on stderr. Set-aside files go once past retention, or past MAX_QUARANTINED.
178
+ */
179
+ /** Documents set aside by this process (readAll reports the ones its read set aside). */
180
+ let setAside = 0;
181
+ function quarantine(app, name, why) {
182
+ setAside++;
183
+ const dir = join(app.state.dir, "cli");
184
+ const to = `history.bad-${Date.now()}-${name}.json`;
185
+ try {
186
+ renameSync(join(dir, `${name}.json`), join(dir, to));
187
+ app.io.err(`p2p: message history: ${name} couldn't be opened (${why}); set aside as ${to}`);
188
+ }
189
+ catch {
190
+ // gone meanwhile
191
+ }
192
+ }
193
+ function pruneQuarantine(app, cutoff) {
194
+ const dir = join(app.state.dir, "cli");
195
+ let files;
196
+ try {
197
+ files = readdirSync(dir)
198
+ .map((f) => ({ f, m: QUARANTINE_RE.exec(f) }))
199
+ .filter((x) => x.m)
200
+ .map((x) => ({ f: x.f, at: Number(x.m[1]) }))
201
+ .sort((a, b) => a.at - b.at);
202
+ }
203
+ catch {
204
+ return;
205
+ }
206
+ for (const [i, x] of files.entries())
207
+ if (x.at < cutoff || i < files.length - MAX_QUARANTINED)
208
+ rmSync(join(dir, x.f), { force: true });
209
+ }
210
+ /** One document read and opened; never throws (each document's failure is its own). */
211
+ async function readSealed(app, key, name, hash) {
212
+ let doc;
213
+ try {
214
+ doc = await app.state.backend.read(name);
215
+ }
216
+ catch {
217
+ return { ok: false, missing: false, why: "not readable" };
218
+ }
219
+ if (doc === undefined || doc === null)
220
+ return { ok: false, missing: true, why: "missing" };
221
+ if (hash !== undefined && docHash(doc) !== hash)
222
+ return { ok: false, missing: false, why: "not the copy the index names" };
223
+ const v = open(key, name, doc);
224
+ return v === undefined ? { ok: false, missing: false, why: "altered, or sealed under another key" } : { ok: true, value: v, doc };
225
+ }
226
+ /** A segment's records (and what it replaces), or why not. */
227
+ async function readSeg(app, key, name, hash) {
228
+ const got = await readSealed(app, key, name, hash);
229
+ if (!got.ok)
230
+ return got;
231
+ const v = got.value;
232
+ if (!v || v.v !== 2 || !Array.isArray(v.recs))
233
+ return { ok: false, missing: false, why: "not a history segment" };
234
+ return { ok: true, seg: v, doc: got.doc };
235
+ }
236
+ /** A segment's place in the index, from its records. */
237
+ function segEntry(name, items, sealed) {
238
+ return {
239
+ name,
240
+ first: items.length ? Math.min(...items.map((r) => r.at)) : 0,
241
+ last: items.length ? Math.max(...items.map((r) => r.at)) : 0,
242
+ bytes: items.reduce((n, r) => n + recBytes(r), 0),
243
+ count: items.length,
244
+ h: docHash(sealed),
245
+ };
246
+ }
247
+ const okIndex = (v) => {
248
+ const i = v;
249
+ return !!i && i.v === 1 && Array.isArray(i.segs) && Number.isSafeInteger(i.next);
250
+ };
251
+ /**
252
+ * The index as the last write left it (see "Writing" above), with segments a crash left unlisted
253
+ * adopted or removed. Under the lock. `changed`: it differs from what is on disk.
254
+ */
255
+ async function loadIndex(app, key) {
256
+ const b = app.state.backend;
257
+ const main = await readSealed(app, key, INDEX);
258
+ let idx = main.ok && okIndex(main.value) ? main.value : undefined;
259
+ let changed = false;
260
+ if (!idx) {
261
+ if (!main.ok && !main.missing)
262
+ quarantine(app, INDEX, main.why);
263
+ const copy = await readSealed(app, key, MARK);
264
+ if (copy.ok && okIndex(copy.value))
265
+ idx = copy.value;
266
+ else {
267
+ if (!copy.ok && !copy.missing)
268
+ quarantine(app, MARK, copy.why);
269
+ // Nothing says which segments are current: none is trusted (an older copy could be any of them).
270
+ const names = segmentNames(app);
271
+ for (const name of names)
272
+ quarantine(app, name, "no index names it");
273
+ idx = { v: 1, segs: [], next: Math.max(0, ...names.map(segNum)) + 1 };
274
+ }
275
+ changed = true;
276
+ }
277
+ idx = { ...idx, segs: [...idx.segs] };
278
+ const listed = new Set(idx.segs.map((s) => s.name));
279
+ for (const name of segmentNames(app)) {
280
+ if (listed.has(name))
281
+ continue;
282
+ if (segNum(name) < idx.next) {
283
+ // An old version: pruned, superseded (a crash before its removal), or put back. Never adopted.
284
+ if (b.remove)
285
+ await b.remove(name);
286
+ else
287
+ await b.write(name, null);
288
+ continue;
289
+ }
290
+ // Written after the index (a crash before the index write): kept if it opens.
291
+ const seg = await readSeg(app, key, name);
292
+ if (!seg.ok) {
293
+ if (!seg.missing)
294
+ quarantine(app, name, seg.why);
295
+ continue;
296
+ }
297
+ if (seg.seg.replaces)
298
+ idx.segs = idx.segs.filter((s) => s.name !== seg.seg.replaces);
299
+ idx.segs.push(segEntry(name, seg.seg.recs, seg.doc));
300
+ idx.next = Math.max(idx.next, segNum(name) + 1);
301
+ changed = true;
302
+ }
303
+ // Oldest first, by their records (a trimmed oldest segment keeps its place under its new number).
304
+ idx.segs.sort((a, b) => a.first - b.first || segNum(a.name) - segNum(b.name));
305
+ return { idx, changed };
306
+ }
307
+ /**
308
+ * Appends records, then prunes by age and size, under the state lock. Never throws: history is a
309
+ * convenience, and a full disk or a missing key must not fail a send or a delivery.
310
+ */
311
+ export async function recordHistory(app, recs, now = Date.now()) {
312
+ if (recs.length === 0 || app.readOnly || typeof app.home !== "string")
313
+ return;
314
+ const settings = historySettings(app);
315
+ if (!settings.enabled)
316
+ return;
317
+ try {
318
+ const key = historyKey(app.home, true);
319
+ if (!key)
320
+ return;
321
+ await app.state.withLock(async () => {
322
+ const { idx } = await loadIndex(app, key);
323
+ const old = [];
324
+ const last = idx.segs.at(-1);
325
+ let items = [];
326
+ let replaces;
327
+ if (last && last.bytes < SEGMENT_BYTES) {
328
+ const seg = await readSeg(app, key, last.name, last.h);
329
+ if (seg.ok) {
330
+ items = seg.seg.recs;
331
+ replaces = last.name;
332
+ }
333
+ else if (!seg.missing)
334
+ quarantine(app, last.name, seg.why);
335
+ // Either way, a new version of it (or a new segment) takes its place; it goes once the index no longer names it.
336
+ if (seg.ok)
337
+ old.push(last.name);
338
+ idx.segs.pop();
339
+ }
340
+ const have = new Set(items.map((r) => r.id));
341
+ for (const r0 of recs) {
342
+ const r = { ...r0, text: r0.text.length > MAX_RECORD_TEXT ? r0.text.slice(0, MAX_RECORD_TEXT) : r0.text };
343
+ if (have.has(r.id))
344
+ continue;
345
+ if (recBytesOf(items) >= SEGMENT_BYTES) {
346
+ await writeSeg(app, key, idx, items, replaces);
347
+ items = [];
348
+ replaces = undefined;
349
+ }
350
+ items.push(r);
351
+ have.add(r.id);
352
+ }
353
+ if (items.length > 0)
354
+ await writeSeg(app, key, idx, items, replaces);
355
+ old.push(...(await prune(app, key, idx, settings, now)));
356
+ await commitIndex(app, key, idx, old);
357
+ });
358
+ }
359
+ catch (e) {
360
+ app.io.err(`p2p: message history not written: ${sanitizePeerText(e.message, 200)}`);
361
+ }
362
+ }
363
+ const recBytesOf = (items) => items.reduce((n, r) => n + recBytes(r), 0);
364
+ /** Writes `items` as a new segment (a fresh name) and lists it in `idx` (not yet written). */
365
+ async function writeSeg(app, key, idx, items, replaces) {
366
+ const name = `history-${idx.next++}`;
367
+ const sealed = seal(key, name, { v: 2, recs: [...items], ...(replaces ? { replaces } : {}) });
368
+ await app.state.backend.write(name, sealed);
369
+ idx.segs.push(segEntry(name, items, sealed));
370
+ }
371
+ /** The index, then its copy, then the segments they no longer name are removed. */
372
+ async function commitIndex(app, key, idx, old) {
373
+ const b = app.state.backend;
374
+ await b.write(INDEX, seal(key, INDEX, idx));
375
+ await b.write(MARK, seal(key, MARK, idx));
376
+ const listed = new Set(idx.segs.map((s) => s.name));
377
+ for (const name of old) {
378
+ if (listed.has(name))
379
+ continue;
380
+ if (b.remove)
381
+ await b.remove(name);
382
+ else
383
+ await b.write(name, null);
384
+ }
385
+ }
386
+ /**
387
+ * Drops what is past retention or the size cap, oldest first (the lock is held). Returns the
388
+ * segments to remove once the index no longer names them.
389
+ */
390
+ async function prune(app, key, idx, s, now) {
391
+ const cutoff = now - s.retentionDays * 86_400_000;
392
+ const gone = [];
393
+ pruneQuarantine(app, cutoff);
394
+ // Whole segments past retention.
395
+ while (idx.segs.length > 0 && idx.segs[0].last < cutoff)
396
+ gone.push(idx.segs.shift().name);
397
+ // Past the size cap: whole segments, oldest first, but never the newest one.
398
+ let total = idx.segs.reduce((n, x) => n + x.bytes, 0);
399
+ while (idx.segs.length > 1 && total > s.maxBytes) {
400
+ const g = idx.segs.shift();
401
+ total -= g.bytes;
402
+ gone.push(g.name);
403
+ }
404
+ // The oldest segment still holding records past retention, or the only one over the cap: trimmed
405
+ // (copy-on-write, like every segment write).
406
+ const first = idx.segs[0];
407
+ if (first && (first.first < cutoff || total > s.maxBytes)) {
408
+ const seg = await readSeg(app, key, first.name, first.h);
409
+ idx.segs.shift();
410
+ if (!seg.ok) {
411
+ if (!seg.missing)
412
+ quarantine(app, first.name, seg.why);
413
+ return gone;
414
+ }
415
+ gone.push(first.name);
416
+ const items = seg.seg.recs.filter((r) => r.at >= cutoff);
417
+ let bytes = recBytesOf(items);
418
+ const others = total - first.bytes;
419
+ while (items.length > 0 && others + bytes > s.maxBytes)
420
+ bytes -= recBytes(items.shift());
421
+ if (items.length > 0) {
422
+ await writeSeg(app, key, idx, items, first.name);
423
+ idx.segs.sort((a, b) => a.first - b.first || segNum(a.name) - segNum(b.name));
424
+ }
425
+ }
426
+ return gone;
427
+ }
428
+ /**
429
+ * `p2p history --clear`: every segment, the index and its copy, set-aside files and the key, and the
430
+ * messages and extension notices in the event log `p2p watch` reads (events.json), so no copy of
431
+ * their text is left in P2P_HOME. A message a session's watch hasn't printed yet is gone with it.
432
+ */
433
+ export async function clearHistory(app) {
434
+ const key = historyKey(app.home, false);
435
+ const b = app.state.backend;
436
+ const cleared = await app.state.withLock(async () => {
437
+ let n = 0;
438
+ const idx = key ? await readSealed(app, key, INDEX) : undefined;
439
+ const segs = idx?.ok && okIndex(idx.value) ? idx.value.segs : [];
440
+ for (const s of segs)
441
+ n += s.count;
442
+ for (const name of new Set([...segs.map((s) => s.name), ...segmentNames(app), INDEX, MARK])) {
443
+ if (b.remove)
444
+ await b.remove(name);
445
+ else
446
+ await b.write(name, null);
447
+ }
448
+ pruneQuarantine(app, Number.MAX_SAFE_INTEGER);
449
+ rmSync(historyKeyFile(app.home), { force: true });
450
+ return n;
451
+ });
452
+ const events = await app.state.update("events", (cur) => {
453
+ if (!cur)
454
+ return { result: 0 };
455
+ const keep = cur.items.filter((e) => e.kind !== "p2p.message" && e.kind !== "p2p.ext");
456
+ return keep.length === cur.items.length ? { result: 0 } : { next: { ...cur, items: keep }, result: cur.items.length - keep.length };
457
+ });
458
+ return { cleared, events };
459
+ }
460
+ // ---------------------------------------------------------------------------
461
+ // What gets recorded
462
+ /** The marker a record carries when its session's projects were unknown (fail closed: the person's only). */
463
+ export const UNBOUND = "!unbound";
464
+ /** The projects a session is bound to now (projects.ts), for the record's boundary; [UNBOUND] when none or unreadable. */
465
+ async function projectsOf(app, sid) {
466
+ if (sid === undefined || sid === PERSON_SESSION)
467
+ return undefined;
468
+ try {
469
+ const ids = Object.keys((await sessionBinding(app, sid))?.projects ?? {}).sort();
470
+ return ids.length > 0 ? ids : [UNBOUND];
471
+ }
472
+ catch {
473
+ return [UNBOUND];
474
+ }
475
+ }
476
+ async function circleOf(app, own, sid) {
477
+ try {
478
+ const r = own === app.userId ? (await app.state.get("sessions"))?.[sid] : await app.store.getRoster(own, sid);
479
+ return r && "circle" in r && typeof r.circle === "string" ? r.circle : undefined;
480
+ }
481
+ catch {
482
+ return undefined;
483
+ }
484
+ }
485
+ /** Received messages and extension notices among events just added to the log (inbound.ts). */
486
+ export async function recordEvents(app, events) {
487
+ if (!events.some((e) => e.kind === "p2p.message" || e.kind === "p2p.ext") || app.readOnly || !historySettings(app).enabled)
488
+ return;
489
+ await historyRecords(app, events).then((recs) => recordHistory(app, recs), () => undefined);
490
+ }
491
+ async function historyRecords(app, events) {
492
+ const recs = [];
493
+ for (const e of events) {
494
+ if (e.kind !== "p2p.message" && e.kind !== "p2p.ext")
495
+ continue;
496
+ const d = e.data;
497
+ // The copy for a session that ended: the message itself is kept, once.
498
+ if (d.unclaimedFor !== undefined)
499
+ continue;
500
+ if (typeof d.from?.userId !== "string")
501
+ continue;
502
+ const text = e.kind === "p2p.message" ? d.text : d.fallback;
503
+ if (typeof text !== "string")
504
+ continue;
505
+ const session = e.toSession;
506
+ // Their session, when it went into one of theirs; into one of ours, the envelope names only ours.
507
+ const peerSession = typeof d.own === "string" && d.own !== app.userId && typeof d.sid === "string" ? { own: d.own, sid: d.sid, ref: typeof d.ref === "string" ? d.ref : "" } : undefined;
508
+ const circle = peerSession ? await circleOf(app, peerSession.own, peerSession.sid) : undefined;
509
+ const projects = await projectsOf(app, session);
510
+ recs.push({
511
+ id: e.id,
512
+ at: Date.now(),
513
+ sentAt: e.at,
514
+ dir: "in",
515
+ type: e.kind === "p2p.message" ? "message" : "ext",
516
+ ...(session !== undefined ? { session } : {}),
517
+ peer: { userId: d.from.userId, address: typeof d.from.address === "string" ? d.from.address : d.from.userId, ...(d.from.self === true ? { self: true } : {}) },
518
+ ...(peerSession ? { peerSession } : {}),
519
+ ...(circle ? { circle } : {}),
520
+ text,
521
+ ...(e.kind === "p2p.ext" && typeof d.ext === "string" ? { ext: d.ext } : {}),
522
+ ...(projects ? { projects } : {}),
523
+ });
524
+ }
525
+ return recs;
526
+ }
527
+ /** A send this device made (sessions.ts sendMessage, sendExtension). */
528
+ export async function recordSent(app, o) {
529
+ if (app.readOnly || !historySettings(app).enabled)
530
+ return;
531
+ const projects = await projectsOf(app, o.fromSession);
532
+ const circle = await circleOf(app, o.to.own, o.to.sid);
533
+ await recordHistory(app, [
534
+ {
535
+ id: `out:${randomBytes(9).toString("base64url")}`,
536
+ at: Date.now(),
537
+ dir: "out",
538
+ type: o.ext ? "ext" : "message",
539
+ session: o.fromSession,
540
+ peer: { userId: o.to.userId, address: o.to.address, ...(o.to.userId === app.userId ? { self: true } : {}) },
541
+ peerSession: { own: o.to.own, sid: o.to.sid, ref: o.to.ref },
542
+ ...(circle ? { circle } : {}),
543
+ text: o.text,
544
+ ...(o.ext ? { ext: o.ext } : {}),
545
+ ...(o.state ? { state: o.state } : {}),
546
+ ...(projects ? { projects } : {}),
547
+ },
548
+ ]);
549
+ }
550
+ // ---------------------------------------------------------------------------
551
+ // Reading
552
+ /** Whether a record is the person's own inbox: to no session, or the `tui` session's. */
553
+ export function isPersonRecord(r) {
554
+ return r.session === undefined || r.session === PERSON_SESSION;
555
+ }
556
+ /**
557
+ * Every record held (decrypted), oldest first, without the ones past retention, and how many
558
+ * documents couldn't be opened (set aside, never shown). Under the state lock, so a write in
559
+ * another process (copy-on-write: a segment's old version is removed once the index moved on)
560
+ * never shows as a document that couldn't be opened; a crash's newest segment is adopted here too.
561
+ */
562
+ async function readAll(app, now) {
563
+ const key = historyKey(app.home, false);
564
+ if (!key)
565
+ return { recs: [], unreadable: 0 };
566
+ const cutoff = now - historySettings(app).retentionDays * 86_400_000;
567
+ return app.state.withLock(async () => {
568
+ const before = setAside;
569
+ let unreadable = 0;
570
+ {
571
+ const { idx } = await loadIndex(app, key);
572
+ const out = [];
573
+ for (const s of idx.segs) {
574
+ if (s.last < cutoff)
575
+ continue;
576
+ const seg = await readSeg(app, key, s.name, s.h);
577
+ if (!seg.ok) {
578
+ unreadable++;
579
+ continue;
580
+ }
581
+ for (const r of seg.seg.recs)
582
+ if (r && typeof r.at === "number" && r.at >= cutoff && typeof r.text === "string")
583
+ out.push(r);
584
+ }
585
+ return { recs: out.sort((a, b) => a.at - b.at), unreadable: unreadable + setAside - before };
586
+ }
587
+ });
588
+ }
589
+ /**
590
+ * Who may read: the person (every record), or one session (its own records, within its projects).
591
+ * `sid` absent or `tui`: the person's own view. The gates are the existing ones (projects.ts):
592
+ * assertPersonForWidening for the person, the registration a front end made for a session.
593
+ */
594
+ export async function assertHistoryReader(app, sid) {
595
+ if (sid === undefined || sid === PERSON_SESSION) {
596
+ await assertPersonForWidening(app, "history", app.confirmTty, "shows your own messages");
597
+ return { person: true };
598
+ }
599
+ if (!app.front) {
600
+ // Without the token: inside an agent's session nobody reads a session's history (its front end
601
+ // reads it for it); outside one, only the person, on their own terminal.
602
+ if (agentContext(app.env)) {
603
+ throw new CliError("refused", `session ${sid}: inside an agent's session only its front end reads a session's history (the Codex bridge's p2p_history), never the shell`);
604
+ }
605
+ await assertPersonForWidening(app, `history --session ${sid}`, app.confirmTty, "shows your own messages");
606
+ return { person: true };
607
+ }
608
+ // The front end (it holds the person token) speaks for its own session: one it registered.
609
+ const b = await sessionBinding(app, sid);
610
+ if (!b?.registered)
611
+ throw new CliError("refused", `session ${sid} isn't a session a front end of yours registered: no history is read for it`);
612
+ // A binding from before it had a start (`since`) shows nothing until the session's next status gives it one.
613
+ return { person: false, sid, projects: new Set(Object.keys(b.projects ?? {})), since: typeof b.since === "number" ? b.since : Number.MAX_SAFE_INTEGER };
614
+ }
615
+ /**
616
+ * Whether `reader` may see `r`. A session sees only its own: recorded since its binding began (a
617
+ * binding made anew, after the old one expired, inherits nothing), with projects known (never
618
+ * UNBOUND or none), all of which it is still bound to.
619
+ */
620
+ export function mayRead(reader, r) {
621
+ if (reader.person)
622
+ return true;
623
+ if (isPersonRecord(r) || r.session !== reader.sid)
624
+ return false;
625
+ if (typeof r.at !== "number" || r.at < reader.since)
626
+ return false;
627
+ if (!Array.isArray(r.projects) || r.projects.length === 0 || r.projects.includes(UNBOUND))
628
+ return false;
629
+ return r.projects.every((p) => reader.projects.has(p));
630
+ }
631
+ /** Parses `--since`: `30m`, `12h`, `7d`, `2w`, or a date (ISO 8601). */
632
+ export function parseSince(s, now = Date.now()) {
633
+ const m = /^(\d{1,6})\s*(m|min|h|d|w)$/i.exec(s.trim());
634
+ if (m) {
635
+ const n = Number(m[1]);
636
+ const unit = m[2].toLowerCase();
637
+ const ms = unit === "w" ? 7 * 86_400_000 : unit === "d" ? 86_400_000 : unit === "h" ? 3_600_000 : 60_000;
638
+ return now - n * ms;
639
+ }
640
+ const t = Date.parse(s);
641
+ if (!Number.isFinite(t))
642
+ throw new CliError("usage", "--since takes a duration (30m, 12h, 7d, 2w) or a date (2026-11-01, 2026-11-01T09:00)");
643
+ return t;
644
+ }
645
+ /** `p2p history`: the records `reader` may see that match `q`, oldest first, at most `limit` (the newest). */
646
+ export async function readHistory(app, reader, q = {}, now = Date.now()) {
647
+ const s = historySettings(app);
648
+ const all = await readAll(app, now);
649
+ let recs = all.recs.filter((r) => mayRead(reader, r));
650
+ if (!reader.person)
651
+ recs = recs.filter((r) => r.session === reader.sid);
652
+ else if (q.inbox)
653
+ recs = recs.filter(isPersonRecord);
654
+ else if (q.session !== undefined)
655
+ recs = recs.filter((r) => (q.session === PERSON_SESSION ? isPersonRecord(r) : r.session === q.session));
656
+ if (q.since !== undefined)
657
+ recs = recs.filter((r) => r.at >= q.since);
658
+ if (q.peer !== undefined) {
659
+ const u = await app.resolveUser(q.peer);
660
+ recs = recs.filter((r) => r.peer.userId === u);
661
+ }
662
+ if (q.circle !== undefined) {
663
+ const { resolveCircle } = await import("./circle-ops.js");
664
+ const c = await resolveCircle(app, q.circle);
665
+ const lc = await loadCircle(app.store, c.record.cid).catch(() => undefined);
666
+ const members = new Set(lc?.chain.head.members ?? []);
667
+ recs = recs.filter((r) => r.circle === c.record.cid || (members.has(r.peer.userId) && r.peer.userId !== app.userId));
668
+ }
669
+ const limit = Math.min(HISTORY_LIST_MAX, Math.max(1, q.limit ?? HISTORY_LIST_DEFAULT));
670
+ const truncated = recs.length > limit;
671
+ if (truncated)
672
+ recs = recs.slice(recs.length - limit);
673
+ // What a session's reader gets never names other projects (the boundary is already applied).
674
+ const messages = recs.map((r) => {
675
+ const { projects: _p, ...rest } = r;
676
+ void _p;
677
+ return { ...rest, ...(reader.person && isPersonRecord(r) ? { inbox: true } : {}) };
678
+ });
679
+ return { messages, truncated, ...(all.unreadable > 0 ? { unreadable: all.unreadable } : {}), retention: { days: s.retentionDays, maxBytes: s.maxBytes, enabled: s.enabled } };
680
+ }
681
+ /** One record as a terminal line: peer text sanitized (no control, bidi or format characters, one line). */
682
+ export function historyLine(r) {
683
+ const when = new Date(r.at).toISOString().replace("T", " ").slice(0, 16);
684
+ const who = `${sanitizePeerText(r.peer.address, 120)}${r.peerSession?.ref ? ` [${sanitizePeerText(r.peerSession.ref, 12)}]` : ""}`;
685
+ const where = isPersonRecord(r) ? "you" : `session ${sanitizePeerText(r.session, 128)}`;
686
+ const arrow = r.dir === "in" ? `${who} → ${where}` : `${where} → ${who}`;
687
+ const kind = r.type === "ext" ? ` (${sanitizePeerText(r.ext ?? "extension", 64)})` : "";
688
+ const state = r.state && r.state !== "sent" ? ` [${r.state}]` : "";
689
+ return `${when} ${arrow}${kind}${state}: ${capText(sanitizePeerText(r.text, HISTORY_SHOW_MAX + 1))}`;
690
+ }
691
+ /** What one record shows at most, in a terminal or to a model (the rest: `--json`). */
692
+ export const HISTORY_SHOW_MAX = 4000;
693
+ /** `s` cut at HISTORY_SHOW_MAX characters, saying so. */
694
+ export function capText(s, max = HISTORY_SHOW_MAX) {
695
+ const cps = [...s];
696
+ return cps.length > max ? `${cps.slice(0, max).join("")}… (truncated)` : s;
697
+ }