nimblebrain 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/nimblebrain.js +163 -111
  2. package/package.json +1 -1
@@ -6,7 +6,7 @@ import { writeSync } from "node:fs";
6
6
  // src/deps.ts
7
7
  import { spawn } from "node:child_process";
8
8
  import { constants } from "node:fs";
9
- import { access, chmod, mkdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
9
+ import { access, chmod, mkdir, readFile, rename, rm, rmdir, writeFile } from "node:fs/promises";
10
10
  import { createServer } from "node:net";
11
11
  import { homedir } from "node:os";
12
12
  import { delimiter, dirname, join, resolve } from "node:path";
@@ -96,8 +96,17 @@ function realDeps() {
96
96
  },
97
97
  async writeText(path, text, mode = 420) {
98
98
  await mkdir(dirname(path), { recursive: true, mode: 448 });
99
- await writeFile(path, text, { mode });
100
- await chmod(path, mode);
99
+ const tmp = `${path}.${process.pid}.tmp`;
100
+ try {
101
+ await writeFile(tmp, text, { mode });
102
+ await chmod(tmp, mode);
103
+ await rename(tmp, path);
104
+ } catch (err) {
105
+ await rm(tmp, { force: true }).catch(() => {
106
+ return;
107
+ });
108
+ throw err;
109
+ }
101
110
  },
102
111
  async remove(path) {
103
112
  try {
@@ -220,11 +229,12 @@ var ERRORS = {
220
229
  LOW_MEMORY: "Give Docker at least 2 GB of memory in its settings, then run this again.",
221
230
  PORT_IN_USE: "Stop whatever holds the port, or pass --port with a free one.",
222
231
  NOT_INSTALLED: "Run `npx nimblebrain` to install it.",
223
- NOT_OURS: "Another install holds this name or its data. Remove it yourself, or choose a --home whose folder has another name.",
232
+ NOT_OURS: "This folder holds files the CLI did not write. Remove them yourself, or choose another --home.",
233
+ INSTALL_INCOMPLETE: "Run `npx nimblebrain` to finish installing it, or `npx nimblebrain uninstall` to remove it.",
224
234
  NETWORK: "Check the network connection, then run the same command again.",
225
- HEALTH_TIMEOUT: "Run `npx nimblebrain logs` and look at the last error line.",
235
+ HEALTH_TIMEOUT: "Run `npx nimblebrain logs` and look at the last error line, then run the command again; `npx nimblebrain` finishes an install whose first start did not.",
226
236
  AGENT_UNSUPPORTED: "Pass --agent claude-code, cursor, codex or none.",
227
- START_FAILED: "Run `npx nimblebrain logs` and look at the last error line, then run this again.",
237
+ START_FAILED: "Run `npx nimblebrain logs` and look at the last error line, then run the command again; `npx nimblebrain` finishes an install whose first start did not.",
228
238
  NEEDS_TERMINAL: "A person runs this in their own terminal; it asks for input no agent should give.",
229
239
  CANCELLED: "Nothing was changed. Run the command again to go ahead.",
230
240
  RUNTIME_UNSUPPORTED: "Pass a newer runtime with --runtime, or leave it out to install the newest release.",
@@ -251,6 +261,9 @@ var FIX_VARIANTS = {
251
261
  mac_brew: "Install Docker Desktop with `brew install --cask docker`, open it once from Applications, then run this again.",
252
262
  mac: "Install Docker Desktop (https://docs.docker.com/desktop/setup/install/mac-install/), open it once, then run this again."
253
263
  },
264
+ DOCKER_NOT_RUNNING: {
265
+ colima: "Start Colima with `colima start`, then run this again."
266
+ },
254
267
  COMPOSE_MISSING: {
255
268
  brew: "Install Compose with `brew install docker-compose`, then run this again."
256
269
  },
@@ -518,13 +531,13 @@ var FLAG_SPECS = {
518
531
  port: {
519
532
  type: "string",
520
533
  takes: "n",
521
- description: `Local port (default ${DEFAULT_PORT})`,
534
+ description: `Local port (default ${DEFAULT_PORT}; for doctor, the install's own port)`,
522
535
  commands: ["init", "doctor"]
523
536
  },
524
537
  home: {
525
538
  type: "string",
526
539
  takes: "dir",
527
- description: "Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME); a home with another folder name is a separate install"
540
+ description: "Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME); each home is a separate install"
528
541
  },
529
542
  provider: {
530
543
  type: "string",
@@ -581,8 +594,8 @@ var options = Object.fromEntries(Object.entries(FLAG_SPECS).map(([name, f]) => [
581
594
  function parse(argv) {
582
595
  const { values, positionals } = parseStrict(argv);
583
596
  const json = values.json === true;
584
- const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
585
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
597
+ const port = values.port === undefined ? undefined : Number(values.port);
598
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
586
599
  throw new CliError("USAGE", `--port must be a port number, not "${values.port}".`);
587
600
  }
588
601
  let agent;
@@ -669,15 +682,13 @@ function wantsJson(argv) {
669
682
  }
670
683
 
671
684
  // src/compose.ts
685
+ import { randomBytes } from "node:crypto";
672
686
  import { basename, join as join2 } from "node:path";
673
- var DEFAULT_PROJECT = "nimblebrain-local";
674
- function projectFor(home) {
687
+ function newProject(home) {
675
688
  const slug = basename(home).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9]+$/, "");
676
- if (!slug)
677
- return "nimblebrain";
678
- return slug.startsWith("nimblebrain") ? slug : `nimblebrain-${slug}`;
689
+ const name = !slug ? "nimblebrain" : slug.startsWith("nimblebrain") ? slug : `nimblebrain-${slug}`;
690
+ return `${name}-${randomBytes(3).toString("hex")}`;
679
691
  }
680
- var volumeOf = (project) => `${project}_workspace`;
681
692
  var RAW = "https://raw.githubusercontent.com/NimbleBrainInc/nimblebrain";
682
693
  async function fetchCompose(deps, tag) {
683
694
  const res = await deps.getText(`${RAW}/${tag}/docker-compose.yml`, 15000);
@@ -762,11 +773,26 @@ async function compose(deps, home, args, timeoutMs = 120000) {
762
773
  timeoutMs
763
774
  });
764
775
  }
776
+ async function claimWritten(deps, home) {
777
+ return await deps.readText(paths(home).env) !== undefined;
778
+ }
779
+ async function runningHere(deps, home) {
780
+ if (!await claimWritten(deps, home))
781
+ return false;
782
+ const res = await compose(deps, home, ["ps", "-q"], 30000);
783
+ return res.code === 0 && res.stdout.trim() !== "";
784
+ }
785
+ function daemonVariant(text) {
786
+ return /\/\.colima\/default\//.test(text) ? "colima" : undefined;
787
+ }
765
788
  function startError(res) {
766
789
  const text = `${res.stderr}
767
790
  ${res.stdout}`;
768
791
  const last = text.trim().split(`
769
792
  `).filter((l) => l.trim()).pop() ?? "Compose failed.";
793
+ if (/cannot connect to the docker daemon|failed to connect to the docker api/i.test(text)) {
794
+ return new CliError("DOCKER_NOT_RUNNING", last, {}, daemonVariant(text));
795
+ }
770
796
  if (/no such host|timeout|TLS handshake|connection refused|network is unreachable/i.test(text)) {
771
797
  return new CliError("NETWORK", last);
772
798
  }
@@ -851,7 +877,7 @@ async function checkDaemon(deps, log) {
851
877
  ${info.stdout}`)) {
852
878
  log.fail("docker-daemon", "DOCKER_PERMISSION", "This user may not use Docker.");
853
879
  }
854
- log.fail("docker-daemon", "DOCKER_NOT_RUNNING", "Docker is installed but not running.");
880
+ log.fail("docker-daemon", "DOCKER_NOT_RUNNING", "Docker is installed but not running.", daemonVariant(info.stderr));
855
881
  }
856
882
  log.pass("docker-daemon", "running");
857
883
  return parseInfo(info.stdout);
@@ -902,6 +928,7 @@ function gib(bytes) {
902
928
  // src/answers.ts
903
929
  var STATE = {
904
930
  version: "The NimbleBrain runtime release installed, without the leading v",
931
+ phase: "starting until the install's first start answers health, else ready; npx nimblebrain finishes a starting install, and only down, logs, uninstall, status and doctor act on one",
905
932
  cli_version: "This CLI's version; it moves independently of the runtime",
906
933
  health: "ok when NimbleBrain answers, else down",
907
934
  url: "Where the web UI and API answer, on 127.0.0.1",
@@ -1168,6 +1195,8 @@ var TELEMETRY_KEY = "phc_qKmpYhdDtcFYZchu3KAKFFmYHG88nfUDPCFqxoAmbS7E";
1168
1195
  var ENDPOINT = "https://us.i.posthog.com/batch/";
1169
1196
  var QUESTION = "Help improve NimbleBrain by sending anonymous usage data? No prompts, content, names or keys are sent.";
1170
1197
  var reportPath = (home) => join4(home, "telemetry-report.jsonl");
1198
+ var idPath = (home) => join4(home, "telemetry-id");
1199
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1171
1200
  var RELEASED = true;
1172
1201
  function telemetryKey(deps) {
1173
1202
  return deps.env.NIMBLEBRAIN_TELEMETRY_KEY ?? (RELEASED ? TELEMETRY_KEY : "");
@@ -1176,7 +1205,7 @@ function doNotTrack(deps) {
1176
1205
  return deps.env.DO_NOT_TRACK === "1";
1177
1206
  }
1178
1207
  function lockedHere(deps) {
1179
- if (doNotTrack(deps) || deps.env.NB_TELEMETRY_DISABLED === "1")
1208
+ if (doNotTrack(deps))
1180
1209
  return "do_not_track";
1181
1210
  if (!telemetryKey(deps))
1182
1211
  return "no_destination";
@@ -1237,6 +1266,21 @@ async function send(deps, home, batch) {
1237
1266
  else
1238
1267
  await deps.writeText(reportPath(home), toLines(batch), 384);
1239
1268
  }
1269
+ async function installId(deps, home) {
1270
+ if (lockedHere(deps))
1271
+ return;
1272
+ try {
1273
+ const kept = (await deps.readText(idPath(home)))?.trim();
1274
+ if (kept && UUID.test(kept))
1275
+ return kept.toLowerCase();
1276
+ const id = await reportId(deps, home) ?? randomUUID();
1277
+ await deps.writeText(idPath(home), `${id}
1278
+ `, 384);
1279
+ return id;
1280
+ } catch {
1281
+ return;
1282
+ }
1283
+ }
1240
1284
  async function reportId(deps, home) {
1241
1285
  return (await readReport(deps, home))[0]?.distinct_id;
1242
1286
  }
@@ -1284,9 +1328,10 @@ async function settleWaiting(deps, home, version) {
1284
1328
  }
1285
1329
  function envValues(deps, id, consent, asksFirst) {
1286
1330
  const values = {
1287
- NB_TELEMETRY_ID: id,
1288
1331
  NB_TELEMETRY_KEY: asksFirst ? telemetryKey(deps) : ""
1289
1332
  };
1333
+ if (id)
1334
+ values.NB_TELEMETRY_ID = id;
1290
1335
  if (consent !== "undecided")
1291
1336
  values.NB_TELEMETRY_CONSENT = consent;
1292
1337
  return values;
@@ -1316,7 +1361,7 @@ async function setRuntimeTelemetry(deps, url, consent) {
1316
1361
  // package.json
1317
1362
  var package_default = {
1318
1363
  name: "nimblebrain",
1319
- version: "0.7.0",
1364
+ version: "0.8.0",
1320
1365
  description: "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
1321
1366
  license: "Apache-2.0",
1322
1367
  type: "module",
@@ -1350,7 +1395,7 @@ async function readInstall(deps, home) {
1350
1395
  return;
1351
1396
  try {
1352
1397
  const state = JSON.parse(text);
1353
- if (typeof state.version !== "string" || typeof state.port !== "number" || typeof state.project !== "string") {
1398
+ if (typeof state?.version !== "string" || typeof state.port !== "number" || typeof state.project !== "string" || state.phase !== "starting" && state.phase !== "ready") {
1354
1399
  return;
1355
1400
  }
1356
1401
  return state;
@@ -1358,13 +1403,24 @@ async function readInstall(deps, home) {
1358
1403
  return;
1359
1404
  }
1360
1405
  }
1361
- async function status(deps, home) {
1406
+ async function requireInstall(deps, home) {
1362
1407
  const install = await readInstall(deps, home);
1363
1408
  if (!install)
1364
1409
  throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1410
+ return install;
1411
+ }
1412
+ async function requireReady(deps, home) {
1413
+ const install = await requireInstall(deps, home);
1414
+ if (install.phase !== "ready") {
1415
+ throw new CliError("INSTALL_INCOMPLETE", `The NimbleBrain install in ${home} has not finished installing.`);
1416
+ }
1417
+ return install;
1418
+ }
1419
+ async function status(deps, home) {
1420
+ const install = await requireInstall(deps, home);
1365
1421
  const url = installUrl(install);
1366
1422
  const up = await isUp(deps, url);
1367
- const workspaces = up ? await readWorkspaces(deps, url) : [];
1423
+ const workspaces = up && install.phase === "ready" ? await readWorkspaces(deps, url) : [];
1368
1424
  const composeText = await deps.readText(join5(home, "docker-compose.yml")) ?? "";
1369
1425
  const vars = keyVars(composeText);
1370
1426
  const envText = await deps.readText(join5(home, ".env")) ?? "";
@@ -1372,6 +1428,7 @@ async function status(deps, home) {
1372
1428
  return {
1373
1429
  ok: true,
1374
1430
  version: install.version,
1431
+ phase: install.phase,
1375
1432
  cli_version: VERSION,
1376
1433
  health: up ? "ok" : "down",
1377
1434
  url,
@@ -1423,9 +1480,7 @@ async function openBrowser(deps, url) {
1423
1480
  }
1424
1481
  async function open(ctx) {
1425
1482
  const { deps, home } = ctx;
1426
- const install = await readInstall(deps, home);
1427
- if (!install)
1428
- throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1483
+ const install = await requireReady(deps, home);
1429
1484
  const url = installUrl(install);
1430
1485
  if (!await isUp(deps, url))
1431
1486
  throw new CliError("NOT_RUNNING", "NimbleBrain is not running.", { url });
@@ -1512,14 +1567,16 @@ function confirmOllamaStart(ctx, unasked) {
1512
1567
  }
1513
1568
  async function init(ctx) {
1514
1569
  const { deps, flags, home } = ctx;
1515
- if (await readInstall(deps, home))
1570
+ const record = await readInstall(deps, home);
1571
+ if (record?.phase === "ready")
1516
1572
  return { ...await status(deps, home), already: true };
1517
- const consent = await chooseConsent(ctx);
1518
- const rec = recorder2(deps, ctx.version, await reportId(deps, home));
1573
+ const consent = await chooseConsent(ctx, record);
1574
+ const id = await foreignFile(deps, home) ? undefined : await installId(deps, home);
1575
+ const rec = recorder2(deps, ctx.version, id ?? await reportId(deps, home));
1519
1576
  const begun = Date.now();
1520
1577
  rec.record("cli.init_started", { agent: flags.agent ?? null, interactive: deps.interactive });
1521
1578
  try {
1522
- return await openWhenDone(ctx, await install(ctx, consent, rec, begun));
1579
+ return await openWhenDone(ctx, await install(ctx, record, consent, rec, begun));
1523
1580
  } catch (err) {
1524
1581
  if (!(err instanceof CliError))
1525
1582
  throw err;
@@ -1541,11 +1598,17 @@ async function settleFailure(rec, home, consent, err) {
1541
1598
  rec.record(check ? "cli.doctor_failed" : "cli.init_failed", { error: err.code, check });
1542
1599
  await rec.settle(home, consent);
1543
1600
  }
1544
- async function chooseConsent(ctx) {
1601
+ async function chooseConsent(ctx, record) {
1545
1602
  if (lockedHere(ctx.deps))
1546
1603
  return "off";
1547
1604
  if (ctx.flags.telemetry)
1548
1605
  return ctx.flags.telemetry;
1606
+ if (record) {
1607
+ const env = await ctx.deps.readText(paths(ctx.home).env) ?? "";
1608
+ const held = env.match(/^NB_TELEMETRY_CONSENT=(on|off)\r?$/m)?.[1];
1609
+ if (held === "on" || held === "off")
1610
+ return held;
1611
+ }
1549
1612
  if (!asks(ctx))
1550
1613
  return "undecided";
1551
1614
  const consent = parseAnswer(await ctx.deps.prompt(`${QUESTION} [Y/n] `));
@@ -1553,30 +1616,29 @@ async function chooseConsent(ctx) {
1553
1616
  ctx.deps.say(consent === "on" ? `Sending anonymous usage data. Turn it off any time: ${cli} telemetry off` : `No usage data will be sent. Turn it on any time: ${cli} telemetry on`);
1554
1617
  return consent;
1555
1618
  }
1556
- async function install(ctx, consent, rec, begun) {
1619
+ async function install(ctx, record, consent, rec, begun) {
1557
1620
  const { deps, flags, home } = ctx;
1558
- await doctor(deps, flags.port);
1559
- const project = await guardOurs(deps, home);
1560
- const tag = await runtimeTag(deps, flags.runtime);
1621
+ const port = flags.port ?? record?.port ?? DEFAULT_PORT;
1622
+ const ours = record?.port === port && await runningHere(deps, home);
1623
+ await doctor(deps, port, ours);
1624
+ if (!record)
1625
+ await refuseForeign(deps, home);
1626
+ const tag = record && !flags.runtime ? `v${record.version}` : await runtimeTag(deps, flags.runtime);
1561
1627
  const composeText = await fetchCompose(deps, tag);
1562
- await confirmStart(ctx, tag);
1563
- await writeInstallFiles(deps, home, project, tag, flags.port, composeText, envValues(deps, rec.id, consent, asksConsent(composeText)));
1564
- const envText = await deps.readText(paths(home).env) ?? "";
1565
- const hasModel = hasKey(envText, keyVars(composeText)) || localModelOf(envText) !== undefined;
1566
- const local = flags.localModel ?? (!hasModel && asks(ctx) && takesLocalModel(composeText) ? await chooseModelSource(deps) : undefined);
1567
- let ollamaStarted;
1568
- if (local)
1569
- ollamaStarted = (await useLocalModel(ctx, composeText, local)).started;
1570
- else if (!hasModel && asks(ctx))
1571
- await enterKey(ctx, false);
1628
+ await confirmStart(ctx, tag, port);
1629
+ const state = {
1630
+ project: record?.project ?? newProject(home),
1631
+ port,
1632
+ version: tag.replace(/^v/, ""),
1633
+ phase: "starting"
1634
+ };
1635
+ await writeState(deps, home, state);
1636
+ await writeInstallFiles(deps, home, state.project, tag, port, composeText, envValues(deps, lockedHere(deps) ? undefined : rec.id, consent, asksConsent(composeText)));
1637
+ const ollamaStarted = await prepareModel2(ctx, composeText);
1572
1638
  return carryingStarted(ollamaStarted, async () => {
1573
1639
  deps.say(`Starting NimbleBrain ${tag}. The first start downloads about 2 GB of images.`);
1574
- await start(deps, home, flags.port);
1575
- const state = {
1576
- version: tag.replace(/^v/, ""),
1577
- port: flags.port,
1578
- project
1579
- };
1640
+ await start(deps, home, port);
1641
+ state.phase = "ready";
1580
1642
  await writeState(deps, home, state);
1581
1643
  const manual = await connectChosenAgent(ctx, state);
1582
1644
  if (state.agent)
@@ -1597,10 +1659,10 @@ async function install(ctx, consent, rec, begun) {
1597
1659
  return { ...result };
1598
1660
  });
1599
1661
  }
1600
- async function confirmStart(ctx, tag) {
1662
+ async function confirmStart(ctx, tag, port) {
1601
1663
  if (!asks(ctx))
1602
1664
  return;
1603
- const answer = await ctx.deps.prompt(`Start NimbleBrain ${tag} at http://127.0.0.1:${ctx.flags.port}? [Y/n] `);
1665
+ const answer = await ctx.deps.prompt(`Start NimbleBrain ${tag} at http://127.0.0.1:${port}? [Y/n] `);
1604
1666
  if (/^n/i.test(answer))
1605
1667
  throw new CliError("CANCELLED", "Nothing was installed.");
1606
1668
  }
@@ -1622,7 +1684,7 @@ async function connectChosenAgent(ctx, state) {
1622
1684
  }
1623
1685
  async function up(ctx) {
1624
1686
  const { deps, home } = ctx;
1625
- const install = await requireInstall(ctx);
1687
+ const install = await requireReady(ctx.deps, home);
1626
1688
  const local = localModelOf(await deps.readText(paths(home).env) ?? "");
1627
1689
  const ollama = local ? await ensureOllama(deps, confirmOllamaStart(ctx, true)).catch((err) => {
1628
1690
  if (err instanceof CliError)
@@ -1641,14 +1703,18 @@ async function up(ctx) {
1641
1703
  }
1642
1704
  var lowerFirst = (s) => s.charAt(0).toLowerCase() + s.slice(1);
1643
1705
  async function down(ctx) {
1644
- await requireInstall(ctx);
1706
+ await requireInstall(ctx.deps, ctx.home);
1707
+ if (!await claimWritten(ctx.deps, ctx.home))
1708
+ return { ok: true, health: "down" };
1645
1709
  const res = await compose(ctx.deps, ctx.home, ["down"]);
1646
1710
  if (res.code !== 0)
1647
1711
  throw startError(res);
1648
1712
  return { ok: true, health: "down" };
1649
1713
  }
1650
1714
  async function logs(ctx) {
1651
- await requireInstall(ctx);
1715
+ await requireInstall(ctx.deps, ctx.home);
1716
+ if (!await claimWritten(ctx.deps, ctx.home))
1717
+ return { ok: true, lines: [] };
1652
1718
  const res = await compose(ctx.deps, ctx.home, [
1653
1719
  "logs",
1654
1720
  "--no-color",
@@ -1663,7 +1729,7 @@ async function logs(ctx) {
1663
1729
  }
1664
1730
  async function update(ctx) {
1665
1731
  const { deps, home } = ctx;
1666
- const install = await requireInstall(ctx);
1732
+ const install = await requireReady(deps, home);
1667
1733
  const tag = await runtimeTag(deps, ctx.flags.runtime);
1668
1734
  const from = `v${install.version}`;
1669
1735
  const order = compareVersions(tag, from);
@@ -1692,7 +1758,7 @@ async function refreshAgentSkill(deps, install) {
1692
1758
  }
1693
1759
  async function uninstall(ctx) {
1694
1760
  const { deps, flags, home } = ctx;
1695
- const install = await requireInstall(ctx);
1761
+ const install = await requireInstall(deps, home);
1696
1762
  if (!flags.yes) {
1697
1763
  if (!deps.interactive || flags.json) {
1698
1764
  throw new CliError("CANCELLED", "Removing deletes every conversation; pass --yes to confirm.");
@@ -1701,28 +1767,30 @@ async function uninstall(ctx) {
1701
1767
  if (!/^y/i.test(answer))
1702
1768
  throw new CliError("CANCELLED", "Nothing was removed.");
1703
1769
  }
1704
- const res = await compose(deps, home, ["down", "-v", "--rmi", "all"], START_TIMEOUT_MS);
1705
- if (res.code !== 0)
1706
- throw startError(res);
1770
+ if (await claimWritten(deps, home)) {
1771
+ const res = await compose(deps, home, ["down", "-v", "--rmi", "all"], START_TIMEOUT_MS);
1772
+ if (res.code !== 0)
1773
+ throw startError(res);
1774
+ }
1707
1775
  if (install.agent === "claude-code")
1708
1776
  await deps.exec("claude", ["mcp", "remove", "-s", "user", SERVER_NAME]);
1709
1777
  if (install.agent === "codex")
1710
1778
  await deps.exec("codex", ["mcp", "remove", SERVER_NAME]);
1711
- for (const file of [...Object.values(paths(home)), reportPath(home)])
1779
+ for (const file of [...Object.values(paths(home)), reportPath(home), idPath(home)])
1712
1780
  await deps.remove(file);
1713
1781
  await deps.remove(home);
1714
1782
  return { ok: true, removed: true };
1715
1783
  }
1716
1784
  async function telemetry(ctx) {
1717
1785
  const { deps, home } = ctx;
1718
- const install = await requireInstall(ctx);
1786
+ const install = await requireReady(deps, home);
1719
1787
  const url = `http://127.0.0.1:${install.port}`;
1720
1788
  if (ctx.arg !== "on" && ctx.arg !== "off") {
1721
1789
  return { ok: true, telemetry: (await status(deps, home)).telemetry };
1722
1790
  }
1723
1791
  const here = lockedHere(deps);
1724
1792
  if (here) {
1725
- throw new CliError("TELEMETRY_LOCKED", here === "do_not_track" ? "DO_NOT_TRACK (or NB_TELEMETRY_DISABLED) is set, so telemetry stays off." : "This CLI has nowhere to send telemetry.");
1793
+ throw new CliError("TELEMETRY_LOCKED", here === "do_not_track" ? "DO_NOT_TRACK is set, so telemetry stays off." : "This CLI has nowhere to send telemetry.");
1726
1794
  }
1727
1795
  const rt = await runtimeTelemetry(deps, url);
1728
1796
  if (!rt)
@@ -1735,10 +1803,10 @@ async function telemetry(ctx) {
1735
1803
  return { ok: true, telemetry: field(ctx.arg, invocation(deps, home)) };
1736
1804
  }
1737
1805
  async function key(ctx) {
1806
+ await requireReady(ctx.deps, ctx.home);
1738
1807
  if (!ctx.deps.interactive) {
1739
1808
  throw new CliError("NEEDS_TERMINAL", "`key` asks for a model key at a hidden prompt.");
1740
1809
  }
1741
- await requireInstall(ctx);
1742
1810
  return enterKey(ctx, true);
1743
1811
  }
1744
1812
  async function enterKey(ctx, restart) {
@@ -1761,12 +1829,12 @@ async function enterKey(ctx, restart) {
1761
1829
  await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", { [variable]: value }), 384);
1762
1830
  if (restart) {
1763
1831
  const install = await readInstall(deps, home);
1764
- await start(deps, home, install?.port ?? flags.port);
1832
+ await start(deps, home, install?.port ?? DEFAULT_PORT);
1765
1833
  }
1766
1834
  return { ok: true, provider, model_key: "set" };
1767
1835
  }
1768
1836
  async function localModel(ctx) {
1769
- const install = await requireInstall(ctx);
1837
+ const install = await requireReady(ctx.deps, ctx.home);
1770
1838
  const composeText = await ctx.deps.readText(paths(ctx.home).compose) ?? "";
1771
1839
  const model = ctx.arg ?? ctx.flags.localModel ?? DEFAULT_LOCAL_MODEL;
1772
1840
  const { name, started } = await useLocalModel(ctx, composeText, model);
@@ -1839,48 +1907,37 @@ async function writeInstallFiles(deps, home, project, tag, port, composeText, ex
1839
1907
  });
1840
1908
  await deps.writeText(p.env, env, 384);
1841
1909
  }
1910
+ async function prepareModel2(ctx, composeText) {
1911
+ const { deps, flags, home } = ctx;
1912
+ const envText = await deps.readText(paths(home).env) ?? "";
1913
+ const saved = localModelOf(envText) !== undefined;
1914
+ const hasModel = saved || hasKey(envText, keyVars(composeText));
1915
+ const local = flags.localModel ?? (!hasModel && asks(ctx) && takesLocalModel(composeText) ? await chooseModelSource(deps) : undefined);
1916
+ if (local)
1917
+ return (await useLocalModel(ctx, composeText, local)).started;
1918
+ if (saved)
1919
+ return (await ensureOllama(deps, confirmOllamaStart(ctx, true))).started;
1920
+ if (!hasModel && asks(ctx))
1921
+ await enterKey(ctx, false);
1922
+ return;
1923
+ }
1842
1924
  async function writeState(deps, home, state) {
1843
1925
  await deps.writeText(paths(home).install, `${JSON.stringify(state, null, 2)}
1844
1926
  `);
1845
1927
  }
1846
- async function requireInstall({ deps, home }) {
1847
- const install = await readInstall(deps, home);
1848
- if (!install)
1849
- throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1850
- return install;
1928
+ async function refuseForeign(deps, home) {
1929
+ const file = await foreignFile(deps, home);
1930
+ if (file)
1931
+ throw new CliError("NOT_OURS", `${file} already exists and this CLI did not write it.`);
1851
1932
  }
1852
- async function guardOurs(deps, home) {
1853
- const project = projectFor(home);
1854
- const env = await deps.readText(paths(home).env);
1855
- const marked = env?.match(/^COMPOSE_PROJECT_NAME=(.*?)\r?$/m)?.[1];
1856
- if (marked === project || marked === DEFAULT_PROJECT)
1857
- return marked;
1933
+ async function foreignFile(deps, home) {
1934
+ if (await readInstall(deps, home))
1935
+ return;
1858
1936
  for (const file of Object.values(paths(home))) {
1859
- if (await deps.readText(file) !== undefined) {
1860
- throw new CliError("NOT_OURS", `${file} already exists and this CLI did not write it.`);
1861
- }
1862
- }
1863
- const projects = await composeExec(deps, ["ls", "-a", "--format", "json"]);
1864
- const taken = projects.code === 0 && listsProject(projects.stdout, project);
1865
- const volumes = await deps.exec("docker", [
1866
- "volume",
1867
- "ls",
1868
- "-q",
1869
- "--filter",
1870
- `name=^${volumeOf(project)}$`
1871
- ]);
1872
- if (taken || volumes.stdout.trim() !== "") {
1873
- throw new CliError("NOT_OURS", `Docker already has a "${project}" project or volume that this install did not make.`);
1874
- }
1875
- return project;
1876
- }
1877
- function listsProject(stdout, project) {
1878
- try {
1879
- const list = JSON.parse(stdout);
1880
- return Array.isArray(list) && list.some((p) => p?.Name === project);
1881
- } catch {
1882
- return false;
1937
+ if (await deps.readText(file) !== undefined)
1938
+ return file;
1883
1939
  }
1940
+ return;
1884
1941
  }
1885
1942
 
1886
1943
  // src/mcp.ts
@@ -1905,9 +1962,7 @@ var ADD_TIMEOUT_MS = 60000;
1905
1962
  var CALL_TIMEOUT_MS = 15000;
1906
1963
  async function reach(ctx, adding) {
1907
1964
  const { deps, home, flags } = ctx;
1908
- const install = await readInstall(deps, home);
1909
- if (!install)
1910
- throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1965
+ const install = await requireReady(deps, home);
1911
1966
  if (adding && !hostLoopback(await deps.readText(paths(home).compose) ?? "")) {
1912
1967
  throw new CliError("UPDATE_REQUIRED", `NimbleBrain ${install.version} cannot reach a server on this machine.`, { version: install.version });
1913
1968
  }
@@ -2117,9 +2172,10 @@ async function run(argv, deps) {
2117
2172
  switch (command) {
2118
2173
  case "doctor": {
2119
2174
  const install = await readInstall(deps, home);
2120
- const ours = install !== undefined && install.port === flags.port && await isHealthy(deps, flags.port);
2175
+ const port = flags.port ?? install?.port ?? DEFAULT_PORT;
2176
+ const ours = install?.port === port && await runningHere(deps, home);
2121
2177
  const startOllama = confirmOllamaStart({ deps, flags }, false);
2122
- result = { ...await doctorInstall(deps, home, flags.port, ours, startOllama) };
2178
+ result = { ...await doctorInstall(deps, home, port, ours, startOllama) };
2123
2179
  break;
2124
2180
  }
2125
2181
  case "status":
@@ -2192,10 +2248,6 @@ async function doctorInstall(deps, home, port, ours, startOllama) {
2192
2248
  throw err.with({ checks: [...machine.checks, ...local] });
2193
2249
  }
2194
2250
  }
2195
- async function isHealthy(deps, port) {
2196
- const res = await deps.getJson(`http://127.0.0.1:${port}/v1/health`);
2197
- return res?.status === 200;
2198
- }
2199
2251
  function toFailure(err) {
2200
2252
  if (err instanceof CliError)
2201
2253
  return failure(err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nimblebrain",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",