@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.
- package/LICENSE +201 -0
- package/README.md +370 -2
- package/dist/ancestry.d.ts +13 -0
- package/dist/ancestry.js +71 -0
- package/dist/app.d.ts +368 -0
- package/dist/app.js +1181 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +56 -0
- package/dist/circle-ops.d.ts +402 -0
- package/dist/circle-ops.js +1725 -0
- package/dist/cli.d.ts +660 -0
- package/dist/cli.js +1787 -0
- package/dist/codes.d.ts +231 -0
- package/dist/codes.js +998 -0
- package/dist/config.d.ts +159 -0
- package/dist/config.js +294 -0
- package/dist/doctor.d.ts +113 -0
- package/dist/doctor.js +930 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +29 -0
- package/dist/ext-host.d.ts +38 -0
- package/dist/ext-host.js +293 -0
- package/dist/extensions.d.ts +487 -0
- package/dist/extensions.js +406 -0
- package/dist/features.d.ts +91 -0
- package/dist/features.js +164 -0
- package/dist/format.d.ts +57 -0
- package/dist/format.js +248 -0
- package/dist/graph-memory.d.ts +107 -0
- package/dist/graph-memory.js +393 -0
- package/dist/history.d.ts +155 -0
- package/dist/history.js +697 -0
- package/dist/identity.d.ts +239 -0
- package/dist/identity.js +759 -0
- package/dist/inbound.d.ts +32 -0
- package/dist/inbound.js +261 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/ix-local.d.ts +76 -0
- package/dist/ix-local.js +203 -0
- package/dist/join-answers.d.ts +49 -0
- package/dist/join-answers.js +149 -0
- package/dist/outbox.d.ts +109 -0
- package/dist/outbox.js +337 -0
- package/dist/pretty.d.ts +100 -0
- package/dist/pretty.js +256 -0
- package/dist/procstart.d.ts +1 -0
- package/dist/procstart.js +66 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +78 -0
- package/dist/projects.d.ts +491 -0
- package/dist/projects.js +1383 -0
- package/dist/prompt/picker.d.ts +64 -0
- package/dist/prompt/picker.js +152 -0
- package/dist/prompt/tty.d.ts +29 -0
- package/dist/prompt/tty.js +122 -0
- package/dist/readonly.d.ts +20 -0
- package/dist/readonly.js +50 -0
- package/dist/receipts.d.ts +99 -0
- package/dist/receipts.js +182 -0
- package/dist/relay-client.d.ts +277 -0
- package/dist/relay-client.js +873 -0
- package/dist/relay-info.d.ts +24 -0
- package/dist/relay-info.js +53 -0
- package/dist/rotation.d.ts +402 -0
- package/dist/rotation.js +2054 -0
- package/dist/running.d.ts +5 -0
- package/dist/running.js +74 -0
- package/dist/sessions.d.ts +355 -0
- package/dist/sessions.js +1247 -0
- package/dist/shortcode.d.ts +149 -0
- package/dist/shortcode.js +465 -0
- package/dist/social.d.ts +139 -0
- package/dist/social.js +485 -0
- package/dist/state.d.ts +509 -0
- package/dist/state.js +220 -0
- package/dist/stdin.d.ts +17 -0
- package/dist/stdin.js +46 -0
- package/dist/sync.d.ts +77 -0
- package/dist/sync.js +375 -0
- package/dist/transient.d.ts +1 -0
- package/dist/transient.js +28 -0
- package/dist/trust.d.ts +37 -0
- package/dist/trust.js +134 -0
- package/dist/tty-confirm.d.ts +2 -0
- package/dist/tty-confirm.js +53 -0
- package/dist/tui/command.d.ts +20 -0
- package/dist/tui/command.js +70 -0
- package/dist/tui/frame.d.ts +43 -0
- package/dist/tui/frame.js +111 -0
- package/dist/tui/model.d.ts +221 -0
- package/dist/tui/model.js +259 -0
- package/dist/tui/sanitize.d.ts +13 -0
- package/dist/tui/sanitize.js +151 -0
- package/dist/tui/terminal.d.ts +88 -0
- package/dist/tui/terminal.js +354 -0
- package/dist/tui/tui.d.ts +78 -0
- package/dist/tui/tui.js +612 -0
- package/dist/tui/view.d.ts +4 -0
- package/dist/tui/view.js +358 -0
- package/dist/unknown-kinds.d.ts +12 -0
- package/dist/unknown-kinds.js +66 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +5 -0
- package/dist/want-pow.d.ts +12 -0
- package/dist/want-pow.js +46 -0
- package/dist/watch.d.ts +35 -0
- package/dist/watch.js +331 -0
- package/dist/xstate.d.ts +125 -0
- package/dist/xstate.js +422 -0
- package/package.json +60 -4
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,930 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// `p2p doctor [<user>]`: why sessions are or aren't visible, in plain words.
|
|
4
|
+
//
|
|
5
|
+
// Without a user it checks this device: the identity and its document's
|
|
6
|
+
// freshness, each relay (reachable, latency, this device's mailbox and auth,
|
|
7
|
+
// our document published there, the clock vs the relay), the default circle
|
|
8
|
+
// and our standing in it, which sessions are shared and with whom, when a
|
|
9
|
+
// status last went out, and the CLI version vs the mod's bundled one.
|
|
10
|
+
//
|
|
11
|
+
// With a user (an address, a petname, a name or a userId) it explains
|
|
12
|
+
// whether we can see them: friendship or shared circles, their identity
|
|
13
|
+
// document, their relays and whether we share a reachable one, the caps each
|
|
14
|
+
// side holds (as far as this side can tell), when anything last arrived from
|
|
15
|
+
// them, blocks, suspensions and held items, and whether the sessions they
|
|
16
|
+
// shared include us.
|
|
17
|
+
//
|
|
18
|
+
// Each check is ✓ (fine), ✗ (a problem, with a one-line fix) or ? (unknown or a warning,
|
|
19
|
+
// with what would tell). Read-only: the relay probes authenticate but never
|
|
20
|
+
// ack what is queued, publish nothing and send nothing. Every network step is
|
|
21
|
+
// bounded (P2P_DOCTOR_TIMEOUT_MS, default 5 s, never more than the connect
|
|
22
|
+
// timeout), and so is every local step, so the command can't hang. Nothing
|
|
23
|
+
// secret is ever in the output: no keys, caps, invite or link codes, envelopes.
|
|
24
|
+
import { readdirSync, statSync } from "node:fs";
|
|
25
|
+
import { readFile, stat } from "node:fs/promises";
|
|
26
|
+
import { dirname, join } from "node:path";
|
|
27
|
+
import { fileURLToPath } from "node:url";
|
|
28
|
+
import { capAllowsKind, daysPastExp, decodeTyped, DEFAULT_SKEW_SEC, displayAddress, identityFreshness, isLive, isUserId, liveFriendshipsV3, nowSec, peekIdentityDoc, sanitizePeerText, TYP3, unfriendApplies, refreshIdentity as coreRefreshIdentity, } from "@peer2peer/core/v3";
|
|
29
|
+
import { App, capPeek, joinCapOf, orderRelays, REPUBLISH_DOC_WITHIN_SEC } from "./app.js";
|
|
30
|
+
import { CAP_PROJECTS, CLI_CAPS, KNOWN_FEATURES, peerDevices, unavailableBetween } from "./features.js";
|
|
31
|
+
import { circleMembers, listCircles } from "./circle-ops.js";
|
|
32
|
+
import { defaultRelays } from "./config.js";
|
|
33
|
+
import { CliError } from "./errors.js";
|
|
34
|
+
import { readCapped, RelayConnection } from "./relay-client.js";
|
|
35
|
+
import { rosterAudience, sessionRef } from "./sessions.js";
|
|
36
|
+
import { enabledNamespaces } from "./extensions.js";
|
|
37
|
+
import { extIxInstalled, ixBinary, IX_INSTALL_URL, ixMemorySupport, ixVersion, runIx } from "./ix-local.js";
|
|
38
|
+
import { graphMemoryReport } from "./graph-memory.js";
|
|
39
|
+
import { graphMemoryEnabled } from "./config.js";
|
|
40
|
+
import { describeGraphTarget, listProjects, localGraphEndpoint, projectOf, projectsDoc, projectGraphTarget, sessionWorkdir } from "./projects.js";
|
|
41
|
+
/**
|
|
42
|
+
* Clock skew. Signed objects (device certificates, documents, caps, invites, statements) are
|
|
43
|
+
* refused when their `iat` is more than DEFAULT_SKEW_SEC (300 s) ahead of the verifier's clock,
|
|
44
|
+
* in core and at relays (relay auth too). Envelope `ts` alone tolerates 10 minutes
|
|
45
|
+
* (REPLAY_FUTURE_SKEW_MS), so 300 s is the real limit. Under SKEW_OK_SEC is fine (the Date
|
|
46
|
+
* header has 1 s resolution, plus half a round trip); up to the limit still works, so it is a
|
|
47
|
+
* warning; only past it does anything break.
|
|
48
|
+
*/
|
|
49
|
+
export const SKEW_OK_SEC = 30;
|
|
50
|
+
export const SKEW_FAIL_SEC = DEFAULT_SKEW_SEC;
|
|
51
|
+
const DAY = 86_400;
|
|
52
|
+
const MARK = { ok: "✓", fail: "✗", unknown: "?" };
|
|
53
|
+
/** A promise bounded by `ms`: `undefined` with `timedOut` when it doesn't settle in time. */
|
|
54
|
+
async function bounded(p, ms) {
|
|
55
|
+
let timer;
|
|
56
|
+
try {
|
|
57
|
+
return await Promise.race([
|
|
58
|
+
p.then((value) => ({ value }), (error) => ({ error })),
|
|
59
|
+
new Promise((r) => {
|
|
60
|
+
timer = setTimeout(() => r({ timedOut: true }), ms);
|
|
61
|
+
timer.unref?.();
|
|
62
|
+
}),
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
if (timer)
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const ago = (ms) => {
|
|
71
|
+
const s = Math.max(0, Math.round(ms / 1000));
|
|
72
|
+
if (s < 90)
|
|
73
|
+
return `${s}s ago`;
|
|
74
|
+
if (s < 90 * 60)
|
|
75
|
+
return `${Math.round(s / 60)}m ago`;
|
|
76
|
+
if (s < 36 * 3600)
|
|
77
|
+
return `${Math.round(s / 3600)}h ago`;
|
|
78
|
+
return `${Math.round(s / DAY)} days ago`;
|
|
79
|
+
};
|
|
80
|
+
const days = (sec) => {
|
|
81
|
+
const d = Math.floor(Math.abs(sec) / DAY);
|
|
82
|
+
if (d >= 1)
|
|
83
|
+
return `${d} day${d === 1 ? "" : "s"}`;
|
|
84
|
+
const h = Math.max(1, Math.round(Math.abs(sec) / 3600));
|
|
85
|
+
return `${h} hour${h === 1 ? "" : "s"}`;
|
|
86
|
+
};
|
|
87
|
+
const errText = (e) => sanitizePeerText(e?.message ?? String(e), 200);
|
|
88
|
+
/** A peer-written string, inert and short. */
|
|
89
|
+
const peer = (s, max = 64) => sanitizePeerText(s, max).replace(/["`]/g, "'") || "?";
|
|
90
|
+
/** A relay URL a peer chose (their document, a cap they gave us): quoted peer data, at most 200 characters. */
|
|
91
|
+
const peerUrl = (s) => `"${peer(s, 200)}"`;
|
|
92
|
+
/** A session id from a peer, safe as part of a check id: [A-Za-z0-9._-], at most 128. */
|
|
93
|
+
const safeSid = (s) => String(s).replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 128) || "_";
|
|
94
|
+
/** At most this many of a peer's relays are ever probed (§5.8: a document lists 1-5). */
|
|
95
|
+
const MAX_PEER_RELAYS = 5;
|
|
96
|
+
/** One bounded GET (the relay's document API), with its latency and the server's Date header. */
|
|
97
|
+
export async function httpProbe(url, timeoutMs, opts = {}) {
|
|
98
|
+
const ctl = new AbortController();
|
|
99
|
+
const t = setTimeout(() => ctl.abort(), timeoutMs);
|
|
100
|
+
t.unref?.();
|
|
101
|
+
const t0 = Date.now();
|
|
102
|
+
try {
|
|
103
|
+
const res = await fetch(url, { signal: ctl.signal, headers: { accept: "application/json" }, ...(opts.noRedirect ? { redirect: "error" } : {}) });
|
|
104
|
+
const t1 = Date.now();
|
|
105
|
+
const date = res.headers.get("date");
|
|
106
|
+
const serverMs = date ? Date.parse(date) : NaN;
|
|
107
|
+
// A body only when asked for (our own document), capped; a peer's relay's answer is never kept.
|
|
108
|
+
let body;
|
|
109
|
+
if (opts.maxBody) {
|
|
110
|
+
try {
|
|
111
|
+
const text = await readCapped(res, opts.maxBody);
|
|
112
|
+
body = text ? JSON.parse(text) : undefined;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
body = undefined;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
else
|
|
119
|
+
await res.body?.cancel().catch(() => { });
|
|
120
|
+
return {
|
|
121
|
+
ok: true,
|
|
122
|
+
status: res.status,
|
|
123
|
+
ms: t1 - t0,
|
|
124
|
+
...(Number.isFinite(serverMs) ? { serverMs: serverMs + 500, localMs: Math.round((t0 + t1) / 2) } : {}),
|
|
125
|
+
...(body && typeof body === "object" ? { body } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
const ms = Date.now() - t0;
|
|
130
|
+
if (ctl.signal.aborted)
|
|
131
|
+
return { ok: false, ms, code: "timeout", error: `no answer after ${Math.round(timeoutMs / 1000)}s` };
|
|
132
|
+
const code = e.cause?.code ?? "";
|
|
133
|
+
if (["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ETIMEDOUT"].includes(code)) {
|
|
134
|
+
return { ok: false, ms, code: "unreachable", error: code === "ECONNREFUSED" ? "connection refused" : code === "ENOTFOUND" || code === "EAI_AGAIN" ? "can't resolve the host" : "no route to it" };
|
|
135
|
+
}
|
|
136
|
+
return { ok: false, ms, code: "network", error: errText(e) };
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
clearTimeout(t);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** Dials one relay as this device (or anonymously), checks hello and auth, and makes one authenticated round trip. */
|
|
143
|
+
export async function wsProbe(app, relay, timeoutMs, auth) {
|
|
144
|
+
let queued = 0;
|
|
145
|
+
const conn = new RelayConnection(relay, app.transport(relay), {
|
|
146
|
+
...(auth ? { auth: { cert: app.keys.cert, signingSecretKey: app.device.signingSecretKey } } : {}),
|
|
147
|
+
// Accepted, so a relay that doesn't list this device yet is reported as such.
|
|
148
|
+
allowRestricted: true,
|
|
149
|
+
timeoutMs,
|
|
150
|
+
requestTimeoutMs: timeoutMs,
|
|
151
|
+
rememberUnreachable: false,
|
|
152
|
+
// Counted, never acked: they stay queued for the next real command.
|
|
153
|
+
onEnv: () => {
|
|
154
|
+
queued++;
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
const t0 = Date.now();
|
|
158
|
+
try {
|
|
159
|
+
// The whole open (dial, hello, auth) within the doctor's bound, not one bound per stage.
|
|
160
|
+
const opened = await bounded(conn.open(), timeoutMs);
|
|
161
|
+
if (opened.timedOut)
|
|
162
|
+
return { authed: false, restricted: false, queued, code: "timeout", error: `no answer after ${Math.round(timeoutMs / 1000)}s` };
|
|
163
|
+
if (opened.error !== undefined) {
|
|
164
|
+
const e = opened.error;
|
|
165
|
+
return { authed: false, restricted: false, queued, code: e.code ?? "network", error: errText(e) };
|
|
166
|
+
}
|
|
167
|
+
const connectMs = Date.now() - t0;
|
|
168
|
+
if (!auth)
|
|
169
|
+
return { connectMs, authed: false, restricted: false, queued };
|
|
170
|
+
let rttMs;
|
|
171
|
+
if (!conn.restricted) {
|
|
172
|
+
const t1 = Date.now();
|
|
173
|
+
const r = await bounded(conn.request({ t: "invite-list" }, timeoutMs), timeoutMs + 500);
|
|
174
|
+
if (r.value)
|
|
175
|
+
rttMs = Date.now() - t1;
|
|
176
|
+
}
|
|
177
|
+
return { connectMs, ...(rttMs !== undefined ? { rttMs } : {}), authed: conn.authed, restricted: conn.restricted, queued };
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
conn.close();
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// ---------------------------------------------------------------------------
|
|
184
|
+
// Local state
|
|
185
|
+
/** The newest status this device posted (the mod's status publisher, or `p2p status`). */
|
|
186
|
+
function ownStatuses(app, peers) {
|
|
187
|
+
return Object.values(peers)
|
|
188
|
+
.filter((p) => p.own === app.userId && p.did === app.did)
|
|
189
|
+
.sort((a, b) => b.ts - a.ts);
|
|
190
|
+
}
|
|
191
|
+
/** The newest `p2p watch` cursor write: when a watcher last handed an event on (or started). */
|
|
192
|
+
function watchCursor(home) {
|
|
193
|
+
let best;
|
|
194
|
+
try {
|
|
195
|
+
for (const name of readdirSync(join(home, "cursors"))) {
|
|
196
|
+
if (!name.endsWith(".cursor"))
|
|
197
|
+
continue;
|
|
198
|
+
const at = statSync(join(home, "cursors", name)).mtimeMs;
|
|
199
|
+
if (!best || at > best.at)
|
|
200
|
+
best = { sid: name.slice(0, -".cursor".length), at };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
return best;
|
|
207
|
+
}
|
|
208
|
+
/** The mod's folder: P2P_MOD_ROOT, or the plugin around a bundled `bin/p2p.mjs`. */
|
|
209
|
+
function findModRoot(app, given) {
|
|
210
|
+
const fromEnv = given ?? app.env.P2P_MOD_ROOT?.trim();
|
|
211
|
+
if (fromEnv)
|
|
212
|
+
return fromEnv;
|
|
213
|
+
try {
|
|
214
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
215
|
+
const root = dirname(here);
|
|
216
|
+
statSync(join(root, ".claude-plugin", "plugin.json"));
|
|
217
|
+
return root;
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/** The plugin's version and the version of the `p2p` it bundles (read from the file, not run). */
|
|
224
|
+
/** Files bigger than this aren't read (the bundled CLI is ~1.2 MB). */
|
|
225
|
+
const MAX_MOD_FILE_BYTES = 16 * 1024 * 1024;
|
|
226
|
+
async function readSmall(path) {
|
|
227
|
+
if ((await stat(path)).size > MAX_MOD_FILE_BYTES)
|
|
228
|
+
throw new Error("too large");
|
|
229
|
+
return readFile(path, "utf8");
|
|
230
|
+
}
|
|
231
|
+
export async function modVersions(root) {
|
|
232
|
+
const out = {};
|
|
233
|
+
try {
|
|
234
|
+
const v = JSON.parse(await readSmall(join(root, ".claude-plugin", "plugin.json"))).version;
|
|
235
|
+
if (typeof v === "string")
|
|
236
|
+
out.plugin = peer(v, 32);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
// no plugin.json
|
|
240
|
+
}
|
|
241
|
+
try {
|
|
242
|
+
const m = /^var VERSION = "([^"]{1,32})";$/m.exec(await readSmall(join(root, "bin", "p2p.mjs")));
|
|
243
|
+
if (m)
|
|
244
|
+
out.bundled = peer(m[1], 32);
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
// no bundled CLI
|
|
248
|
+
}
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
// ---------------------------------------------------------------------------
|
|
252
|
+
// The checks
|
|
253
|
+
class Checks {
|
|
254
|
+
list = [];
|
|
255
|
+
add(id, status, title, detail, fix) {
|
|
256
|
+
const c = { id, status, title, detail, ...(fix && status !== "ok" ? { fix } : {}) };
|
|
257
|
+
this.list.push(c);
|
|
258
|
+
return c;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/** Probes each relay over WebSocket (as this device) and the document API, in parallel. */
|
|
262
|
+
async function probeRelays(app, relays, timeoutMs, auth, docUser) {
|
|
263
|
+
return Promise.all(relays.map(async (relay) => {
|
|
264
|
+
const http = docUser ? `${app.transport(relay).http}/identity/${encodeURIComponent(docUser)}` : `${new URL(app.transport(relay).http).origin}/healthz`;
|
|
265
|
+
const [ws, hp] = await Promise.all([
|
|
266
|
+
wsProbe(app, relay, timeoutMs, auth).catch((e) => ({ authed: false, restricted: false, queued: 0, code: "network", error: errText(e) })),
|
|
267
|
+
// Our own head document (≤ 16 KiB per protocol §2.5; room to spare).
|
|
268
|
+
httpProbe(http, timeoutMs, docUser ? { maxBody: 64 * 1024 } : {}),
|
|
269
|
+
]);
|
|
270
|
+
return { relay, ws, http: hp, reachable: ws.connectMs !== undefined || hp.ok };
|
|
271
|
+
}));
|
|
272
|
+
}
|
|
273
|
+
function relayChecks(c, app, reports, head) {
|
|
274
|
+
for (const r of reports) {
|
|
275
|
+
const id = `relay:${r.relay}`;
|
|
276
|
+
if (r.ws.connectMs === undefined) {
|
|
277
|
+
const why = r.ws.error ?? r.http.error ?? "no answer";
|
|
278
|
+
const refused = r.ws.code === "auth_failed";
|
|
279
|
+
c.add(id, "fail", `relay ${r.relay}`, refused ? `reachable, but it refused this device (${why})` : r.ws.code === "relay_mismatch" ? "it introduced itself as another relay" : `unreachable: ${why}`, refused
|
|
280
|
+
? "this device may have been revoked: run `p2p whoami` on another of your devices, or re-link this one (`p2p link start` there, `p2p link join <code>` here)"
|
|
281
|
+
: r.ws.code === "relay_mismatch"
|
|
282
|
+
? "check the URL and any transport override (P2P_RELAY_TRANSPORT, config.json `transport`)"
|
|
283
|
+
: "check your network, VPN or firewall (WebSocket over port 443); if it stays down, add another relay: `p2p relays add <wss://…>` (or `/peers relays add <wss://…>`)");
|
|
284
|
+
}
|
|
285
|
+
else if (app.keys && r.ws.restricted) {
|
|
286
|
+
c.add(id, "fail", `relay ${r.relay}`, `reachable (${r.ws.connectMs} ms), but it doesn't list this device yet, so its mailbox is closed to it`, "publish your current document there: `p2p identity republish`");
|
|
287
|
+
}
|
|
288
|
+
else if (app.keys && !r.ws.authed) {
|
|
289
|
+
c.add(id, "fail", `relay ${r.relay}`, `reachable (${r.ws.connectMs} ms), but this device couldn't sign in`, "run `p2p identity republish`, then `p2p doctor` again");
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
const lat = `${r.ws.connectMs} ms to connect${r.ws.rttMs !== undefined ? `, ${r.ws.rttMs} ms round trip` : ""}`;
|
|
293
|
+
const queued = r.ws.queued > 0 ? `; ${r.ws.queued} envelope${r.ws.queued === 1 ? "" : "s"} queued for this device` : "";
|
|
294
|
+
c.add(id, "ok", `relay ${r.relay}`, app.keys ? `reachable (${lat}); this device's mailbox works${queued}` : `reachable (${lat})`);
|
|
295
|
+
}
|
|
296
|
+
if (!app.keys)
|
|
297
|
+
continue;
|
|
298
|
+
// Our document there.
|
|
299
|
+
const did = `published:${r.relay}`;
|
|
300
|
+
if (!r.http.ok)
|
|
301
|
+
c.add(did, "unknown", `identity document on ${r.relay}`, `couldn't ask (${r.http.error ?? "no answer"})`, "run `p2p doctor` again once the relay answers");
|
|
302
|
+
else if (r.http.status === 404)
|
|
303
|
+
c.add(did, "fail", `identity document on ${r.relay}`, "not published there: nobody can find your devices or relays through it", "run `p2p identity republish`");
|
|
304
|
+
else if (r.http.status !== 200 || typeof r.http.body?.doc !== "string")
|
|
305
|
+
c.add(did, "unknown", `identity document on ${r.relay}`, `unexpected answer (HTTP ${r.http.status})`, "run `p2p doctor` again later");
|
|
306
|
+
else {
|
|
307
|
+
let theirs;
|
|
308
|
+
try {
|
|
309
|
+
const p = peekIdentityDoc(r.http.body.doc);
|
|
310
|
+
theirs = { hash: p.hash, ver: p.ver };
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
theirs = undefined;
|
|
314
|
+
}
|
|
315
|
+
if (!theirs)
|
|
316
|
+
c.add(did, "unknown", `identity document on ${r.relay}`, "the relay's copy doesn't parse", "run `p2p identity republish`");
|
|
317
|
+
else if (!head)
|
|
318
|
+
c.add(did, "unknown", `identity document on ${r.relay}`, `version ${theirs.ver} is there; this device holds none to compare`, "run `p2p whoami`");
|
|
319
|
+
else if (theirs.hash === head.hash)
|
|
320
|
+
c.add(did, "ok", `identity document on ${r.relay}`, `published (version ${theirs.ver}, the current one)`);
|
|
321
|
+
else if (theirs.ver < head.ver)
|
|
322
|
+
c.add(did, "fail", `identity document on ${r.relay}`, `the relay has version ${theirs.ver}; yours is ${head.ver}`, "run `p2p identity republish`");
|
|
323
|
+
else
|
|
324
|
+
c.add(did, "unknown", `identity document on ${r.relay}`, `the relay has version ${theirs.ver}; this device holds ${head.ver} (another device published since?)`, "run `p2p whoami` to refresh, then `p2p doctor` again");
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function clockCheck(c, reports) {
|
|
329
|
+
const skews = reports
|
|
330
|
+
.filter((r) => r.http.serverMs !== undefined && r.http.localMs !== undefined)
|
|
331
|
+
.map((r) => ({ relay: r.relay, sec: Math.round((r.http.localMs - r.http.serverMs) / 1000) }));
|
|
332
|
+
const k = clockVerdict(skews);
|
|
333
|
+
c.add("clock", k.status, k.title, k.detail, k.fix);
|
|
334
|
+
}
|
|
335
|
+
const CLOCK_FIX = "turn on automatic time in your system settings (Windows: Settings > Time & language > Sync now)";
|
|
336
|
+
/**
|
|
337
|
+
* The clock check from each relay's skew (seconds, + when this device is ahead): ✓ under
|
|
338
|
+
* SKEW_OK_SEC, ? (a warning) up to the protocol's limit (SKEW_FAIL_SEC, 300 s), ✗ only past it.
|
|
339
|
+
*/
|
|
340
|
+
export function clockVerdict(skews) {
|
|
341
|
+
if (skews.length === 0)
|
|
342
|
+
return { id: "clock", status: "unknown", title: "clock", detail: "no relay answered with its time", fix: "check your system clock is set automatically" };
|
|
343
|
+
const worst = skews.reduce((a, b) => (Math.abs(b.sec) > Math.abs(a.sec) ? b : a));
|
|
344
|
+
const abs = Math.abs(worst.sec);
|
|
345
|
+
const dir = worst.sec > 0 ? "ahead of" : "behind";
|
|
346
|
+
const limit = `the protocol's ${SKEW_FAIL_SEC}s (5-minute) limit`;
|
|
347
|
+
if (abs < SKEW_OK_SEC) {
|
|
348
|
+
return { id: "clock", status: "ok", title: "clock", detail: `within ${Math.max(1, abs)}s of ${skews.length === 1 ? worst.relay : `your relays (worst: ${worst.relay})`}` };
|
|
349
|
+
}
|
|
350
|
+
if (abs <= SKEW_FAIL_SEC) {
|
|
351
|
+
return {
|
|
352
|
+
id: "clock",
|
|
353
|
+
status: "unknown",
|
|
354
|
+
title: "clock",
|
|
355
|
+
detail: `${abs}s ${dir} ${worst.relay}: still within ${limit}, but ${SKEW_FAIL_SEC - abs}s more drift and relays and peers will reject what this device signs (sooner with a peer whose clock is off the other way: the two add up)`,
|
|
356
|
+
fix: CLOCK_FIX,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
return {
|
|
360
|
+
id: "clock",
|
|
361
|
+
status: "fail",
|
|
362
|
+
title: "clock",
|
|
363
|
+
detail: `${abs}s ${dir} ${worst.relay}: past ${limit}, so relays and peers reject what this device signs`,
|
|
364
|
+
fix: CLOCK_FIX,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
async function versionCheck(c, app, o, ms) {
|
|
368
|
+
const root = findModRoot(app, o.modRoot);
|
|
369
|
+
if (!root) {
|
|
370
|
+
c.add("version", "unknown", "versions", `p2p ${o.version}; no Claude mod found next to it`, "run `/peers doctor` in Claude Code to compare with the mod's bundled p2p");
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const read = await bounded(modVersions(root), ms);
|
|
374
|
+
if (read.value === undefined) {
|
|
375
|
+
c.add("version", "unknown", "versions", `p2p ${o.version}; couldn't read the mod's files in ${Math.round(ms / 1000)}s`, "run `p2p doctor` again");
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const v = read.value;
|
|
379
|
+
if (!v.bundled) {
|
|
380
|
+
c.add("version", "unknown", "versions", `p2p ${o.version}; the mod${v.plugin ? ` (${v.plugin})` : ""} bundles no p2p version this can read`, "reinstall the mod: `/plugin install peer2peer@peer2peer`");
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (v.bundled !== o.version) {
|
|
384
|
+
c.add("version", "fail", "versions", `this p2p is ${o.version} but the mod${v.plugin ? ` (${v.plugin})` : ""} bundles ${v.bundled}`, "the mod is running another p2p: check P2P_BIN and `which p2p` (`where p2p` on Windows); update that one to match, or unset P2P_BIN and remove it from your PATH so the bundled p2p is used");
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
c.add("version", "ok", "versions", `p2p ${o.version}, the same as the mod${v.plugin ? ` (${v.plugin})` : ""} bundles`);
|
|
388
|
+
}
|
|
389
|
+
/** The circle summaries this device knows, bounded. */
|
|
390
|
+
async function circlesOf(app, ms) {
|
|
391
|
+
return (await bounded(listCircles(app), ms)).value ?? [];
|
|
392
|
+
}
|
|
393
|
+
async function deviceChecks(c, app, o, ms, reports) {
|
|
394
|
+
const view = (await bounded(app.view(app.userId), ms)).value;
|
|
395
|
+
const name = view?.head.name ?? app.self?.name ?? "?";
|
|
396
|
+
c.add("identity", "ok", "identity", `${displayAddress(app.userId, name)} on device ${app.did}${app.isKeyholder ? " (key holder)" : ""}`);
|
|
397
|
+
if (!view) {
|
|
398
|
+
c.add("document", "fail", "identity document", "this device holds no identity document for itself", "run `p2p identity republish` on a key-holding device, then `p2p whoami` here");
|
|
399
|
+
}
|
|
400
|
+
else {
|
|
401
|
+
const now = nowSec();
|
|
402
|
+
const f = identityFreshness(view.head.exp, now);
|
|
403
|
+
const left = view.head.exp - now;
|
|
404
|
+
const keyholderFix = app.isKeyholder ? "run any `p2p` command here (or keep Claude Code with the mod open) and it re-publishes; `p2p identity republish` forces it" : "run any `p2p` command on a key-holding device: only key holders re-publish";
|
|
405
|
+
if (f === "fail-closed")
|
|
406
|
+
c.add("document", "fail", "identity document", `version ${view.head.ver} expired ${daysPastExp(view.head.exp, now)} days ago (hard expiry): peers now refuse everything from you`, keyholderFix);
|
|
407
|
+
else if (f === "expired")
|
|
408
|
+
c.add("document", "fail", "identity document", `version ${view.head.ver} expired ${days(left)} ago (soft expiry): peers warn, and refuse it after the grace period`, keyholderFix);
|
|
409
|
+
else if (left <= REPUBLISH_DOC_WITHIN_SEC)
|
|
410
|
+
c.add("document", "ok", "identity document", `version ${view.head.ver}, expires in ${days(left)}: due for renewal (a key holder renews it on its next run)`);
|
|
411
|
+
else
|
|
412
|
+
c.add("document", "ok", "identity document", `version ${view.head.ver}, fresh (expires in ${days(left)})`);
|
|
413
|
+
if (view.forked)
|
|
414
|
+
c.add("document-fork", "fail", "identity document history", "forked (two versions claim the same place)", "run `p2p identity republish` on a key holder: it merges the branches");
|
|
415
|
+
if (view.rotations.length > 0)
|
|
416
|
+
c.add("document-rotated", "fail", "identity", "this identity moved to a new key", "follow it: `p2p held` shows the move (approve it there), or re-link with `p2p link join <code> --rotated`");
|
|
417
|
+
}
|
|
418
|
+
relayChecks(c, app, reports, view ? { hash: view.head.hash, ver: view.head.ver } : undefined);
|
|
419
|
+
clockCheck(c, reports);
|
|
420
|
+
// The default circle and our standing in it.
|
|
421
|
+
const def = app.self?.defaultCircle;
|
|
422
|
+
if (!def) {
|
|
423
|
+
c.add("default-circle", "fail", "default circle", "none: invites join no circle by default (sessions follow their project either way: private until you share it)", "pick one: `/peers circle default <cid>` or `p2p circle default <cid>` (`p2p circle ls` lists them); share a project with `p2p project share <cid>` in it (or /peers project share)");
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
const m = await bounded(circleMembers(app, def), ms);
|
|
427
|
+
if (!m.value) {
|
|
428
|
+
c.add("default-circle", "fail", "default circle", `${def} isn't known on this device`, "pick one you're in: `p2p circle ls`, then `p2p circle default <cid>`");
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
const self = m.value.members.find((x) => x.self);
|
|
432
|
+
const nm = peer(m.value.circle.name);
|
|
433
|
+
const others = m.value.members.filter((x) => !x.self && x.stands).length;
|
|
434
|
+
if (!self)
|
|
435
|
+
c.add("default-circle", "fail", "default circle", `"${nm}" (${def}): you're not a member of it any more`, "ask its owner to add you again, or pick another: `p2p circle default <cid>`");
|
|
436
|
+
else if (!self.stands)
|
|
437
|
+
c.add("default-circle", "fail", "default circle", `"${nm}" (${def}): you're listed but don't stand in it (your membership statement is missing or a leave)`, "join it again with a fresh link from its owner (`p2p circle join <link>`)");
|
|
438
|
+
else
|
|
439
|
+
c.add("default-circle", "ok", "default circle", `"${nm}" (${def}): you stand in it as ${m.value.circle.role}, with ${others} other standing member${others === 1 ? "" : "s"}`);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
// Shared sessions and the status publisher.
|
|
443
|
+
const peers = (await bounded(app.state.get("peers"), ms)).value ?? {};
|
|
444
|
+
const sessions = (await bounded(app.state.get("sessions"), ms)).value ?? {};
|
|
445
|
+
const now = Date.now();
|
|
446
|
+
const mine = ownStatuses(app, peers);
|
|
447
|
+
const live = mine.filter((p) => isLive(p.ts, now));
|
|
448
|
+
// Your other devices: one on a client from before project boundaries runs its own sessions by the
|
|
449
|
+
// old rule (new sessions follow the default circle), and can't honour a bounded own-session message.
|
|
450
|
+
const others = Object.values(peers).filter((p) => p.own === app.userId && p.did !== app.did && isLive(p.ts, now));
|
|
451
|
+
const older = [...new Set(others.filter((p) => !(Array.isArray(p.status.caps) && p.status.caps.includes(CAP_PROJECTS))).map((p) => p.did))];
|
|
452
|
+
if (older.length > 0) {
|
|
453
|
+
c.add("other-devices", "fail", "your other devices", `${older.length} of your other devices run a client without project boundaries: their sessions follow your default circle, whatever the project`, "update Peer2Peer on those devices (docs/compatibility.md, \"Project boundaries\")");
|
|
454
|
+
}
|
|
455
|
+
else if (others.length > 0)
|
|
456
|
+
c.add("other-devices", "ok", "your other devices", "every live session of your other devices keeps project boundaries");
|
|
457
|
+
if (live.length === 0) {
|
|
458
|
+
c.add("shared", "unknown", "shared sessions", mine.length === 0 ? "no session on this device has posted a status yet" : "no session on this device is live right now (none posted a status in the last 150 s)", "start Claude Code with the mod (or run `p2p status --session <sid> --state idle`), then `p2p doctor` again");
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
const circles = await circlesOf(app, ms);
|
|
462
|
+
for (const p of live.slice(0, 5)) {
|
|
463
|
+
const s = sessions[p.sid];
|
|
464
|
+
const label = peer(p.status.label);
|
|
465
|
+
const ref = sessionRef(app.userId, p.sid);
|
|
466
|
+
if (!s) {
|
|
467
|
+
c.add(`shared:${safeSid(p.sid)}`, "unknown", `session "${label}" [${ref}]`, "live, but its roster isn't on this device", `run \`p2p session roster ${safeSid(p.sid)}\``);
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
const aud = (await bounded(rosterAudience(app, s), ms)).value;
|
|
471
|
+
const where = s.vis === "circle" && s.circle ? `circle "${peer(circles.find((x) => x.cid === s.circle)?.name ?? s.circle)}"${s.parts.length ? ` plus ${s.parts.length} added` : ""}` : s.parts.length ? `${s.parts.length} added people (private)` : "nobody (private)";
|
|
472
|
+
if (aud === undefined)
|
|
473
|
+
c.add(`shared:${safeSid(p.sid)}`, "unknown", `session "${label}" [${ref}]`, `live, shared with ${where}; couldn't work out who stands in it in time`, "run `p2p doctor` again");
|
|
474
|
+
else if (aud.length === 0)
|
|
475
|
+
c.add(`shared:${safeSid(p.sid)}`, "fail", `session "${label}" [${ref}]`, `live, but shared with ${where}: nobody else can see it`, "its project is private until you share it: `p2p project share <cid>` in it (or /peers project share in that session); `p2p project show` says why");
|
|
476
|
+
else {
|
|
477
|
+
const names = await Promise.all(aud.slice(0, 5).map((u) => app.addressOf(u)));
|
|
478
|
+
c.add(`shared:${safeSid(p.sid)}`, "ok", `session "${label}" [${ref}]`, `live, shared with ${where}: ${aud.length} can see it (${names.join(", ")}${aud.length > 5 ? ", …" : ""})`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (mine.length === 0)
|
|
483
|
+
c.add("publisher", "unknown", "status publisher", "this device has never posted a status", "start Claude Code with the mod: it posts every 60 s while a session runs");
|
|
484
|
+
else if (isLive(mine[0].ts, now))
|
|
485
|
+
c.add("publisher", "ok", "status publisher", `last status from this device ${ago(now - mine[0].ts)} ("${peer(mine[0].status.label)}", ${mine[0].status.state})`);
|
|
486
|
+
else
|
|
487
|
+
c.add("publisher", "fail", "status publisher", `last status from this device ${ago(now - mine[0].ts)}: peers see nothing live from you`, "is Claude Code with the mod running? It posts every 60 s; `p2p status --session <sid> --state idle` posts one by hand");
|
|
488
|
+
const cur = watchCursor(app.home);
|
|
489
|
+
if (!cur)
|
|
490
|
+
c.add("watch", "unknown", "watch", "no `p2p watch` has run on this device (no cursor)", "the mod runs `p2p watch` for each session; start Claude Code with the mod");
|
|
491
|
+
else
|
|
492
|
+
c.add("watch", now - cur.at < 3600_000 ? "ok" : "unknown", "watch", `a watcher last moved its cursor ${ago(now - cur.at)} (it moves only when events arrive, so this doesn't prove it's running)`, "if nothing arrives, restart the Claude Code session (the mod restarts `p2p watch`)");
|
|
493
|
+
// review M-A: envelopes this device dropped unapplied (a count only, never what they held).
|
|
494
|
+
const inbound = await app.state.get("inbound").catch(() => undefined);
|
|
495
|
+
const dropped = inbound?.gaveUp ?? 0;
|
|
496
|
+
const tooOld = inbound?.tooOld ?? 0;
|
|
497
|
+
if (tooOld > 0) {
|
|
498
|
+
c.add("inbound-old", "unknown", "late envelopes", `${tooOld} arrived behind the replay window (more than 512 later ones from the same session first, or a duplicate) and ${tooOld === 1 ? "was" : "were"} dropped`, "if a message from someone seems missing, ask them to send it again");
|
|
499
|
+
}
|
|
500
|
+
if (dropped > 0) {
|
|
501
|
+
c.add("inbound", "unknown", "incoming envelopes", `${dropped} couldn't be applied and ${dropped === 1 ? "was" : "were"} dropped after failing for good (or every attempt)`, "if messages from someone seem missing, ask them to send again; P2P_DEBUG=1 on `p2p ls` shows why one fails");
|
|
502
|
+
}
|
|
503
|
+
await ixChecks(c, app, ms);
|
|
504
|
+
await versionCheck(c, app, o, ms);
|
|
505
|
+
}
|
|
506
|
+
// ---------------------------------------------------------------------------
|
|
507
|
+
// Ix (epic #41): the local CLI, its backend, this checkout's map, and each project's graph target
|
|
508
|
+
/** At most this many projects' graph targets are listed. */
|
|
509
|
+
const MAX_GRAPH_ROWS = 10;
|
|
510
|
+
/**
|
|
511
|
+
* The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
|
|
512
|
+
* whether the project here is mapped, and the graph target of the project here and of each project
|
|
513
|
+
* with a policy ("local only" today). Without Ix nothing is a failure: Peer2Peer works without it.
|
|
514
|
+
* `ix` runs as ext-ix runs it (ix-local.ts): absolute path, allowlisted environment, the local
|
|
515
|
+
* endpoint pinned, read-only commands, bounded.
|
|
516
|
+
*/
|
|
517
|
+
export async function ixChecks(c, app, ms) {
|
|
518
|
+
const local = localGraphEndpoint(app.env, app.file);
|
|
519
|
+
const target = { endpoint: local };
|
|
520
|
+
const bin = ixBinary(app.env);
|
|
521
|
+
const on = enabledNamespaces(app.env, app.file).enabled.includes("ix");
|
|
522
|
+
if (!bin) {
|
|
523
|
+
c.add("ix", "unknown", "Ix", "the Ix CLI isn't installed (Peer2Peer works without it; peers' Ix items show as plain text)", `install Ix (${IX_INSTALL_URL}), then \`p2p extensions enable ix\``);
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
const v = (await bounded(ixVersion(bin, app.env, target, ms), ms + 500)).value;
|
|
527
|
+
if (v)
|
|
528
|
+
c.add("ix", "ok", "Ix", `ix ${v} (${bin})`);
|
|
529
|
+
else
|
|
530
|
+
c.add("ix", "unknown", "Ix", `${bin} didn't answer \`ix --version\` in time`, "run `ix --version` in a terminal");
|
|
531
|
+
if (on)
|
|
532
|
+
c.add("ix-extension", "ok", "Ix extension", "enabled: sessions can share Ix context");
|
|
533
|
+
else
|
|
534
|
+
c.add("ix-extension", "unknown", "Ix extension", "not enabled", extIxInstalled(app.env) ? "`p2p extensions enable ix`" : "`npm i -g @peer2peer/ext-ix`, then `p2p extensions enable ix`");
|
|
535
|
+
if (on)
|
|
536
|
+
await graphMemoryChecks(c, app, bin, target, ms);
|
|
537
|
+
// Never followed elsewhere: a loopback listener that redirects is not the local backend.
|
|
538
|
+
const h = await httpProbe(`${local}/v1/health`, ms, { noRedirect: true });
|
|
539
|
+
if (h.ok && h.status !== undefined && h.status < 500)
|
|
540
|
+
c.add("ix-backend", "ok", "Ix backend", `reachable at ${local} (${h.ms} ms)`);
|
|
541
|
+
else
|
|
542
|
+
c.add("ix-backend", "fail", "Ix backend", `nothing answers at ${local}${h.error ? `: ${h.error}` : h.status ? ` (HTTP ${h.status})` : ""}`, "start it with `ix docker start` (or set `ixEndpoint` in config.json to your local backend)");
|
|
543
|
+
const here = projectOf(sessionWorkdir(app.env));
|
|
544
|
+
if (here.kind === "git" && h.ok) {
|
|
545
|
+
const st = (await bounded(runIx(bin, ["status", "--format", "json", "--root", here.root], { env: app.env, target, cwd: here.root, timeoutMs: ms }), ms + 500)).value;
|
|
546
|
+
let mapped;
|
|
547
|
+
try {
|
|
548
|
+
const j = st && st.code === 0 ? JSON.parse(st.stdout) : undefined;
|
|
549
|
+
mapped = j ? j.graphCompleted === true : undefined;
|
|
550
|
+
}
|
|
551
|
+
catch {
|
|
552
|
+
mapped = undefined;
|
|
553
|
+
}
|
|
554
|
+
if (mapped === true)
|
|
555
|
+
c.add("ix-workspace", "ok", "Ix workspace", `${here.name} is mapped`);
|
|
556
|
+
else if (mapped === false)
|
|
557
|
+
c.add("ix-workspace", "unknown", "Ix workspace", `${here.name} isn't mapped yet`, `run \`ix map\` in ${here.root}`);
|
|
558
|
+
else
|
|
559
|
+
c.add("ix-workspace", "unknown", "Ix workspace", `couldn't tell whether ${here.name} is mapped`, "run `ix status` in it");
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
// Graph targets: the project here first, then each project with a policy.
|
|
563
|
+
const doc = (await bounded(projectsDoc(app), ms)).value ?? { v: 1, projects: {} };
|
|
564
|
+
const here = projectOf(sessionWorkdir(app.env));
|
|
565
|
+
const rows = [{ id: here.id, name: here.name, ...(here.repoPrivate ? { repoPrivate: true } : {}) }];
|
|
566
|
+
const all = (await bounded(listProjects(app), ms)).value ?? [];
|
|
567
|
+
for (const p of all)
|
|
568
|
+
if (!rows.some((r) => r.id === p.id))
|
|
569
|
+
rows.push({ id: p.id, name: p.name });
|
|
570
|
+
for (const r of rows.slice(0, MAX_GRAPH_ROWS)) {
|
|
571
|
+
const t = projectGraphTarget(app, r, doc);
|
|
572
|
+
c.add(`graph:${r.id}`, "ok", `graph of project ${peer(r.name)}${r.id === here.id ? " (here)" : ""}`, `${describeGraphTarget(t)}${t.kind === "local" ? `: ${t.why}` : ""}`);
|
|
573
|
+
}
|
|
574
|
+
if (rows.length > MAX_GRAPH_ROWS)
|
|
575
|
+
c.add("graph:more", "ok", "graphs of other projects", `${rows.length - MAX_GRAPH_ROWS} more not listed (run \`p2p project show\` in each)`);
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Graph memory (graph-memory.ts): whether this Ix has the OSS `ix note` (local) or Ix Pro's (cloud,
|
|
579
|
+
* so memory stays off), and what `p2p watch` wrote, queued and dropped. Never a failure: Peer2Peer
|
|
580
|
+
* works without it.
|
|
581
|
+
*/
|
|
582
|
+
async function graphMemoryChecks(c, app, bin, target, ms) {
|
|
583
|
+
if (!graphMemoryEnabled(app.env, app.home)) {
|
|
584
|
+
c.add("ix-memory", "ok", "Ix graph memory", 'off ("ixMemory": false in config.json, or P2P_IX_MEMORY=0)');
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
const support = (await bounded(ixMemorySupport(bin, app.env, target, ms), ms + 500)).value;
|
|
588
|
+
const doc = (await bounded(graphMemoryReport(app), ms)).value;
|
|
589
|
+
const counts = doc ? `${doc.written} written, ${doc.queue.length} queued` : "nothing written yet";
|
|
590
|
+
const dropped = doc ? Object.entries(doc.dropped).filter(([, n]) => n > 0) : [];
|
|
591
|
+
if (support === "oss")
|
|
592
|
+
c.add("ix-memory", "ok", "Ix graph memory", `on: sessions' records, statuses and edited files go to the local graph only (${target.endpoint}); ${counts}`);
|
|
593
|
+
else if (support === "pro")
|
|
594
|
+
c.add("ix-memory", "unknown", "Ix graph memory", "off: Ix Pro is installed, and its `ix note` writes to your cloud org; Peer2Peer keeps graph writes local", "use an Ix without Pro for local notes (or leave it off)");
|
|
595
|
+
else if (support === "none")
|
|
596
|
+
c.add("ix-memory", "unknown", "Ix graph memory", "off: this Ix has no local `ix note` (it came after Ix 0.13.0)", "upgrade Ix (`ix upgrade`)");
|
|
597
|
+
else
|
|
598
|
+
c.add("ix-memory", "unknown", "Ix graph memory", `couldn't tell whether this Ix has a local \`ix note\`; ${counts}`, "run `ix --help` in a terminal");
|
|
599
|
+
if (dropped.length > 0) {
|
|
600
|
+
const total = dropped.reduce((a, [, n]) => a + n, 0);
|
|
601
|
+
c.add("ix-memory-dropped", "unknown", "Ix graph memory dropped", `${total} item${total === 1 ? "" : "s"} not written (${dropped.map(([r, n]) => `${peer(r)}: ${n}`).join(", ")})`, "best effort: each reason is counted; the queue holds 64 items");
|
|
602
|
+
}
|
|
603
|
+
if (doc?.unavailable && support === "oss") {
|
|
604
|
+
// Who holds the local endpoint's port wasn't this user (ext-ix listener.ts): say what to do.
|
|
605
|
+
const fix = doc.unavailable.reason === "ix_listener"
|
|
606
|
+
? `start your Ix backend (\`ix docker start\`); if another user's process holds the port, use a port of yours (\`ixEndpoint\` in config.json). On Linux, Docker's port proxy runs as root: if this machine's Docker is only yours, set "ixTrustRootListener": true in config.json (by hand)`
|
|
607
|
+
: undefined;
|
|
608
|
+
c.add("ix-memory-last", "unknown", "Ix graph memory", `last stopped: ${peer(doc.unavailable.message, 300)}`, fix);
|
|
609
|
+
}
|
|
610
|
+
if (app.file.ixTrustRootListener === true)
|
|
611
|
+
c.add("ix-memory-root", "ok", "Ix graph memory", 'a root-owned listener on the local port counts as yours ("ixTrustRootListener": true in config.json)');
|
|
612
|
+
}
|
|
613
|
+
// ---------------------------------------------------------------------------
|
|
614
|
+
// About another user
|
|
615
|
+
/**
|
|
616
|
+
* Refreshes `userId`'s document from at most 5 relays, whatever its held (possibly forked) view
|
|
617
|
+
* lists: a peer's document chooses those hosts, so the doctor never contacts more of them than a
|
|
618
|
+
* single document may list (§5.8). Writes land in the read-only overlay (readonly.ts).
|
|
619
|
+
*/
|
|
620
|
+
async function refreshCapped(app, userId, relays) {
|
|
621
|
+
const allowed = new Set(relays.slice(0, MAX_PEER_RELAYS));
|
|
622
|
+
const only = (rs) => rs.filter((r) => allowed.has(r));
|
|
623
|
+
const f = app.fetcher();
|
|
624
|
+
const v = await coreRefreshIdentity(app.store, userId, { tips: (u, rs) => f.tips(u, only(rs)), chain: (u, rs, to, n) => f.chain(u, only(rs), to, n) }, { relays: [...allowed] });
|
|
625
|
+
return v.incomplete ? undefined : v;
|
|
626
|
+
}
|
|
627
|
+
async function userChecks(c, app, userId, ms, mine) {
|
|
628
|
+
const now = Date.now();
|
|
629
|
+
const nowS = nowSec();
|
|
630
|
+
const store = app.store;
|
|
631
|
+
const me = app.userId;
|
|
632
|
+
// Friendship, or circles we share.
|
|
633
|
+
const friendship = await bounded((async () => {
|
|
634
|
+
const live = await liveFriendshipsV3(store, app.signerCtx(), (f) => f.inviter === userId || f.invitee === userId);
|
|
635
|
+
const unfriends = await store.listUnfriends();
|
|
636
|
+
return live.find((f) => !unfriends.some((u) => unfriendApplies(f, u)));
|
|
637
|
+
})(), ms);
|
|
638
|
+
const circles = await circlesOf(app, ms);
|
|
639
|
+
const shared = [];
|
|
640
|
+
for (const s of circles) {
|
|
641
|
+
if (!s.joined)
|
|
642
|
+
continue;
|
|
643
|
+
const m = (await bounded(circleMembers(app, s.cid), ms)).value;
|
|
644
|
+
const them = m?.members.find((x) => x.userId === userId);
|
|
645
|
+
const self = m?.members.find((x) => x.self);
|
|
646
|
+
if (them)
|
|
647
|
+
shared.push({ cid: s.cid, name: peer(s.name), meStands: !!self?.stands, themStands: them.stands });
|
|
648
|
+
}
|
|
649
|
+
const standing = shared.filter((s) => s.meStands && s.themStands);
|
|
650
|
+
const circleText = (list) => list.map((s) => `"${s.name}"`).join(", ");
|
|
651
|
+
if (friendship.timedOut)
|
|
652
|
+
c.add("friendship", "unknown", "friendship", "couldn't check in time", "run `p2p doctor` again");
|
|
653
|
+
else if (friendship.value) {
|
|
654
|
+
c.add("friendship", "ok", "friendship", `friends since ${new Date(friendship.value.iat * 1000).toISOString().slice(0, 10)}${standing.length ? `; you also share ${circleText(standing)}` : ""}`);
|
|
655
|
+
}
|
|
656
|
+
else if (standing.length > 0)
|
|
657
|
+
c.add("friendship", "ok", "friendship", `not friends, but you both stand in ${circleText(standing)}`);
|
|
658
|
+
else if (shared.length > 0)
|
|
659
|
+
c.add("friendship", "fail", "friendship", `not friends; you share ${circleText(shared)} but ${shared.some((s) => !s.themStands) ? "they don't stand in it (no join statement)" : "you don't stand in it"}`, "re-join from a fresh circle link (`p2p circle join <link>`), or become friends: `p2p invite` and they run `p2p join <code>` (or `/peers join <code>`)");
|
|
660
|
+
else
|
|
661
|
+
c.add("friendship", "fail", "friendship", "you're not friends and share no circle", "make an invite: `p2p invite` (or `/peers invite`), and they run `p2p join <code>` (or `/peers join <code>`)");
|
|
662
|
+
// Their identity document.
|
|
663
|
+
const held = (await bounded(app.view(userId), ms)).value;
|
|
664
|
+
const probeRelays = [...new Set([...(held?.relays ?? []), ...app.relays])].slice(0, 5);
|
|
665
|
+
const refreshed = await bounded(refreshCapped(app, userId, probeRelays), ms * 2);
|
|
666
|
+
const view = refreshed.value ?? held;
|
|
667
|
+
if (!view) {
|
|
668
|
+
c.add("their-document", "fail", "their identity document", `not found on ${probeRelays.length ? probeRelays.map(peerUrl).join(", ") : "any relay"}${refreshed.timedOut ? " (timed out)" : ""}`, "ask them to run `p2p doctor` (their document may not be published), or for a fresh invite that carries it");
|
|
669
|
+
}
|
|
670
|
+
else {
|
|
671
|
+
const f = identityFreshness(view.head.exp, nowS);
|
|
672
|
+
const how = refreshed.value ? "fetched just now" : "the copy held here (couldn't refresh it)";
|
|
673
|
+
if (f === "fresh")
|
|
674
|
+
c.add("their-document", refreshed.value ? "ok" : "unknown", "their identity document", `version ${view.head.ver}, fresh (expires in ${days(view.head.exp - nowS)}); ${how}`, "check your relays are reachable, then `p2p doctor <user>` again");
|
|
675
|
+
else
|
|
676
|
+
c.add("their-document", "fail", "their identity document", `version ${view.head.ver} expired ${days(nowS - view.head.exp)} ago (${f === "fail-closed" ? "hard expiry: everything from them is refused" : "soft expiry"}); ${how}`, "they need to run any `p2p` command (or open Claude Code with the mod) on a key-holding device");
|
|
677
|
+
if (view.rotations.length > 0)
|
|
678
|
+
c.add("their-rotation", "fail", "their identity", "they moved to a new key", "approve the move when it's held (`p2p held`), or ask them for a fresh invite");
|
|
679
|
+
}
|
|
680
|
+
// Their relays, and one we share and reach.
|
|
681
|
+
if (view) {
|
|
682
|
+
// A peer's document (every tip of it) chooses these hosts: probe at most 5, keep no answer body.
|
|
683
|
+
const theirs = orderRelays(view.head.relays, view.relays).slice(0, MAX_PEER_RELAYS);
|
|
684
|
+
const ours = new Set(app.relays);
|
|
685
|
+
const mineByRelay = new Map(mine.map((r) => [r.relay, r]));
|
|
686
|
+
const others = theirs.filter((r) => !mineByRelay.has(r));
|
|
687
|
+
const probed = new Map(await Promise.all(others.map(async (r) => [r, (await httpProbe(`${app.transport(r).http}/identity/${encodeURIComponent(userId)}`, ms)).ok])));
|
|
688
|
+
const reach = (r) => (mineByRelay.get(r)?.reachable ?? probed.get(r)) === true;
|
|
689
|
+
const common = theirs.filter((r) => ours.has(r));
|
|
690
|
+
const reachableTheirs = theirs.filter(reach);
|
|
691
|
+
const list = theirs.map((r) => `${peerUrl(r)}${reach(r) ? "" : " (unreachable from here)"}`).join(", ");
|
|
692
|
+
if (common.some(reach))
|
|
693
|
+
c.add("relays", "ok", "relays", `they list ${list}; you share ${common.filter(reach).map(peerUrl).join(", ")}, reachable from here`);
|
|
694
|
+
else if (common.length > 0)
|
|
695
|
+
c.add("relays", "fail", "relays", `they list ${list}; the relay you share isn't reachable from here`, "check your network; or both add another relay you can reach: `p2p relays add <wss://…>`");
|
|
696
|
+
else if (reachableTheirs.length > 0)
|
|
697
|
+
c.add("relays", "unknown", "relays", `they list ${list}; you share none (you reach theirs, but can they reach ${app.relays.join(", ")}?)`, "use a common relay: one of you runs `p2p relays add <url>` (or `/peers relays add <url>`) with a relay the other lists");
|
|
698
|
+
else
|
|
699
|
+
c.add("relays", "fail", "relays", `they list ${list}; you share none and reach none of theirs`, "use a common relay you both reach: `p2p relays add <url>` (or `/peers relays add <url>`)");
|
|
700
|
+
// Caps we hold for them (what `p2p send` and statuses would use).
|
|
701
|
+
const caps = (await bounded(app.capsFor(userId, "status"), ms)).value;
|
|
702
|
+
const targets = theirs.slice(0, 3);
|
|
703
|
+
if (!caps)
|
|
704
|
+
c.add("cap-ours", "unknown", "your capability for them", "couldn't check in time", "run `p2p doctor` again");
|
|
705
|
+
else {
|
|
706
|
+
const usable = targets.filter((r) => caps.has(r));
|
|
707
|
+
if (usable.length > 0)
|
|
708
|
+
c.add("cap-ours", "ok", "your capability for them", `you can reach their mailbox on ${usable.map(peerUrl).join(", ")}`);
|
|
709
|
+
else if (caps.size > 0)
|
|
710
|
+
c.add("cap-ours", "fail", "your capability for them", `the capabilities you hold name ${[...caps.keys()].slice(0, MAX_PEER_RELAYS).map(peerUrl).join(", ")}, none of their current relays`, "they changed relays: a fresh invite re-grants it (`p2p invite`, they run `p2p join <code>`)");
|
|
711
|
+
else
|
|
712
|
+
c.add("cap-ours", "fail", "your capability for them", "you hold none, so your statuses and messages can't reach them", "become friends (`p2p invite` → they `p2p join <code>`) or share a circle you both stand in");
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
// Caps they hold for us, as far as we can tell: what we issued them, and our join cap in circles we share.
|
|
716
|
+
const issued = ((await bounded(store.listCapsIssued(), ms)).value ?? []).filter((x) => x.sub === userId && x.exp > nowS + 60 && capAllowsKind(x.kinds, "status"));
|
|
717
|
+
const ours = new Set(app.relays);
|
|
718
|
+
const fromCircles = [];
|
|
719
|
+
for (const s of standing) {
|
|
720
|
+
const rec = (await bounded(store.getCircle(s.cid), ms)).value;
|
|
721
|
+
const st = rec?.statements[me];
|
|
722
|
+
const cap = st?.op === "join" ? joinCapOf(st.jws) : undefined;
|
|
723
|
+
const p = cap ? capPeek(cap) : undefined;
|
|
724
|
+
if (p && p.exp > nowS + 60)
|
|
725
|
+
fromCircles.push({ relays: p.relays, exp: p.exp });
|
|
726
|
+
}
|
|
727
|
+
const all = [...issued.map((x) => ({ relays: x.relays, exp: x.exp })), ...fromCircles];
|
|
728
|
+
const reaching = all.filter((x) => x.relays.some((r) => ours.has(r)));
|
|
729
|
+
if (reaching.length > 0) {
|
|
730
|
+
const exp = Math.max(...reaching.map((x) => x.exp));
|
|
731
|
+
c.add("cap-theirs", "ok", "their capability for you", `you gave them one for ${[...new Set(reaching.flatMap((x) => x.relays.filter((r) => ours.has(r))))].join(", ")} (good for ${days(exp - nowS)})`);
|
|
732
|
+
}
|
|
733
|
+
else if (all.length > 0)
|
|
734
|
+
c.add("cap-theirs", "fail", "their capability for you", `the capabilities you gave them name ${[...new Set(all.flatMap((x) => x.relays))].join(", ")}, none of your current relays`, "their statuses can't reach you: a fresh invite fixes it (`p2p invite`, they run `p2p join <code>`)");
|
|
735
|
+
else
|
|
736
|
+
c.add("cap-theirs", "fail", "their capability for you", "this device has no record of giving them one, so their statuses can't reach your relays", "become friends (`p2p invite` → they `p2p join <code>`), or both stand in one circle");
|
|
737
|
+
// When anything last arrived from them.
|
|
738
|
+
const peers = (await bounded(app.state.get("peers"), ms)).value ?? {};
|
|
739
|
+
const events = (await bounded(app.state.get("events"), ms)).value;
|
|
740
|
+
const recs = Object.values(peers)
|
|
741
|
+
.filter((p) => p.own === userId)
|
|
742
|
+
.sort((a, b) => b.ts - a.ts);
|
|
743
|
+
const lastEvent = (events?.items ?? [])
|
|
744
|
+
.filter((e) => e.data.from?.userId === userId)
|
|
745
|
+
.reduce((m, e) => Math.max(m, e.at), 0);
|
|
746
|
+
const lastStatus = recs[0]?.ts ?? 0;
|
|
747
|
+
const queued = mine.reduce((n, r) => n + r.ws.queued, 0);
|
|
748
|
+
const queuedNote = queued > 0 ? ` ${queued} envelope${queued === 1 ? " is" : "s are"} still waiting in this device's mailbox: \`p2p ls\` processes them` : "";
|
|
749
|
+
if (lastStatus === 0 && lastEvent === 0) {
|
|
750
|
+
c.add("received", "fail", "last heard from them", `nothing from them has reached this device yet.${queuedNote}`, queued > 0 ? "run `p2p ls`, then `p2p doctor <user>` again" : "ask them to run `p2p doctor <you>` (or `/peers doctor <you>`): their side shows what's missing");
|
|
751
|
+
}
|
|
752
|
+
else {
|
|
753
|
+
const last = Math.max(lastStatus, lastEvent);
|
|
754
|
+
c.add("received", "ok", "last heard from them", `${ago(now - last)}${lastStatus ? ` (last status ${ago(now - lastStatus)})` : ""}${queuedNote ? `.${queuedNote}` : ""}`);
|
|
755
|
+
}
|
|
756
|
+
// Blocked, suspended, held.
|
|
757
|
+
const blocked = (await bounded(store.isBlocked(userId), ms)).value === true;
|
|
758
|
+
const disputes = (await bounded(app.state.get("disputes"), ms)).value ?? {};
|
|
759
|
+
const dispute = Object.values(disputes).find((d) => d.suspended.some((s) => s.userId === userId) || d.candidates.includes(userId));
|
|
760
|
+
const heldItems = ((await bounded(app.state.get("held"), ms)).value ?? []).filter((h) => h.from === userId);
|
|
761
|
+
if (blocked)
|
|
762
|
+
c.add("blocked", "fail", "blocked", "you blocked them: everything from them is refused", `\`p2p unblock ${userId}\``);
|
|
763
|
+
if (dispute)
|
|
764
|
+
c.add("suspended", "fail", "suspended", "suspended: another key also claims to be them (a contested move to a new key)", `check with them another way, then \`p2p identity dispute ${dispute.heldId} --keep <userId>\` (or /peers approve)`);
|
|
765
|
+
for (const h of heldItems.slice(0, 3)) {
|
|
766
|
+
c.add(`held:${h.id}`, "fail", "held", `a ${h.type.replace(/-/g, " ")} from them waits for you`, `\`/peers approve ${h.id}\` or \`p2p held approve ${h.id}\` (decline: \`p2p held decline ${h.id}\`)`);
|
|
767
|
+
}
|
|
768
|
+
if (!blocked && !dispute && heldItems.length === 0)
|
|
769
|
+
c.add("blocked", "ok", "blocks and holds", "not blocked, suspended or held");
|
|
770
|
+
// Their sessions: shared with an audience we're in?
|
|
771
|
+
const myCircle = app.self?.defaultCircle ? standing.find((s) => s.cid === app.self?.defaultCircle) ?? standing[0] : standing[0];
|
|
772
|
+
const askShare = myCircle
|
|
773
|
+
? `they haven't shared any session with "${myCircle.name}": ask them to share their project with it, \`/peers project share ${myCircle.cid}\` in their session (or \`p2p project share ${myCircle.cid}\` in the repository)`
|
|
774
|
+
: `ask them to share their project with you: \`/peers project share --person ${displayAddress(me, app.self?.name ?? "?")}\` in their session (or \`p2p project share --person <you>\` in the repository)`;
|
|
775
|
+
if (recs.length === 0) {
|
|
776
|
+
c.add("their-sessions", "fail", "their sessions", `no status from any of their sessions has reached you.${queuedNote}`, queued > 0 ? "run `p2p ls`, then `p2p doctor <user>` again" : askShare);
|
|
777
|
+
}
|
|
778
|
+
else {
|
|
779
|
+
let reported = 0;
|
|
780
|
+
for (const p of recs.slice(0, 3)) {
|
|
781
|
+
const roster = (await bounded(store.getRoster(userId, p.sid), ms)).value;
|
|
782
|
+
let r = {};
|
|
783
|
+
try {
|
|
784
|
+
r = roster ? decodeTyped(roster.jws, TYP3.roster).payload : {};
|
|
785
|
+
}
|
|
786
|
+
catch {
|
|
787
|
+
r = {};
|
|
788
|
+
}
|
|
789
|
+
const parts = Array.isArray(r.parts) ? r.parts : [];
|
|
790
|
+
const circle = typeof r.circle === "string" ? r.circle : undefined;
|
|
791
|
+
const inCircle = circle ? standing.some((s) => s.cid === circle) : false;
|
|
792
|
+
const circleName = circle ? (shared.find((s) => s.cid === circle)?.name ?? peer(circle, 128)) : undefined;
|
|
793
|
+
const via = parts.includes(me) ? "you directly" : r.vis === "circle" && circle ? `circle "${circleName}"` : "nobody else (private)";
|
|
794
|
+
const label = `session "${peer(p.status.label)}" [${sessionRef(userId, p.sid)}]`;
|
|
795
|
+
const isIn = parts.includes(me) || (r.vis === "circle" && inCircle) || p.viewerRule !== undefined;
|
|
796
|
+
const liveNow = isLive(p.ts, now);
|
|
797
|
+
if (!isIn)
|
|
798
|
+
c.add(`their-session:${safeSid(p.sid)}`, "fail", label, `shared with ${via}, which doesn't include you`, circle && !inCircle ? `you don't stand in that circle: ask its owner to add you, or them to run \`/peers add <you>\` in that session` : askShare);
|
|
799
|
+
else if (!liveNow)
|
|
800
|
+
c.add(`their-session:${safeSid(p.sid)}`, "fail", label, `shared with ${via}, but its last status was ${ago(now - p.ts)}: not live`, "their session isn't running, or its status isn't going out: ask them to run `/peers doctor`");
|
|
801
|
+
else
|
|
802
|
+
c.add(`their-session:${safeSid(p.sid)}`, "ok", label, `live (${p.status.state}, ${ago(now - p.ts)}), shared with ${via}`);
|
|
803
|
+
reported++;
|
|
804
|
+
}
|
|
805
|
+
if (recs.length > reported)
|
|
806
|
+
c.add("their-sessions", "ok", "their sessions", `${recs.length - reported} more not shown`);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
// ---------------------------------------------------------------------------
|
|
810
|
+
export function summarize(checks) {
|
|
811
|
+
return {
|
|
812
|
+
ok: checks.filter((x) => x.status === "ok").length,
|
|
813
|
+
fail: checks.filter((x) => x.status === "fail").length,
|
|
814
|
+
unknown: checks.filter((x) => x.status === "unknown").length,
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
/** The doctor's per-step bound: P2P_DOCTOR_TIMEOUT_MS (default 5 s), never more than the connect timeout. */
|
|
818
|
+
export function doctorTimeoutMs(app, override) {
|
|
819
|
+
if (override !== undefined)
|
|
820
|
+
return override;
|
|
821
|
+
const raw = Number(app.env.P2P_DOCTOR_TIMEOUT_MS);
|
|
822
|
+
const base = Number.isFinite(raw) && raw > 0 ? raw : 5000;
|
|
823
|
+
const cap = app.tun.connectTimeoutMs > 0 ? app.tun.connectTimeoutMs : base;
|
|
824
|
+
return Math.max(200, Math.min(base, cap));
|
|
825
|
+
}
|
|
826
|
+
export async function doctor(app, o) {
|
|
827
|
+
// Read-only, whoever calls: on a writable context, diagnose through a read-only one (readonly.ts).
|
|
828
|
+
if (!app.readOnly)
|
|
829
|
+
app = new App({ env: app.env, io: app.io, readOnly: true });
|
|
830
|
+
const ms = doctorTimeoutMs(app, o.timeoutMs);
|
|
831
|
+
// Every network step the app itself takes (identity refreshes, discovery) is bounded the same way.
|
|
832
|
+
app.tun.connectTimeoutMs = ms;
|
|
833
|
+
app.tun.requestTimeoutMs = ms;
|
|
834
|
+
const c = new Checks();
|
|
835
|
+
const scope = o.user !== undefined ? "user" : "device";
|
|
836
|
+
const hasIdentity = await app.load(false).catch(() => false);
|
|
837
|
+
if (!hasIdentity) {
|
|
838
|
+
c.add("identity", "fail", "identity", "this device has no Peer2Peer identity yet", "run `/peers setup` in Claude Code (or `p2p setup`), then `/peers join <code>` with a code from a friend");
|
|
839
|
+
let relays;
|
|
840
|
+
try {
|
|
841
|
+
relays = defaultRelays(app.env, app.file);
|
|
842
|
+
}
|
|
843
|
+
catch {
|
|
844
|
+
relays = [];
|
|
845
|
+
}
|
|
846
|
+
if (relays.length === 0)
|
|
847
|
+
c.add("relays", "unknown", "relays", "no relays configured yet", "`p2p setup --relay <wss://…>` picks one");
|
|
848
|
+
else
|
|
849
|
+
relayChecks(c, app, await probeRelays(app, relays, ms, false), undefined);
|
|
850
|
+
await versionCheck(c, app, o, ms);
|
|
851
|
+
return { scope, version: o.version, ...(o.user !== undefined ? { user: { input: o.user } } : {}), checks: c.list, summary: summarize(c.list) };
|
|
852
|
+
}
|
|
853
|
+
const reports = await probeRelays(app, app.relays, ms, true, app.userId);
|
|
854
|
+
if (scope === "device") {
|
|
855
|
+
await deviceChecks(c, app, o, ms, reports);
|
|
856
|
+
return { scope, version: o.version, checks: c.list, summary: summarize(c.list) };
|
|
857
|
+
}
|
|
858
|
+
// About a user: who they are first (a userId needn't be known yet).
|
|
859
|
+
const input = o.user.trim();
|
|
860
|
+
let userId;
|
|
861
|
+
try {
|
|
862
|
+
userId = isUserId(input) ? input : await app.resolveUser(input);
|
|
863
|
+
}
|
|
864
|
+
catch (e) {
|
|
865
|
+
const amb = e instanceof CliError && e.code === "ambiguous";
|
|
866
|
+
c.add("user", "fail", "who", amb ? `more than one known identity matches "${peer(input)}"` : `no known identity matches "${peer(input)}"`, amb ? "use their name@fingerprint (as `p2p friends` shows it), or set a petname: `p2p petname <userId> <name>`" : "use their full name@fingerprint or userId (ask them for `p2p whoami`); if you've never connected, make an invite: `p2p invite`");
|
|
867
|
+
return { scope, version: o.version, user: { input }, checks: c.list, summary: summarize(c.list) };
|
|
868
|
+
}
|
|
869
|
+
if (userId === app.userId) {
|
|
870
|
+
await deviceChecks(c, app, o, ms, reports);
|
|
871
|
+
return { scope: "device", version: o.version, user: { input, userId, address: await app.addressOf(userId) }, checks: c.list, summary: summarize(c.list) };
|
|
872
|
+
}
|
|
873
|
+
// This device first, in one line (its details are `p2p doctor` with no user).
|
|
874
|
+
const dev = new Checks();
|
|
875
|
+
await deviceChecks(dev, app, o, ms, reports);
|
|
876
|
+
// Only what decides whether this device can hear anyone: identity, document, relays, clock.
|
|
877
|
+
const bad = dev.list.filter((x) => x.status === "fail" && /^(identity|document|relay:|published:|clock)/.test(x.id));
|
|
878
|
+
if (bad.length === 0)
|
|
879
|
+
c.add("device", "ok", "this device", "identity, relays and clock look fine");
|
|
880
|
+
else
|
|
881
|
+
c.add("device", "fail", "this device", `${bad.length} problem${bad.length === 1 ? "" : "s"}: ${bad.map((x) => x.title).join(", ")}`, "run `p2p doctor` (no user) for details and fixes");
|
|
882
|
+
await userChecks(c, app, userId, ms, reports);
|
|
883
|
+
const versions = await versionChecks(c, app, userId);
|
|
884
|
+
return { scope, version: o.version, user: { input, userId, address: await app.addressOf(userId) }, checks: c.list, summary: summarize(c.list), ...versions };
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* Each of the user's devices with its client version and what it understands (from its identity
|
|
888
|
+
* document entry or its latest status), and the features unavailable between you. A difference is
|
|
889
|
+
* never a failure: the feature is left out between you, and everything you share still works.
|
|
890
|
+
*/
|
|
891
|
+
async function versionChecks(c, app, userId) {
|
|
892
|
+
const devices = await peerDevices(app, userId).catch(() => []);
|
|
893
|
+
for (const d of devices) {
|
|
894
|
+
const name = d.label ? `device "${peer(d.label)}"` : `device ${d.did.slice(0, 12)}`;
|
|
895
|
+
if (!d.source) {
|
|
896
|
+
c.add(`version:${d.did}`, "unknown", name, "its client version isn't known yet (no status from it, and its identity document doesn't say)", "it shows once one of its sessions shares a status with you");
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
const caps = d.caps.filter((x) => !x.startsWith("proto.")).join(", ") || "none listed";
|
|
900
|
+
// The exact version only when the device publishes it (opt-in `dinfo`); else the protocol minor says enough.
|
|
901
|
+
c.add(`version:${d.did}`, "ok", name, `protocol 3.${d.proto}${d.client ? `, client ${peer(d.client)}` : ""}; understands ${caps}${d.source === "status" ? " (from its latest status)" : ""}`);
|
|
902
|
+
}
|
|
903
|
+
const known = devices.filter((d) => d.source).map((d) => d.caps.concat(d.proto > 0 ? [`proto.3.${d.proto}`] : []));
|
|
904
|
+
const unavailable = unavailableBetween(CLI_CAPS, known);
|
|
905
|
+
const words = (caps) => caps.map((cap) => KNOWN_FEATURES.find((f) => f.cap === cap)?.what ?? cap).join("; ");
|
|
906
|
+
if (known.length > 0) {
|
|
907
|
+
if (unavailable.theyLack.length === 0 && unavailable.weLack.length === 0)
|
|
908
|
+
c.add("features", "ok", "features", "everything this client knows works between you");
|
|
909
|
+
else {
|
|
910
|
+
const parts = [
|
|
911
|
+
...(unavailable.theyLack.length ? [`their client can't use: ${words(unavailable.theyLack)}`] : []),
|
|
912
|
+
...(unavailable.weLack.length ? [`yours can't use: ${words(unavailable.weLack)}`] : []),
|
|
913
|
+
];
|
|
914
|
+
c.add("features", "ok", "features", `${parts.join("; ")}. Those are left out between you; the rest works`, unavailable.weLack.length ? "update p2p to use them" : "they can update to use them");
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return { devices, unavailable };
|
|
918
|
+
}
|
|
919
|
+
/** Human output: one line per check (✓ ✗ ?), with its fix indented below. */
|
|
920
|
+
export function formatDoctor(r) {
|
|
921
|
+
const head = r.scope === "user" && r.user ? `p2p doctor: can you see ${r.user.address ?? r.user.input}?` : "p2p doctor: this device";
|
|
922
|
+
const lines = [head, ""];
|
|
923
|
+
for (const x of r.checks) {
|
|
924
|
+
lines.push(`${MARK[x.status]} ${x.title}: ${x.detail}`);
|
|
925
|
+
if (x.fix)
|
|
926
|
+
lines.push(` ${x.status === "unknown" ? "to tell" : "fix"}: ${x.fix}`);
|
|
927
|
+
}
|
|
928
|
+
lines.push("", `${r.summary.ok} ✓ ${r.summary.fail} ✗ ${r.summary.unknown} ?`);
|
|
929
|
+
return lines.join("\n");
|
|
930
|
+
}
|