@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,8 @@
1
+ export declare class CliError extends Error {
2
+ readonly code: string;
3
+ readonly extra: Record<string, unknown>;
4
+ constructor(code: string, message: string, extra?: Record<string, unknown>);
5
+ }
6
+ export declare function usage(message: string): CliError;
7
+ /** `{error, reason}` for any failure (plus the CliError's extra fields). */
8
+ export declare function toErrorJson(err: unknown): Record<string, unknown>;
package/dist/errors.js ADDED
@@ -0,0 +1,29 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // One error type for everything the CLI reports. `code` is the machine
4
+ // readable `error` of `--json` output; core rejections keep their reason.
5
+ import { P2PError } from "@peer2peer/core/v3";
6
+ export class CliError extends Error {
7
+ code;
8
+ extra;
9
+ constructor(code, message, extra = {}) {
10
+ super(message);
11
+ this.code = code;
12
+ this.extra = extra;
13
+ this.name = "CliError";
14
+ }
15
+ }
16
+ export function usage(message) {
17
+ return new CliError("usage", message);
18
+ }
19
+ /** `{error, reason}` for any failure (plus the CliError's extra fields). */
20
+ export function toErrorJson(err) {
21
+ if (err instanceof CliError)
22
+ return { error: err.code, reason: err.message, ...err.extra };
23
+ if (err instanceof P2PError)
24
+ return { error: err.reason, reason: err.message };
25
+ const e = err;
26
+ if (e && typeof e.message === "string")
27
+ return { error: "internal", reason: e.message };
28
+ return { error: "internal", reason: String(err) };
29
+ }
@@ -0,0 +1,32 @@
1
+ import type { Command } from "commander";
2
+ import type { App, Io } from "./app.js";
3
+ import { type ExtContext, type ExtensionRegistry, type P2PExtension } from "./extensions.js";
4
+ export declare const IX_INSTALL_HINT = "https://github.com/ix-infrastructure/Ix";
5
+ export declare function extContext(app: App, ext: P2PExtension, io: Io, json: boolean, confirm: (q: string, yes?: boolean) => Promise<boolean>): ExtContext;
6
+ /** ExtContext.kv: <home>/ext/<ns>.json, written atomically, 0600. */
7
+ export declare const MAX_EXT_STORE_BYTES: number;
8
+ /**
9
+ * The directory extension commands treat as the user's working directory (the
10
+ * repo an Ix command looks at): P2P_WORKDIR when it names an existing absolute
11
+ * directory, else the process's. A client that runs `p2p` from elsewhere (the
12
+ * Claude mod runs it from the plugin folder) passes the session's directory here.
13
+ */
14
+ export declare function extWorkdir(env: Record<string, string | undefined>): string;
15
+ type RunFn = <A extends unknown[]>(fn: (app: App, ...args: A) => Promise<{
16
+ json: unknown;
17
+ human: string;
18
+ }>, opts?: {
19
+ requireIdentity?: boolean;
20
+ }) => (...args: A) => Promise<void>;
21
+ /**
22
+ * Adds `p2p <ns> …` for every loaded extension with commands, a stub for each
23
+ * registered namespace that isn't installed (it explains how to get it), and
24
+ * `p2p extensions`.
25
+ */
26
+ export declare function registerExtensionCommands(program: Command, reg: ExtensionRegistry, deps: {
27
+ io: Io;
28
+ run: RunFn;
29
+ confirm: (q: string, yes?: boolean) => Promise<boolean>;
30
+ collect: (v: string, prev?: string[]) => string[];
31
+ }): void;
32
+ export {};
@@ -0,0 +1,259 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The host side of the extension seam (extensions.ts): the ExtContext a
4
+ // command of an extension runs with, and the `p2p <ns> …` commands built from
5
+ // its declarations. An extension sees only this context: it can send kinds of
6
+ // its own namespace through the ordinary session path (§4.2 decides who may
7
+ // receive them), read the events it rendered, and read the local status
8
+ // table. It never sees keys or the trust store.
9
+ import { createHash, createHmac } from "node:crypto";
10
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { displayStatus, sanitizePeerText } from "@peer2peer/core/v3";
13
+ import { CliError } from "./errors.js";
14
+ import { enabledNamespaces, extensionPackageName, kindNamespace, KNOWN_EXTENSIONS, setExtensionEnabled, } from "./extensions.js";
15
+ import { sessionWorkdir } from "./projects.js";
16
+ import { listPeers, sendExtension, sessionAudience, sessionRef } from "./sessions.js";
17
+ import { sessKey } from "./state.js";
18
+ import { declaredState, expiresAt, keptCopy, liveStates, publishExtensionState } from "./xstate.js";
19
+ /** ExtContext.localMac: HMAC-SHA256 keyed by sha256(label, namespace, this device's signing secret). */
20
+ function localMac(app, ns, data) {
21
+ const secret = app.device?.signingSecretKey;
22
+ if (!secret)
23
+ throw new CliError("no_identity", "no identity here yet: run `p2p init`");
24
+ const key = createHash("sha256").update("p2p/ext-local-mac/v1|").update(ns).update("|").update(secret).digest();
25
+ return createHmac("sha256", key).update(data, "utf8").digest("base64url");
26
+ }
27
+ export const IX_INSTALL_HINT = "https://github.com/ix-infrastructure/Ix";
28
+ function stateValue(r) {
29
+ const body = keptCopy(r.body);
30
+ return { v: r.v, ...(body !== undefined ? { body } : {}), fallback: r.fallback, at: r.ts, expiresAt: expiresAt(r), ...(r.extError ? { extError: r.extError } : {}) };
31
+ }
32
+ function toExtEvent(e) {
33
+ const d = e.data;
34
+ return {
35
+ id: e.id,
36
+ at: e.at,
37
+ kind: String(d.ext),
38
+ from: { userId: String(d.from?.userId ?? ""), address: String(d.from?.address ?? ""), self: d.from?.self === true },
39
+ ...(e.own ? { own: e.own } : {}),
40
+ ...(e.sid ? { sid: e.sid } : {}),
41
+ ...(typeof d.ref === "string" ? { ref: d.ref } : {}),
42
+ fallback: String(d.fallback ?? ""),
43
+ ...(d.rendered && typeof d.rendered === "object" ? { rendered: d.rendered } : {}),
44
+ ...(d._kept && typeof d._kept === "object" ? { kept: d._kept } : {}),
45
+ ...(typeof d.extError === "string" ? { extError: d.extError } : {}),
46
+ };
47
+ }
48
+ export function extContext(app, ext, io, json, confirm) {
49
+ return {
50
+ env: app.env,
51
+ cwd: extWorkdir(app.env),
52
+ io: { err: (s) => io.err(s), ...(io.readStdin ? { readStdin: io.readStdin } : {}) },
53
+ json,
54
+ interactive: !json && io.prompt !== undefined,
55
+ kv: extStore(app.home, ext.ns),
56
+ confirm: (q, yes) => (json && !yes ? Promise.resolve(false) : confirm(q, yes)),
57
+ self: async () => ({ userId: app.userId, address: await app.addressOf(app.userId) }),
58
+ send: async (o) => {
59
+ if (kindNamespace(o.kind) !== ext.ns)
60
+ throw new CliError("usage", `${ext.name} may only send x:${ext.ns}.* kinds`);
61
+ if (ext.state?.[o.kind])
62
+ throw new CliError("usage", `${o.kind} is a state kind: publish it (to the session's status audience), don't send it`);
63
+ return sendExtension(app, { ...o, kind: o.kind });
64
+ },
65
+ publish: async (o) => {
66
+ if (kindNamespace(o.kind) !== ext.ns)
67
+ throw new CliError("usage", `${ext.name} may only publish x:${ext.ns}.* kinds`);
68
+ const decl = ext.state?.[o.kind] ? declaredState(app.extensions, o.kind) : undefined;
69
+ if (!decl)
70
+ throw new CliError("usage", `${o.kind} isn't one of ${ext.name}'s state kinds`);
71
+ return publishExtensionState(app, { fromSession: o.fromSession, kind: o.kind, v: o.v, body: o.body, fallback: o.fallback, ttl: o.ttl ?? decl.ttl });
72
+ },
73
+ peerState: async (kind) => {
74
+ if (kindNamespace(kind) !== ext.ns)
75
+ throw new CliError("usage", `${ext.name} may only read x:${ext.ns}.* state`);
76
+ await app.connectAndDrain().catch((e) => io.err(`p2p: offline: ${sanitizePeerText(e.message, 200)}`));
77
+ const blocks = new Set((await app.store.listBlocks()).map((b) => b.userId));
78
+ const out = [];
79
+ for (const r of await liveStates(app, { kind })) {
80
+ if (blocks.has(r.own))
81
+ continue;
82
+ out.push({ own: r.own, sid: r.sid, ref: sessionRef(r.own, r.sid), address: await app.addressOf(r.own), self: r.own === app.userId, thisDevice: r.own === app.userId && r.did === app.did, kind: r.kind, ...stateValue(r) });
83
+ }
84
+ return out;
85
+ },
86
+ events: async (filter = {}) => {
87
+ const log = (await app.state.get("events"))?.items ?? [];
88
+ return log
89
+ .filter((e) => e.kind === "p2p.ext" && kindNamespace(String(e.data.ext)) === ext.ns)
90
+ .filter((e) => (filter.id === undefined || e.id === filter.id) && (filter.kind === undefined || e.data.ext === filter.kind))
91
+ .map(toExtEvent);
92
+ },
93
+ peers: async (opts = {}) => {
94
+ await app.connectAndDrain().catch((e) => io.err(`p2p: offline: ${sanitizePeerText(e.message, 200)}`));
95
+ const rows = await listPeers(app, { all: opts.all });
96
+ const states = await liveStates(app, { ns: ext.ns });
97
+ return rows.map((r) => {
98
+ const mine = states.filter((x) => x.own === r.own && x.sid === r.sid);
99
+ return {
100
+ own: r.own,
101
+ sid: r.sid,
102
+ ref: r.ref,
103
+ address: r.address,
104
+ self: r.self,
105
+ thisDevice: r.thisDevice,
106
+ live: r.live,
107
+ state: r.state,
108
+ label: r.label,
109
+ ...(r.repo ? { repo: r.repo } : {}),
110
+ ...(r.branch ? { branch: r.branch } : {}),
111
+ files: r.files,
112
+ ...(r.caps ? { caps: [...r.caps] } : {}),
113
+ ...(r.agents ? { agents: r.agents.map((a) => ({ ...a, ...(a.files ? { files: [...a.files] } : {}) })) } : {}),
114
+ ...(mine.length > 0 ? { xstate: Object.fromEntries(mine.map((x) => [x.kind, stateValue(x)])) } : {}),
115
+ };
116
+ });
117
+ },
118
+ audience: (sid) => sessionAudience(app, sid),
119
+ localMac: (data) => localMac(app, ext.ns, data),
120
+ ownStatus: async (sid) => {
121
+ const rec = (await app.state.get("peers"))?.[sessKey(app.userId, sid)];
122
+ if (!rec)
123
+ return undefined;
124
+ // Through displayStatus, as peers() is: the same validation and copies, never the stored objects.
125
+ const d = displayStatus(rec.status);
126
+ return { ...(rec.status.repo ? { repo: rec.status.repo } : {}), files: rec.status.files ?? [], ...(d.caps ? { caps: d.caps } : {}), ...(d.agents ? { agents: d.agents } : {}) };
127
+ },
128
+ };
129
+ }
130
+ /** ExtContext.kv: <home>/ext/<ns>.json, written atomically, 0600. */
131
+ export const MAX_EXT_STORE_BYTES = 64 * 1024;
132
+ function extStore(home, ns) {
133
+ const dir = join(home, "ext");
134
+ const file = join(dir, `${ns}.json`);
135
+ const read = () => {
136
+ try {
137
+ const v = JSON.parse(readFileSync(file, "utf8"));
138
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
139
+ }
140
+ catch {
141
+ return {};
142
+ }
143
+ };
144
+ return {
145
+ get: async (key) => read()[key],
146
+ set: async (key, value) => {
147
+ const next = JSON.stringify({ ...read(), [key]: value });
148
+ if (Buffer.byteLength(next, "utf8") > MAX_EXT_STORE_BYTES)
149
+ throw new CliError("too_large", `the ${ns} extension's store would exceed ${MAX_EXT_STORE_BYTES} bytes`);
150
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
151
+ const tmp = `${file}.${process.pid}.tmp`;
152
+ writeFileSync(tmp, next, { mode: 0o600 });
153
+ renameSync(tmp, file);
154
+ },
155
+ };
156
+ }
157
+ /**
158
+ * The directory extension commands treat as the user's working directory (the
159
+ * repo an Ix command looks at): P2P_WORKDIR when it names an existing absolute
160
+ * directory, else the process's. A client that runs `p2p` from elsewhere (the
161
+ * Claude mod runs it from the plugin folder) passes the session's directory here.
162
+ */
163
+ export function extWorkdir(env) {
164
+ return sessionWorkdir(env);
165
+ }
166
+ /** An error an extension threw, as a CliError (extensions can't share our class: duck-typed `code`). */
167
+ function asCliError(e) {
168
+ if (e instanceof CliError)
169
+ return e;
170
+ const x = e;
171
+ if (x && typeof x.code === "string" && /^[a-z][a-z0-9_]{0,39}$/.test(x.code) && typeof x.message === "string") {
172
+ return new CliError(x.code, x.message, x.extra && typeof x.extra === "object" ? x.extra : {});
173
+ }
174
+ return e;
175
+ }
176
+ /**
177
+ * Adds `p2p <ns> …` for every loaded extension with commands, a stub for each
178
+ * registered namespace that isn't installed (it explains how to get it), and
179
+ * `p2p extensions`.
180
+ */
181
+ export function registerExtensionCommands(program, reg, deps) {
182
+ const taken = (name) => program.commands.some((c) => c.name() === name);
183
+ for (const { ext } of reg.list()) {
184
+ if (!ext.commands?.length || taken(ext.ns))
185
+ continue;
186
+ const group = program.command(ext.ns).description(sanitizePeerText(ext.description ?? `${ext.name} ${ext.version}`, 200));
187
+ for (const c of ext.commands) {
188
+ const cmd = group.command(c.args ? `${c.name} ${c.args}` : c.name).description(sanitizePeerText(c.description, 300));
189
+ for (const o of c.options ?? []) {
190
+ if (o.repeatable)
191
+ cmd.option(o.flags, o.description, deps.collect);
192
+ else if (o.default !== undefined)
193
+ cmd.option(o.flags, o.description, o.default);
194
+ else
195
+ cmd.option(o.flags, o.description);
196
+ }
197
+ cmd.option("--json", "JSON output");
198
+ cmd.action(deps.run(async (app, ...rest) => {
199
+ const command = rest[rest.length - 1];
200
+ const opts = (rest[rest.length - 2] ?? {});
201
+ const args = rest.slice(0, -2);
202
+ try {
203
+ return await c.run(extContext(app, ext, deps.io, Boolean(command.opts().json), deps.confirm), args, opts);
204
+ }
205
+ catch (e) {
206
+ throw asCliError(e);
207
+ }
208
+ }));
209
+ }
210
+ }
211
+ for (const ns of KNOWN_EXTENSIONS) {
212
+ if (reg.get(ns) || taken(ns))
213
+ continue;
214
+ const pkg = extensionPackageName(ns);
215
+ const how = `npm i -g ${pkg}${ns === "ix" ? ` (and Ix itself: ${IX_INSTALL_HINT})` : ""}, then \`p2p extensions enable ${ns}\` (extensions run with your identity: install only ones you trust)`;
216
+ program
217
+ .command(ns)
218
+ .description(`(not enabled) the ${ns} extension: ${how}`)
219
+ .argument("[args...]")
220
+ .allowUnknownOption()
221
+ .helpOption(false)
222
+ .option("--json", "JSON output")
223
+ .action(deps.run(async () => {
224
+ throw new CliError("extension_missing", `\`p2p ${ns}\` needs the ${ns} extension: ${how}`, { extension: pkg });
225
+ }, { requireIdentity: false }));
226
+ }
227
+ const group = program
228
+ .command("extensions")
229
+ .description("Extensions (@peer2peer/ext-*): loaded, enabled, and how to enable one (opt-in; they run with your identity)")
230
+ .option("--json", "JSON output")
231
+ .action(deps.run(async (app) => {
232
+ const loaded = reg.list().map((l) => ({ ns: l.ext.ns, name: l.ext.name, version: l.ext.version, from: l.from, commands: (l.ext.commands ?? []).map((c) => c.name) }));
233
+ const { enabled, ignored } = enabledNamespaces(app.env, app.file);
234
+ const missing = KNOWN_EXTENSIONS.filter((ns) => !reg.get(ns)).map(extensionPackageName);
235
+ const human = [
236
+ ...(loaded.length ? loaded.map((l) => `${l.name} ${l.version} (x:${l.ns}.*): ${l.from}`) : ["no extensions loaded"]),
237
+ `enabled: ${enabled.length ? enabled.join(", ") : "none"}${app.env.P2P_EXTENSIONS !== undefined ? " (from P2P_EXTENSIONS)" : ""}`,
238
+ ...(ignored.length ? [`ignored (not registered): ${ignored.join(", ")}`] : []),
239
+ ].join("\n");
240
+ return { json: { extensions: loaded, enabled, missing, ...(ignored.length ? { ignored } : {}) }, human };
241
+ }, { requireIdentity: false }));
242
+ for (const on of [true, false]) {
243
+ group
244
+ .command(`${on ? "enable" : "disable"} <ns>`)
245
+ .description(on ? `Enable an installed extension (${KNOWN_EXTENSIONS.join(", ")}): its code runs inside p2p with your identity` : "Disable an extension")
246
+ .option("--json", "JSON output")
247
+ .action(deps.run(async (app, ns) => {
248
+ let list;
249
+ try {
250
+ list = setExtensionEnabled(app.home, ns, on);
251
+ }
252
+ catch (e) {
253
+ throw new CliError("usage", e.message);
254
+ }
255
+ const note = app.env.P2P_EXTENSIONS !== undefined ? " (P2P_EXTENSIONS is set and overrides config.json)" : "";
256
+ return { json: { enabled: list }, human: `${on ? "Enabled" : "Disabled"} ${ns}; enabled: ${list.length ? list.join(", ") : "none"}${note}.` };
257
+ }, { requireIdentity: false }));
258
+ }
259
+ }