@infernetprotocol/cli 0.1.82 → 0.1.84

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.
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * `infernet doctor` — diagnose all three sides of a P2P chat round-trip.
3
3
  *
4
+ * 0. CLI install — one CLI version on the machine, daemon runs it
4
5
  * 1. Local config — file present, mode 0600, has identity + URL
5
6
  * 2. Engine — Ollama reachable, configured model is pulled
6
7
  * 3. Control plane — URL responds, /api/overview is reachable
@@ -24,6 +25,8 @@ import { isDaemonAlive, sendToDaemon } from "../lib/ipc.js";
24
25
  import { readLiveSupervisorPid, spawnDetachedSupervisor } from "../lib/supervisor.js";
25
26
  import { createNodeClient } from "../lib/node-client.js";
26
27
  import { submitChatJob, streamChatEvents } from "../lib/remote-chat.js";
28
+ import { CLI_DIR, RUNNING_VERSION } from "../lib/version.js";
29
+ import { inventory } from "../lib/cli-copies.js";
27
30
 
28
31
  const HELP = `infernet doctor — diagnose P2P chat readiness
29
32
 
@@ -72,6 +75,78 @@ function printCheck(idx, total, name, result) {
72
75
  }
73
76
  }
74
77
 
78
+ // ---------------------------------------------------------------------------
79
+ // 0. CLI install: one version per node
80
+ // ---------------------------------------------------------------------------
81
+ /**
82
+ * Pure: judge an inventory. `daemon` is { version, cliDir } from the daemon's
83
+ * stats (null when it is not running; version undefined on daemons before
84
+ * 0.1.84, which did not report it).
85
+ */
86
+ export function judgeCliInstall({ running, copies = [], pathFirst = null, wrapper = null, daemon = null }) {
87
+ const lines = [];
88
+ const problems = [];
89
+ lines.push(`running: v${running.version} at ${running.dir}`);
90
+ const distinct = new Map();
91
+ for (const c of copies) distinct.set(c.dir, c);
92
+ distinct.set(running.dir, { ...running, kind: distinct.get(running.dir)?.kind ?? "running" });
93
+ for (const c of distinct.values()) {
94
+ if (c.dir === running.dir) continue;
95
+ lines.push(`${c.kind}: v${c.version ?? "?"} at ${c.dir}`);
96
+ }
97
+ const versions = new Set([...distinct.values()].map((c) => c.version).filter(Boolean));
98
+ if (versions.size > 1) problems.push(`${versions.size} CLI versions installed (${[...versions].join(", ")})`);
99
+ else if (distinct.size > 1) problems.push(`${distinct.size} copies of the CLI installed`);
100
+ if (wrapper) lines.push(`installer wrapper runs: ${wrapper}`);
101
+ if (pathFirst) {
102
+ lines.push(`\`infernet\` on PATH: ${pathFirst.path} (${pathFirst.via})${pathFirst.dir ? ` -> ${pathFirst.dir}` : ""}`);
103
+ const target = pathFirst.dir ? distinct.get(pathFirst.dir) : null;
104
+ if (wrapper && pathFirst.dir && pathFirst.dir !== wrapper) {
105
+ problems.push(`\`infernet\` on PATH runs ${target?.version ? `v${target.version} ` : ""}${pathFirst.dir}, not the installed CLI`);
106
+ }
107
+ }
108
+ if (daemon) {
109
+ if (!daemon.version) {
110
+ problems.push("daemon is older than 0.1.84 (does not report its version)");
111
+ } else {
112
+ lines.push(`daemon: v${daemon.version}${daemon.cliDir ? ` at ${daemon.cliDir}` : ""}`);
113
+ const expected = wrapper ? distinct.get(wrapper)?.version : running.version;
114
+ if (expected && daemon.version !== expected) problems.push(`daemon runs v${daemon.version}, CLI is v${expected}`);
115
+ }
116
+ }
117
+ const skew = problems.some((p) => /versions|runs v|not the installed|older than/.test(p));
118
+ return {
119
+ status: problems.length === 0 ? "ok" : skew ? "fail" : "warn",
120
+ summary: problems.length === 0 ? `v${running.version}, one CLI on this machine` : problems.join("; "),
121
+ details: lines.join("\n"),
122
+ hint: problems.length === 0 ? undefined
123
+ : "run `infernet upgrade` (it keeps the installed CLI and removes stray npm-global copies), then `infernet restart` if the daemon is behind"
124
+ };
125
+ }
126
+
127
+ async function checkCliInstall() {
128
+ let inv;
129
+ try {
130
+ inv = inventory({ runningDir: CLI_DIR });
131
+ } catch (err) {
132
+ return { status: "warn", summary: `could not list CLI copies: ${err?.message ?? err}` };
133
+ }
134
+ let daemon = null;
135
+ try {
136
+ if (await isDaemonAlive(500)) {
137
+ const r = await sendToDaemon("stats", null, { timeoutMs: 1500 });
138
+ if (r?.ok) daemon = { version: r.data?.version ?? null, cliDir: r.data?.cliDir ?? null };
139
+ }
140
+ } catch { /* daemon check below reports it */ }
141
+ return judgeCliInstall({
142
+ running: { version: RUNNING_VERSION, dir: CLI_DIR },
143
+ copies: inv.copies,
144
+ pathFirst: inv.pathFirst,
145
+ wrapper: inv.wrapper,
146
+ daemon
147
+ });
148
+ }
149
+
75
150
  // ---------------------------------------------------------------------------
76
151
  // 1. Local config
77
152
  // ---------------------------------------------------------------------------
@@ -435,38 +510,43 @@ export default async function doctor(args) {
435
510
  const modelOverride = args.get("model") ? String(args.get("model")) : null;
436
511
 
437
512
  const results = [];
438
- const checks = ["Local config", "Engine", "Control plane", "Daemon", "Provider row", "End-to-end"];
513
+ const checks = ["CLI install", "Local config", "Engine", "Control plane", "Daemon", "Provider row", "End-to-end"];
439
514
  if (skipE2E) checks.pop();
440
515
 
441
516
  process.stdout.write(`\n${C.bold}infernet doctor${C.reset}\n\n`);
442
517
 
518
+ // 0. CLI install (version skew between copies, PATH and the daemon)
519
+ const cliResult = await checkCliInstall();
520
+ if (!jsonMode) printCheck(1, checks.length, "CLI install", cliResult);
521
+ results.push({ name: "CLI install", ...cliResult });
522
+
443
523
  // 1. Config
444
524
  const cfgResult = await checkConfig();
445
- if (!jsonMode) printCheck(1, checks.length, "Local config", cfgResult);
525
+ if (!jsonMode) printCheck(2, checks.length, "Local config", cfgResult);
446
526
  results.push({ name: "Local config", ...cfgResult });
447
527
  const config = cfgResult.config ?? null;
448
528
 
449
529
  // 2. Engine
450
530
  const engineResult = await checkEngine(config ?? {});
451
- if (!jsonMode) printCheck(2, checks.length, "Engine", engineResult);
531
+ if (!jsonMode) printCheck(3, checks.length, "Engine", engineResult);
452
532
  results.push({ name: "Engine", ...engineResult });
453
533
 
454
534
  // 3. Control plane
455
535
  const url = urlOverride ?? config?.controlPlane?.url ?? null;
456
536
  const cpResult = await checkControlPlane(url);
457
- if (!jsonMode) printCheck(3, checks.length, "Control plane", cpResult);
537
+ if (!jsonMode) printCheck(4, checks.length, "Control plane", cpResult);
458
538
  results.push({ name: "Control plane", ...cpResult });
459
539
 
460
540
  // 4. Daemon
461
541
  const daemonResult = await checkDaemon();
462
- if (!jsonMode) printCheck(4, checks.length, "Daemon", daemonResult);
542
+ if (!jsonMode) printCheck(5, checks.length, "Daemon", daemonResult);
463
543
  results.push({ name: "Daemon", ...daemonResult });
464
544
 
465
545
  // 5. Provider row
466
546
  const provResult = config
467
547
  ? await checkProviderRow(config)
468
548
  : { status: "skip", summary: "no config — skipped" };
469
- if (!jsonMode) printCheck(5, checks.length, "Provider row", provResult);
549
+ if (!jsonMode) printCheck(6, checks.length, "Provider row", provResult);
470
550
  results.push({ name: "Provider row", ...provResult });
471
551
 
472
552
  // 6. End-to-end
@@ -474,7 +554,7 @@ export default async function doctor(args) {
474
554
  if (!skipE2E) {
475
555
  const model = modelOverride ?? config?.engine?.model ?? null;
476
556
  e2eResult = await checkEndToEnd(config ?? {}, { url, model });
477
- if (!jsonMode) printCheck(6, checks.length, "End-to-end", e2eResult);
557
+ if (!jsonMode) printCheck(7, checks.length, "End-to-end", e2eResult);
478
558
  results.push({ name: "End-to-end", ...e2eResult });
479
559
  }
480
560
 
@@ -41,7 +41,7 @@ INFERNET_UNCENSORED_MODELS=0, INFERNET_HOUSE_MODELS_MAX_GB=<n>.
41
41
  House models are ON by default. The daemon checks
42
42
  https://infernetprotocol.com/house-models.json on start and every 6 hours,
43
43
  pulls listed models that fit (RAM >= min_ram_gb, and the pull leaves at least
44
- 10% of the disk free, 10-50 GB), one at a time and never during a job, verifies
44
+ 10% of the disk free, 10-50 GB), one at a time (waiting up to 10 min for a running job), verifies
45
45
  each model's digest, and removes house models that leave the list. A model you
46
46
  pulled yourself is never removed.
47
47
  `;
@@ -101,6 +101,7 @@ export default async function houseModels(args) {
101
101
  const verdict = new Map();
102
102
  for (const m of plan.keep) verdict.set(m.ollama_name, 'installed');
103
103
  for (const m of plan.pull) verdict.set(m.ollama_name, 'will pull');
104
+ for (const m of plan.update) verdict.set(m.ollama_name, `will update (installed ${String(m.installed_digest ?? '?').replace(/^sha256:/, '').slice(0, 12)}, pinned ${String(m.digest).replace(/^sha256:/, '').slice(0, 12)})`);
104
105
  for (const r of plan.remove) verdict.set(r.name, `will remove: ${r.reason}`);
105
106
  for (const s of plan.skipped) verdict.set(s.name, `skip: ${s.reason}`);
106
107
  process.stdout.write(`manifest: ${settings.manifestUrl}${manifest.updated ? ` (updated ${manifest.updated})` : ''}\n\n`);
package/commands/start.js CHANGED
@@ -63,7 +63,7 @@ import { getOrCreateModelKey, getModelPublicKeys } from '../lib/model-key.js';
63
63
  import { pullLatestBinary } from './upgrade.js';
64
64
  import { PROBE_INTERVAL_MS, runProbeRound } from '../lib/aggregator.js';
65
65
  import { nodeTokenLogin } from './login.js';
66
- import { CURRENT_VERSION, fetchLatestVersion, isNewerVersion, readInstalledVersion } from '../lib/version.js';
66
+ import { CLI_DIR, CURRENT_VERSION, fetchLatestVersion, isNewerVersion, readRunningVersion } from '../lib/version.js';
67
67
  import { readInferenceState, readInferenceStateSync, isPidAlive } from '../lib/inference/state.js';
68
68
  import { resolveSettings as resolveHouseSettings, syncHouseModels, readState as readHouseState, FIRST_SYNC_DELAY_MS as HOUSE_FIRST_SYNC_DELAY_MS } from '../lib/house-models.js';
69
69
 
@@ -1302,6 +1302,8 @@ async function runDaemon(args, ctx) {
1302
1302
  function snapshot() {
1303
1303
  return {
1304
1304
  pid: process.pid,
1305
+ version: CURRENT_VERSION,
1306
+ cliDir: CLI_DIR,
1305
1307
  startedAt: startedAt.toISOString(),
1306
1308
  uptimeMs: Date.now() - startedAt.getTime(),
1307
1309
  node: {
@@ -1669,8 +1671,8 @@ async function runDaemon(args, ctx) {
1669
1671
  isBusy: () => stats.activeJobIds.size > 0 || shuttingDown,
1670
1672
  log: (m) => process.stdout.write(`[${new Date().toISOString()}] [house-models] ${m}\n`)
1671
1673
  });
1672
- process.stdout.write(`[${new Date().toISOString()}] [house-models] sync (${why}): pulled ${summary.pulled.length}, removed ${summary.removed.length}, skipped ${summary.skipped.length}, errors ${summary.errors.length}\n`);
1673
- if (summary.pulled.length > 0 || summary.removed.length > 0) {
1674
+ process.stdout.write(`[${new Date().toISOString()}] [house-models] sync (${why}): pulled ${summary.pulled.length}, updated ${summary.updated?.length ?? 0}, removed ${summary.removed.length}, skipped ${summary.skipped.length}, errors ${summary.errors.length}\n`);
1675
+ if (summary.pulled.length > 0 || summary.updated?.length > 0 || summary.removed.length > 0) {
1674
1676
  invalidateSpecsCache();
1675
1677
  heartbeat().catch(() => {});
1676
1678
  }
@@ -1697,10 +1699,22 @@ async function runDaemon(args, ctx) {
1697
1699
  const followOnly = process.env.INFERNET_AUTO_UPDATE === 'follow';
1698
1700
  const checkForUpdate = async () => {
1699
1701
  if (shuttingDown || isUpgrading || Date.now() < updatePausedUntil) return;
1700
- // Never start an upgrade under a running job; the next check retries.
1701
- if (stats.activeJobIds.size > 0) return;
1702
- const latest = followOnly ? readInstalledVersion() : await fetchLatestVersion();
1702
+ // follow: restart only once THIS daemon's own code on disk is newer;
1703
+ // restarting re-runs the same entry, so another copy's newer version
1704
+ // would only restart it into the same old code every minute.
1705
+ const latest = followOnly ? readRunningVersion() : await fetchLatestVersion();
1703
1706
  if (!latest || !isNewerVersion(CURRENT_VERSION, latest)) return;
1707
+ // Never start an upgrade under a running job. But a node that is always
1708
+ // busy used to skip every check and never update (bonita sat on 0.1.77
1709
+ // for four releases under steady chat load), so stop taking new jobs
1710
+ // and upgrade on the first check after the running ones finish.
1711
+ if (stats.activeJobIds.size > 0) {
1712
+ if (!stats.draining) {
1713
+ stats.draining = true;
1714
+ process.stdout.write(`[update] v${latest} available (running v${CURRENT_VERSION}) — finishing ${stats.activeJobIds.size} running job(s) first, taking no new ones\n`);
1715
+ }
1716
+ return;
1717
+ }
1704
1718
  isUpgrading = true;
1705
1719
 
1706
1720
  if (followOnly) {
@@ -1710,6 +1724,7 @@ async function runDaemon(args, ctx) {
1710
1724
  const ok = await pullLatestBinary();
1711
1725
  if (!ok) {
1712
1726
  process.stderr.write('[update] installer failed — will retry next check\n');
1727
+ stats.draining = false;
1713
1728
  isUpgrading = false;
1714
1729
  return;
1715
1730
  }
@@ -1717,10 +1732,12 @@ async function runDaemon(args, ctx) {
1717
1732
  // whose package.json lagged the release, or npm writing to another
1718
1733
  // prefix). Restarting then would rerun the same update every 60 seconds
1719
1734
  // forever, so keep serving and try again much later.
1720
- const installed = readInstalledVersion();
1735
+ // What a restart would run: this daemon's own entry, re-read from disk.
1736
+ const installed = readRunningVersion();
1721
1737
  if (!isNewerVersion(CURRENT_VERSION, installed)) {
1722
1738
  updatePausedUntil = Date.now() + UPDATE_PAUSE_MS;
1723
- process.stderr.write(`[update] installer left v${installed} here (latest v${latest}); not restarting, next try in ${UPDATE_PAUSE_MS / 3_600_000}h\n`);
1739
+ process.stderr.write(`[update] installer left v${installed} at ${CLI_DIR}, which this daemon runs from (latest v${latest}); not restarting, next try in ${UPDATE_PAUSE_MS / 3_600_000}h. Run \`infernet doctor\` to see every CLI copy.\n`);
1740
+ stats.draining = false;
1724
1741
  isUpgrading = false;
1725
1742
  return;
1726
1743
  }
@@ -12,6 +12,7 @@ import { spawn } from 'node:child_process';
12
12
  import { compareVersions } from '@profullstack/cli';
13
13
  import setup from './setup.js';
14
14
  import { CURRENT_VERSION, fetchLatestVersion } from '../lib/version.js';
15
+ import { pruneCliCopies, wrapperTarget } from '../lib/cli-copies.js';
15
16
 
16
17
  const HELP = `infernet update — pull latest CLI + autonomous post-upgrade setup
17
18
 
@@ -23,6 +24,7 @@ Flags:
23
24
  --force Reinstall when the published version matches (never downgrades).
24
25
  --quiet Suppress routine update progress.
25
26
  --skip-setup Just re-run the installer; don't run setup afterward.
27
+ --keep-copies Don't remove other npm-global copies of the CLI.
26
28
  --help Show this help.
27
29
 
28
30
  What it does (fully autonomous, no manual steps):
@@ -34,6 +36,10 @@ What it does (fully autonomous, no manual steps):
34
36
  - Re-registers specs with the control plane
35
37
  - Restarts the daemon so the new code is live
36
38
  - Verifies the heartbeat reaches the control plane
39
+ 3. Keeps one CLI per node: removes npm-global @infernetprotocol/cli
40
+ copies under other Node installs (mise, nvm, system npm) that are
41
+ not the install the wrapper runs, so a stale copy can never shadow
42
+ the current one on PATH. Runs even when nothing new was published.
37
43
 
38
44
  \`infernet upgrade\` is an alias for this command.
39
45
  `;
@@ -61,6 +67,28 @@ export async function pullLatestBinary({ quiet = false } = {}) {
61
67
  return true;
62
68
  }
63
69
 
70
+ /**
71
+ * Remove stray npm-global CLI copies (see lib/cli-copies.js). Keeps the copy
72
+ * the installer's wrapper runs; with no wrapper, keeps nothing but the
73
+ * source install, and with neither it removes nothing.
74
+ */
75
+ export function cleanCliCopies({ quiet = false, version = null } = {}) {
76
+ try {
77
+ const r = pruneCliCopies({
78
+ keepDirs: [wrapperTarget()],
79
+ version,
80
+ log: (m) => { if (!quiet) process.stdout.write(` ${m}\n`); }
81
+ });
82
+ for (const d of r.removed) process.stdout.write(`Removed stray infernet CLI copy ${d}\n`);
83
+ for (const d of r.updated) process.stdout.write(`Updated infernet CLI copy ${d} to v${version}\n`);
84
+ for (const f of r.failed) process.stderr.write(`warning: could not clean ${f.dir}: ${f.error}\n`);
85
+ return r;
86
+ } catch (err) {
87
+ process.stderr.write(`warning: CLI copy check failed: ${err?.message ?? err}\n`);
88
+ return null;
89
+ }
90
+ }
91
+
64
92
  export default async function update(args, ctx) {
65
93
  if (args.has('help') || args.has('h')) {
66
94
  process.stdout.write(HELP);
@@ -68,6 +96,7 @@ export default async function update(args, ctx) {
68
96
  }
69
97
 
70
98
  const quiet = args.has('quiet');
99
+ const clean = () => { if (!args.has('keep-copies') && !args.has('check')) cleanCliCopies({ quiet, version: CURRENT_VERSION }); };
71
100
  const latest = await fetchLatestVersion();
72
101
  if (!latest) {
73
102
  process.stderr.write('error: could not check the latest Infernet version; installer was not run.\n');
@@ -80,10 +109,12 @@ export default async function update(args, ctx) {
80
109
  }
81
110
  if (comparison > 0) {
82
111
  if (!quiet) process.stdout.write(`Infernet ${CURRENT_VERSION} is newer than the published ${latest}; refusing to downgrade.\n`);
112
+ clean();
83
113
  return 0;
84
114
  }
85
115
  if (comparison === 0 && !args.has('force')) {
86
116
  if (!quiet) process.stdout.write(`Infernet ${CURRENT_VERSION} is already current; skipping reinstall.\n`);
117
+ clean();
87
118
  return 0;
88
119
  }
89
120
  if (args.has('check')) {
@@ -94,6 +125,10 @@ export default async function update(args, ctx) {
94
125
  const ok = await pullLatestBinary({ quiet });
95
126
  if (!ok) return 1;
96
127
 
128
+ // The installer already pruned other copies (install.sh); this catches an
129
+ // older installer and copies the installer could not see.
130
+ if (!args.has('keep-copies')) cleanCliCopies({ quiet, version: latest });
131
+
97
132
  if (args.has('skip-setup')) {
98
133
  process.stdout.write("\n✓ Binary updated (skipped setup).\n");
99
134
  return 0;
package/index.js CHANGED
@@ -14,8 +14,9 @@
14
14
 
15
15
  import { loadConfig, getConfigPath } from './lib/config.js';
16
16
  import { createNodeClientFromConfig } from './lib/node-client.js';
17
- import { decideRoute } from './lib/route.js';
18
- import { CURRENT_VERSION, fetchLatestVersion, isNewerVersion } from './lib/version.js';
17
+ import { decideRoute, unknownCommandMessage } from './lib/route.js';
18
+ import { CLI_DIR, RUNNING_VERSION, fetchLatestVersion, isNewerVersion } from './lib/version.js';
19
+ import { inventory } from './lib/cli-copies.js';
19
20
 
20
21
  import help, { USAGE } from './commands/help.js';
21
22
  import init from './commands/init.js';
@@ -127,12 +128,26 @@ const NO_CLIENT = new Set();
127
128
 
128
129
  const KNOWN_COMMAND_NAMES = new Set(Object.keys(COMMANDS));
129
130
 
130
- async function printVersion() {
131
- process.stdout.write(`infernet v${CURRENT_VERSION}\n`);
131
+ async function printVersion({ verbose = false } = {}) {
132
+ // The version of THIS code, read from the package.json beside it. Not the
133
+ // newest version on disk: a stale copy that says it is current is how a
134
+ // node ran 0.1.80 code under a "v0.1.83" banner.
135
+ process.stdout.write(`infernet v${RUNNING_VERSION}${verbose ? ` (${CLI_DIR})` : ''}\n`);
136
+ try {
137
+ const inv = inventory({ runningDir: CLI_DIR });
138
+ const others = inv.copies.filter((c) => c.dir !== CLI_DIR && c.version && c.version !== RUNNING_VERSION);
139
+ for (const c of others) {
140
+ process.stdout.write(` other copy: v${c.version} at ${c.dir}\n`);
141
+ }
142
+ if (inv.pathFirst?.dir && inv.pathFirst.dir !== CLI_DIR) {
143
+ process.stdout.write(` note: \`infernet\` on PATH (${inv.pathFirst.path}, ${inv.pathFirst.via}) runs ${inv.pathFirst.dir}\n`);
144
+ }
145
+ if (others.length) process.stdout.write(' more than one CLI version on this machine: run `infernet upgrade` (keeps one) and `infernet doctor`\n');
146
+ } catch { /* inventory is advisory */ }
132
147
  const latest = await fetchLatestVersion();
133
148
  if (!latest) {
134
149
  process.stdout.write(` update check failed (offline?)\n`);
135
- } else if (isNewerVersion(CURRENT_VERSION, latest)) {
150
+ } else if (isNewerVersion(RUNNING_VERSION, latest)) {
136
151
  process.stdout.write(` update available: v${latest} → run \`infernet upgrade\`\n`);
137
152
  } else {
138
153
  process.stdout.write(` up to date\n`);
@@ -144,7 +159,7 @@ async function main() {
144
159
 
145
160
  // --version / -v / -V (checked before full routing)
146
161
  if (argv[0] === '--version' || argv[0] === '-v' || argv[0] === '-V') {
147
- await printVersion();
162
+ await printVersion({ verbose: true });
148
163
  process.exit(0);
149
164
  }
150
165
 
@@ -152,6 +167,11 @@ async function main() {
152
167
  const sub = route.command;
153
168
  const rest = route.rest;
154
169
 
170
+ if (sub === 'unknown') {
171
+ process.stderr.write(unknownCommandMessage(route.name, { version: RUNNING_VERSION, entry: CLI_DIR }));
172
+ process.exit(2);
173
+ }
174
+
155
175
  if (sub === 'help') {
156
176
  // Bare `infernet` → show version + up-to-date status, then help.
157
177
  if (argv.length === 0) {
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Find (and prune) every copy of the infernet CLI on this machine.
3
+ *
4
+ * 2026-11-02, node bonita: an npm-global @infernetprotocol/cli@0.1.80 under
5
+ * mise's Node shadowed the installer's shim (~/.local/bin/infernet ->
6
+ * ~/.infernet/source, 0.1.83) because mise's shims dir comes first on PATH.
7
+ * 0.1.80 had no `house-models` command, so `infernet house-models off` (the
8
+ * documented opt-out) became a chat prompt to a model. One CLI version per
9
+ * node is the rule now: the installer and `infernet update` keep the install
10
+ * the wrapper points at and remove every other global copy, and doctor
11
+ * reports what it finds.
12
+ *
13
+ * Also runnable from install.sh (plain node, no workspace deps):
14
+ * node lib/cli-copies.js --prune --keep <dir|none> [--version X.Y.Z] [--json]
15
+ */
16
+
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { spawnSync } from 'node:child_process';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ export const PACKAGE = '@infernetprotocol/cli';
24
+
25
+ function realpathOr(p) {
26
+ try { return fs.realpathSync(p); } catch { return null; }
27
+ }
28
+
29
+ function readVersion(dir) {
30
+ try {
31
+ const v = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version;
32
+ return typeof v === 'string' ? v : null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function listDirs(parent) {
39
+ try {
40
+ return fs.readdirSync(parent).map((n) => path.join(parent, n));
41
+ } catch {
42
+ return [];
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Every lib/node_modules a global npm install could have used. Version
48
+ * managers each keep one per Node version, which is how a stale copy hides.
49
+ */
50
+ export function globalModuleRoots({ env = process.env, home = os.homedir(), npmPrefix = undefined } = {}) {
51
+ const roots = [];
52
+ const add = (prefix) => { if (prefix) roots.push(path.join(prefix, 'lib', 'node_modules')); };
53
+
54
+ const miseData = env.MISE_DATA_DIR || path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'mise');
55
+ for (const d of listDirs(path.join(miseData, 'installs', 'node'))) add(d);
56
+ for (const d of listDirs(path.join(env.NVM_DIR || path.join(home, '.nvm'), 'versions', 'node'))) add(d);
57
+ for (const d of listDirs(path.join(home, '.asdf', 'installs', 'nodejs'))) add(d);
58
+ for (const d of listDirs(path.join(env.FNM_DIR || path.join(home, '.local', 'share', 'fnm'), 'node-versions'))) add(path.join(d, 'installation'));
59
+ add(path.join(home, '.volta', 'tools', 'image', 'packages', PACKAGE));
60
+ add(path.join(home, '.npm-global'));
61
+ add(path.join(home, '.local'));
62
+ if (env.npm_config_prefix) add(env.npm_config_prefix);
63
+ if (env.NPM_CONFIG_PREFIX) add(env.NPM_CONFIG_PREFIX);
64
+ for (const p of ['/usr/local', '/usr', '/opt/homebrew']) add(p);
65
+
66
+ let prefix = npmPrefix;
67
+ if (prefix === undefined) {
68
+ const r = spawnSync('npm', ['prefix', '-g'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] });
69
+ prefix = r.status === 0 ? r.stdout.trim() : null;
70
+ }
71
+ add(prefix);
72
+ return roots;
73
+ }
74
+
75
+ /**
76
+ * npm-global copies, deduped by real path (mise's 24 / lts / latest are
77
+ * symlinks to one install). Each: { dir, version, prefixes, bins }.
78
+ */
79
+ export function findGlobalCopies(opts = {}) {
80
+ const byDir = new Map();
81
+ for (const root of globalModuleRoots(opts)) {
82
+ const pkgDir = path.join(root, PACKAGE);
83
+ const real = realpathOr(pkgDir);
84
+ if (!real || !fs.existsSync(path.join(real, 'package.json'))) continue;
85
+ const prefix = path.dirname(path.dirname(root));
86
+ let copy = byDir.get(real);
87
+ if (!copy) {
88
+ copy = { kind: 'npm-global', dir: real, version: readVersion(real), prefixes: [], bins: [] };
89
+ byDir.set(real, copy);
90
+ }
91
+ if (!copy.prefixes.includes(prefix)) copy.prefixes.push(prefix);
92
+ const bin = path.join(prefix, 'bin', 'infernet');
93
+ const target = realpathOr(bin);
94
+ if (target && target.startsWith(real + path.sep) && !copy.bins.includes(bin)) copy.bins.push(bin);
95
+ }
96
+ return [...byDir.values()];
97
+ }
98
+
99
+ /** The installer's git checkout, if there is one. */
100
+ export function findSourceInstall({ env = process.env, home = os.homedir() } = {}) {
101
+ const dir = path.join(env.INFERNET_HOME || path.join(home, '.infernet'), 'source', 'apps', 'cli');
102
+ const real = realpathOr(dir);
103
+ if (!real || !fs.existsSync(path.join(real, 'package.json'))) return null;
104
+ return { kind: 'source', dir: real, version: readVersion(real) };
105
+ }
106
+
107
+ export function wrapperPath({ env = process.env, home = os.homedir() } = {}) {
108
+ return path.join(env.INFERNET_BIN || path.join(home, '.local', 'bin'), 'infernet');
109
+ }
110
+
111
+ /**
112
+ * Which CLI directory the installer's wrapper runs. The git path writes
113
+ * `exec bun "<home>/source/apps/cli/index.js"`, the npm path
114
+ * `exec "<prefix>/bin/infernet"`. Returns a real path or null.
115
+ */
116
+ export function wrapperTarget(opts = {}) {
117
+ const w = wrapperPath(opts);
118
+ let text;
119
+ try { text = fs.readFileSync(w, 'utf8'); } catch { return null; }
120
+ if (text.length > 64 * 1024 || !text.startsWith('#!')) {
121
+ // A symlink to index.js, or a binary: resolve it directly.
122
+ const real = realpathOr(w);
123
+ return real ? findPackageDir(real) : null;
124
+ }
125
+ const m = text.match(/^\s*exec\s+(?:[^"\s]\S*\s+)?"([^"]+)"/m);
126
+ if (!m) return null;
127
+ const real = realpathOr(m[1]);
128
+ return real ? findPackageDir(real) : null;
129
+ }
130
+
131
+ function findPackageDir(file) {
132
+ let d = fs.statSync(file, { throwIfNoEntry: false })?.isDirectory() ? file : path.dirname(file);
133
+ for (let i = 0; i < 4; i += 1) {
134
+ try {
135
+ const name = JSON.parse(fs.readFileSync(path.join(d, 'package.json'), 'utf8')).name;
136
+ if (name === PACKAGE) return d;
137
+ } catch { /* keep walking */ }
138
+ d = path.dirname(d);
139
+ }
140
+ return null;
141
+ }
142
+
143
+ /** Unit / plist files that start a daemon from a CLI path. */
144
+ export function serviceFiles({ home = os.homedir() } = {}) {
145
+ const files = [];
146
+ for (const dir of [path.join(home, '.config', 'systemd', 'user'), '/etc/systemd/system', '/lib/systemd/system']) {
147
+ for (const f of listDirs(dir)) if (/\/infernet[^/]*\.service$/.test(f)) files.push(f);
148
+ }
149
+ for (const f of listDirs(path.join(home, 'Library', 'LaunchAgents'))) if (f.includes('infernetprotocol')) files.push(f);
150
+ return files;
151
+ }
152
+
153
+ /** Copies a service starts the daemon from: removing those would break the unit. */
154
+ export function copiesUsedByServices(copies, files = serviceFiles()) {
155
+ const used = new Map();
156
+ for (const f of files) {
157
+ let text;
158
+ try { text = fs.readFileSync(f, 'utf8'); } catch { continue; }
159
+ for (const c of copies) {
160
+ const aliases = [c.dir, ...c.prefixes.map((p) => path.join(p, 'lib', 'node_modules', PACKAGE)), ...c.bins];
161
+ if (aliases.some((a) => text.includes(a))) used.set(c.dir, f);
162
+ }
163
+ }
164
+ return used;
165
+ }
166
+
167
+ /**
168
+ * Copies a running process was started from (Linux /proc only). A detached
169
+ * `infernet start` re-execs its own entry on self-update, so deleting its
170
+ * copy under it would leave nothing to restart into.
171
+ */
172
+ export function copiesUsedByProcesses(copies, { procDir = '/proc', selfPid = process.pid } = {}) {
173
+ const used = new Map();
174
+ if (copies.length === 0) return used;
175
+ for (const d of listDirs(procDir)) {
176
+ const pid = Number(path.basename(d));
177
+ if (!Number.isInteger(pid) || pid === selfPid) continue;
178
+ let cmd;
179
+ try { cmd = fs.readFileSync(path.join(d, 'cmdline'), 'utf8'); } catch { continue; }
180
+ if (!cmd.includes('infernet')) continue;
181
+ for (const c of copies) {
182
+ const aliases = [c.dir, ...c.prefixes.map((p) => path.join(p, 'lib', 'node_modules', PACKAGE)), ...c.bins];
183
+ if (aliases.some((a) => cmd.includes(a))) used.set(c.dir, `running process ${pid}`);
184
+ }
185
+ }
186
+ return used;
187
+ }
188
+
189
+ /**
190
+ * Pure decision: which copies to keep, update in place, or remove.
191
+ * copies findGlobalCopies() output
192
+ * keepDirs real paths that ARE the install (the wrapper's target)
193
+ * usedBy Map dir -> service file (copiesUsedByServices)
194
+ * version the version every kept copy should be on
195
+ */
196
+ export function planPrune({ copies, keepDirs = [], usedBy = new Map(), version = null }) {
197
+ const keep = new Set(keepDirs.filter(Boolean));
198
+ const plan = { keep: [], update: [], remove: [] };
199
+ for (const c of copies) {
200
+ if (keep.has(c.dir)) plan.keep.push(c);
201
+ else if (usedBy.has(c.dir)) {
202
+ if (version && c.version !== version) plan.update.push({ ...c, service: usedBy.get(c.dir) });
203
+ else plan.keep.push({ ...c, service: usedBy.get(c.dir) });
204
+ } else plan.remove.push(c);
205
+ }
206
+ return plan;
207
+ }
208
+
209
+ function miseBinary(env = process.env, home = os.homedir()) {
210
+ for (const c of [env.MISE_INSTALL_PATH, path.join(home, '.local', 'bin', 'mise')]) {
211
+ if (c && fs.existsSync(c)) return c;
212
+ }
213
+ const r = spawnSync('sh', ['-c', 'command -v mise'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
214
+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
215
+ }
216
+
217
+ /**
218
+ * Remove every global copy that is not the install, update in place the ones
219
+ * a service runs, then `mise reshim` so mise's shim for the removed binary
220
+ * stops shadowing the installer's wrapper. Never uses sudo: a copy we cannot
221
+ * remove is reported, not escalated.
222
+ */
223
+ export function pruneCliCopies({
224
+ keepDirs = undefined,
225
+ version = null,
226
+ dryRun = false,
227
+ env = process.env,
228
+ home = os.homedir(),
229
+ log = () => {},
230
+ copies = undefined,
231
+ usedBy = undefined
232
+ } = {}) {
233
+ const found = copies ?? findGlobalCopies({ env, home });
234
+ const keep = (keepDirs ?? [wrapperTarget({ env, home })]).filter(Boolean);
235
+ if (keep.length === 0 && !findSourceInstall({ env, home })) {
236
+ // No installer wrapper and no ~/.infernet/source: a global npm copy
237
+ // may be the only CLI here (someone ran `npm i -g` by hand). Never
238
+ // remove it.
239
+ return { kept: found.map((c) => c.dir), updated: [], removed: [], failed: [], skipped: 'no installer wrapper or source install on this machine' };
240
+ }
241
+ const inUse = usedBy ?? new Map([
242
+ ...copiesUsedByProcesses(found),
243
+ ...copiesUsedByServices(found, serviceFiles({ home }))
244
+ ]);
245
+ const plan = planPrune({ copies: found, keepDirs: keep, usedBy: inUse, version });
246
+ const result = { kept: plan.keep.map((c) => c.dir), updated: [], removed: [], failed: [] };
247
+
248
+ for (const c of plan.update) {
249
+ const npm = c.prefixes.map((p) => path.join(p, 'bin', 'npm')).find((p) => fs.existsSync(p));
250
+ if (!npm) { result.failed.push({ dir: c.dir, error: `no npm beside it; ${c.service} runs v${c.version}` }); continue; }
251
+ log(`updating ${c.dir} (v${c.version}, used by ${c.service}) to v${version}`);
252
+ if (dryRun) { result.updated.push(c.dir); continue; }
253
+ const r = spawnSync(npm, ['install', '-g', `${PACKAGE}@${version}`], {
254
+ encoding: 'utf8', timeout: 300_000,
255
+ env: { ...env, PATH: `${path.dirname(npm)}:${env.PATH ?? ''}` }
256
+ });
257
+ if (r.status === 0) result.updated.push(c.dir);
258
+ else result.failed.push({ dir: c.dir, error: `npm install exited ${r.status}: ${(r.stderr || '').trim().split('\n').pop()}` });
259
+ }
260
+
261
+ for (const c of plan.remove) {
262
+ log(`removing stray ${PACKAGE}@${c.version ?? '?'} at ${c.dir}`);
263
+ if (dryRun) { result.removed.push(c.dir); continue; }
264
+ try {
265
+ for (const b of c.bins) fs.rmSync(b, { force: true });
266
+ fs.rmSync(c.dir, { recursive: true, force: true });
267
+ result.removed.push(c.dir);
268
+ } catch (err) {
269
+ result.failed.push({ dir: c.dir, error: err?.code === 'EACCES' || err?.code === 'EPERM' ? `permission denied (remove it with: sudo npm uninstall -g ${PACKAGE})` : (err?.message ?? String(err)) });
270
+ }
271
+ }
272
+
273
+ if (!dryRun && result.removed.length > 0) {
274
+ const mise = miseBinary(env, home);
275
+ if (mise) spawnSync(mise, ['reshim'], { stdio: 'ignore', timeout: 30_000, env });
276
+ }
277
+ return result;
278
+ }
279
+
280
+ /**
281
+ * Every CLI on this machine plus what `infernet` on PATH resolves to.
282
+ * Used by doctor and `infernet --version`.
283
+ */
284
+ export function inventory({ env = process.env, home = os.homedir(), runningDir = null } = {}) {
285
+ const copies = findGlobalCopies({ env, home });
286
+ const source = findSourceInstall({ env, home });
287
+ const all = [...(source ? [source] : []), ...copies];
288
+ if (runningDir) {
289
+ const real = realpathOr(runningDir) ?? runningDir;
290
+ if (!all.some((c) => c.dir === real)) all.push({ kind: 'other', dir: real, version: readVersion(real) });
291
+ }
292
+ return { copies: all, wrapper: wrapperTarget({ env, home }), pathFirst: resolvePathInfernet({ env, home, copies }) };
293
+ }
294
+
295
+ /** First `infernet` on PATH and the CLI directory it ends up running. */
296
+ export function resolvePathInfernet({ env = process.env, home = os.homedir(), copies = [] } = {}) {
297
+ for (const dir of String(env.PATH ?? '').split(path.delimiter)) {
298
+ if (!dir) continue;
299
+ const p = path.join(dir, 'infernet');
300
+ if (!fs.existsSync(p)) continue;
301
+ const real = realpathOr(p);
302
+ // A mise shim is a symlink to mise itself; it runs the active Node's
303
+ // global bin, so name the mise-managed copy.
304
+ if (real && path.basename(real) === 'mise') {
305
+ const miseCopy = copies.find((c) => c.prefixes.some((pre) => pre.includes(`${path.sep}mise${path.sep}installs${path.sep}node${path.sep}`)));
306
+ return { path: p, via: 'mise shim', dir: miseCopy?.dir ?? null };
307
+ }
308
+ if (real && real === realpathOr(wrapperPath({ env, home }))) return { path: p, via: 'installer wrapper', dir: wrapperTarget({ env, home }) };
309
+ return { path: p, via: real && real !== p ? `-> ${real}` : 'file', dir: real ? findPackageDir(real) : null };
310
+ }
311
+ return null;
312
+ }
313
+
314
+ // ---------------------------------------------------------------------------
315
+ // CLI entry for install.sh
316
+ // ---------------------------------------------------------------------------
317
+ const isMain = (() => {
318
+ try { return process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); } catch { return false; }
319
+ })();
320
+
321
+ if (isMain) {
322
+ const argv = process.argv.slice(2);
323
+ const flag = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; };
324
+ const keepArg = flag('--keep');
325
+ const keepDirs = keepArg === undefined ? undefined : keepArg === 'none' ? [] : [realpathOr(keepArg) ?? keepArg];
326
+ if (argv.includes('--prune')) {
327
+ const r = pruneCliCopies({
328
+ keepDirs,
329
+ version: flag('--version') ?? null,
330
+ dryRun: argv.includes('--dry-run'),
331
+ log: (m) => process.stdout.write(` ${m}\n`)
332
+ });
333
+ if (argv.includes('--json')) process.stdout.write(JSON.stringify(r) + '\n');
334
+ for (const f of r.failed) process.stderr.write(` could not clean ${f.dir}: ${f.error}\n`);
335
+ process.exitCode = r.failed.length ? 1 : 0;
336
+ } else {
337
+ process.stdout.write(JSON.stringify(inventory(), null, 2) + '\n');
338
+ }
339
+ }
@@ -7,7 +7,7 @@
7
7
  * house-models.json), served at https://infernetprotocol.com/house-models.json.
8
8
  * Adding a model is a PR to that file. The daemon fetches it on start and every
9
9
  * few hours, pulls each listed model that fits this machine into Ollama (one at
10
- * a time, never while a job is running), verifies the pulled model's digest and
10
+ * a time, preferring idle moments), verifies the pulled model's digest and
11
11
  * size against the manifest, and removes house models that leave the manifest.
12
12
  * Pulled models show up in served_models like any other Ollama model.
13
13
  *
@@ -64,6 +64,28 @@ function stripDigest(d) {
64
64
  return typeof d === 'string' ? d.replace(/^sha256:/, '').toLowerCase() : null;
65
65
  }
66
66
 
67
+ function shortDigest(d) {
68
+ const s = stripDigest(d);
69
+ return s ? s.slice(0, 12) : '?';
70
+ }
71
+
72
+ /**
73
+ * True when the manifest pins a digest and Ollama reports a different one.
74
+ * No pin, or no digest from Ollama, is never "outdated": nothing to compare.
75
+ */
76
+ export function isOutdated(entry, installedModel) {
77
+ const want = stripDigest(entry?.digest);
78
+ const got = stripDigest(installedModel?.digest);
79
+ return Boolean(want && got && want !== got);
80
+ }
81
+
82
+ /** `name:tag` -> `name:infernet-prev`, the backup tag kept during an update. */
83
+ export function backupTag(ollamaName) {
84
+ const n = normalizeOllamaName(ollamaName);
85
+ const i = n.lastIndexOf(':');
86
+ return `${n.slice(0, i)}:infernet-prev`;
87
+ }
88
+
67
89
  /**
68
90
  * Validate a manifest document. Bad entries are dropped individually (and
69
91
  * reported in `rejected`) so one typo cannot stop every other model.
@@ -188,11 +210,17 @@ export function diskReserveBytes(totalBytes) {
188
210
  * settings resolveSettings() output
189
211
  * failures { [ollama_name]: { at } }: recent pull/verify failures
190
212
  *
191
- * Returns { pull: [entry], remove: [{ name, reason }], keep: [entry], skipped: [{ name, reason }] }.
213
+ * Returns { pull: [entry], update: [entry], remove: [{ name, reason }], keep: [entry], skipped: [{ name, reason }] }.
214
+ *
215
+ * `update` holds models the daemon pulled whose installed digest no longer
216
+ * matches the manifest pin (we re-pinned a new build). Before 0.1.84 an
217
+ * installed model was always kept, so a re-pin never reached any node that
218
+ * already had the old build. A model the operator pulled themselves is never
219
+ * touched; it is reported in `skipped` as outdated instead.
192
220
  */
193
221
  export function planSync({ manifest, installed = [], owned = {}, capacity = {}, settings, failures = {}, now = Date.now() }) {
194
222
  const installedByName = new Map(installed.map((m) => [normalizeOllamaName(m.name ?? m.model), m]));
195
- const plan = { pull: [], remove: [], keep: [], skipped: [] };
223
+ const plan = { pull: [], update: [], remove: [], keep: [], skipped: [] };
196
224
  const models = manifest?.models ?? [];
197
225
  const listed = new Set(models.map((m) => m.ollama_name));
198
226
 
@@ -219,9 +247,40 @@ export function planSync({ manifest, installed = [], owned = {}, capacity = {},
219
247
  else if (used + m.size_bytes > capBytes) reason = `over the house-models disk cap of ${settings.maxDiskGb} GB`;
220
248
 
221
249
  if (have) {
222
- if (reason && ours) plan.remove.push({ name: m.ollama_name, reason });
223
- else if (reason) plan.skipped.push({ name: m.ollama_name, reason: `${reason} (kept: you installed it yourself)` });
224
- else { plan.keep.push(m); if (ours) used += m.size_bytes; }
250
+ if (reason && ours) { plan.remove.push({ name: m.ollama_name, reason }); continue; }
251
+ if (reason) { plan.skipped.push({ name: m.ollama_name, reason: `${reason} (kept: you installed it yourself)` }); continue; }
252
+ const outdated = isOutdated(m, have);
253
+ if (!outdated) { plan.keep.push(m); if (ours) used += m.size_bytes; continue; }
254
+ const pin = `installed ${shortDigest(have.digest)}, house manifest pins ${shortDigest(m.digest)}`;
255
+ if (!ours) {
256
+ plan.keep.push(m);
257
+ plan.skipped.push({ name: m.ollama_name, reason: `outdated vs house manifest (${pin}); not updated: you installed it yourself`, outdated: true });
258
+ continue;
259
+ }
260
+ // Ours and re-pinned: re-pull, under the same backoff and disk
261
+ // rules as a fresh pull. The old build stays until the new one
262
+ // verifies (syncHouseModels keeps a backup tag).
263
+ used += m.size_bytes;
264
+ const failedUpdate = failures[m.ollama_name];
265
+ if (failedUpdate && now - Date.parse(failedUpdate.at) < FAILURE_BACKOFF_MS) {
266
+ plan.keep.push(m);
267
+ plan.skipped.push({ name: m.ollama_name, reason: `update failed (${failedUpdate.error ?? 'error'}); kept the old build, retrying after 24 h`, outdated: true });
268
+ continue;
269
+ }
270
+ if (Number.isFinite(free)) {
271
+ const needFree = m.size_bytes + reserve;
272
+ if (free < needFree) {
273
+ plan.keep.push(m);
274
+ plan.skipped.push({
275
+ name: m.ollama_name,
276
+ reason: `update waiting for disk (${pin}): ${(free / GB).toFixed(1)} GB free, needs ${(needFree / GB).toFixed(1)} GB`,
277
+ outdated: true
278
+ });
279
+ continue;
280
+ }
281
+ free -= m.size_bytes;
282
+ }
283
+ plan.update.push({ ...m, installed_digest: have.digest ? `sha256:${stripDigest(have.digest)}` : null });
225
284
  continue;
226
285
  }
227
286
  if (reason) { plan.skipped.push({ name: m.ollama_name, reason }); continue; }
@@ -349,6 +408,16 @@ export async function ollamaDelete(name, { host = ollamaHost(), fetchImpl = fetc
349
408
  if (!res.ok && res.status !== 404) throw new Error(`ollama delete HTTP ${res.status}`);
350
409
  }
351
410
 
411
+ /** Copy a tag (manifest only; the blobs are shared, so this costs no disk). */
412
+ export async function ollamaCopy(source, destination, { host = ollamaHost(), fetchImpl = fetch } = {}) {
413
+ const res = await fetchImpl(new URL('/api/copy', host), {
414
+ method: 'POST',
415
+ headers: { 'content-type': 'application/json' },
416
+ body: JSON.stringify({ source, destination })
417
+ });
418
+ if (!res.ok) throw new Error(`ollama copy HTTP ${res.status}`);
419
+ }
420
+
352
421
  /** Where Ollama keeps blobs, best guess; used only to measure free disk. */
353
422
  export function ollamaModelsDir(env = process.env) {
354
423
  const candidates = [
@@ -383,8 +452,10 @@ export function ramGb() {
383
452
 
384
453
  /**
385
454
  * Fetch the manifest, plan, then remove and pull one model at a time.
386
- * `isBusy()` is checked before each pull so a pull never starts while the
387
- * node is running a job. Writes the state file. Returns a summary.
455
+ * Before each pull it waits up to `busyWaitMs` (10 min) for the node to be
456
+ * idle (`isBusy()`), then pulls anyway: a pull is network and disk work that
457
+ * Ollama does beside inference, and a node that is never idle must still get
458
+ * its house models. Writes the state file. Returns a summary.
388
459
  */
389
460
  export async function syncHouseModels({
390
461
  settings,
@@ -392,13 +463,15 @@ export async function syncHouseModels({
392
463
  host = ollamaHost(),
393
464
  statePath = getStatePath(),
394
465
  isBusy = () => false,
466
+ busyWaitMs = 10 * 60 * 1000,
467
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
395
468
  log = () => {},
396
469
  capacity = null,
397
470
  manifest = null
398
471
  } = {}) {
399
472
  const state = readState(statePath);
400
473
  const at = new Date().toISOString();
401
- const summary = { at, pulled: [], removed: [], skipped: [], errors: [] };
474
+ const summary = { at, pulled: [], updated: [], removed: [], skipped: [], errors: [] };
402
475
  try {
403
476
  const man = manifest ?? await fetchManifest({ url: settings.manifestUrl, fetchImpl });
404
477
  for (const r of man.rejected) log(`manifest entry ${r.name} rejected: ${r.reasons.join('; ')}`);
@@ -428,10 +501,8 @@ export async function syncHouseModels({
428
501
  }
429
502
 
430
503
  for (const m of plan.pull) {
431
- if (isBusy()) {
432
- summary.skipped.push({ name: m.ollama_name, reason: 'node busy with a job; next sync' });
433
- continue;
434
- }
504
+ const waitUntil = Date.now() + busyWaitMs;
505
+ while (isBusy() && Date.now() < waitUntil) await sleep(15_000);
435
506
  log(`pulling ${m.ollama_name} (${(m.size_bytes / GB).toFixed(1)} GB)`);
436
507
  try {
437
508
  let lastLog = 0;
@@ -463,6 +534,47 @@ export async function syncHouseModels({
463
534
  }
464
535
  await writeState({ ...state, last_sync: summary }, statePath).catch(() => {});
465
536
  }
537
+ for (const m of plan.update) {
538
+ const waitUntil = Date.now() + busyWaitMs;
539
+ while (isBusy() && Date.now() < waitUntil) await sleep(15_000);
540
+ const backup = backupTag(m.ollama_name);
541
+ log(`updating ${m.ollama_name}: installed ${shortDigest(m.installed_digest)}, manifest pins ${shortDigest(m.digest)}`);
542
+ let backedUp = false;
543
+ try {
544
+ // Keep the old build under a backup tag so a failed or bad
545
+ // pull never leaves the node without the model.
546
+ await ollamaCopy(m.ollama_name, backup, { host, fetchImpl });
547
+ backedUp = true;
548
+ await ollamaPull(m.source, { host, fetchImpl });
549
+ installed = await ollamaTags({ host, fetchImpl });
550
+ const got = installed.find((t) => normalizeOllamaName(t.name) === m.ollama_name);
551
+ const v = verifyPulled(m, got);
552
+ if (!v.ok) throw new Error(`verification failed: ${v.error}`);
553
+ await ollamaDelete(backup, { host, fetchImpl }).catch(() => {});
554
+ state.owned[m.ollama_name] = { digest: got.digest ?? null, size_bytes: Number(got.size) || m.size_bytes, pulled_at: new Date().toISOString(), uncensored: m.uncensored, updated_from: m.installed_digest };
555
+ delete state.failures[m.ollama_name];
556
+ summary.updated.push(m.ollama_name);
557
+ log(`updated and verified ${m.ollama_name}`);
558
+ } catch (err) {
559
+ let error = (err?.message ?? String(err)).slice(0, 300);
560
+ if (backedUp) {
561
+ // Put the old build back under the real name.
562
+ try {
563
+ await ollamaCopy(backup, m.ollama_name, { host, fetchImpl });
564
+ await ollamaDelete(backup, { host, fetchImpl });
565
+ error += ' (kept the old build)';
566
+ } catch (restoreErr) {
567
+ error += `; restoring the old build failed: ${restoreErr?.message ?? restoreErr} (it is still under ${backup})`;
568
+ }
569
+ } else {
570
+ error += ' (kept the old build)';
571
+ }
572
+ state.failures[m.ollama_name] = { at: new Date().toISOString(), error, update: true };
573
+ summary.errors.push({ name: m.ollama_name, error });
574
+ log(`update ${m.ollama_name} failed: ${error}`);
575
+ }
576
+ await writeState({ ...state, last_sync: summary }, statePath).catch(() => {});
577
+ }
466
578
  state.manifest = { url: settings.manifestUrl, version: man.version, updated: man.updated, models: man.models.map((m) => m.ollama_name) };
467
579
  } catch (err) {
468
580
  summary.errors.push({ name: null, error: err?.message ?? String(err) });
package/lib/route.js CHANGED
@@ -16,11 +16,33 @@
16
16
  * chat REPL)
17
17
  * 3. argv empty + piped stdin (`echo … | infernet`) → chat
18
18
  * 4. argv[0] is a known subcommand → that command
19
- * 5. argv[0] is anything else → chat with
19
+ * 5. argv[0] looks like a command word and argv is short
20
+ * (`infernet house-models off`) but is not one we know → unknown
21
+ * command. Sending it to chat would turn an operator's command (an
22
+ * opt-out, even) into a prompt to a model, which is what a stale CLI
23
+ * copy shadowing a newer one on PATH did on 2026-11-02.
24
+ * 6. argv[0] is anything else → chat with
20
25
  * all of argv as
21
26
  * the prompt
27
+ *
28
+ * Free text still chats: `infernet "what is 2+2"` (a space in the first
29
+ * token), `infernet what is 2+2?` (punctuation) and longer prompts
30
+ * (`infernet tell me a joke`) all go to chat.
22
31
  */
23
32
 
33
+ /** A token that could only be a subcommand name: `house-models`, `doctor`. */
34
+ export const COMMAND_WORD_RE = /^[a-z][a-z0-9-]*$/;
35
+ /** Tokens after it that read like subcommand args: `sync`, `off`, `8`, `--yes`. */
36
+ const ARG_WORD_RE = /^(?:-{1,2}[a-z0-9][a-z0-9-]*(?:=\S*)?|[a-z0-9][a-z0-9._-]*)$/i;
37
+ /** `infernet house-models uncensored off` is the longest real command shape. */
38
+ export const MAX_COMMAND_TOKENS = 3;
39
+
40
+ export function looksLikeCommand(argv) {
41
+ if (!Array.isArray(argv) || argv.length === 0 || argv.length > MAX_COMMAND_TOKENS) return false;
42
+ if (!COMMAND_WORD_RE.test(argv[0])) return false;
43
+ return argv.slice(1).every((t) => typeof t === 'string' && ARG_WORD_RE.test(t));
44
+ }
45
+
24
46
  export function decideRoute(argv, knownCommands, { isTTY = true } = {}) {
25
47
  if (!Array.isArray(argv)) throw new TypeError("decideRoute: argv must be an array");
26
48
  if (!(knownCommands instanceof Set)) throw new TypeError("decideRoute: knownCommands must be a Set");
@@ -40,5 +62,17 @@ export function decideRoute(argv, knownCommands, { isTTY = true } = {}) {
40
62
  return { command: sub, rest: argv.slice(1) };
41
63
  }
42
64
 
65
+ if (looksLikeCommand(argv)) {
66
+ return { command: "unknown", name: sub, rest: argv.slice(1) };
67
+ }
68
+
43
69
  return { command: "chat", rest: argv };
44
70
  }
71
+
72
+ /** The message for rule 5: say which CLI answered so a stale copy is obvious. */
73
+ export function unknownCommandMessage(name, { version, entry } = {}) {
74
+ const which = version ? `this CLI is v${version}${entry ? ` at ${entry}` : ''}` : 'this CLI';
75
+ return `infernet: unknown command '${name}' (${which}; run \`infernet upgrade\` if it should exist)\n`
76
+ + ` to ask a model instead, quote the prompt: infernet "${name} ..." or infernet chat ...\n`
77
+ + ` all commands: infernet help\n`;
78
+ }
package/lib/version.js CHANGED
@@ -4,18 +4,50 @@ import { homedir } from 'node:os';
4
4
  import { fileURLToPath } from 'node:url';
5
5
 
6
6
  const _dir = dirname(fileURLToPath(import.meta.url));
7
- export const CURRENT_VERSION = readInstalledVersion();
7
+
8
+ /** The CLI package directory this code is running from. */
9
+ export const CLI_DIR = join(_dir, '..');
10
+
11
+ /**
12
+ * The version of the code that is actually running: the package.json next to
13
+ * this file and nothing else. Before 0.1.84 this was the newest of that and
14
+ * ~/.infernet/source, so a stale npm-global copy shadowing the installer's
15
+ * shim printed the source tree's version while running its own old code.
16
+ */
17
+ export const RUNNING_VERSION = readRunningVersion();
18
+ /** Kept for existing imports; it is the running version. */
19
+ export const CURRENT_VERSION = RUNNING_VERSION;
20
+
21
+ export function readRunningVersion(dir = CLI_DIR) {
22
+ try {
23
+ const v = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version;
24
+ return typeof v === 'string' ? v : '0.0.0';
25
+ } catch {
26
+ return '0.0.0';
27
+ }
28
+ }
29
+
30
+ /** Version of the installer's git checkout (~/.infernet/source), or null. */
31
+ export function readSourceVersion(env = process.env) {
32
+ const sourceHome = env.INFERNET_HOME || join(homedir(), '.infernet');
33
+ try {
34
+ const v = JSON.parse(readFileSync(join(sourceHome, 'source', 'apps', 'cli', 'package.json'), 'utf8')).version;
35
+ return typeof v === 'string' ? v : null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
8
40
 
9
41
  /**
10
- * The version on disk right now, read fresh (CURRENT_VERSION is what this
11
- * process started with). Self-update compares the two after the installer
42
+ * The newest CLI version installed on this machine right now, read fresh
43
+ * (RUNNING_VERSION is what this process started with). Self-update compares the two after the installer
12
44
  * runs: if nothing newer landed, restarting would only repeat the same update
13
45
  * every 60 seconds.
14
46
  */
15
47
  export function readInstalledVersion() {
16
48
  const versions = [];
17
49
  try {
18
- versions.push(JSON.parse(readFileSync(join(_dir, '../package.json'), 'utf8')).version);
50
+ versions.push(JSON.parse(readFileSync(join(CLI_DIR, 'package.json'), 'utf8')).version);
19
51
  } catch { /* this install may be a source checkout, not an npm package */ }
20
52
 
21
53
  // When npm is behind master, install.sh deliberately switches to the git
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infernetprotocol/cli",
3
- "version": "0.1.82",
3
+ "version": "0.1.84",
4
4
  "description": "GPU-node CLI / daemon for the Infernet Protocol — register a GPU server with a Supabase control plane and start earning.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -32,14 +32,14 @@
32
32
  "ora": "^9.4.1",
33
33
  "react": "^17.0.2",
34
34
  "react-blessed": "^0.7.2",
35
- "@infernetprotocol/auth": "0.1.82",
36
- "@infernetprotocol/config": "0.1.82",
37
- "@infernetprotocol/deploy-providers": "0.1.82",
38
- "@infernetprotocol/engine": "0.1.82",
39
- "@infernetprotocol/gpu": "0.1.82",
40
- "@infernetprotocol/liquid-agent": "0.1.82",
41
- "@infernetprotocol/rpc-adapter": "0.1.82",
42
- "@infernetprotocol/training": "0.1.82"
35
+ "@infernetprotocol/auth": "0.1.84",
36
+ "@infernetprotocol/config": "0.1.84",
37
+ "@infernetprotocol/deploy-providers": "0.1.84",
38
+ "@infernetprotocol/engine": "0.1.84",
39
+ "@infernetprotocol/gpu": "0.1.84",
40
+ "@infernetprotocol/liquid-agent": "0.1.84",
41
+ "@infernetprotocol/rpc-adapter": "0.1.84",
42
+ "@infernetprotocol/training": "0.1.84"
43
43
  },
44
44
  "repository": {
45
45
  "type": "git",