@infernetprotocol/cli 0.1.22

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 (50) hide show
  1. package/LICENSE +15 -0
  2. package/commands/chat.js +268 -0
  3. package/commands/console.js +229 -0
  4. package/commands/debug.js +222 -0
  5. package/commands/deploy.js +524 -0
  6. package/commands/doctor.js +501 -0
  7. package/commands/firewall.js +39 -0
  8. package/commands/gpu.js +130 -0
  9. package/commands/help.js +54 -0
  10. package/commands/init.js +304 -0
  11. package/commands/login.js +305 -0
  12. package/commands/logs.js +93 -0
  13. package/commands/model.js +359 -0
  14. package/commands/payments.js +92 -0
  15. package/commands/payout.js +128 -0
  16. package/commands/pubkey.js +116 -0
  17. package/commands/register.js +304 -0
  18. package/commands/remove.js +230 -0
  19. package/commands/service.js +255 -0
  20. package/commands/setup.js +869 -0
  21. package/commands/start.js +903 -0
  22. package/commands/stats.js +85 -0
  23. package/commands/status.js +116 -0
  24. package/commands/stop.js +81 -0
  25. package/commands/train.js +563 -0
  26. package/commands/tui.js +285 -0
  27. package/commands/uncensored.js +222 -0
  28. package/commands/update.js +80 -0
  29. package/commands/upgrade.js +2 -0
  30. package/examples/app.js +153 -0
  31. package/index.js +207 -0
  32. package/lib/chat-executor.js +232 -0
  33. package/lib/config.js +148 -0
  34. package/lib/daemonize.js +46 -0
  35. package/lib/firewall.js +190 -0
  36. package/lib/hf-model.js +166 -0
  37. package/lib/identity.js +18 -0
  38. package/lib/ipc.js +114 -0
  39. package/lib/model-fit.js +67 -0
  40. package/lib/model-key.js +52 -0
  41. package/lib/network.js +240 -0
  42. package/lib/nip44.js +130 -0
  43. package/lib/node-client.js +152 -0
  44. package/lib/peers.js +133 -0
  45. package/lib/prompt.js +49 -0
  46. package/lib/remote-chat.js +115 -0
  47. package/lib/route.js +44 -0
  48. package/lib/runtime-config.js +130 -0
  49. package/lib/version.js +32 -0
  50. package/package.json +57 -0
@@ -0,0 +1,501 @@
1
+ /**
2
+ * `infernet doctor` — diagnose all three sides of a P2P chat round-trip.
3
+ *
4
+ * 1. Local config — file present, mode 0600, has identity + URL
5
+ * 2. Engine — Ollama reachable, configured model is pulled
6
+ * 3. Control plane — URL responds, /api/overview is reachable
7
+ * 4. Daemon — running, IPC socket healthy, recent heartbeat
8
+ * 5. Provider row — signed `me` returns this node's row
9
+ * 6. End-to-end — submit a tiny chat job, see it routed + done
10
+ *
11
+ * Each check is independent — failures don't abort, they're reported
12
+ * with a remediation hint and the doctor moves on. Exit 0 if all pass,
13
+ * 1 if any failed.
14
+ *
15
+ * Usage:
16
+ * infernet doctor # full sweep
17
+ * infernet doctor --skip-e2e # skip the test inference
18
+ * infernet doctor --url <url> # override control-plane URL
19
+ */
20
+
21
+ import fs from "node:fs/promises";
22
+ import { loadConfig, getConfigPath, getConfigDir, getDaemonLogPath, fixConfigPermissions } from "../lib/config.js";
23
+ import { isDaemonAlive, sendToDaemon } from "../lib/ipc.js";
24
+ import { spawnDetachedDaemon } from "../lib/daemonize.js";
25
+ import { createNodeClient } from "../lib/node-client.js";
26
+ import { submitChatJob, streamChatEvents } from "../lib/remote-chat.js";
27
+
28
+ const HELP = `infernet doctor — diagnose P2P chat readiness
29
+
30
+ Usage:
31
+ infernet doctor [flags]
32
+
33
+ Flags:
34
+ --url <url> Override control-plane URL (default: config.controlPlane.url)
35
+ --skip-e2e Skip the end-to-end test inference
36
+ --model <name> Model to request in the e2e test (default: config.engine.model)
37
+ --json Emit results as one JSON object per check
38
+ -h, --help Show this help
39
+
40
+ Exit code: 0 if every check passes, 1 if any fails.
41
+ `;
42
+
43
+ const TTY = process.stdout.isTTY && !process.env.NO_COLOR;
44
+ const C = {
45
+ reset: TTY ? "\x1b[0m" : "",
46
+ bold: TTY ? "\x1b[1m" : "",
47
+ dim: TTY ? "\x1b[2m" : "",
48
+ green: TTY ? "\x1b[32m" : "",
49
+ red: TTY ? "\x1b[31m" : "",
50
+ yellow: TTY ? "\x1b[33m" : "",
51
+ blue: TTY ? "\x1b[34m" : ""
52
+ };
53
+
54
+ const ICON = {
55
+ ok: `${C.green}✓${C.reset}`,
56
+ fail: `${C.red}✗${C.reset}`,
57
+ warn: `${C.yellow}!${C.reset}`,
58
+ skip: `${C.dim}—${C.reset}`
59
+ };
60
+
61
+ function printCheck(idx, total, name, result) {
62
+ const icon = ICON[result.status] ?? "?";
63
+ const pad = name.padEnd(26);
64
+ process.stdout.write(`[${idx}/${total}] ${pad} ${icon} ${result.summary}\n`);
65
+ if (result.details) {
66
+ for (const line of result.details.split("\n")) {
67
+ if (line) process.stdout.write(` ${C.dim}${line}${C.reset}\n`);
68
+ }
69
+ }
70
+ if (result.hint) {
71
+ process.stdout.write(` ${C.yellow}→${C.reset} ${result.hint}\n`);
72
+ }
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // 1. Local config
77
+ // ---------------------------------------------------------------------------
78
+ async function checkConfig() {
79
+ const path = getConfigPath();
80
+ let stat;
81
+ try {
82
+ stat = await fs.stat(path);
83
+ } catch {
84
+ return {
85
+ status: "fail",
86
+ summary: `no config at ${path}`,
87
+ hint: "run `infernet init` to create one"
88
+ };
89
+ }
90
+ const config = await loadConfig();
91
+ if (!config) {
92
+ return {
93
+ status: "fail",
94
+ summary: `config at ${path} is unreadable`,
95
+ hint: "delete it and re-run `infernet init`"
96
+ };
97
+ }
98
+ const mode = (stat.mode & 0o777).toString(8).padStart(3, "0");
99
+ const role = config.node?.role ?? "(unset)";
100
+ const name = config.node?.name ?? config.node?.nodeId ?? "(unnamed)";
101
+ const hasKey = !!(config.node?.publicKey && config.node?.privateKey);
102
+ const hasUrl = !!config.controlPlane?.url;
103
+
104
+ const issues = [];
105
+ if (mode !== "600") {
106
+ // Auto-heal: fix permissions right here so the next daemon start
107
+ // doesn't find them wrong.
108
+ try {
109
+ await fixConfigPermissions();
110
+ } catch { /* ignore — may already be correct */ }
111
+ issues.push(`mode was ${mode} (auto-fixed to 600)`);
112
+ }
113
+ if (!hasKey) issues.push("missing Nostr keypair");
114
+ if (!hasUrl) issues.push("missing controlPlane.url");
115
+
116
+ if (issues.length) {
117
+ const onlyPermFix = issues.length === 1 && issues[0].includes("auto-fixed");
118
+ return {
119
+ status: onlyPermFix ? "ok" : "fail",
120
+ summary: `${role}/${name}, key=${config.node.publicKey?.slice(0, 12) ?? "?"}…`,
121
+ details: issues.join("\n"),
122
+ hint: !hasKey || !hasUrl ? "run `infernet init` to fix" : undefined,
123
+ config
124
+ };
125
+ }
126
+ return {
127
+ status: "ok",
128
+ summary: `${role}/${name}, key=${config.node.publicKey.slice(0, 12)}…`,
129
+ details: `path: ${path} (mode ${mode})\nurl: ${config.controlPlane.url}`,
130
+ config
131
+ };
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // 2. Engine (Ollama + configured model)
136
+ // ---------------------------------------------------------------------------
137
+ async function checkEngine(config) {
138
+ const cfgEngine = config?.engine ?? {};
139
+ const host = cfgEngine.ollamaHost ?? process.env.OLLAMA_HOST ?? "http://localhost:11434";
140
+ const wantedModel = cfgEngine.model ?? null;
141
+
142
+ let body;
143
+ try {
144
+ const ctrl = new AbortController();
145
+ const t = setTimeout(() => ctrl.abort(), 2500);
146
+ const res = await fetch(new URL("/api/tags", host), { signal: ctrl.signal });
147
+ clearTimeout(t);
148
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
149
+ body = await res.json();
150
+ } catch (err) {
151
+ return {
152
+ status: "fail",
153
+ summary: `Ollama not reachable at ${host}`,
154
+ details: err?.message ?? String(err),
155
+ hint: "run `infernet setup` to install / start Ollama"
156
+ };
157
+ }
158
+
159
+ const models = body.models ?? [];
160
+ if (!wantedModel) {
161
+ return {
162
+ status: "warn",
163
+ summary: `Ollama up @ ${host}, ${models.length} model${models.length === 1 ? "" : "s"} pulled, no engine.model set`,
164
+ hint: "run `infernet model use <name>` to pick one"
165
+ };
166
+ }
167
+ const have = models.some((m) => (m.name ?? m.model) === wantedModel);
168
+ if (!have) {
169
+ return {
170
+ status: "fail",
171
+ summary: `engine.model=${wantedModel} not pulled`,
172
+ hint: `run \`infernet model pull ${wantedModel}\``
173
+ };
174
+ }
175
+ return {
176
+ status: "ok",
177
+ summary: `Ollama up @ ${host}, model ${wantedModel} pulled`
178
+ };
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // 3. Control plane reachability
183
+ // ---------------------------------------------------------------------------
184
+ async function checkControlPlane(url) {
185
+ if (!url) {
186
+ return {
187
+ status: "fail",
188
+ summary: "no control-plane URL",
189
+ hint: "set with `infernet login --url <https://...>`"
190
+ };
191
+ }
192
+ const start = Date.now();
193
+ try {
194
+ const ctrl = new AbortController();
195
+ const t = setTimeout(() => ctrl.abort(), 5000);
196
+ const res = await fetch(new URL("/api/overview", url), { signal: ctrl.signal });
197
+ clearTimeout(t);
198
+ const elapsed = Date.now() - start;
199
+ if (!res.ok) {
200
+ return {
201
+ status: "fail",
202
+ summary: `${url} → HTTP ${res.status}`,
203
+ details: `${elapsed}ms`,
204
+ hint: "verify the URL or check the deployment is up"
205
+ };
206
+ }
207
+ return {
208
+ status: "ok",
209
+ summary: `${url} (HTTP ${res.status}, ${elapsed}ms)`
210
+ };
211
+ } catch (err) {
212
+ return {
213
+ status: "fail",
214
+ summary: `${url} unreachable`,
215
+ details: err?.message ?? String(err),
216
+ hint: "verify network access to the control plane"
217
+ };
218
+ }
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // 4. Daemon
223
+ // ---------------------------------------------------------------------------
224
+ async function checkDaemon() {
225
+ let alive = await isDaemonAlive(500);
226
+ if (!alive) {
227
+ // Auto-start: doctor starts the daemon rather than just warning.
228
+ try {
229
+ spawnDetachedDaemon([]);
230
+ } catch (err) {
231
+ return {
232
+ status: "fail",
233
+ summary: "daemon not running, auto-start failed",
234
+ details: err?.message ?? String(err),
235
+ hint: "check config with `infernet init` then run `infernet start`"
236
+ };
237
+ }
238
+ // Poll up to 15 seconds — Node.js + ESM startup can be slow.
239
+ for (let i = 0; i < 30; i++) {
240
+ await new Promise((r) => setTimeout(r, 500));
241
+ alive = await isDaemonAlive(500);
242
+ if (alive) break;
243
+ }
244
+ if (!alive) {
245
+ // Grab last few log lines to surface the crash reason.
246
+ let logTail = "";
247
+ try {
248
+ const logPath = getDaemonLogPath();
249
+ const raw = await fs.readFile(logPath, "utf8");
250
+ const lines = raw.trimEnd().split("\n");
251
+ logTail = lines.slice(-6).join("\n");
252
+ } catch { /* log may not exist yet */ }
253
+ return {
254
+ status: "fail",
255
+ summary: "daemon auto-start attempted but not responding",
256
+ details: logTail || undefined,
257
+ hint: "check full log with `infernet logs`"
258
+ };
259
+ }
260
+ // Wait for the first heartbeat so downstream checks (provider row,
261
+ // e2e) see status=available rather than the registration-time default.
262
+ process.stdout.write(" auto-started daemon, waiting for first heartbeat…\n");
263
+ for (let i = 0; i < 90; i++) {
264
+ await new Promise((r) => setTimeout(r, 500));
265
+ const probe = await sendToDaemon("stats", null, { timeoutMs: 1000 });
266
+ if (probe?.ok && probe.data?.stats?.lastHeartbeatAt) break;
267
+ }
268
+ }
269
+ const r = await sendToDaemon("stats", null, { timeoutMs: 1500 });
270
+ if (!r?.ok) {
271
+ return {
272
+ status: "fail",
273
+ summary: "daemon reachable but stats call failed",
274
+ details: r?.error ?? "unknown",
275
+ hint: "try `infernet stop && infernet start`"
276
+ };
277
+ }
278
+ const stats = r.data?.stats ?? {};
279
+ const lastHb = stats.lastHeartbeatAt;
280
+ const ageMs = lastHb ? Date.now() - new Date(lastHb).getTime() : null;
281
+ if (ageMs == null) {
282
+ return {
283
+ status: "warn",
284
+ summary: `pid=${r.data?.pid}, never heartbeated yet`,
285
+ hint: "wait ~30s, then re-run doctor"
286
+ };
287
+ }
288
+ if (ageMs > 60_000) {
289
+ return {
290
+ status: "fail",
291
+ summary: `last heartbeat ${Math.round(ageMs / 1000)}s ago`,
292
+ details: stats.lastHeartbeatError ?? "",
293
+ hint: "check the daemon log: `infernet logs`"
294
+ };
295
+ }
296
+ return {
297
+ status: "ok",
298
+ summary: `pid=${r.data?.pid}, last heartbeat ${Math.round(ageMs / 1000)}s ago, jobs ${stats.jobsCompleted ?? 0}/${stats.jobsPicked ?? 0}`
299
+ };
300
+ }
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // 5. Provider row on the control plane
304
+ // ---------------------------------------------------------------------------
305
+ async function checkProviderRow(config) {
306
+ if (!config.controlPlane?.url || !config.node?.publicKey) {
307
+ return { status: "skip", summary: "no URL or pubkey — skipped" };
308
+ }
309
+ let client;
310
+ try {
311
+ client = createNodeClient({
312
+ url: config.controlPlane.url,
313
+ publicKey: config.node.publicKey,
314
+ privateKey: config.node.privateKey,
315
+ role: config.node.role
316
+ });
317
+ } catch (err) {
318
+ return {
319
+ status: "fail",
320
+ summary: "could not build signed client",
321
+ details: err?.message ?? String(err)
322
+ };
323
+ }
324
+ try {
325
+ const row = await client.me();
326
+ const model = row?.gpu_model ?? row?.model ?? null;
327
+ const status = row?.status ?? "unknown";
328
+ return {
329
+ status: "ok",
330
+ summary: `registered as ${config.node.publicKey.slice(0, 8)}…, status=${status}${model ? `, gpu=${model}` : ""}`
331
+ };
332
+ } catch (err) {
333
+ const msg = err?.message ?? String(err);
334
+ return {
335
+ status: "fail",
336
+ summary: "signed `me` call failed",
337
+ details: msg,
338
+ hint: msg.includes("not found") || msg.includes("404")
339
+ ? "run `infernet register` to create the row"
340
+ : "check `infernet logs` and the control plane logs"
341
+ };
342
+ }
343
+ }
344
+
345
+ // ---------------------------------------------------------------------------
346
+ // 6. End-to-end inference
347
+ // ---------------------------------------------------------------------------
348
+ async function checkEndToEnd(config, { url, model, timeoutMs = 30_000 }) {
349
+ if (!url) return { status: "skip", summary: "no URL — skipped" };
350
+
351
+ const messages = [{ role: "user", content: "ping" }];
352
+ // Retry submit up to 6 times (30s) — on a fresh daemon start the provider
353
+ // row may still show status=unknown until the first heartbeat propagates.
354
+ let job;
355
+ for (let attempt = 0; attempt < 6; attempt++) {
356
+ try {
357
+ job = await submitChatJob(url, { messages, model, maxTokens: 8 });
358
+ break;
359
+ } catch (err) {
360
+ const msg = err?.message ?? String(err);
361
+ if (msg.includes("503") || msg.includes("no live providers")) {
362
+ if (attempt < 5) {
363
+ await new Promise((r) => setTimeout(r, 5000));
364
+ continue;
365
+ }
366
+ }
367
+ return {
368
+ status: "fail",
369
+ summary: `POST /api/chat failed: ${msg}`,
370
+ hint: "check `checkControlPlane` above; verify /api/chat is enabled"
371
+ };
372
+ }
373
+ }
374
+ if (!job) {
375
+ return {
376
+ status: "fail",
377
+ summary: "no live providers available after 30s",
378
+ hint: "daemon may not have heartbeated yet — re-run doctor in a minute"
379
+ };
380
+ }
381
+
382
+ const ctrl = new AbortController();
383
+ const deadline = setTimeout(() => ctrl.abort(), timeoutMs);
384
+
385
+ let firstToken = null;
386
+ let done = null;
387
+ let errorEv = null;
388
+ const start = Date.now();
389
+ try {
390
+ for await (const ev of streamChatEvents(url, job.streamUrl, { signal: ctrl.signal })) {
391
+ if (ev.event === "token" && firstToken == null) firstToken = Date.now() - start;
392
+ if (ev.event === "done") { done = ev.data; break; }
393
+ if (ev.event === "error") { errorEv = ev.data; break; }
394
+ }
395
+ } catch (err) {
396
+ clearTimeout(deadline);
397
+ return {
398
+ status: "fail",
399
+ summary: ctrl.signal.aborted ? `timed out after ${timeoutMs}ms` : `stream failed: ${err?.message ?? err}`,
400
+ hint: "no provider may be online for the requested model — try without --model"
401
+ };
402
+ } finally {
403
+ clearTimeout(deadline);
404
+ }
405
+
406
+ if (errorEv) {
407
+ return {
408
+ status: "fail",
409
+ summary: `error event: ${errorEv?.message ?? "unknown"}`,
410
+ hint: "check the daemon log on the provider"
411
+ };
412
+ }
413
+ if (!done) {
414
+ return { status: "fail", summary: "stream ended without `done`", hint: "verify the SSE route is forwarding events" };
415
+ }
416
+ const total = Date.now() - start;
417
+ return {
418
+ status: "ok",
419
+ summary: `routed via=${job.source}${job.provider ? `, provider=${job.provider.name ?? job.provider.nodeId}` : ""}, first token ${firstToken ?? "?"}ms, total ${total}ms`
420
+ };
421
+ }
422
+
423
+ // ---------------------------------------------------------------------------
424
+ // main
425
+ // ---------------------------------------------------------------------------
426
+ export default async function doctor(args) {
427
+ if (args.has("help") || args.has("h")) {
428
+ process.stdout.write(HELP);
429
+ return 0;
430
+ }
431
+ const skipE2E = args.has("skip-e2e");
432
+ const jsonMode = args.has("json");
433
+ const urlOverride = args.get("url") ? String(args.get("url")) : null;
434
+ const modelOverride = args.get("model") ? String(args.get("model")) : null;
435
+
436
+ const results = [];
437
+ const checks = ["Local config", "Engine", "Control plane", "Daemon", "Provider row", "End-to-end"];
438
+ if (skipE2E) checks.pop();
439
+
440
+ process.stdout.write(`\n${C.bold}infernet doctor${C.reset}\n\n`);
441
+
442
+ // 1. Config
443
+ const cfgResult = await checkConfig();
444
+ if (!jsonMode) printCheck(1, checks.length, "Local config", cfgResult);
445
+ results.push({ name: "Local config", ...cfgResult });
446
+ const config = cfgResult.config ?? null;
447
+
448
+ // 2. Engine
449
+ const engineResult = await checkEngine(config ?? {});
450
+ if (!jsonMode) printCheck(2, checks.length, "Engine", engineResult);
451
+ results.push({ name: "Engine", ...engineResult });
452
+
453
+ // 3. Control plane
454
+ const url = urlOverride ?? config?.controlPlane?.url ?? null;
455
+ const cpResult = await checkControlPlane(url);
456
+ if (!jsonMode) printCheck(3, checks.length, "Control plane", cpResult);
457
+ results.push({ name: "Control plane", ...cpResult });
458
+
459
+ // 4. Daemon
460
+ const daemonResult = await checkDaemon();
461
+ if (!jsonMode) printCheck(4, checks.length, "Daemon", daemonResult);
462
+ results.push({ name: "Daemon", ...daemonResult });
463
+
464
+ // 5. Provider row
465
+ const provResult = config
466
+ ? await checkProviderRow(config)
467
+ : { status: "skip", summary: "no config — skipped" };
468
+ if (!jsonMode) printCheck(5, checks.length, "Provider row", provResult);
469
+ results.push({ name: "Provider row", ...provResult });
470
+
471
+ // 6. End-to-end
472
+ let e2eResult = { status: "skip", summary: "skipped" };
473
+ if (!skipE2E) {
474
+ const model = modelOverride ?? config?.engine?.model ?? null;
475
+ e2eResult = await checkEndToEnd(config ?? {}, { url, model });
476
+ if (!jsonMode) printCheck(6, checks.length, "End-to-end", e2eResult);
477
+ results.push({ name: "End-to-end", ...e2eResult });
478
+ }
479
+
480
+ if (jsonMode) {
481
+ for (const r of results) {
482
+ const { config: _drop, ...clean } = r;
483
+ process.stdout.write(JSON.stringify(clean) + "\n");
484
+ }
485
+ }
486
+
487
+ const failed = results.filter((r) => r.status === "fail").length;
488
+ const warned = results.filter((r) => r.status === "warn").length;
489
+
490
+ if (!jsonMode) {
491
+ process.stdout.write("\n");
492
+ if (failed === 0 && warned === 0) {
493
+ process.stdout.write(`${C.green}${C.bold}All checks passed.${C.reset}\n`);
494
+ } else if (failed === 0) {
495
+ process.stdout.write(`${C.yellow}${warned} warning${warned === 1 ? "" : "s"}, no failures.${C.reset}\n`);
496
+ } else {
497
+ process.stdout.write(`${C.red}${failed} check${failed === 1 ? "" : "s"} failed.${C.reset}\n`);
498
+ }
499
+ }
500
+ return failed === 0 ? 0 : 1;
501
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `infernet firewall` — print the commands needed to open the P2P port
3
+ * on whichever firewall manager is available on this host.
4
+ *
5
+ * We do NOT mutate firewall state — system-wide firewall rules touch
6
+ * shared state and nearly always require sudo. Printing the exact
7
+ * command to run is the safest posture.
8
+ */
9
+
10
+ import { DEFAULT_P2P_PORT, resolveP2pPort } from '../lib/network.js';
11
+ import { printFirewallHint } from '../lib/firewall.js';
12
+
13
+ const HELP = `infernet firewall — print firewall commands for the P2P port
14
+
15
+ Usage:
16
+ infernet firewall [flags]
17
+
18
+ Flags:
19
+ --port <n> Override the port (default: config.node.port or ${DEFAULT_P2P_PORT})
20
+ --help Show this help
21
+
22
+ Prints the exact commands to open the port on ufw / firewalld / nftables /
23
+ iptables (Linux), pf (macOS), or netsh (Windows). You must run the
24
+ suggested commands yourself (sudo required on Linux).
25
+ `;
26
+
27
+ export default async function firewall(args, ctx) {
28
+ if (args.has('help') || args.has('h')) {
29
+ process.stdout.write(HELP);
30
+ return 0;
31
+ }
32
+
33
+ const portArg = args.get('port');
34
+ const port = Number.parseInt(portArg ?? '', 10) || resolveP2pPort(ctx?.config ?? null);
35
+ printFirewallHint(port, 'infernet firewall');
36
+ return 0;
37
+ }
38
+
39
+ export { HELP };
@@ -0,0 +1,130 @@
1
+ /**
2
+ * `infernet gpu` — print every locally-detected GPU and CPU group.
3
+ *
4
+ * Shells out to vendor tooling for GPUs (nvidia-smi, rocm-smi,
5
+ * system_profiler on macOS) and uses node:os for CPU info. Multiple
6
+ * of either are listed individually.
7
+ *
8
+ * Privacy: detection happens locally. The control plane only ever
9
+ * receives the coarse `{ vendor, vram_tier, model }` GPU summary
10
+ * via `infernet register` / heartbeats — no CPU info, no hostname,
11
+ * no full model strings (per IPIP-0001).
12
+ */
13
+
14
+ import {
15
+ detectGpus, formatGpuLine,
16
+ detectCpus, detectHost, formatCpuLine,
17
+ detectInterconnects, formatInterconnectSummary
18
+ } from "@infernetprotocol/gpu";
19
+
20
+ const HELP = `infernet gpu — list local hardware
21
+
22
+ Usage:
23
+ infernet gpu [flags]
24
+
25
+ Flags:
26
+ --json Emit JSON instead of human-readable
27
+ -h, --help Show this help
28
+
29
+ What it shows:
30
+ - Every detected GPU (NVIDIA via nvidia-smi, AMD via rocm-smi,
31
+ Apple Silicon via system_profiler) with vendor, model, VRAM,
32
+ utilization, temperature, power, and driver version.
33
+ - Every CPU group (collapsed by model — most machines have one;
34
+ heterogeneous boxes like Apple Silicon list their P+E cores).
35
+ - Host platform / arch / total RAM.
36
+
37
+ The list is local-only — nothing here is sent to the control plane
38
+ without your explicit opt-in via 'infernet register'.
39
+ `;
40
+
41
+ function jsonReport(gpus, cpus, host, interconnects) {
42
+ return {
43
+ host,
44
+ gpus,
45
+ cpus,
46
+ interconnects
47
+ };
48
+ }
49
+
50
+ function summary(count, label) {
51
+ if (count === 0) return `0 ${label}`;
52
+ if (count === 1) return `1 ${label}`;
53
+ return `${count} ${label}s`;
54
+ }
55
+
56
+ export default async function gpuCommand(args) {
57
+ if (args.has("help") || args.has("h")) {
58
+ process.stdout.write(HELP);
59
+ return 0;
60
+ }
61
+
62
+ const json = args.has("json");
63
+
64
+ let gpus = [];
65
+ try {
66
+ gpus = await detectGpus();
67
+ } catch (err) {
68
+ process.stderr.write(`gpu detection error: ${err?.message ?? err}\n`);
69
+ }
70
+ const cpus = detectCpus();
71
+ const host = detectHost();
72
+ let interconnects = { nvlink: { available: false, links: [] }, infiniband: { available: false, devices: [] }, rdma_capable: false };
73
+ try {
74
+ interconnects = await detectInterconnects();
75
+ } catch (err) {
76
+ process.stderr.write(`interconnect detection error: ${err?.message ?? err}\n`);
77
+ }
78
+
79
+ if (json) {
80
+ process.stdout.write(JSON.stringify(jsonReport(gpus, cpus, host, interconnects), null, 2) + "\n");
81
+ return 0;
82
+ }
83
+
84
+ process.stdout.write(`\nHost\n`);
85
+ process.stdout.write(` platform: ${host.platform}/${host.arch}\n`);
86
+ process.stdout.write(` node: v${host.node_version}\n`);
87
+ process.stdout.write(` ram: ${(host.total_ram_mb / 1024).toFixed(1)} GB total, ${(host.free_ram_mb / 1024).toFixed(1)} GB free\n`);
88
+ process.stdout.write(` load avg: ${host.load_avg.map((n) => n.toFixed(2)).join(" / ")}\n`);
89
+
90
+ process.stdout.write(`\nCPU (${summary(cpus.length, "group")}, ${host.cpu_count} logical cores)\n`);
91
+ if (cpus.length === 0) {
92
+ process.stdout.write(` (none detected)\n`);
93
+ } else {
94
+ for (const c of cpus) {
95
+ process.stdout.write(` ${formatCpuLine(c)}\n`);
96
+ }
97
+ }
98
+
99
+ process.stdout.write(`\nGPU (${summary(gpus.length, "device")})\n`);
100
+ if (gpus.length === 0) {
101
+ process.stdout.write(` (none detected — CPU-only provider)\n`);
102
+ process.stdout.write(` ${"-".repeat(40)}\n`);
103
+ process.stdout.write(` Need GPU tooling? Install one of:\n`);
104
+ process.stdout.write(` nvidia-smi (NVIDIA driver + CUDA)\n`);
105
+ process.stdout.write(` rocm-smi (AMD ROCm stack)\n`);
106
+ process.stdout.write(` system_profiler (macOS — bundled)\n`);
107
+ } else {
108
+ for (const g of gpus) {
109
+ process.stdout.write(` ${formatGpuLine(g)}\n`);
110
+ }
111
+ }
112
+
113
+ process.stdout.write(`\nInterconnect\n`);
114
+ process.stdout.write(` ${formatInterconnectSummary(interconnects)}\n`);
115
+ if (interconnects.nvlink.available) {
116
+ for (const l of interconnects.nvlink.links) {
117
+ process.stdout.write(` NVLink: GPU${l.from} ↔ GPU${l.to} (${l.kind})\n`);
118
+ }
119
+ }
120
+ if (interconnects.infiniband.devices.length) {
121
+ for (const d of interconnects.infiniband.devices) {
122
+ const rate = d.rate ? ` ${d.rate}` : "";
123
+ const ll = d.link_layer ? ` ${d.link_layer}` : "";
124
+ const port = d.port != null ? `/p${d.port}` : "";
125
+ process.stdout.write(` IB ${d.name}${port} — ${d.state ?? "?"}${rate}${ll}\n`);
126
+ }
127
+ }
128
+ process.stdout.write(`\n`);
129
+ return 0;
130
+ }