@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,116 @@
1
+ /**
2
+ * `infernet pubkey link` — claim this node's Nostr pubkey under your
3
+ * Infernet user account, so /dashboard can show "providers I operate".
4
+ *
5
+ * Authenticates with TWO credentials:
6
+ * - bearer JWT (config.auth.bearerToken) — proves you're the Supabase user
7
+ * - Nostr signature (config.node.privateKey) — proves you own the pubkey
8
+ *
9
+ * Without both, the link can't safely happen — bearer alone wouldn't
10
+ * prove pubkey control; signature alone wouldn't bind to a user.
11
+ */
12
+
13
+ import { signRequest, AUTH_HEADER } from "@infernetprotocol/auth";
14
+ import { loadConfig } from "../lib/config.js";
15
+
16
+ const HELP = `infernet pubkey link — bind this node's pubkey to your account
17
+
18
+ Usage:
19
+ infernet pubkey link [flags]
20
+
21
+ Flags:
22
+ --role <role> provider | aggregator | client (default: from config.node.role)
23
+ --label <name> Friendly label for this node (defaults to node name)
24
+ --help
25
+
26
+ After this succeeds, /dashboard will show this provider under your account.
27
+ You only need to do it once per (pubkey, role) pair — re-running is a no-op
28
+ (or refreshes the label).
29
+ `;
30
+
31
+ const PATH = "/api/v1/user/pubkey/link";
32
+
33
+ export default async function pubkeyCommand(args) {
34
+ if (args.has("help") || args.has("h")) {
35
+ process.stdout.write(HELP);
36
+ return 0;
37
+ }
38
+
39
+ const sub = args.positional?.[0] ?? "link";
40
+ if (sub !== "link") {
41
+ process.stderr.write(`unknown subcommand: ${sub}\n${HELP}`);
42
+ return 2;
43
+ }
44
+
45
+ const config = (await loadConfig()) ?? {};
46
+ const baseUrl = config?.controlPlane?.url;
47
+ const bearer = config?.auth?.bearerToken;
48
+ const role = (args.get("role") ?? config?.node?.role ?? "").toLowerCase();
49
+ const label = args.get("label") ?? config?.node?.name ?? null;
50
+ const publicKey = config?.node?.publicKey;
51
+ const privateKey = config?.node?.privateKey;
52
+
53
+ if (!baseUrl) {
54
+ process.stderr.write("error: no controlPlane.url. Run `infernet init` first.\n");
55
+ return 1;
56
+ }
57
+ if (!bearer) {
58
+ process.stderr.write("error: not signed in. Run `infernet login` first.\n");
59
+ return 1;
60
+ }
61
+ if (!publicKey || !privateKey) {
62
+ process.stderr.write("error: no node identity. Run `infernet init` first.\n");
63
+ return 1;
64
+ }
65
+ if (!["provider", "aggregator", "client"].includes(role)) {
66
+ process.stderr.write(`error: --role must be provider | aggregator | client (got ${role || "(none)"})\n`);
67
+ return 1;
68
+ }
69
+
70
+ const bodyText = JSON.stringify({ role, ...(label ? { label } : {}) });
71
+ const { header } = signRequest({
72
+ method: "POST",
73
+ path: PATH,
74
+ body: bodyText,
75
+ publicKey,
76
+ privateKey
77
+ });
78
+
79
+ let res;
80
+ try {
81
+ res = await fetch(new URL(PATH, baseUrl), {
82
+ method: "POST",
83
+ headers: {
84
+ "content-type": "application/json",
85
+ authorization: `Bearer ${bearer}`,
86
+ [AUTH_HEADER]: header
87
+ },
88
+ body: bodyText
89
+ });
90
+ } catch (err) {
91
+ process.stderr.write(`error: could not reach ${baseUrl}: ${err?.message ?? err}\n`);
92
+ return 1;
93
+ }
94
+
95
+ const text = await res.text();
96
+ let payload = null;
97
+ try { payload = text ? JSON.parse(text) : null; } catch { /* ignore */ }
98
+
99
+ if (!res.ok) {
100
+ const msg = payload?.error ?? `HTTP ${res.status}`;
101
+ process.stderr.write(`error: link failed — ${msg}\n`);
102
+ return 1;
103
+ }
104
+
105
+ const row = payload?.data;
106
+ if (!row) {
107
+ process.stderr.write("error: server response missing data\n");
108
+ return 1;
109
+ }
110
+ process.stdout.write(
111
+ row.created
112
+ ? `✓ linked ${role} pubkey ${publicKey.slice(0, 12)}… to your account\n`
113
+ : `✓ already linked${row.label ? ` (label: ${row.label})` : ""}\n`
114
+ );
115
+ return 0;
116
+ }
@@ -0,0 +1,304 @@
1
+ /**
2
+ * `infernet register`
3
+ *
4
+ * Announces this node to the control plane via a Nostr-signed POST to
5
+ * /api/v1/node/register. The server verifies ownership of the pubkey and
6
+ * upserts a row in providers / aggregators / clients keyed on node_id.
7
+ *
8
+ * Only coarse capability data is sent — vendor + VRAM tier per GPU. No
9
+ * hostname, platform, CPU model, or RAM total leaves the node.
10
+ */
11
+
12
+ import { saveConfig, loadConfig } from '../lib/config.js';
13
+ import { resolveP2pPort, detectLocalAddress } from '../lib/network.js';
14
+ import { detectGpus, detectInterconnects, detectCpus, detectHost } from '@infernetprotocol/gpu';
15
+
16
+ /**
17
+ * Probe Ollama for the actual list of models pulled locally, with
18
+ * sizes. Empty array on any failure — we still want to register the
19
+ * node even if the engine isn't up at register time.
20
+ */
21
+ async function detectOllamaModels(host) {
22
+ if (!host) return [];
23
+ try {
24
+ const res = await fetch(new URL('/api/tags', host), { signal: AbortSignal.timeout?.(2000) });
25
+ if (!res.ok) return [];
26
+ const json = await res.json();
27
+ const models = Array.isArray(json?.models) ? json.models : [];
28
+ return models
29
+ .map((m) => ({
30
+ name: m.name ?? m.model,
31
+ size_bytes: typeof m.size === 'number' ? m.size : null
32
+ }))
33
+ .filter((m) => typeof m.name === 'string' && m.name);
34
+ } catch {
35
+ return [];
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Filter out models that physically can't fit on this node. A node
41
+ * advertising a model it can't actually serve is worse than not
42
+ * advertising at all — clients route there, the inference 500s mid-
43
+ * stream, the network's reputation rots.
44
+ *
45
+ * Heuristic (intentionally conservative — better to under-advertise):
46
+ * - GPU box: model fits if size < 0.85 × total VRAM across all GPUs.
47
+ * 0.15 headroom covers KV cache + quantization overhead.
48
+ * - CPU-only box: model fits if size < 0.6 × total RAM. Lower because
49
+ * the OS, Ollama itself, and other processes need RAM too, and CPU
50
+ * inference's working set is roughly the model size + activations.
51
+ *
52
+ * Models with no reported size pass through (we can't verify, so we
53
+ * trust the operator + Ollama's own load-time check).
54
+ */
55
+ export function filterFittingModels(models, { totalVramBytes, totalRamBytes }) {
56
+ const hasGpu = Number.isFinite(totalVramBytes) && totalVramBytes > 0;
57
+ const ceiling = hasGpu
58
+ ? totalVramBytes * 0.85
59
+ : (Number.isFinite(totalRamBytes) ? totalRamBytes * 0.6 : Number.POSITIVE_INFINITY);
60
+
61
+ const fitting = [];
62
+ const rejected = [];
63
+ for (const m of models) {
64
+ if (!Number.isFinite(m.size_bytes)) {
65
+ // Unknown size — pass through. Ollama will reject at load time
66
+ // if it really can't fit; our heuristic is just a pre-filter.
67
+ fitting.push(m.name);
68
+ continue;
69
+ }
70
+ if (m.size_bytes <= ceiling) {
71
+ fitting.push(m.name);
72
+ } else {
73
+ rejected.push({ name: m.name, size_gb: +(m.size_bytes / 1024 ** 3).toFixed(2) });
74
+ }
75
+ }
76
+ return { fitting, rejected, ceiling_gb: +(ceiling / 1024 ** 3).toFixed(2), mode: hasGpu ? 'gpu' : 'cpu' };
77
+ }
78
+
79
+ const HELP = `infernet register — announce this node to the control plane
80
+
81
+ Usage:
82
+ infernet register [flags]
83
+
84
+ Flags:
85
+ --address <host> Public address to advertise
86
+ --port <n> Public port to advertise
87
+ --gpu-model <name> GPU model (providers only)
88
+ --price <n> Price offer (providers only)
89
+ --no-advertise Don't send address / port
90
+ --help Show this help
91
+ `;
92
+
93
+ function vramTier(vramMb) {
94
+ if (!Number.isFinite(vramMb) || vramMb <= 0) return 'unknown';
95
+ if (vramMb < 8 * 1024) return '<8gb';
96
+ if (vramMb < 16 * 1024) return '8-16gb';
97
+ if (vramMb < 24 * 1024) return '16-24gb';
98
+ if (vramMb < 48 * 1024) return '24-48gb';
99
+ return '>=48gb';
100
+ }
101
+
102
+ /**
103
+ * Reduce interconnect detection to a coarse, leak-free shape:
104
+ * - device names / board_ids stripped
105
+ * - just the capability flags clients need for matchmaking
106
+ */
107
+ function summarizeInterconnects(ic) {
108
+ const nvlink = ic?.nvlink ?? { available: false, topology: 'none', links: [] };
109
+ const xgmi = ic?.xgmi ?? { available: false, topology: 'none', links: [] };
110
+ const ib = ic?.infiniband ?? { available: false, devices: [] };
111
+ const efa = ic?.efa ?? { available: false, devices: [] };
112
+ const activePorts = ib.devices.filter((d) => d.state === 'active');
113
+ return {
114
+ nvlink: {
115
+ available: !!nvlink.available,
116
+ topology: nvlink.topology ?? 'none',
117
+ link_count: Array.isArray(nvlink.links) ? nvlink.links.length : 0
118
+ },
119
+ xgmi: {
120
+ available: !!xgmi.available,
121
+ topology: xgmi.topology ?? 'none',
122
+ link_count: Array.isArray(xgmi.links) ? xgmi.links.length : 0
123
+ },
124
+ infiniband: {
125
+ available: !!ib.available,
126
+ active_port_count: activePorts.length
127
+ },
128
+ efa: {
129
+ available: !!efa.available,
130
+ adapter_count: Array.isArray(efa.devices) ? efa.devices.length : 0
131
+ },
132
+ rdma_capable: !!ic?.rdma_capable
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Coarse CPU summary: vendor, arch, total core count, and group count.
138
+ * Deliberately omits the exact CPU model string + clock speed (those
139
+ * fingerprint the SKU). Vendor + arch + core count is enough for
140
+ * matchmaking and dashboard display.
141
+ */
142
+ function summarizeCpu() {
143
+ const host = detectHost();
144
+ const cpus = detectCpus();
145
+ const first = cpus[0] ?? {};
146
+ return {
147
+ vendor: first.vendor ?? null, // intel | amd | apple | aws | ampere | null
148
+ arch: host.arch, // x64 | arm64 | ...
149
+ cores: host.cpu_count, // logical cores
150
+ groups: cpus.length, // 1 for homogeneous boxes; >1 for P+E etc
151
+ ram_gb: Math.round(host.total_ram_mb / 1024)
152
+ };
153
+ }
154
+
155
+ export async function gatherCoarseSpecs() {
156
+ const [gpus, interconnects, config] = await Promise.all([
157
+ detectGpus(),
158
+ detectInterconnects(),
159
+ loadConfig().catch(() => ({}))
160
+ ]);
161
+
162
+ // Models: every model Ollama has pulled, FILTERED to those that
163
+ // actually fit this box's RAM/VRAM. Advertising a model we can't
164
+ // serve is worse than not advertising it — clients route there,
165
+ // inference 500s mid-stream, network reputation tanks.
166
+ const configuredModel = config?.engine?.model ?? null;
167
+ const ollamaHost = config?.engine?.ollamaHost ?? null;
168
+ const pulledModels = ollamaHost ? await detectOllamaModels(ollamaHost) : [];
169
+
170
+ // Capacity inputs in bytes — sum VRAM across all GPUs (multi-GPU
171
+ // boxes can fit a model larger than any single card via tensor
172
+ // parallelism, which Ollama handles automatically when it sees both).
173
+ const totalVramBytes = gpus.reduce(
174
+ (a, g) => a + (Number.isFinite(g.vram_mb) ? g.vram_mb * 1024 * 1024 : 0),
175
+ 0
176
+ );
177
+ const host = detectHost();
178
+ const totalRamBytes = host.total_ram_mb * 1024 * 1024;
179
+
180
+ const { fitting, rejected } = filterFittingModels(pulledModels, {
181
+ totalVramBytes,
182
+ totalRamBytes
183
+ });
184
+
185
+ if (rejected.length > 0) {
186
+ const sizes = rejected.map((r) => `${r.name} (${r.size_gb} GB)`).join(', ');
187
+ process.stderr.write(
188
+ `\nNote: ${rejected.length} model(s) may be tight on memory: ${sizes}\n` +
189
+ ` Advertising anyway — Ollama will handle it at load time.\n` +
190
+ ` Remove with \`infernet model remove <name>\` if you want to drop it.\n\n`
191
+ );
192
+ }
193
+
194
+ // Advertise all pulled models — operator explicitly installed them so we
195
+ // trust they know their hardware. The fit check is informational only.
196
+ const served_models = [...new Set(pulledModels.map((m) => m.name))];
197
+
198
+ return {
199
+ cpu: summarizeCpu(),
200
+ gpu_count: gpus.length,
201
+ gpus: gpus.map((g) => ({
202
+ vendor: (g.vendor ?? 'unknown').toLowerCase(),
203
+ vram_tier: vramTier(g.vram_mb),
204
+ model: typeof g.model === 'string' ? g.model.slice(0, 64) : null
205
+ })),
206
+ interconnects: summarizeInterconnects(interconnects),
207
+ served_models
208
+ };
209
+ }
210
+
211
+ export default async function register(args, ctx) {
212
+ if (args.has('help') || args.has('h')) {
213
+ process.stdout.write(HELP);
214
+ return 0;
215
+ }
216
+
217
+ const { config, client, configPath } = ctx;
218
+ const node = config.node ?? {};
219
+ if (!node.role || !node.nodeId) {
220
+ process.stderr.write('Config is missing node.role or node.nodeId. Run `infernet init` first.\n');
221
+ return 1;
222
+ }
223
+
224
+ const noAdvertise = args.has('no-advertise');
225
+ const addressFlag = args.get('address');
226
+ const portFlag = args.get('port') ?? args.get('p2p-port');
227
+ const address = noAdvertise ? undefined : (addressFlag ?? node.address ?? await detectLocalAddress());
228
+ const portRaw = portFlag ?? node.port;
229
+ const port = noAdvertise ? undefined
230
+ : (portRaw ? Number.parseInt(portRaw, 10) : resolveP2pPort({ node }));
231
+
232
+ const payload = {
233
+ node_id: node.nodeId,
234
+ name: node.name ?? node.nodeId
235
+ };
236
+ if (address) payload.address = address;
237
+ if (Number.isFinite(port) && port > 0) payload.port = port;
238
+
239
+ if (node.role === 'provider') {
240
+ const specs = await gatherCoarseSpecs();
241
+ payload.specs = specs;
242
+ const gpuModel = args.get('gpu-model') ?? specs.gpus?.[0]?.model;
243
+ if (gpuModel) payload.gpu_model = gpuModel;
244
+ const price = args.get('price');
245
+ if (price !== undefined) {
246
+ const n = Number.parseFloat(price);
247
+ if (Number.isFinite(n)) payload.price = n;
248
+ }
249
+ }
250
+
251
+ // Display: lead with the human-readable name when one is configured;
252
+ // fall back to the machine node_id otherwise. Operators recognize
253
+ // their own user@host name; nobody recognizes "provider-0f44326c".
254
+ const displayName = node.name && node.name !== node.nodeId ? node.name : node.nodeId;
255
+ process.stdout.write(`Registering ${node.role} "${displayName}" (node_id=${node.nodeId})...\n`);
256
+
257
+ let row;
258
+ try {
259
+ row = await client.register(payload);
260
+ } catch (err) {
261
+ process.stderr.write(`Register failed: ${err?.message ?? err}\n`);
262
+ return 1;
263
+ }
264
+
265
+ // The register response can be terse on older deployments
266
+ // (sometimes just { node_id }, no id). Fetch the canonical row
267
+ // via the signed `me` endpoint so we always have the server's
268
+ // truth, regardless of the deployed register handler's shape.
269
+ let canonical = row;
270
+ let canonicalId = row?.id ?? null;
271
+ try {
272
+ const me = await client.me();
273
+ if (me && typeof me === "object") {
274
+ canonical = me;
275
+ canonicalId = me.id ?? canonicalId;
276
+ }
277
+ } catch {
278
+ // Non-fatal: we'll fall back to whatever register returned.
279
+ }
280
+
281
+ const nextConfig = {
282
+ ...config,
283
+ node: {
284
+ ...node,
285
+ id: canonicalId ?? node.id ?? null,
286
+ address: noAdvertise ? null : (address ?? node.address ?? null),
287
+ port: noAdvertise ? null : (Number.isFinite(port) ? port : node.port ?? null)
288
+ }
289
+ };
290
+ await saveConfig(nextConfig);
291
+
292
+ const displayId = canonicalId ?? "(server did not return one)";
293
+ const displayNodeId = canonical?.node_id ?? row?.node_id ?? node.nodeId;
294
+ process.stdout.write(`Registered. id=${displayId} node_id=${displayNodeId}\n`);
295
+ if (canonicalId) {
296
+ process.stdout.write(`Config updated with assigned uuid at ${configPath}\n`);
297
+ } else {
298
+ process.stdout.write(`Note: control plane returned no id — likely an older deployment.\n`);
299
+ process.stdout.write(` registration succeeded; id will populate after first heartbeat.\n`);
300
+ }
301
+ return 0;
302
+ }
303
+
304
+ export { HELP, vramTier, summarizeCpu, summarizeInterconnects };
@@ -0,0 +1,230 @@
1
+ /**
2
+ * `infernet remove` — deregister this node, wipe local config, and
3
+ * uninstall the CLI binary.
4
+ *
5
+ * This is the inverse of the curl installer:
6
+ *
7
+ * curl -fsSL https://infernetprotocol.com/install.sh | sh
8
+ *
9
+ * The installer drops files in three layers:
10
+ * 1. ~/.config/infernet/ — node identity + daemon state
11
+ * 2. ~/.infernet/source — git clone + node_modules
12
+ * 3. ~/.local/bin/infernet — wrapper shim
13
+ * /usr/local/bin/infernet — system symlink (any of these)
14
+ * /usr/bin/infernet — system symlink
15
+ * /opt/bin/infernet — system symlink
16
+ * /etc/profile.d/infernet.sh — login-shell PATH hook
17
+ *
18
+ * `remove` peels all three back. Flags let operators keep any layer:
19
+ *
20
+ * --keep-config Skip wiping ~/.config/infernet
21
+ * --keep-binary Skip wiping the install dir + wrapper
22
+ * --keep-remote Skip the deregister-from-control-plane step
23
+ * --yes Don't prompt for confirmation
24
+ *
25
+ * For backwards compat, `--purge` is accepted but is the default
26
+ * (full uninstall). To do a partial cleanup, pass --keep-* flags.
27
+ */
28
+
29
+ import fs from 'node:fs/promises';
30
+ import os from 'node:os';
31
+ import path from 'node:path';
32
+
33
+ import { getConfigDir, getConfigPath, getDaemonPidPath, loadConfig } from '../lib/config.js';
34
+ import { createNodeClientFromConfig } from '../lib/node-client.js';
35
+ import { question } from '../lib/prompt.js';
36
+
37
+ const HELP = `infernet remove — deregister this node and uninstall the CLI
38
+
39
+ Usage:
40
+ infernet remove [flags]
41
+
42
+ Flags:
43
+ --yes Skip confirmation prompt
44
+ --keep-config Leave ~/.config/infernet/config.json in place
45
+ --keep-binary Leave ~/.infernet and ~/.local/bin/infernet in place
46
+ --keep-remote Leave the remote row intact (don't deregister)
47
+ --help Show this help
48
+
49
+ By default this:
50
+ 1. Deregisters this node from the control plane (signed POST).
51
+ 2. Deletes ~/.config/infernet/ (node identity + daemon state).
52
+ 3. Removes the install dir (~/.infernet) and the wrapper at
53
+ ~/.local/bin/infernet, plus any system symlinks (/usr/local/bin,
54
+ /usr/bin, /opt/bin) and /etc/profile.d/infernet.sh.
55
+
56
+ Step 3 is the inverse of the curl one-line installer.
57
+ `;
58
+
59
+ const SYSTEM_BIN_DIRS = ['/usr/local/bin', '/usr/bin', '/opt/bin'];
60
+ const PROFILE_D_HOOK = '/etc/profile.d/infernet.sh';
61
+
62
+ async function unlinkIfExists(p) {
63
+ try { await fs.unlink(p); return true; }
64
+ catch (err) { if (err.code === 'ENOENT') return false; throw err; }
65
+ }
66
+
67
+ async function rmdirIfExists(p) {
68
+ try { await fs.rm(p, { recursive: true, force: true }); return true; }
69
+ catch (err) { if (err.code === 'ENOENT') return false; throw err; }
70
+ }
71
+
72
+ function home() {
73
+ return process.env.HOME || os.homedir();
74
+ }
75
+
76
+ function resolveInstallDir() {
77
+ return process.env.INFERNET_HOME || path.join(home(), '.infernet');
78
+ }
79
+
80
+ function resolveBinDir() {
81
+ return process.env.INFERNET_BIN || path.join(home(), '.local', 'bin');
82
+ }
83
+
84
+ async function tryUnlink(p, removed) {
85
+ try {
86
+ await fs.unlink(p);
87
+ removed.push(p);
88
+ return true;
89
+ } catch (err) {
90
+ if (err.code === 'ENOENT') return false;
91
+ // EACCES/EPERM on /usr/local/bin etc. is normal for non-root.
92
+ return false;
93
+ }
94
+ }
95
+
96
+ async function uninstallBinary() {
97
+ const removed = [];
98
+ const skipped = [];
99
+
100
+ // 1. The install dir (clone + node_modules + vllm venv).
101
+ const installDir = resolveInstallDir();
102
+ if (await rmdirIfExists(installDir)) {
103
+ removed.push(installDir);
104
+ }
105
+
106
+ // 2. The user-space wrapper.
107
+ const wrapper = path.join(resolveBinDir(), 'infernet');
108
+ if (await unlinkIfExists(wrapper)) {
109
+ removed.push(wrapper);
110
+ }
111
+
112
+ // 3. System-bin symlinks. These usually need root, so collect what
113
+ // we can't unlink for the operator to clean up by hand.
114
+ for (const dir of SYSTEM_BIN_DIRS) {
115
+ const link = path.join(dir, 'infernet');
116
+ try {
117
+ await fs.lstat(link);
118
+ } catch (err) {
119
+ if (err.code === 'ENOENT') continue;
120
+ }
121
+ const ok = await tryUnlink(link, removed);
122
+ if (!ok) skipped.push(link);
123
+ }
124
+
125
+ // 4. /etc/profile.d hook.
126
+ try {
127
+ await fs.access(PROFILE_D_HOOK);
128
+ const ok = await tryUnlink(PROFILE_D_HOOK, removed);
129
+ if (!ok) skipped.push(PROFILE_D_HOOK);
130
+ } catch { /* not present */ }
131
+
132
+ return { removed, skipped };
133
+ }
134
+
135
+ export default async function remove(args, ctx) {
136
+ if (args.has('help') || args.has('h')) {
137
+ process.stdout.write(HELP);
138
+ return 0;
139
+ }
140
+
141
+ let config = ctx?.config ?? null;
142
+ let client = ctx?.client ?? null;
143
+ // The router puts `remove` in NO_CONFIG so it can still wipe a
144
+ // half-broken box; load config opportunistically so we can also
145
+ // deregister when there IS one.
146
+ if (!config) config = await loadConfig().catch(() => null);
147
+ if (config && !client) {
148
+ try { client = createNodeClientFromConfig(config); }
149
+ catch { client = null; }
150
+ }
151
+ const node = config?.node ?? {};
152
+ const keepConfig = args.has('keep-config');
153
+ const keepBinary = args.has('keep-binary');
154
+ const keepRemote = args.has('keep-remote');
155
+ const assumeYes = args.has('yes') || args.has('y');
156
+
157
+ const haveConfig = !!config;
158
+ const haveClient = !!client;
159
+ const canDeregister = !keepRemote && haveConfig && haveClient && node.nodeId;
160
+
161
+ const summary = [];
162
+ if (canDeregister) {
163
+ summary.push(` - deregister ${node.role} "${node.nodeId}" from ${config.controlPlane?.url}`);
164
+ } else if (!keepRemote && haveConfig && !node.nodeId) {
165
+ summary.push(' - (skip remote deregister — config has no node.nodeId)');
166
+ } else if (!keepRemote && !haveConfig) {
167
+ summary.push(' - (skip remote deregister — no local config to identify this node)');
168
+ }
169
+ if (!keepConfig) {
170
+ summary.push(` - delete local config at ${getConfigPath()}`);
171
+ }
172
+ if (!keepBinary) {
173
+ summary.push(` - remove install dir ${resolveInstallDir()}`);
174
+ summary.push(` - remove wrapper at ${path.join(resolveBinDir(), 'infernet')}`);
175
+ summary.push(` - remove system symlinks (${SYSTEM_BIN_DIRS.join(', ')}) and ${PROFILE_D_HOOK}`);
176
+ }
177
+
178
+ if (summary.length === 0) {
179
+ process.stdout.write('Nothing to do (everything kept via flags).\n');
180
+ return 0;
181
+ }
182
+
183
+ process.stdout.write('This will:\n');
184
+ for (const line of summary) process.stdout.write(`${line}\n`);
185
+
186
+ if (!assumeYes) {
187
+ if (!process.stdin.isTTY) {
188
+ process.stderr.write('\nRefusing to proceed without --yes in non-interactive mode.\n');
189
+ return 1;
190
+ }
191
+ const answer = (await question('\nContinue? [y/N] ', { default: 'n' })) ?? 'n';
192
+ if (!/^y(es)?$/i.test(answer.trim())) {
193
+ process.stdout.write('Aborted.\n');
194
+ return 0;
195
+ }
196
+ }
197
+
198
+ if (canDeregister) {
199
+ try {
200
+ await client.remove();
201
+ process.stdout.write(`Deregistered ${node.role} "${node.nodeId}"\n`);
202
+ } catch (err) {
203
+ process.stderr.write(`Remote deregister failed: ${err?.message ?? err}\n`);
204
+ // Don't bail — operator wants this gone locally either way.
205
+ }
206
+ }
207
+
208
+ if (!keepConfig) {
209
+ await unlinkIfExists(getDaemonPidPath());
210
+ await rmdirIfExists(getConfigDir());
211
+ process.stdout.write('Local config removed.\n');
212
+ }
213
+
214
+ if (!keepBinary) {
215
+ const { removed, skipped } = await uninstallBinary();
216
+ for (const p of removed) process.stdout.write(`Removed ${p}\n`);
217
+ if (skipped.length > 0) {
218
+ process.stdout.write('\nThese paths still exist (need root to unlink):\n');
219
+ for (const p of skipped) process.stdout.write(` ${p}\n`);
220
+ process.stdout.write('\nClean up with:\n');
221
+ process.stdout.write(` sudo rm -f ${skipped.join(' ')}\n`);
222
+ }
223
+ process.stdout.write('\nIf you installed via npm, also run:\n');
224
+ process.stdout.write(' npm uninstall -g @infernetprotocol/cli\n');
225
+ }
226
+
227
+ return 0;
228
+ }
229
+
230
+ export { HELP };