@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
package/dist/state.js ADDED
@@ -0,0 +1,220 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The CLI's own documents in `<home>/cli` (0700, 0600 files, atomic writes,
4
+ // one cross-process lock), next to the core trust store in `<home>/v3`.
5
+ // Every read-modify-write runs under the lock, so `p2p watch` and short
6
+ // commands can run at the same time.
7
+ //
8
+ // keys this device's secrets (and the identity seed on key holders)
9
+ // self name, relays, did, the default circle
10
+ // sessions own session rosters, by sid
11
+ // seq envelope sequence counters, by (own, sid)
12
+ // peers the latest status of every session heard of, by (own, sid)
13
+ // held first contacts and circle invites waiting for the user
14
+ // events the accepted-event log `watch` prints from (bounded)
15
+ // spoke which local session last spoke to a peer session
16
+ // subs notify-when-idle subscriptions
17
+ // joins circle joins waiting for confirmation answers
18
+ // transfers transfer consents received, by cid
19
+ // fetched when each contact's identity document was last refreshed
20
+ // codes short-code invites this user issued (P4), by lid
21
+ // redeemed bundles fetched with `p2p join`, by lid (a retry needs no relay: the code is single-use)
22
+ // codeJoins circles a redeemed code joins, waiting for the inviter to add us, by cid
23
+ // admits members-only relays: a redeemed code's admission key, by relay, until used
24
+ // rotations rotation statements seen from friends and co-members (§2.8), by old userId
25
+ // follows rotations of our own identity a key holder sent (with their one-time link codes), by held id
26
+ // rotationAlerts rotations of our own identity this device already alerted about
27
+ // circleHold owned circles whose changes (proposals, rotated members) wait for approval
28
+ // xstate extension state kinds (§4.3, xstate.v1): an index of senders; each sender's values (latest per
29
+ // (sid, kind)) and per-session rate windows are in a document of their own, xstate-<hash>
30
+ // xstateSent when this device last published each (sid, kind), for the sender's rate limit
31
+ // outbox sealed messages no relay accepted yet (outbox.ts), retried by watch, 7 days at most
32
+ // receipts delivery receipts (receipts.ts): ids this device asked for, messages that asked it, what it sent
33
+ // unknownKinds when each (sender, kind) of an envelope this version doesn't know was last noticed
34
+ // relayInfo the relays' /.well-known/p2p-relay.json (features and frames), as last fetched
35
+ // projects project policies (projects.ts): shared with circles and people, or private (the default)
36
+ // sessionProjects the projects each session worked in (projects.ts), by sid
37
+ // ixNotice when the one-time "Ix on by default" notice was shown (ix-local.ts)
38
+ // graphMemory graph memory (graph-memory.ts): what was recorded of each own session, the bounded queue, counters
39
+ // history, history-<n> message history (history.ts): sealed with the key in history.key, never plaintext
40
+ import { join } from "node:path";
41
+ import { FileDocBackend } from "@peer2peer/core/v3/node";
42
+ import { debug, step } from "./progress.js";
43
+ export const sessKey = (own, sid) => `${own}|${sid}`;
44
+ /** Events older than this, or beyond the count cap, are pruned. */
45
+ export const EVENT_RETENTION_MS = 7 * 24 * 3600 * 1000;
46
+ export const EVENT_MAX = 2000;
47
+ /** Back-to-back state updates from one process before it leaves other processes a gap. */
48
+ export const STATE_BURST = 8;
49
+ /** The gap: longer than FileDocBackend's longest wait between lock attempts (50 ms). */
50
+ export const STATE_YIELD_MS = 60;
51
+ export class CliState {
52
+ dir;
53
+ progress;
54
+ backend;
55
+ eventListeners = new Set();
56
+ /**
57
+ * In-process queue in front of the cross-process lock: concurrent updates from this process
58
+ * (a status going to several recipients at once) wait their turn here instead of polling the
59
+ * lock file with backoff. The lock itself is still taken for every update.
60
+ */
61
+ queue = Promise.resolve();
62
+ /** Updates queued here and not yet done. */
63
+ queued = 0;
64
+ /** Updates run back to back with more waiting (the lock went straight from one to the next). */
65
+ streak = 0;
66
+ locked(fn) {
67
+ this.queued++;
68
+ const t0 = Date.now();
69
+ const run = this.queue.then(async () => {
70
+ const waited = Date.now() - t0;
71
+ if (waited >= 10)
72
+ debug(this.progress, `state queue: waited ${waited}ms behind ${this.queued - 1} update(s) of this process`);
73
+ // Fair to other processes (pre-release review L3): the file lock is released after every update, but
74
+ // a long burst from here would win it straight back each time, while a waiter in another
75
+ // process sleeps up to 50 ms between tries. After a few in a row, leave it a gap.
76
+ if (this.streak >= STATE_BURST) {
77
+ this.streak = 0;
78
+ await new Promise((r) => setTimeout(r, STATE_YIELD_MS));
79
+ }
80
+ try {
81
+ return await this.backend.withLock(fn);
82
+ }
83
+ finally {
84
+ this.queued--;
85
+ this.streak = this.queued > 0 ? this.streak + 1 : 0;
86
+ }
87
+ });
88
+ this.queue = run.catch(() => { });
89
+ return run;
90
+ }
91
+ constructor(dir, progress,
92
+ /** `p2p doctor`: an in-memory overlay (readonly.ts), so nothing is written to `dir`. */
93
+ backend, lockOpts = {}) {
94
+ this.dir = dir;
95
+ this.progress = progress;
96
+ this.backend = backend ?? new FileDocBackend(join(dir, "cli"), lockOpts);
97
+ }
98
+ async get(name) {
99
+ return (await this.backend.read(name));
100
+ }
101
+ /** Read-modify-write under the cross-process lock. Return `undefined` as `next` to leave it. */
102
+ /**
103
+ * Runs `fn` under the state lock (the same one every update takes), for a read-modify-write of a
104
+ * file outside the state documents: config.json (config.ts updateFileConfigField).
105
+ */
106
+ withLock(fn) {
107
+ return step(this.progress, `waiting for p2p's state lock in ${this.dir} (is another p2p command running?)`, () => this.locked(fn), { noDebug: true });
108
+ }
109
+ update(name, fn) {
110
+ // The lock waits at most 10 s (then "is locked"); past 3 s it says why it is waiting.
111
+ return step(this.progress, `waiting for p2p's state lock in ${this.dir} (is another p2p command running?)`, () => this.locked(async () => {
112
+ const { next, result } = fn((await this.backend.read(name)));
113
+ if (next !== undefined)
114
+ await this.backend.write(name, next);
115
+ return result;
116
+ }), { noDebug: true });
117
+ }
118
+ /**
119
+ * update() for a decision that must await something while holding the lock
120
+ * (rosters: the trust store's putRoster, whose own lock is another file's
121
+ * and never takes this one). `fn` must not call back into this state.
122
+ */
123
+ updateAsync(name, fn) {
124
+ return step(this.progress, `waiting for p2p's state lock in ${this.dir} (is another p2p command running?)`, () => this.locked(async () => {
125
+ const { next, result } = await fn((await this.backend.read(name)));
126
+ if (next !== undefined)
127
+ await this.backend.write(name, next);
128
+ return result;
129
+ }), { noDebug: true });
130
+ }
131
+ /** A document outside the fixed set (one per key, e.g. a join answer per confirmer), read without the lock. */
132
+ async getDoc(name) {
133
+ return (await this.backend.read(name));
134
+ }
135
+ /** update() for a document outside the fixed set: only that document is rewritten. */
136
+ updateDoc(name, fn) {
137
+ return step(this.progress, `waiting for p2p's state lock in ${this.dir} (is another p2p command running?)`, () => this.locked(async () => {
138
+ const { next, result } = fn((await this.backend.read(name)));
139
+ if (next !== undefined)
140
+ await this.backend.write(name, next);
141
+ return result;
142
+ }), { noDebug: true });
143
+ }
144
+ async removeDoc(name) {
145
+ await this.locked(async () => {
146
+ if (this.backend.remove)
147
+ await this.backend.remove(name);
148
+ else
149
+ await this.backend.write(name, null);
150
+ });
151
+ }
152
+ async put(name, value) {
153
+ await this.update(name, () => ({ next: value, result: undefined }));
154
+ }
155
+ /** The next envelope seq for (own, sid) on this device. */
156
+ async nextSeq(own, sid) {
157
+ return (await this.nextSeqs(own, sid, 1))[0];
158
+ }
159
+ /**
160
+ * `count` consecutive envelope seqs for (own, sid) on this device, in one write.
161
+ *
162
+ * A missing counter starts at the clock in ms (as on main, so it lands above every window a
163
+ * receiver already holds for the session, and a lost or never-written seq.json heals); after
164
+ * that it counts up by one (review M1, third round). Jumping to the clock on every send put two
165
+ * sends a second apart ~1000 seqs apart, so an earlier envelope applied after a later one (a
166
+ * crash, a transient failure, another relay's late copy) was dropped as seq-too-old.
167
+ *
168
+ * Residual: a counter restored from a backup taken after the session's first send is behind
169
+ * seqs it already spent. Until it passes them, receivers drop its envelopes: as replays while
170
+ * within their 512-seq window, and as late envelopes (counted in `p2p doctor`) below it.
171
+ *
172
+ * One counter serves every recipient device of a send (a status fan-out takes one seq per
173
+ * device), so a receiver sees gaps of up to the number of other copies: its 512-seq window
174
+ * tolerates about 512 / (devices per send) sends of reordering, ~36 statuses at 14 copies.
175
+ */
176
+ nextSeqs(own, sid, count) {
177
+ return this.update("seq", (cur = {}) => {
178
+ const k = sessKey(own, sid);
179
+ const last = cur[k];
180
+ const first = last === undefined ? Date.now() : last + 1;
181
+ const out = Array.from({ length: count }, (_, i) => first + i);
182
+ return { next: { ...cur, [k]: first + count - 1 }, result: out };
183
+ });
184
+ }
185
+ /**
186
+ * Calls `fn` whenever this process has appended events, so `watch` prints them at once instead
187
+ * of at its next poll. Returns the unsubscribe.
188
+ */
189
+ onEventsAdded(fn) {
190
+ this.eventListeners.add(fn);
191
+ return () => this.eventListeners.delete(fn);
192
+ }
193
+ /** Appends events; returns them with their log positions. Duplicate ids are dropped. */
194
+ async addEvents(events, now = Date.now()) {
195
+ if (events.length === 0)
196
+ return [];
197
+ const added = await this.appendEvents(events, now);
198
+ if (added.length > 0)
199
+ for (const fn of [...this.eventListeners])
200
+ fn();
201
+ return added;
202
+ }
203
+ appendEvents(events, now) {
204
+ return this.update("events", (cur = { next: 1, items: [] }) => {
205
+ const seen = new Set(cur.items.map((e) => e.id));
206
+ const added = [];
207
+ let next = cur.next;
208
+ for (const e of events) {
209
+ if (seen.has(e.id))
210
+ continue;
211
+ seen.add(e.id);
212
+ added.push({ ...e, n: next++ });
213
+ }
214
+ let items = [...cur.items, ...added].filter((e) => now - e.at <= EVENT_RETENTION_MS);
215
+ if (items.length > EVENT_MAX)
216
+ items = items.slice(items.length - EVENT_MAX);
217
+ return { next: { next, items }, result: added };
218
+ });
219
+ }
220
+ }
@@ -0,0 +1,17 @@
1
+ export interface StdinLike {
2
+ isTTY?: boolean;
3
+ on(ev: "data", f: (c: Buffer | string) => void): unknown;
4
+ on(ev: "end", f: () => void): unknown;
5
+ on(ev: "error", f: (e: Error) => void): unknown;
6
+ removeAllListeners(ev?: string): unknown;
7
+ pause(): unknown;
8
+ resume(): unknown;
9
+ }
10
+ export declare const STDIN_IDLE_MS = 3000;
11
+ export declare const END_OF_INPUT_HINT = "reading from stdin\u2026 (end the input with Ctrl-D, or Ctrl-Z then Enter on Windows)";
12
+ export declare function readAll(stream: StdinLike, opts?: {
13
+ implicit?: boolean;
14
+ idleMs?: number;
15
+ hintMs?: number;
16
+ hint?: (msg: string) => void;
17
+ }): Promise<string>;
package/dist/stdin.js ADDED
@@ -0,0 +1,46 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Reading stdin without hanging silently. A shell can hand a command a stdin
4
+ // that never ends: PowerShell running an npm `.cmd`/`.ps1` shim, an IDE
5
+ // task, a CI step. So:
6
+ // - when the user didn't ask for stdin (`send` with no text), give up with
7
+ // "" if nothing arrives within `idleMs`;
8
+ // - when they did (`--stdin`, `backup restore`), keep reading, but say how to
9
+ // end the input once nothing has arrived for `hintMs`.
10
+ export const STDIN_IDLE_MS = 3000;
11
+ export const END_OF_INPUT_HINT = "reading from stdin… (end the input with Ctrl-D, or Ctrl-Z then Enter on Windows)";
12
+ export function readAll(stream, opts = {}) {
13
+ if (stream.isTTY)
14
+ return Promise.resolve("");
15
+ return new Promise((resolve, reject) => {
16
+ const chunks = [];
17
+ let got = false;
18
+ const finish = (v) => {
19
+ clearTimeout(timer);
20
+ stream.removeAllListeners("data");
21
+ stream.removeAllListeners("end");
22
+ stream.removeAllListeners("error");
23
+ stream.pause();
24
+ resolve(v);
25
+ };
26
+ const timer = setTimeout(() => {
27
+ if (got)
28
+ return;
29
+ if (opts.implicit)
30
+ finish("");
31
+ else
32
+ opts.hint?.(END_OF_INPUT_HINT);
33
+ }, opts.implicit ? (opts.idleMs ?? STDIN_IDLE_MS) : (opts.hintMs ?? STDIN_IDLE_MS));
34
+ timer.unref?.();
35
+ stream.on("data", (c) => {
36
+ got = true;
37
+ chunks.push(typeof c === "string" ? Buffer.from(c) : c);
38
+ });
39
+ stream.on("end", () => finish(Buffer.concat(chunks).toString("utf8")));
40
+ stream.on("error", (e) => {
41
+ clearTimeout(timer);
42
+ reject(e);
43
+ });
44
+ stream.resume();
45
+ });
46
+ }
package/dist/sync.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ import { type StoredCapV3, type StoredOutgoingInviteV3 } from "@peer2peer/core/v3";
2
+ import { App } from "./app.js";
3
+ export interface SyncCircle {
4
+ cid: string;
5
+ versions: string[];
6
+ statements: string[];
7
+ joinedByMe: boolean;
8
+ myN?: number;
9
+ /** The owner's removal record (StoredCircleV3.removed): it only ever holds a join, never admits one. */
10
+ removed?: string[];
11
+ }
12
+ export interface SyncBody {
13
+ friendships?: {
14
+ invite: string;
15
+ accept: string;
16
+ }[];
17
+ unfriends?: string[];
18
+ blocks?: string[];
19
+ unblocks?: string[];
20
+ petnames?: Record<string, string | null>;
21
+ capsHeld?: string[];
22
+ capsIssued?: StoredCapV3[];
23
+ outgoing?: StoredOutgoingInviteV3[];
24
+ circles?: SyncCircle[];
25
+ contacts?: string[];
26
+ defaultCircle?: string | null;
27
+ /** The default circle was set by a code join (running sessions don't move into it). */
28
+ defaultFromJoin?: string;
29
+ /** Wants this device answered (circle-ops noteAnswered): our other devices' fallback stays quiet, and budgets are shared. */
30
+ wantAnswered?: unknown[];
31
+ /** P4 short codes this user issued (CodeRecord). */
32
+ codes?: unknown[];
33
+ /**
34
+ * §2.8 step 4: our identity is rotating. `{statement, link, keyholder?}`:
35
+ * the two-part statement and a one-time link code minted by the new
36
+ * identity for this device only.
37
+ */
38
+ rotation?: unknown;
39
+ /** pre-release re-review M2: rotations this user carried over on one device (`{old, to, kind, cid?}`), so every device suspends on a later conflict. */
40
+ rotationApprovals?: unknown[];
41
+ /** A contested rotation (`{old, candidates, suspended}`): every device suspends the same identities and holds the dispute. */
42
+ rotationDispute?: unknown;
43
+ /** A dispute a key holder settled (`{old, keep, rejected}`); taken from a current key holder only. */
44
+ rotationResolved?: unknown;
45
+ }
46
+ /**
47
+ * Keeps each sync (and circle bundle) plaintext under the 64 KiB envelope cap (§1). Sealing and the
48
+ * two layers of base64 (the ciphertext, then the JWS payload) make an envelope about 16/9 of its
49
+ * plaintext, plus ~3 KiB of certificate and fields: 36 KiB came out at ~66 KB, and a long circle
50
+ * chain could no longer be sent at all (found by the soak harness). 30 KiB leaves ~9 KiB spare.
51
+ */
52
+ export declare const SYNC_CHUNK_BYTES: number;
53
+ /**
54
+ * A circle export cut into items that each fit a chunk (review M2): its versions in order, then its
55
+ * statements, each item carrying the circle's metadata. importCircle puts them back together.
56
+ */
57
+ export declare function splitCircle(c: SyncCircle, max?: number): SyncCircle[];
58
+ /** Splits a body of arrays into several bodies, each at most `max` bytes of UTF-8 JSON (single items may exceed it). */
59
+ export declare function chunkBody<T extends Record<string, unknown>>(body: T, max?: number): T[];
60
+ export declare function exportCircle(app: App, cid: string): Promise<SyncCircle | undefined>;
61
+ /**
62
+ * Takes over another store of ours' removal record (a device of ours by sync, or our old identity
63
+ * on rotation): the union of the removed members still off the head. It can only add holds: every
64
+ * former member's open re-join is held anyway (review H1, as on main).
65
+ */
66
+ export declare function mergeRemovals(app: App, cid: string, removed: readonly string[] | undefined): Promise<void>;
67
+ /** Everything a newly linked device needs (§2.4 is followed by a sync). */
68
+ export declare function exportAll(app: App): Promise<SyncBody>;
69
+ /** The store keeps outgoing invites by `inv` without a list API; read its document directly (read-only). */
70
+ export declare function listOutgoing(app: App): Promise<StoredOutgoingInviteV3[]>;
71
+ /** Sends `body` to our other devices (all of them, or `only`), chunked. */
72
+ export declare function sendSync(app: App, body: SyncBody, only?: readonly string[]): Promise<number>;
73
+ export declare function importSync(app: App, raw: Record<string, unknown>, meta?: {
74
+ fdid?: string;
75
+ }): Promise<void>;
76
+ /** A cap this user issued, from its JWS: signature and cert checked, every field taken from the payload. */
77
+ export declare function verifiedIssuedCap(app: App, jws: unknown): StoredCapV3 | undefined;