@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,57 @@
1
+ import type { Delivery } from "./app.js";
2
+ import type { CircleSummary, JoinResult, MemberRow } from "./circle-ops.js";
3
+ import type { CodeRow } from "./codes.js";
4
+ import type { DeviceRow, WhoamiResult } from "./identity.js";
5
+ import type { PeerRow, RosterView } from "./sessions.js";
6
+ import type { FriendRow } from "./social.js";
7
+ import type { RotateResult, RotationPlan } from "./rotation.js";
8
+ export declare function formatAge(sec: number): string;
9
+ export declare function formatDate(sec: number): string;
10
+ export declare function plural(n: number, one: string, many?: string): string;
11
+ export declare function formatCodes(rows: CodeRow[]): string;
12
+ /** "delivered via 2 relays (1 device)". */
13
+ export declare function formatDelivery(d: Pick<Delivery, "relays" | "devices">): string;
14
+ /** A terminal QR code of `text`; empty when it can't be rendered. */
15
+ export declare function qr(text: string): string;
16
+ export declare function formatDevices(rows: DeviceRow[]): string;
17
+ export declare function formatWhoami(r: WhoamiResult): string;
18
+ export declare function formatPeers(rows: PeerRow[]): string;
19
+ export declare function formatFriends(r: {
20
+ friends: FriendRow[];
21
+ invites: {
22
+ outgoing: {
23
+ inv: string;
24
+ aud: string;
25
+ exp: number;
26
+ }[];
27
+ held: number;
28
+ };
29
+ blocked: {
30
+ address: string;
31
+ }[];
32
+ }): string;
33
+ export declare function formatCircles(rows: CircleSummary[]): string;
34
+ export declare function formatMembers(r: {
35
+ circle: CircleSummary;
36
+ members: MemberRow[];
37
+ }): string;
38
+ export declare function formatRoster(r: RosterView): string;
39
+ export declare function formatJoin(r: JoinResult): string;
40
+ export declare function formatRotationPlan(p: RotationPlan): string;
41
+ export declare function formatRotation(r: RotateResult): string;
42
+ /**
43
+ * review M2: what any printer writes to a terminal. Strips escape sequences'
44
+ * control characters (ESC, CSI, OSC, BEL, ...) and bidi/format characters,
45
+ * keeping newlines and tabs. Applied to every human line and every
46
+ * diagnostic, whatever its source (relay replies, core rejection messages,
47
+ * peer text).
48
+ */
49
+ export declare function safeTerminal(s: unknown): string;
50
+ /**
51
+ * JSON for stdout (`--json`, `watch --jsonl`): the same data, with the
52
+ * characters JSON.stringify leaves raw but a terminal could act on (DEL, C1,
53
+ * U+2028/9, format characters) written as \u escapes.
54
+ */
55
+ export declare function safeJson(v: unknown): string;
56
+ /** Message text for a terminal: one sanitizer, a generous cap. */
57
+ export declare function terminalText(s: string): string;
package/dist/format.js ADDED
@@ -0,0 +1,248 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Human output. Pure functions over the commands' JSON results, so the
4
+ // `--json` shape and the terminal text never drift apart. Every peer string
5
+ // reaching here was already passed through the core sanitizer; message text
6
+ // (shown raw in JSON) is sanitized for the terminal here.
7
+ import { sanitizePeerText } from "@peer2peer/core/v3";
8
+ import { renderUnicodeCompact } from "uqr";
9
+ export function formatAge(sec) {
10
+ if (sec < 60)
11
+ return `${Math.max(0, Math.round(sec))}s`;
12
+ if (sec < 3600)
13
+ return `${Math.floor(sec / 60)}m`;
14
+ if (sec < 86_400)
15
+ return `${Math.floor(sec / 3600)}h`;
16
+ return `${Math.floor(sec / 86_400)}d`;
17
+ }
18
+ export function formatDate(sec) {
19
+ return new Date(sec * 1000).toISOString().slice(0, 10);
20
+ }
21
+ export function plural(n, one, many = `${one}s`) {
22
+ return `${n} ${n === 1 ? one : many}`;
23
+ }
24
+ export function formatCodes(rows) {
25
+ if (rows.length === 0)
26
+ return "No invite codes. Make one: p2p invite <label>";
27
+ const now = Date.now() / 1000;
28
+ return rows
29
+ .map((r) => {
30
+ const who = r.label ? ` ${r.label}` : "";
31
+ const circle = r.circle ? ` +circle "${r.circle.name}"` : "";
32
+ const to = r.to ? ` (only ${r.to.address})` : "";
33
+ let st;
34
+ switch (r.status) {
35
+ case "open":
36
+ st = `open, ${plural(Math.max(1, Math.round((r.exp - now) / 86_400)), "day")} left`;
37
+ break;
38
+ case "evicted":
39
+ st = "evicted by the relay (it was full): make a new code";
40
+ break;
41
+ case "taken":
42
+ st = "TAKEN, but nobody joined yet: if that wasn't them, `p2p invites revoke` refuses the join";
43
+ break;
44
+ case "redeemed":
45
+ st = `redeemed by ${r.redeemedBy?.address ?? "?"} (not them? p2p remove ${r.redeemedBy?.userId ?? ""})`;
46
+ break;
47
+ default:
48
+ st = r.status;
49
+ }
50
+ const shown = r.status === "open" || r.status === "taken" ? r.code : r.code.replace(/[^/]*$/, (c) => `${c.slice(0, 4)}…`);
51
+ return `${shown}${who}${circle}${to}: ${st}`;
52
+ })
53
+ .join("\n");
54
+ }
55
+ /** "delivered via 2 relays (1 device)". */
56
+ export function formatDelivery(d) {
57
+ return `delivered via ${plural(d.relays.length, "relay")} (${plural(d.devices, "device")})`;
58
+ }
59
+ /** A terminal QR code of `text`; empty when it can't be rendered. */
60
+ export function qr(text) {
61
+ try {
62
+ return renderUnicodeCompact(text, { border: 1, ecc: "L" });
63
+ }
64
+ catch {
65
+ return "";
66
+ }
67
+ }
68
+ function table(rows) {
69
+ if (rows.length === 0)
70
+ return "";
71
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => [...(r[i] ?? "")].length)));
72
+ return rows.map((r) => r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(widths[i]))).join(" ").trimEnd()).join("\n");
73
+ }
74
+ export function formatDevices(rows) {
75
+ return table([
76
+ ["DEVICE", "LABEL", "ROLE", "CERT EXPIRES"],
77
+ ...rows.map((d) => [`${d.did}${d.thisDevice ? " *" : ""}`, d.label || "-", d.keyholder ? "key holder" : "device", d.certExp ? formatDate(d.certExp) : "-"]),
78
+ ]);
79
+ }
80
+ export function formatWhoami(r) {
81
+ const lines = [
82
+ `${r.address}`,
83
+ ` userId ${r.userId}`,
84
+ ` fingerprint ${r.fingerprint}`,
85
+ ` this device ${r.did}${r.keyholder ? " (key holder)" : ""}`,
86
+ ` relays ${r.relays.join(", ")}`,
87
+ ` document version ${r.doc.ver}, expires ${formatDate(r.doc.exp)}${r.doc.freshness !== "fresh" ? ` (${r.doc.freshness}, ${r.doc.daysPastExp} days past)` : ""}${r.doc.forked ? ", forked" : ""}`,
88
+ ];
89
+ if (r.profile.bio)
90
+ lines.push(` bio ${r.profile.bio}`);
91
+ if (r.profile.links.length > 0)
92
+ lines.push(` links ${r.profile.links.join(" ")}`);
93
+ if (r.defaultCircle)
94
+ lines.push(` circle ${r.defaultCircle} (default)`);
95
+ lines.push("", formatDevices(r.devices));
96
+ for (const w of r.warnings)
97
+ lines.push("", `! ${w}`);
98
+ return lines.join("\n");
99
+ }
100
+ export function formatPeers(rows) {
101
+ if (rows.length === 0)
102
+ return "No live sessions. Friends' and circle-mates' sessions appear here once they post a status.";
103
+ const out = [];
104
+ for (const r of rows) {
105
+ const who = r.self ? `${r.address} (you${r.thisDevice ? ", this device" : ""})` : r.address;
106
+ const where = [r.repo, r.branch].filter(Boolean).join("@");
107
+ out.push(`${r.live ? (r.state === "busy" ? "●" : "○") : "·"} ${who} [${r.ref}] ${r.label} ${r.state}${where ? ` ${where}` : ""} ${formatAge(r.ageSec)} ago${r.live ? "" : " (stale)"}`);
108
+ if (r.summary)
109
+ out.push(` ${r.summary}`);
110
+ if (r.files.length > 0)
111
+ out.push(` files: ${r.files.slice(0, 8).join(", ")}${r.files.length > 8 ? ` +${r.files.length - 8}` : ""}`);
112
+ // Validated by displayStatus: ids, types and states are of strict charsets, tasks and files one sanitized line.
113
+ for (const a of r.agents ?? []) {
114
+ const where = [a.state, a.wt ? `worktree${a.branch ? ` ${a.branch}` : ""}` : ""].filter(Boolean).join(", ");
115
+ const files = a.files?.length ? `: ${a.files.slice(0, 4).join(", ")}${a.files.length > 4 ? ` +${a.files.length - 4}` : ""}` : "";
116
+ out.push(` ${a.parent ? ` ${a.id} (of ${a.parent})` : a.id} ${a.type} "${a.task}" (${where})${files}`);
117
+ }
118
+ // Extension state (§4.3): only its sanitized fallback line, never a body.
119
+ for (const x of r.xstate ?? [])
120
+ out.push(` ${x.kind}: ${x.fallback}`);
121
+ }
122
+ return out.join("\n");
123
+ }
124
+ export function formatFriends(r) {
125
+ const out = [];
126
+ if (r.friends.length === 0)
127
+ out.push("No friends yet: `p2p invite` makes a link to send someone.");
128
+ else {
129
+ out.push(table([
130
+ ["FRIEND", "SINCE", "STATUS"],
131
+ ...r.friends.map((f) => [f.address, formatDate(f.since), f.canMessage ? "connected" : "waiting for their cap"]),
132
+ ]));
133
+ }
134
+ if (r.invites.outgoing.length > 0)
135
+ out.push("", `${plural(r.invites.outgoing.length, "open invite")} (yours, not yet accepted)`);
136
+ if (r.invites.held > 0)
137
+ out.push("", `${plural(r.invites.held, "held item")} waiting for you: \`p2p held\``);
138
+ if (r.blocked.length > 0)
139
+ out.push("", `blocked: ${r.blocked.map((b) => b.address).join(", ")}`);
140
+ return out.join("\n");
141
+ }
142
+ export function formatCircles(rows) {
143
+ if (rows.length === 0)
144
+ return "No circles: `p2p circle create <name>` or `p2p circle join <link>`.";
145
+ return table([
146
+ ["CIRCLE", "NAME", "ROLE", "MEMBERS", "POLICY", "OWNER"],
147
+ ...rows.map((c) => [
148
+ `${c.cid}${c.isDefault ? " *" : ""}`,
149
+ c.name,
150
+ c.frozen ? `${c.role} (frozen)` : c.role,
151
+ `${c.standing}/${c.members}`,
152
+ c.policy,
153
+ c.ownerAddress,
154
+ ]),
155
+ ]);
156
+ }
157
+ export function formatMembers(r) {
158
+ const head = `${r.circle.name} (${r.circle.cid}), version ${r.circle.ver}, ${r.circle.policy}${r.circle.policy === "open" ? ": anyone with the link can join" : ""}`;
159
+ return [
160
+ head,
161
+ table([
162
+ ["MEMBER", "ROLE", "STANDING"],
163
+ ...r.members.map((m) => [`${m.address}${m.self ? " (you)" : ""}`, m.owner ? "owner" : m.admin ? "admin" : "member", m.stands ? "stands" : m.statement === "leave" ? "left" : "not joined yet"]),
164
+ ]),
165
+ ].join("\n");
166
+ }
167
+ export function formatRoster(r) {
168
+ const who = r.vis === "circle" ? `circle ${r.circleName ?? r.circle}${r.parts.length ? ` + ${r.parts.map((p) => p.address).join(", ")}` : ""}` : r.parts.length ? r.parts.map((p) => p.address).join(", ") : "nobody else (private)";
169
+ return `session ${r.sid} [${r.ref}] v${r.ver}: shared with ${who}${r.openCircle ? "\n! this circle is open: anyone the owner admits sees this session" : ""}`;
170
+ }
171
+ export function formatJoin(r) {
172
+ const owner = r.ownershipChanged ? `owner ${r.ownerAddress} (founded by ${r.founder})` : `owner ${r.ownerAddress}`;
173
+ switch (r.status) {
174
+ case "joined":
175
+ return `Joined "${r.name}" (${r.cid}), ${owner}.${r.confirmation === "owner-only" ? " Confirmed with the owner (no other member to ask)." : r.confirmation === "unconfirmed" ? " Joined without a second confirmation, as you chose." : " Confirmed with the owner and another member."}${r.openWarning ? "\nThis circle is open: anyone with its link can join." : ""}`;
176
+ case "waiting":
177
+ return `Asked ${r.asked.length || "the owner"} for "${r.name}"'s history; no answer yet. Run the same command again once they've been online (or wait with --wait <seconds>).`;
178
+ case "unconfirmed":
179
+ return `Couldn't confirm "${r.name}" with a second member. Run again with --yes to join anyway.`;
180
+ case "already":
181
+ return `You're already in "${r.name}" (${r.cid}).`;
182
+ case "refused":
183
+ return `Not joined "${r.name}" (${r.cid}): ${r.refused}.`;
184
+ }
185
+ }
186
+ export function formatRotationPlan(p) {
187
+ // A label from a version this device didn't publish is shown as such (pre-release re-review N2), and so is why a device is dropped.
188
+ const dev = (d) => ` ${d.did}${d.label ? ` (${d.labelTrusted === false ? "unverified label: " : ""}${sanitizePeerText(d.label, 64)})` : ""}${d.keyholder ? ", key holder" : ""}${d.why ? `: DROPPED, ${d.why} (keep it with --keep ${d.did})` : ""}`;
189
+ return [
190
+ `${p.contest ? "Contesting a rotation you didn't publish: moving" : "Rotating"} ${p.address} to a new identity key ${p.newFingerprint} (§2.8).`,
191
+ ...(p.backup ? [`Its backup phrase is in ${p.backup.file}.`] : []),
192
+ p.follow.length ? `These devices get the rotation to follow (each follows only when you accept it there):\n${p.follow.map(dev).join("\n")}` : "No other device follows.",
193
+ ...(p.excluded.length ? [`These devices do NOT follow (excluded):\n${p.excluded.map(dev).join("\n")}`] : []),
194
+ `${plural(p.friends, "friend")} get a fresh invite (they approve it); ${plural(p.owned, "circle")} you own move to the new key; in ${plural(p.memberOf, "other circle")} the owner swaps you in.`,
195
+ // pre-release re-review M1: friendships this device can't vouch for are invited only when the user says so.
196
+ ...((p.friendsOptIn ?? []).length
197
+ ? [
198
+ `These friends are NOT invited unless you say so (a thief's device may have made them):\n${p.friendsOptIn
199
+ .map((f) => ` ${sanitizePeerText(f.address ?? f.userId, 96)}: ${f.why}${f.invited ? " [INVITED: you chose to]" : ` (invite with --invite ${f.userId})`}`)
200
+ .join("\n")}`,
201
+ ]
202
+ : []),
203
+ "A lost or stolen device listed above must be dropped (--exclude <did>): it is revoked before any code goes out. Last, your old identity publishes a final version with no devices.",
204
+ ].join("\n");
205
+ }
206
+ export function formatRotation(r) {
207
+ const lines = [`Your identity is now ${r.address} (was ${r.from}); old identity final version ${r.finalVer ?? "?"}.`];
208
+ if (r.devices.followed.length)
209
+ lines.push(`Followed: ${r.devices.followed.map((d) => d.label || d.did).join(", ")}.`);
210
+ if (r.devices.offline.length)
211
+ lines.push(`Didn't follow (re-link each with \`p2p link join <code> --rotated\`): ${r.devices.offline.map((d) => d.label || d.did).join(", ")}.`);
212
+ lines.push(`Friends invited: ${r.friends.invited}${r.friends.failed.length ? `; not reached: ${r.friends.failed.length} (they can join a fresh code from you)` : ""}.`);
213
+ for (const c of r.circles)
214
+ lines.push(` circle "${sanitizePeerText(c.name, 64)}" (${c.cid}): ${c.role === "owner" ? "handed to the new key" : "join sent to the owner"}${c.status === "done" ? "" : ` [${c.status}${c.reason ? `: ${c.reason}` : ""}]`}`);
215
+ for (const p of r.proofs)
216
+ lines.push(`Proof ${p.kind}: ${p.claim}. ${p.publish}`);
217
+ if (r.backup)
218
+ lines.push(`New backup phrase saved to ${r.backup.file}: copy it somewhere safe, then delete the file. The old phrase no longer works.`);
219
+ return lines.join("\n");
220
+ }
221
+ // Everything but tab and newline that a terminal could act on: C0, DEL, C1
222
+ // (incl. 8-bit CSI/OSC), U+2028/9, format characters (bidi overrides), lone surrogates.
223
+ const TERMINAL_UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029\p{Cf}]|\p{Cs}/gu;
224
+ /**
225
+ * review M2: what any printer writes to a terminal. Strips escape sequences'
226
+ * control characters (ESC, CSI, OSC, BEL, ...) and bidi/format characters,
227
+ * keeping newlines and tabs. Applied to every human line and every
228
+ * diagnostic, whatever its source (relay replies, core rejection messages,
229
+ * peer text).
230
+ */
231
+ export function safeTerminal(s) {
232
+ return String(s).replace(TERMINAL_UNSAFE, "");
233
+ }
234
+ /**
235
+ * JSON for stdout (`--json`, `watch --jsonl`): the same data, with the
236
+ * characters JSON.stringify leaves raw but a terminal could act on (DEL, C1,
237
+ * U+2028/9, format characters) written as \u escapes.
238
+ */
239
+ export function safeJson(v) {
240
+ return JSON.stringify(v).replace(/[\u007f-\u009f\u2028\u2029\p{Cf}]/gu, (c) => c
241
+ .split("")
242
+ .map((u) => `\\u${u.charCodeAt(0).toString(16).padStart(4, "0")}`)
243
+ .join(""));
244
+ }
245
+ /** Message text for a terminal: one sanitizer, a generous cap. */
246
+ export function terminalText(s) {
247
+ return sanitizePeerText(s, 4000);
248
+ }
@@ -0,0 +1,107 @@
1
+ import type { App } from "./app.js";
2
+ import { type ExtMemory, type ExtMemoryItem, type ExtMemoryUnavailable, type P2PExtension } from "./extensions.js";
3
+ import { type GraphTarget } from "./projects.js";
4
+ import type { PeerStatusRec } from "./state.js";
5
+ /** How often `p2p watch` gathers and drains (P2P_IX_MEMORY_TICK_MS, 1-60 s, for tests). */
6
+ export declare const GRAPH_MEMORY_TICK_MS = 5000;
7
+ /** At most this many items wait; past it, new ones are dropped (counted as `queue_full`). */
8
+ export declare const GRAPH_MEMORY_QUEUE_MAX = 64;
9
+ /** At most this many items are handed over in one drain. */
10
+ export declare const GRAPH_MEMORY_BATCH = 16;
11
+ /** At most this many sessions are tracked (the oldest ended ones go first). */
12
+ export declare const GRAPH_MEMORY_SESSIONS_MAX = 64;
13
+ /** At most this many files are remembered as recorded per session. */
14
+ export declare const GRAPH_MEMORY_FILES_MAX = 200;
15
+ /** A session first seen with no status newer than this isn't recorded (one from before an upgrade). */
16
+ export declare const GRAPH_MEMORY_FRESH_MS: number;
17
+ /** While memory is unavailable, it is asked again this often (Ix installed or upgraded meanwhile). */
18
+ export declare const GRAPH_MEMORY_RECHECK_MS: number;
19
+ /** One drain gives up waiting on the extension after this long (its `ix` calls are bounded too). */
20
+ export declare const GRAPH_MEMORY_DRAIN_MS = 120000;
21
+ export type GraphMemoryItem = ExtMemoryItem & {
22
+ sid: string;
23
+ };
24
+ export interface GraphMemorySession {
25
+ /** When the session's start was queued (ms). */
26
+ start: number;
27
+ /** The last status one-liner queued. */
28
+ summary?: string;
29
+ /** Files already queued (capped). */
30
+ files: string[];
31
+ /** When its end was queued. */
32
+ ended?: number;
33
+ }
34
+ export interface GraphMemoryDoc {
35
+ v: 1;
36
+ sessions: Record<string, GraphMemorySession>;
37
+ queue: GraphMemoryItem[];
38
+ /** Items written to the local graph. */
39
+ written: number;
40
+ /** Items dropped, by reason (queue_full, not_local, ix_failed, ix_timeout, graph_target, ix_unconfirmed, …). */
41
+ dropped: Record<string, number>;
42
+ lastWriteAt?: number;
43
+ lastDropAt?: number;
44
+ /** Why memory is off now (no Ix, an Ix without local notes, Ix Pro), as the extension said it. */
45
+ unavailable?: {
46
+ reason: string;
47
+ message: string;
48
+ at: number;
49
+ };
50
+ /**
51
+ * Sessions a drain is writing now, until when (ms): one writer per session at a time, across
52
+ * every process (take() skips them), so a session's record is never created twice.
53
+ */
54
+ leases?: Record<string, number>;
55
+ }
56
+ /**
57
+ * What changed in this device's own sessions since the last look, as items, queued (pure, for
58
+ * tests: `ended` says whether a session's watch is gone). Returns the next doc and how many were
59
+ * queued and dropped. Only sessions `recordable` says yes to are gathered: a session whose project
60
+ * ceiling isn't shared (a private or unmapped project, `.p2p-private`, not bound yet) is never
61
+ * recorded, and one that becomes so stops being recorded (fail closed: its context never reaches a
62
+ * graph that a shared session's agent could read and pass on).
63
+ */
64
+ export declare function gather(doc: GraphMemoryDoc, recs: readonly PeerStatusRec[], ended: (sid: string) => boolean, now?: number, recordable?: (sid: string) => boolean): {
65
+ doc: GraphMemoryDoc;
66
+ queued: number;
67
+ dropped: number;
68
+ };
69
+ /** Gathers and queues what changed (under the state lock). */
70
+ export declare function gatherGraphMemory(app: App, now?: number): Promise<{
71
+ queued: number;
72
+ dropped: number;
73
+ }>;
74
+ export interface DrainDeps {
75
+ /** The graph target of a session's batch (default: the chokepoint, projects.ts graphTarget). */
76
+ target?: (sid: string) => Promise<GraphTarget>;
77
+ log?: (msg: string) => void;
78
+ /** One session's time to write (tests); default GRAPH_MEMORY_DRAIN_MS. */
79
+ deadlineMs?: number;
80
+ /** After the abort, how long to wait for the writer to settle (tests); default GRAPH_MEMORY_SETTLE_MS. */
81
+ settleMs?: number;
82
+ }
83
+ /** After a timed-out batch is aborted, how long the drain waits for the writer to settle before giving up on it. */
84
+ export declare const GRAPH_MEMORY_SETTLE_MS = 30000;
85
+ /** How long a session's lease lasts: past every drain's own bound, then free again (a crashed writer). */
86
+ export declare const GRAPH_MEMORY_LEASE_MS: number;
87
+ /**
88
+ * Hands the next batch to the extension, a session at a time. A session whose graph target isn't
89
+ * local is never handed over: its items are dropped as `not_local`. Returns what happened.
90
+ */
91
+ export declare function drainGraphMemory(app: App, ext: P2PExtension, mem: ExtMemory, deps?: DrainDeps): Promise<{
92
+ written: number;
93
+ dropped: number;
94
+ unavailable?: ExtMemoryUnavailable;
95
+ }>;
96
+ /** The tick interval (P2P_IX_MEMORY_TICK_MS, 1-60 s). */
97
+ export declare function graphMemoryTickMs(env: Record<string, string | undefined>): number;
98
+ /**
99
+ * The loop `p2p watch` runs: `tick()` gathers and drains when memory is on and available (asked of
100
+ * the extension at most every GRAPH_MEMORY_RECHECK_MS while it isn't). Never throws; one tick at a
101
+ * time.
102
+ */
103
+ export declare function graphMemoryLoop(app: App, deps?: DrainDeps): {
104
+ tick(): Promise<void>;
105
+ };
106
+ /** What `p2p doctor` says about graph memory (undefined: nothing recorded yet). */
107
+ export declare function graphMemoryReport(app: App): Promise<GraphMemoryDoc | undefined>;