@peer2peer/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +366 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +363 -0
  6. package/dist/app.js +1177 -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 +611 -0
  12. package/dist/cli.js +1650 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +112 -0
  16. package/dist/config.js +243 -0
  17. package/dist/doctor.d.ts +99 -0
  18. package/dist/doctor.js +817 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +32 -0
  22. package/dist/ext-host.js +259 -0
  23. package/dist/extensions.d.ts +386 -0
  24. package/dist/extensions.js +395 -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/identity.d.ts +236 -0
  30. package/dist/identity.js +751 -0
  31. package/dist/inbound.d.ts +32 -0
  32. package/dist/inbound.js +258 -0
  33. package/dist/index.d.ts +8 -0
  34. package/dist/index.js +14 -0
  35. package/dist/join-answers.d.ts +49 -0
  36. package/dist/join-answers.js +149 -0
  37. package/dist/outbox.d.ts +109 -0
  38. package/dist/outbox.js +337 -0
  39. package/dist/pretty.d.ts +100 -0
  40. package/dist/pretty.js +256 -0
  41. package/dist/procstart.d.ts +1 -0
  42. package/dist/procstart.js +66 -0
  43. package/dist/progress.d.ts +30 -0
  44. package/dist/progress.js +78 -0
  45. package/dist/projects.d.ts +240 -0
  46. package/dist/projects.js +699 -0
  47. package/dist/prompt/picker.d.ts +64 -0
  48. package/dist/prompt/picker.js +152 -0
  49. package/dist/prompt/tty.d.ts +29 -0
  50. package/dist/prompt/tty.js +122 -0
  51. package/dist/readonly.d.ts +20 -0
  52. package/dist/readonly.js +50 -0
  53. package/dist/receipts.d.ts +99 -0
  54. package/dist/receipts.js +180 -0
  55. package/dist/relay-client.d.ts +277 -0
  56. package/dist/relay-client.js +873 -0
  57. package/dist/relay-info.d.ts +24 -0
  58. package/dist/relay-info.js +53 -0
  59. package/dist/rotation.d.ts +402 -0
  60. package/dist/rotation.js +2054 -0
  61. package/dist/running.d.ts +5 -0
  62. package/dist/running.js +74 -0
  63. package/dist/sessions.d.ts +340 -0
  64. package/dist/sessions.js +1152 -0
  65. package/dist/shortcode.d.ts +149 -0
  66. package/dist/shortcode.js +465 -0
  67. package/dist/social.d.ts +139 -0
  68. package/dist/social.js +485 -0
  69. package/dist/state.d.ts +483 -0
  70. package/dist/state.js +217 -0
  71. package/dist/stdin.d.ts +17 -0
  72. package/dist/stdin.js +46 -0
  73. package/dist/sync.d.ts +77 -0
  74. package/dist/sync.js +375 -0
  75. package/dist/transient.d.ts +1 -0
  76. package/dist/transient.js +28 -0
  77. package/dist/trust.d.ts +37 -0
  78. package/dist/trust.js +134 -0
  79. package/dist/tty-confirm.d.ts +2 -0
  80. package/dist/tty-confirm.js +53 -0
  81. package/dist/tui/command.d.ts +20 -0
  82. package/dist/tui/command.js +70 -0
  83. package/dist/tui/frame.d.ts +43 -0
  84. package/dist/tui/frame.js +111 -0
  85. package/dist/tui/model.d.ts +215 -0
  86. package/dist/tui/model.js +255 -0
  87. package/dist/tui/sanitize.d.ts +13 -0
  88. package/dist/tui/sanitize.js +151 -0
  89. package/dist/tui/terminal.d.ts +88 -0
  90. package/dist/tui/terminal.js +354 -0
  91. package/dist/tui/tui.d.ts +71 -0
  92. package/dist/tui/tui.js +571 -0
  93. package/dist/tui/view.d.ts +4 -0
  94. package/dist/tui/view.js +356 -0
  95. package/dist/unknown-kinds.d.ts +12 -0
  96. package/dist/unknown-kinds.js +66 -0
  97. package/dist/version.d.ts +1 -0
  98. package/dist/version.js +5 -0
  99. package/dist/want-pow.d.ts +12 -0
  100. package/dist/want-pow.js +46 -0
  101. package/dist/watch.d.ts +35 -0
  102. package/dist/watch.js +325 -0
  103. package/dist/xstate.d.ts +125 -0
  104. package/dist/xstate.js +422 -0
  105. package/package.json +60 -4
@@ -0,0 +1,395 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The extension seam (docs/architecture.md "The rules that keep the layers
4
+ // apart", docs/protocol.md §4.3 and §8). `p2p` never imports an extension
5
+ // statically: it loads the ones the user enabled with a dynamic import of a
6
+ // *resolved file URL*, never of a literal specifier, so
7
+ // scripts/check-boundaries.mjs keeps refusing every static (or literal
8
+ // dynamic) import of an extension while allowing this one loader (it is
9
+ // allowlisted by path there).
10
+ //
11
+ // Trust: an extension is code that runs inside `p2p`, with everything `p2p`
12
+ // can reach (the home directory, the identity and device keys). ExtContext
13
+ // is the API it is meant to use, not a sandbox. So loading is opt-in:
14
+ // - Which: only namespaces registered in protocol §8.3 (KNOWN_EXTENSIONS)
15
+ // that the user enabled: P2P_EXTENSIONS ("ix,kartr"; "none" = none), else
16
+ // `extensions` in <home>/config.json (`p2p extensions enable ix`). Nothing
17
+ // enabled, nothing loaded.
18
+ // - Where: only explicit node_modules directories: each P2P_EXTENSION_PATH
19
+ // entry (a directory, or its node_modules), then the CLI's own sibling
20
+ // node_modules when it is installed as a package. No walk-up, NODE_PATH
21
+ // or global folders; the entry file must lie inside the package.
22
+ // - The first load from a new location is announced (stderr).
23
+ //
24
+ // What an extension is for (P2PExtension):
25
+ // - `receive`: validate, sanitize and render the body of an inbound
26
+ // `x:<ns>.*` envelope into a JSON digest that `p2p watch --jsonl` prints.
27
+ // It must not act on the content (protocol §4.3). Anything it throws, or
28
+ // a digest that is too big, degrades to the plain fallback.
29
+ // - `state`: kinds that are a session's latest value rather than events
30
+ // (§4.3 "Extension state kinds", cap xstate.v1; xstate.ts): sent with
31
+ // `publish` to the session's status audience, stored latest-wins with a
32
+ // ttl, never logged, toasted or shown to a model.
33
+ // - `commands`: subcommands under `p2p <ns> …`, declared as data; `p2p`
34
+ // builds them and owns the output and exit codes, and hands them an
35
+ // ExtContext (send kinds of their namespace through the ordinary
36
+ // §4.2-authorised path, read the events they rendered, list live peers).
37
+ //
38
+ // A missing, broken or incompatible extension never fails a command: it is
39
+ // skipped with a warning, and its kinds are shown as their fallback.
40
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
41
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
42
+ import { fileURLToPath, pathToFileURL } from "node:url";
43
+ import { extensionKindCap, isExtensionKind, isExtStateTtl, sanitizePeerText } from "@peer2peer/core/v3";
44
+ /** The seam's version; an extension declares the one it was built against. */
45
+ export const EXTENSION_API = 1;
46
+ /** Namespaces registered in docs/protocol.md §8.3: the only ones that can be enabled. */
47
+ export const KNOWN_EXTENSIONS = ["ix", "kartr"];
48
+ /** Cap on the JSON a `receive` digest may add to an event. */
49
+ export const MAX_RENDERED_BYTES = 16 * 1024;
50
+ /** Cap on the validated body kept with an event (for user-initiated actions later). */
51
+ export const MAX_KEPT_BYTES = 24 * 1024;
52
+ /** Each string in a digest passes the peer-text sanitizer with this cap. */
53
+ export const MAX_RENDERED_STRING = 4000;
54
+ export function extensionPackageName(ns) {
55
+ return `@peer2peer/ext-${ns}`;
56
+ }
57
+ /** The namespace of an `x:<ns>.<type>` kind. */
58
+ export function kindNamespace(kind) {
59
+ return isExtensionKind(kind) ? kind.slice(2, kind.indexOf(".")) : undefined;
60
+ }
61
+ export class ExtensionRegistry {
62
+ byNs = new Map();
63
+ constructor(list = []) {
64
+ for (const l of list)
65
+ if (!this.byNs.has(l.ext.ns))
66
+ this.byNs.set(l.ext.ns, l);
67
+ }
68
+ get(ns) {
69
+ return this.byNs.get(ns)?.ext;
70
+ }
71
+ forKind(kind) {
72
+ const ns = kindNamespace(kind);
73
+ return ns ? this.get(ns) : undefined;
74
+ }
75
+ list() {
76
+ return [...this.byNs.values()];
77
+ }
78
+ }
79
+ /** Validates what a module exports; undefined (with a reason) when it isn't a usable extension. */
80
+ export function checkExtension(mod, ns) {
81
+ const m = mod;
82
+ const ext = (m?.extension ?? m?.default?.extension ?? m?.default);
83
+ if (!ext || typeof ext !== "object")
84
+ return { why: "exports no `extension`" };
85
+ if (ext.api !== EXTENSION_API)
86
+ return { why: `built for extension API ${String(ext.api)}, this p2p has ${EXTENSION_API}` };
87
+ if (ext.ns !== ns)
88
+ return { why: `declares namespace ${String(ext.ns)}, expected ${ns}` };
89
+ if (ext.receive !== undefined && typeof ext.receive !== "function")
90
+ return { why: "receive is not a function" };
91
+ if (ext.state !== undefined) {
92
+ if (typeof ext.state !== "object" || ext.state === null || Array.isArray(ext.state))
93
+ return { why: "state is malformed" };
94
+ for (const [kind, d] of Object.entries(ext.state)) {
95
+ if (!isExtensionKind(kind) || kindNamespace(kind) !== ns)
96
+ return { why: `state kind ${sanitizePeerText(kind, 60)} is not an x:${ns}.<type> kind` };
97
+ if (!extensionKindCap(kind))
98
+ return { why: `state kind ${kind} is too long for its cap (${kind}.v1, at most 40 characters)` };
99
+ if (typeof d !== "object" || d === null || (d.ttl !== undefined && !isExtStateTtl(d.ttl)))
100
+ return { why: `state kind ${kind}: ttl must be an integer of 10-3600 seconds` };
101
+ }
102
+ }
103
+ if (ext.commands !== undefined && (!Array.isArray(ext.commands) || ext.commands.some((c) => !c || typeof c.name !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(c.name) || typeof c.run !== "function"))) {
104
+ return { why: "commands are malformed" };
105
+ }
106
+ return { ext };
107
+ }
108
+ /**
109
+ * The namespaces the user enabled (opt-in): P2P_EXTENSIONS when set ("none"
110
+ * or "" = none; "config" = defer to config.json), else `extensions` in
111
+ * config.json, else none. Only
112
+ * namespaces registered in protocol §8.3 count; others are ignored (`ignored`).
113
+ */
114
+ export function enabledNamespaces(env, config) {
115
+ let raw;
116
+ // "config" means: only config.json counts (a client that must not inherit its user's shell setting).
117
+ if (env.P2P_EXTENSIONS !== undefined && env.P2P_EXTENSIONS.trim() !== "config") {
118
+ const t = env.P2P_EXTENSIONS.trim();
119
+ raw = t === "" || t === "none" || t === "0" ? [] : t.split(/[\s,]+/);
120
+ }
121
+ else if (Array.isArray(config?.extensions)) {
122
+ raw = config.extensions.filter((x) => typeof x === "string");
123
+ }
124
+ else
125
+ raw = [];
126
+ const enabled = [];
127
+ const ignored = [];
128
+ for (const r of raw) {
129
+ const ns = r.trim().replace(/^@peer2peer\/ext-/, "");
130
+ if (ns === "")
131
+ continue;
132
+ if (KNOWN_EXTENSIONS.includes(ns)) {
133
+ if (!enabled.includes(ns))
134
+ enabled.push(ns);
135
+ }
136
+ else
137
+ ignored.push(sanitizePeerText(r, 64));
138
+ }
139
+ return { enabled, ignored };
140
+ }
141
+ /**
142
+ * The CLI's own sibling node_modules, when it is installed as a package
143
+ * (`…/node_modules/@peer2peer/cli/dist/extensions.js` → `…/node_modules`):
144
+ * where a global `npm i -g @peer2peer/cli @peer2peer/ext-ix` puts both.
145
+ * Nothing for a checkout or the bundled single file.
146
+ */
147
+ export function siblingNodeModules(selfFile) {
148
+ const parts = resolvePath(selfFile).split(sep);
149
+ for (let i = parts.length - 3; i >= 0; i--) {
150
+ if (parts[i] === "node_modules" && parts[i + 1] === "@peer2peer" && parts[i + 2] === "cli")
151
+ return parts.slice(0, i + 1).join(sep) || sep;
152
+ }
153
+ return undefined;
154
+ }
155
+ /** A path with symlinks resolved as far as it exists (a missing tail is kept as written). */
156
+ function realish(p) {
157
+ try {
158
+ return realpathSync(p);
159
+ }
160
+ catch {
161
+ const parent = dirname(p);
162
+ return parent === p ? p : join(realish(parent), basename(p));
163
+ }
164
+ }
165
+ /** Whether `p` is `dir` or inside it, comparing real paths (a symlink can't hide where it points). */
166
+ export function isInside(p, dir) {
167
+ const r = realish(resolvePath(p));
168
+ const d = realish(resolvePath(dir));
169
+ const rel = relative(d, r);
170
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
171
+ }
172
+ /**
173
+ * The node_modules directories searched, in order: P2P_EXTENSION_PATH's, then the CLI's sibling one.
174
+ * P2P_EXTENSION_EXCLUDE (path-delimiter separated) drops entries inside those directories, by real
175
+ * path: a client passes the session's repository, so a cloned repo can't supply an extension.
176
+ */
177
+ export function extensionDirs(env, selfUrl) {
178
+ const excluded = (env.P2P_EXTENSION_EXCLUDE ?? "")
179
+ .split(delimiter)
180
+ .map((d) => d.trim())
181
+ .filter((d) => d !== "" && isAbsolute(d));
182
+ const dirs = (env.P2P_EXTENSION_PATH ?? "")
183
+ .split(delimiter)
184
+ .map((d) => d.trim())
185
+ .filter(Boolean)
186
+ .filter((d) => !excluded.some((x) => isInside(d, x)))
187
+ .map((d) => (basename(d) === "node_modules" ? d : join(d, "node_modules")));
188
+ const self = selfUrl.startsWith("file:") ? fileURLToPath(selfUrl) : selfUrl;
189
+ const sib = siblingNodeModules(self);
190
+ return [...new Set([...dirs, ...(sib ? [sib] : [])])];
191
+ }
192
+ export class ExtResolveError extends Error {
193
+ }
194
+ /**
195
+ * Resolves `name` inside one node_modules directory only: no walk-up, no
196
+ * NODE_PATH, no global folders. The package's entry (exports "." import /
197
+ * default, else main, else index.js) must be a file inside the package.
198
+ * Undefined when the package isn't there; ExtResolveError when it is but is
199
+ * malformed.
200
+ */
201
+ export function resolveIn(nodeModules, name) {
202
+ const pkgDir = join(nodeModules, ...name.split("/"));
203
+ if (!existsSync(join(pkgDir, "package.json")))
204
+ return undefined;
205
+ let pkg;
206
+ try {
207
+ pkg = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"));
208
+ }
209
+ catch {
210
+ throw new ExtResolveError(`${join(pkgDir, "package.json")} is not valid JSON`);
211
+ }
212
+ if (pkg?.name !== name)
213
+ throw new ExtResolveError(`${pkgDir} is not ${name}`);
214
+ const dot = typeof pkg.exports === "string" ? pkg.exports : pkg.exports?.["."];
215
+ const cond = typeof dot === "string" ? dot : dot && typeof dot === "object" ? (dot.import ?? dot.default) : undefined;
216
+ const entry = typeof cond === "string" ? cond : typeof pkg.main === "string" ? pkg.main : "index.js";
217
+ let real;
218
+ let realPkg;
219
+ try {
220
+ realPkg = realpathSync(pkgDir);
221
+ real = realpathSync(resolvePath(pkgDir, entry));
222
+ }
223
+ catch {
224
+ throw new ExtResolveError(`${name}'s entry ${sanitizePeerText(entry, 120)} doesn't exist`);
225
+ }
226
+ if (!real.startsWith(realPkg + sep))
227
+ throw new ExtResolveError(`${name}'s entry points outside the package`);
228
+ return real;
229
+ }
230
+ const SEEN_FILE = "extension-locations.json";
231
+ /** Records where each namespace was loaded from; true when this location is new for it. */
232
+ function firstFromHere(home, ns, file) {
233
+ if (!home)
234
+ return true;
235
+ const p = join(home, SEEN_FILE);
236
+ let seen = {};
237
+ try {
238
+ seen = JSON.parse(readFileSync(p, "utf8"));
239
+ }
240
+ catch {
241
+ // none yet
242
+ }
243
+ if (seen[ns] === file)
244
+ return false;
245
+ try {
246
+ if (existsSync(home)) {
247
+ const tmp = `${p}.${process.pid}.tmp`;
248
+ writeFileSync(tmp, JSON.stringify({ ...seen, [ns]: file }), { mode: 0o600 });
249
+ renameSync(tmp, p);
250
+ }
251
+ }
252
+ catch {
253
+ // best effort: it is said again next time
254
+ }
255
+ return true;
256
+ }
257
+ /**
258
+ * Loads the extensions the user enabled, from the explicit directories only.
259
+ * Never throws: an enabled one that isn't found, a bad directory, or a broken
260
+ * package is a warning, and the rest still load.
261
+ */
262
+ export async function loadExtensions(opts) {
263
+ const warn = opts.warn ?? (() => { });
264
+ const log = opts.env.P2P_DEBUG === "1" ? (opts.log ?? warn) : () => { };
265
+ const { enabled, ignored } = enabledNamespaces(opts.env, opts.config);
266
+ if (ignored.length)
267
+ warn(`p2p: ignoring extensions that aren't registered (protocol §8.3): ${ignored.join(", ")}`);
268
+ if (enabled.length === 0)
269
+ return new ExtensionRegistry();
270
+ const dirs = extensionDirs(opts.env, opts.selfUrl ?? import.meta.url);
271
+ const loaded = [];
272
+ for (const ns of enabled) {
273
+ const name = extensionPackageName(ns);
274
+ let file;
275
+ for (const dir of dirs) {
276
+ try {
277
+ file = resolveIn(dir, name);
278
+ }
279
+ catch (e) {
280
+ // L1: a bad base is skipped, not the namespace.
281
+ warn(`p2p: skipping ${sanitizePeerText(dir, 200)} for ${name}: ${sanitizePeerText(e.message, 300)}`);
282
+ continue;
283
+ }
284
+ if (file)
285
+ break;
286
+ }
287
+ if (!file) {
288
+ warn(`p2p: extension ${name} is enabled but not installed in ${dirs.length ? dirs.map((d) => sanitizePeerText(d, 200)).join(", ") : "any extension directory (set P2P_EXTENSION_PATH)"}`);
289
+ continue;
290
+ }
291
+ try {
292
+ // The one dynamic import of an extension: a resolved file URL, never a literal specifier.
293
+ const href = pathToFileURL(file).href;
294
+ const mod = await import(href);
295
+ const { ext, why } = checkExtension(mod, ns);
296
+ if (!ext) {
297
+ warn(`p2p: extension ${name} skipped: ${why}`);
298
+ continue;
299
+ }
300
+ if (firstFromHere(opts.home, ns, file))
301
+ warn(`p2p: loading extension ${name} ${sanitizePeerText(ext.version, 32)} from ${file} (it runs with your p2p identity: only enable extensions you trust)`);
302
+ else
303
+ log(`p2p: extension ${name} from ${file}`);
304
+ loaded.push({ ext, from: file });
305
+ }
306
+ catch (e) {
307
+ warn(`p2p: extension ${name} failed to load: ${sanitizePeerText(e.message, 300)}`);
308
+ }
309
+ }
310
+ return new ExtensionRegistry(loaded);
311
+ }
312
+ /** `p2p extensions enable|disable <ns>`: edits `extensions` in <home>/config.json. */
313
+ export function setExtensionEnabled(home, ns, on) {
314
+ if (!KNOWN_EXTENSIONS.includes(ns))
315
+ throw new Error(`${ns} is not a registered extension namespace (${KNOWN_EXTENSIONS.join(", ")})`);
316
+ const p = join(home, "config.json");
317
+ let cfg = {};
318
+ if (existsSync(p)) {
319
+ const v = JSON.parse(readFileSync(p, "utf8"));
320
+ if (typeof v !== "object" || v === null || Array.isArray(v))
321
+ throw new Error("config.json must hold a JSON object");
322
+ cfg = v;
323
+ }
324
+ const cur = Array.isArray(cfg.extensions) ? cfg.extensions.filter((x) => typeof x === "string") : [];
325
+ const next = on ? [...new Set([...cur, ns])] : cur.filter((x) => x !== ns);
326
+ mkdirSync(home, { recursive: true, mode: 0o700 });
327
+ const tmp = `${p}.${process.pid}.tmp`;
328
+ writeFileSync(tmp, JSON.stringify({ ...cfg, extensions: next }, null, 2) + "\n", { mode: 0o600 });
329
+ renameSync(tmp, p);
330
+ return next;
331
+ }
332
+ // ---------------------------------------------------------------------------
333
+ // Receiving: render through the extension, or degrade to the fallback
334
+ /** Every string sanitized and capped; depth- and size-bounded; non-JSON values dropped. */
335
+ export function sanitizeRendered(v, depth = 0) {
336
+ if (depth > 6)
337
+ return undefined;
338
+ if (typeof v === "string")
339
+ return sanitizePeerText(v, MAX_RENDERED_STRING);
340
+ if (typeof v === "number")
341
+ return Number.isFinite(v) ? v : undefined;
342
+ if (typeof v === "boolean" || v === null)
343
+ return v;
344
+ if (Array.isArray(v))
345
+ return v.slice(0, 200).map((x) => sanitizeRendered(x, depth + 1)).filter((x) => x !== undefined);
346
+ if (typeof v === "object") {
347
+ const out = {};
348
+ for (const [k, x] of Object.entries(v).slice(0, 100)) {
349
+ if (!/^[A-Za-z][A-Za-z0-9_]{0,39}$/.test(k))
350
+ continue;
351
+ const s = sanitizeRendered(x, depth + 1);
352
+ if (s !== undefined)
353
+ out[k] = s;
354
+ }
355
+ return out;
356
+ }
357
+ return undefined;
358
+ }
359
+ /** Runs the extension's `receive` defensively. Without one, nothing (the fallback stands). */
360
+ export function renderExtension(reg, input) {
361
+ const ext = reg?.forKind(input.kind);
362
+ if (!ext?.receive)
363
+ return {};
364
+ let r;
365
+ try {
366
+ r = ext.receive(input);
367
+ }
368
+ catch (e) {
369
+ return { extError: sanitizePeerText(`${ext.name} failed: ${e?.message ?? String(e)}`, 200) };
370
+ }
371
+ if (!r || typeof r !== "object")
372
+ return { extError: "the extension returned nothing" };
373
+ if (!r.ok)
374
+ return { extError: sanitizePeerText(String(r.reason), 200) };
375
+ const out = {};
376
+ // A state kind needs no digest (it is never printed), only what it keeps.
377
+ if (!(input.state && r.rendered === undefined)) {
378
+ const rendered = sanitizeRendered(r.rendered);
379
+ if (rendered && typeof rendered === "object" && Buffer.byteLength(JSON.stringify(rendered), "utf8") <= MAX_RENDERED_BYTES)
380
+ out.rendered = rendered;
381
+ else
382
+ out.extError = "the rendered digest was too large";
383
+ }
384
+ if (r.keep !== undefined) {
385
+ try {
386
+ const s = JSON.stringify(r.keep);
387
+ if (s !== undefined && Buffer.byteLength(s, "utf8") <= MAX_KEPT_BYTES)
388
+ out.kept = { v: input.v, body: JSON.parse(s) };
389
+ }
390
+ catch {
391
+ // not JSON: not kept
392
+ }
393
+ }
394
+ return out;
395
+ }
@@ -0,0 +1,91 @@
1
+ import { type DeviceInfo } from "@peer2peer/core/v3";
2
+ import type { App } from "./app.js";
3
+ import { type PeerStatusRec } from "./state.js";
4
+ /** This client's protocol minor: 3.1 is forward compatibility (must-ignore, crit, unknown kinds). */
5
+ export declare const PROTO_MINOR = 1;
6
+ export declare const PROTO_CAP = "proto.3.1";
7
+ /** This client redeems codes that join several circles (the bundle's `circles`, docs/protocol.md P4). */
8
+ export declare const CAP_INVITE_CIRCLES = "invite.circles.v1";
9
+ /** This client keeps project boundaries (projects.ts): it honours `bound` on messages between one user's own sessions. */
10
+ export declare const CAP_PROJECTS = "projects.v1";
11
+ /**
12
+ * This CLI's own: its protocol minor. Not its exact version: a status goes to everyone the roster
13
+ * allows, and an exact version would help single out a device (and its unpatched bugs); the version
14
+ * rides only in the opt-in identity document entry (`dinfo.client`). docs/compatibility.md.
15
+ */
16
+ export declare const CLI_FEATURE_CAPS: readonly string[];
17
+ /**
18
+ * Everything this CLI itself understands (§4.3 "Status caps"), as its statuses and its identity
19
+ * document entry (`dinfo`) advertise it. A front end adds its own (the mod's receipts.v1).
20
+ */
21
+ export declare const CLI_CAPS: readonly string[];
22
+ /** The protocol minor a cap list advertises (0: none, a client from before 3.1). */
23
+ export declare function protoMinor(caps: readonly string[] | undefined): number;
24
+ /** Features a person may care about, in words (doctor's "unavailable between you"). */
25
+ export declare const KNOWN_FEATURES: readonly {
26
+ cap: string;
27
+ what: string;
28
+ session?: boolean;
29
+ }[];
30
+ /** Where peerSupports looks: a session (its live status), a device, or every live session of the user. */
31
+ export type FeatureScope = {
32
+ sid: string;
33
+ } | {
34
+ did: string;
35
+ } | {
36
+ all: true;
37
+ };
38
+ export interface FeatureSources {
39
+ peers: Record<string, PeerStatusRec>;
40
+ /** The user's identity document `dinfo`, when it has one. */
41
+ dinfo?: Record<string, DeviceInfo>;
42
+ self: {
43
+ userId: string;
44
+ did: string;
45
+ };
46
+ now?: number;
47
+ }
48
+ /** The caps a device advertises: its identity document entry, else its latest status. */
49
+ export declare function deviceCaps(src: Pick<FeatureSources, "peers" | "dinfo">, userId: string, did: string): {
50
+ caps: string[];
51
+ source: "identity" | "status";
52
+ } | undefined;
53
+ /**
54
+ * Whether `userId`'s client understands `feature`, from what we hold (no network):
55
+ * - `{sid}`: that session is live now and its status lists it (a stale status never decides: a session
56
+ * since restarted on an older client would reject what it doesn't know, pre-release review R2);
57
+ * - `{did}`: that device's identity-document entry lists it, else its latest status does;
58
+ * - `{all}`: every live session of theirs we know of (other than this device's own) lists it, and
59
+ * there is at least one (a status goes to a user: one plaintext for all their devices).
60
+ */
61
+ export declare function supportsIn(src: FeatureSources, userId: string, scope: FeatureScope, feature: string): boolean;
62
+ /** supportsIn over this device's state: the helper every feature-gated send uses. */
63
+ export declare function peerSupports(app: App, userId: string, scope: FeatureScope, feature: string): Promise<boolean>;
64
+ export interface PeerDevice {
65
+ did: string;
66
+ label?: string;
67
+ keyholder: boolean;
68
+ /** Where the caps came from; absent when we know nothing of this device's client. */
69
+ source?: "identity" | "status";
70
+ client?: string;
71
+ proto: number;
72
+ caps: string[];
73
+ /** When its latest status was sent (ms), if any. */
74
+ lastSeen?: number;
75
+ }
76
+ /** A user's devices as their identity document lists them, with what each one's client understands. */
77
+ export declare function peerDevices(app: App, userId: string): Promise<PeerDevice[]>;
78
+ /**
79
+ * The known features one side has and the other lacks, given the caps of this client and of every
80
+ * one of the peer's devices we know of (a feature counts for them only when all of them have it).
81
+ */
82
+ export declare function unavailableBetween(mine: readonly string[], theirs: readonly (readonly string[])[]): {
83
+ theyLack: string[];
84
+ weLack: string[];
85
+ };
86
+ /**
87
+ * Whether what we hold of `userId`'s client shows it lacks `feature`: its latest status (any session,
88
+ * any age) or its identity document entry lists caps, and not that one. No evidence is "no" here too:
89
+ * this is only for telling the user something, never for deciding what to send.
90
+ */
91
+ export declare function peerLacks(app: App, userId: string, feature: string): Promise<boolean>;
@@ -0,0 +1,164 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // What a peer's client understands, and the one helper every feature-gated send asks
4
+ // (docs/compatibility.md, protocol.md "Forward compatibility").
5
+ //
6
+ // - A feature is a cap id: `receipts.v1`, `agents.v1`, `xstate.v1`, `status.tolerant.v1`, and the
7
+ // protocol minor `proto.3.<n>` (3.1: unknown fields and kinds degrade instead of failing). The
8
+ // exact client version is only in the opt-in identity document entry (`dinfo.client`).
9
+ // - Where it is learnt, per device: the device's entry in its user's identity document (`dinfo`,
10
+ // when present), else the latest status we have from any session on that device. Per session: that
11
+ // session's live status (a front end's own caps, such as receipts.v1, are per session).
12
+ // - peerSupports says yes only on positive evidence. No evidence is "no": a sender then leaves the
13
+ // feature out, which every older client handles.
14
+ import { isLive, STATUS_CAP_AGENTS, STATUS_CAP_TOLERANT, STATUS_CAP_XSTATE, statusHasCap } from "@peer2peer/core/v3";
15
+ import { sessKey } from "./state.js";
16
+ /** This client's protocol minor: 3.1 is forward compatibility (must-ignore, crit, unknown kinds). */
17
+ export const PROTO_MINOR = 1;
18
+ export const PROTO_CAP = `proto.3.${PROTO_MINOR}`;
19
+ /** This client redeems codes that join several circles (the bundle's `circles`, docs/protocol.md P4). */
20
+ export const CAP_INVITE_CIRCLES = "invite.circles.v1";
21
+ /** This client keeps project boundaries (projects.ts): it honours `bound` on messages between one user's own sessions. */
22
+ export const CAP_PROJECTS = "projects.v1";
23
+ const PROTO_RE = /^proto\.3\.(\d{1,4})$/;
24
+ /**
25
+ * This CLI's own: its protocol minor. Not its exact version: a status goes to everyone the roster
26
+ * allows, and an exact version would help single out a device (and its unpatched bugs); the version
27
+ * rides only in the opt-in identity document entry (`dinfo.client`). docs/compatibility.md.
28
+ */
29
+ export const CLI_FEATURE_CAPS = [PROTO_CAP, CAP_INVITE_CIRCLES, CAP_PROJECTS];
30
+ /**
31
+ * Everything this CLI itself understands (§4.3 "Status caps"), as its statuses and its identity
32
+ * document entry (`dinfo`) advertise it. A front end adds its own (the mod's receipts.v1).
33
+ */
34
+ export const CLI_CAPS = [STATUS_CAP_TOLERANT, STATUS_CAP_AGENTS, STATUS_CAP_XSTATE, ...CLI_FEATURE_CAPS];
35
+ /** The protocol minor a cap list advertises (0: none, a client from before 3.1). */
36
+ export function protoMinor(caps) {
37
+ let best = 0;
38
+ for (const c of caps ?? []) {
39
+ const m = PROTO_RE.exec(c);
40
+ if (m)
41
+ best = Math.max(best, Number(m[1]));
42
+ }
43
+ return best;
44
+ }
45
+ /** Features a person may care about, in words (doctor's "unavailable between you"). */
46
+ export const KNOWN_FEATURES = [
47
+ { cap: "status.tolerant.v1", what: "statuses that can grow new fields" },
48
+ { cap: "agents.v1", what: "subagents in statuses" },
49
+ { cap: "xstate.v1", what: "extension state (Ix footprints)" },
50
+ { cap: "receipts.v1", what: "delivery receipts", session: true },
51
+ { cap: PROTO_CAP, what: "forward compatibility (newer fields and kinds degrade instead of failing)" },
52
+ { cap: CAP_INVITE_CIRCLES, what: "invite codes that join several circles" },
53
+ ];
54
+ /** The latest status we hold from any session on device `did` of `userId`. */
55
+ function latestFromDevice(peers, userId, did) {
56
+ let best;
57
+ for (const p of Object.values(peers))
58
+ if (p.own === userId && p.did === did && (!best || p.ts > best.ts))
59
+ best = p;
60
+ return best;
61
+ }
62
+ /** The caps a device advertises: its identity document entry, else its latest status. */
63
+ export function deviceCaps(src, userId, did) {
64
+ const d = src.dinfo?.[did];
65
+ if (d)
66
+ return { caps: [...d.caps], source: "identity" };
67
+ const s = latestFromDevice(src.peers, userId, did)?.status.caps;
68
+ return Array.isArray(s) ? { caps: [...s], source: "status" } : undefined;
69
+ }
70
+ /**
71
+ * Whether `userId`'s client understands `feature`, from what we hold (no network):
72
+ * - `{sid}`: that session is live now and its status lists it (a stale status never decides: a session
73
+ * since restarted on an older client would reject what it doesn't know, pre-release review R2);
74
+ * - `{did}`: that device's identity-document entry lists it, else its latest status does;
75
+ * - `{all}`: every live session of theirs we know of (other than this device's own) lists it, and
76
+ * there is at least one (a status goes to a user: one plaintext for all their devices).
77
+ */
78
+ export function supportsIn(src, userId, scope, feature) {
79
+ const now = src.now ?? Date.now();
80
+ if ("sid" in scope) {
81
+ const rec = src.peers[sessKey(userId, scope.sid)];
82
+ return rec !== undefined && isLive(rec.ts, now) && statusHasCap(rec.status, feature);
83
+ }
84
+ if ("did" in scope)
85
+ return deviceCaps(src, userId, scope.did)?.caps.includes(feature) === true;
86
+ const live = Object.values(src.peers).filter((p) => p.own === userId && isLive(p.ts, now) && !(p.own === src.self.userId && p.did === src.self.did));
87
+ return live.length > 0 && live.every((p) => statusHasCap(p.status, feature));
88
+ }
89
+ async function sources(app, userId) {
90
+ const view = await app.view(userId).catch(() => undefined);
91
+ return { peers: (await app.state.get("peers")) ?? {}, ...(view?.head.dinfo ? { dinfo: view.head.dinfo } : {}), self: { userId: app.userId, did: app.did } };
92
+ }
93
+ /** supportsIn over this device's state: the helper every feature-gated send uses. */
94
+ export async function peerSupports(app, userId, scope, feature) {
95
+ return supportsIn(await sources(app, userId), userId, scope, feature);
96
+ }
97
+ /** A user's devices as their identity document lists them, with what each one's client understands. */
98
+ export async function peerDevices(app, userId) {
99
+ const view = await app.view(userId).catch(() => undefined);
100
+ if (!view)
101
+ return [];
102
+ const src = await sources(app, userId);
103
+ const labels = new Map();
104
+ for (const c of view.head.certs ?? []) {
105
+ try {
106
+ const p = JSON.parse(Buffer.from(c.split(".")[1] ?? "", "base64url").toString());
107
+ if (typeof p.did === "string" && typeof p.label === "string")
108
+ labels.set(p.did, p.label);
109
+ }
110
+ catch {
111
+ // not ours to judge here: the cert was verified when the document was
112
+ }
113
+ }
114
+ return view.devices.map((did) => {
115
+ const d = deviceCaps(src, userId, did);
116
+ const seen = latestFromDevice(src.peers, userId, did)?.ts;
117
+ // The exact version only from the device's own (opt-in) identity document entry.
118
+ const client = src.dinfo?.[did]?.client;
119
+ return {
120
+ did,
121
+ ...(labels.has(did) ? { label: labels.get(did) } : {}),
122
+ keyholder: view.keyholders.includes(did),
123
+ ...(d ? { source: d.source } : {}),
124
+ ...(client ? { client } : {}),
125
+ proto: protoMinor(d?.caps),
126
+ caps: d?.caps ?? [],
127
+ ...(seen !== undefined ? { lastSeen: seen } : {}),
128
+ };
129
+ });
130
+ }
131
+ /**
132
+ * The known features one side has and the other lacks, given the caps of this client and of every
133
+ * one of the peer's devices we know of (a feature counts for them only when all of them have it).
134
+ */
135
+ export function unavailableBetween(mine, theirs) {
136
+ const all = (cap) => theirs.length > 0 && theirs.every((t) => t.includes(cap));
137
+ const theyLack = [];
138
+ const weLack = [];
139
+ // A front end's own features (receipts.v1: the mod's, per session) aren't this client's to compare.
140
+ for (const f of KNOWN_FEATURES.filter((x) => !x.session)) {
141
+ if (mine.includes(f.cap) && !all(f.cap))
142
+ theyLack.push(f.cap);
143
+ if (!mine.includes(f.cap) && theirs.length > 0 && all(f.cap))
144
+ weLack.push(f.cap);
145
+ }
146
+ return { theyLack, weLack };
147
+ }
148
+ /**
149
+ * Whether what we hold of `userId`'s client shows it lacks `feature`: its latest status (any session,
150
+ * any age) or its identity document entry lists caps, and not that one. No evidence is "no" here too:
151
+ * this is only for telling the user something, never for deciding what to send.
152
+ */
153
+ export async function peerLacks(app, userId, feature) {
154
+ const src = await sources(app, userId);
155
+ const dinfo = Object.values(src.dinfo ?? {});
156
+ if (dinfo.length > 0)
157
+ return dinfo.some((d) => !d.caps.includes(feature));
158
+ let latest;
159
+ for (const p of Object.values(src.peers))
160
+ if (p.own === userId && (!latest || p.ts > latest.ts))
161
+ latest = p;
162
+ const caps = latest?.status.caps;
163
+ return Array.isArray(caps) && !caps.includes(feature);
164
+ }