nimblebrain 0.2.1 → 0.4.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.
@@ -5,10 +5,11 @@ import { writeSync } from "node:fs";
5
5
 
6
6
  // src/deps.ts
7
7
  import { spawn } from "node:child_process";
8
- import { chmod, mkdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
8
+ import { constants } from "node:fs";
9
+ import { access, chmod, mkdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
9
10
  import { createServer } from "node:net";
10
11
  import { homedir } from "node:os";
11
- import { dirname, join } from "node:path";
12
+ import { delimiter, dirname, join, resolve } from "node:path";
12
13
  function realDeps() {
13
14
  return {
14
15
  exec(cmd, args, opts = {}) {
@@ -35,6 +36,18 @@ function realDeps() {
35
36
  child.on("close", (code) => resolve({ code, stdout, stderr, missing }));
36
37
  });
37
38
  },
39
+ async which(cmd) {
40
+ const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE").split(";") : [""];
41
+ for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
42
+ for (const ext of exts) {
43
+ try {
44
+ await access(join(dir, cmd + ext), constants.X_OK);
45
+ return true;
46
+ } catch {}
47
+ }
48
+ }
49
+ return false;
50
+ },
38
51
  portFree(port) {
39
52
  return new Promise((resolve) => {
40
53
  const server = createServer();
@@ -78,7 +91,9 @@ function realDeps() {
78
91
  `);
79
92
  },
80
93
  env: process.env,
81
- home: homedir()
94
+ platform: process.platform,
95
+ home: homedir(),
96
+ cwd: process.cwd()
82
97
  };
83
98
  }
84
99
  async function request(url, init, timeoutMs) {
@@ -151,7 +166,20 @@ function typeHidden(value, chunk) {
151
166
  return { value: v };
152
167
  }
153
168
  function installHome(deps, flag) {
154
- return flag ?? deps.env.NIMBLEBRAIN_HOME ?? join(deps.home, ".nimblebrain-local");
169
+ return resolve(deps.cwd, flag ?? deps.env.NIMBLEBRAIN_HOME ?? join(deps.home, ".nimblebrain-local"));
170
+ }
171
+ var BARE_CLI = "npx nimblebrain";
172
+ function invocation(deps, home) {
173
+ const fallback = resolve(deps.cwd, join(deps.home, ".nimblebrain-local"));
174
+ if (home === fallback && installHome(deps) === fallback)
175
+ return BARE_CLI;
176
+ return `${BARE_CLI} --home ${shellQuote(home)}`;
177
+ }
178
+ function shellQuote(s) {
179
+ return /^[A-Za-z0-9_./,:@%+=-]+$/.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`;
180
+ }
181
+ function forInstall(text, cli) {
182
+ return text.replaceAll(BARE_CLI, () => cli);
155
183
  }
156
184
 
157
185
  // src/args.ts
@@ -168,7 +196,7 @@ var ERRORS = {
168
196
  LOW_MEMORY: "Give Docker at least 2 GB of memory in its settings, then run this again.",
169
197
  PORT_IN_USE: "Stop whatever holds the port, or pass --port with a free one.",
170
198
  NOT_INSTALLED: "Run `npx nimblebrain` to install it.",
171
- NOT_OURS: "Another install holds this name or its data. Remove it yourself, or choose another --home.",
199
+ NOT_OURS: "Another install holds this name or its data. Remove it yourself, or choose a --home whose folder has another name.",
172
200
  NETWORK: "Check the network connection, then run the same command again.",
173
201
  MODEL_KEY_MISSING: "Run `npx nimblebrain key` in your own terminal to enter a model key.",
174
202
  HEALTH_TIMEOUT: "Run `npx nimblebrain logs` and look at the last error line.",
@@ -183,58 +211,333 @@ var ERRORS = {
183
211
  LOCAL_MODEL_MISSING: "Download the model with `ollama pull <model>`, or check that Ollama has disk space, then run this again.",
184
212
  LOCAL_MODEL_NO_TOOLS: "Choose a model with tool calling, such as gemma4:e4b; https://docs.nimblebrain.ai/config/local-models/ lists the ones run with NimbleBrain.",
185
213
  LOCAL_CONTEXT_SMALL: "Run `npx nimblebrain local-model` to prepare the model again with a 32k context window.",
186
- INTERRUPTED: "Run `npx nimblebrain status` to see what is in place, then run the same command again."
214
+ INTERRUPTED: "Run `npx nimblebrain status` to see what is in place, then run the same command again.",
215
+ UPDATE_REQUIRED: "Run `npx nimblebrain update`; this install's NimbleBrain cannot reach servers on this machine yet.",
216
+ WORKSPACE_NOT_FOUND: "Run `npx nimblebrain status` for the workspace ids, then pass one with --workspace.",
217
+ SERVER_NOT_FOUND: "Run `npx nimblebrain mcp list` for the server names in this workspace.",
218
+ DIRECT_URL_NOT_ALLOWED: "Adding a server by URL needs a local install made by `npx nimblebrain`; run `npx nimblebrain update`, or add the server to the instance's connector catalog.",
219
+ URL_NOT_LOOPBACK: "Run the server on this machine and pass its localhost, 127.0.0.1 or [::1] URL, such as http://127.0.0.1:8000/mcp.",
220
+ URL_INVALID: "Pass the server's full MCP URL, such as http://127.0.0.1:8000/mcp.",
221
+ INVALID_SERVER_NAME: "Pass another name with --name: lowercase letters, digits and hyphens.",
222
+ NAME_TAKEN: "Pass another name with --name, or remove the existing one with `npx nimblebrain mcp remove <serverName>`.",
223
+ NAME_IS_CATALOG_ENTRY: "Pass another name with --name; this one belongs to a catalog connector.",
224
+ REQUEST_FAILED: "Run `npx nimblebrain logs` and look at the last error line, then run this again."
225
+ };
226
+ var FIX_VARIANTS = {
227
+ LOCAL_MODEL_UNREACHABLE: {
228
+ brew_install: "Install Ollama with `brew install ollama`, then run this again; it offers to start Ollama for you.",
229
+ app: "Open the Ollama app, then run this again.",
230
+ brew: "Run `brew services start ollama` (it then also starts at login), then run this again.",
231
+ systemd: "Run `sudo systemctl start ollama`, then run this again.",
232
+ serve: "Run `ollama serve` in another terminal, then run this again."
233
+ }
187
234
  };
188
235
 
189
236
  class CliError extends Error {
190
237
  code;
191
238
  fix;
192
239
  detail;
193
- constructor(code, message, detail = {}) {
240
+ variant;
241
+ constructor(code, message, detail = {}, variant) {
194
242
  super(message ?? code);
195
243
  this.code = code;
196
- this.fix = ERRORS[code];
244
+ const variants = FIX_VARIANTS[code];
245
+ this.fix = variant && variants?.[variant] || ERRORS[code];
246
+ this.variant = variant;
197
247
  this.detail = detail;
198
248
  }
249
+ with(detail, message = this.message) {
250
+ return new CliError(this.code, message, { ...this.detail, ...detail }, this.variant);
251
+ }
199
252
  }
200
253
  function failure(err) {
201
254
  return { ...err.detail, ok: false, error: err.code, message: err.message, fix: err.fix };
202
255
  }
203
256
  function exitCodeFor(result) {
204
- if (result.ok)
205
- return 0;
206
- return result.error === "USAGE" ? 2 : 1;
257
+ return result.ok ? 0 : exitCodeOf(result.error);
258
+ }
259
+ function exitCodeOf(code) {
260
+ return code === "USAGE" ? 2 : 1;
207
261
  }
208
262
 
209
- // src/args.ts
210
- var COMMANDS = [
211
- "init",
212
- "doctor",
213
- "status",
214
- "key",
215
- "up",
216
- "down",
217
- "logs",
218
- "update",
219
- "uninstall",
220
- "telemetry",
221
- "local-model"
263
+ // src/local-model.ts
264
+ var OLLAMA_URL = "http://127.0.0.1:11434";
265
+ var OLLAMA_FROM_CONTAINER = "http://host.docker.internal:11434/v1";
266
+ var DEFAULT_LOCAL_MODEL = "gemma4:e4b";
267
+ var LOCAL_CONTEXT = 32768;
268
+ var PULL_TIMEOUT_MS = 60 * 60 * 1000;
269
+ var OLLAMA_START_TIMEOUT_MS = 30000;
270
+ var CREATE_TIMEOUT_MS = 2 * 60 * 1000;
271
+ function takesLocalModel(composeText) {
272
+ return composeText.includes("NB_LOCAL_MODEL_URL");
273
+ }
274
+ function nimblebrainModelName(model) {
275
+ return `nimblebrain-${model.replace(/[^A-Za-z0-9._-]+/g, "-")}`;
276
+ }
277
+ function localModelOf(envText) {
278
+ const line = envText.split(`
279
+ `).find((l) => l.startsWith("NB_LOCAL_MODEL="));
280
+ const value = line?.slice("NB_LOCAL_MODEL=".length).trim();
281
+ return value ? value : undefined;
282
+ }
283
+ async function show(deps, model) {
284
+ const res = await deps.postJson(`${OLLAMA_URL}/api/show`, { model });
285
+ return res?.status === 200 ? res.body : undefined;
286
+ }
287
+ function numCtxOf(parameters) {
288
+ const match = parameters?.match(/^num_ctx\s+(\d+)/m);
289
+ return match ? Number(match[1]) : undefined;
290
+ }
291
+ async function ollamaVersion(deps) {
292
+ const res = await deps.getJson(`${OLLAMA_URL}/api/version`);
293
+ const version = res?.body?.version;
294
+ return res?.status === 200 && typeof version === "string" ? version : undefined;
295
+ }
296
+ var SYSTEMD_UNITS = [
297
+ "/etc/systemd/system/ollama.service",
298
+ "/usr/lib/systemd/system/ollama.service"
222
299
  ];
300
+ async function findOllama(deps) {
301
+ const apps = ["/Applications", `${deps.home}/Applications`].map((dir) => `${dir}/Ollama.app/Contents/Info.plist`);
302
+ if (deps.platform === "darwin" && await anyFile(deps, apps))
303
+ return { kind: "app", start: ["open", "-g", "-a", "Ollama"], fix: "app" };
304
+ if (deps.platform === "linux" && await anyFile(deps, SYSTEMD_UNITS))
305
+ return {
306
+ kind: "systemd",
307
+ start: ["systemctl", "start", "--no-ask-password", "ollama"],
308
+ fix: "systemd"
309
+ };
310
+ const brew = await deps.exec("brew", ["list", "--versions", "ollama"]);
311
+ if (brew.code === 0 && brew.stdout.trim())
312
+ return { kind: "brew", start: ["brew", "services", "start", "ollama"], fix: "brew" };
313
+ if (await deps.which("ollama"))
314
+ return { kind: "binary", fix: "serve" };
315
+ return { kind: "none", fix: brew.missing ? undefined : "brew_install" };
316
+ }
317
+ async function anyFile(deps, files) {
318
+ for (const file of files)
319
+ if (await deps.readText(file) !== undefined)
320
+ return true;
321
+ return false;
322
+ }
323
+ async function ensureOllama(deps, confirm) {
324
+ const running = await ollamaVersion(deps);
325
+ if (running)
326
+ return { version: running };
327
+ const install = await findOllama(deps);
328
+ const down = (message, extra = {}) => new CliError("LOCAL_MODEL_UNREACHABLE", message, { check: "ollama", ollama: install.kind, ...extra }, install.fix);
329
+ if (!install.start) {
330
+ throw down(install.kind === "none" ? `Ollama does not answer at ${OLLAMA_URL}, and it does not look installed.` : `Ollama does not answer at ${OLLAMA_URL}.`);
331
+ }
332
+ const command = install.start.join(" ");
333
+ if (!await confirm(command)) {
334
+ throw down(`Ollama is installed but not running at ${OLLAMA_URL}; it was not started.`);
335
+ }
336
+ deps.say(`Starting Ollama: ${command}`);
337
+ const [cmd = "", ...args] = install.start;
338
+ const res = await deps.exec(cmd, args, { timeoutMs: 60000 });
339
+ if (res.code !== 0 || res.missing) {
340
+ const why = res.stderr.trim().split(`
341
+ `)[0];
342
+ throw down(`\`${command}\` did not start Ollama${why ? `: ${why}` : "."}`);
343
+ }
344
+ for (let waited = 0;waited < OLLAMA_START_TIMEOUT_MS; waited += 1000) {
345
+ await deps.sleep(1000);
346
+ const version = await ollamaVersion(deps);
347
+ if (version) {
348
+ deps.say(`Ollama ${version} is running.`);
349
+ if (deps.platform === "linux")
350
+ deps.say("On Linux, NimbleBrain's container reaches Ollama only when it listens beyond 127.0.0.1 (OLLAMA_HOST=0.0.0.0).");
351
+ return { version, started: command };
352
+ }
353
+ }
354
+ throw down(`Ollama was started with \`${command}\` but did not answer at ${OLLAMA_URL} within 30 seconds.`, { ollama_started: command });
355
+ }
356
+ async function setupLocalModel(deps, model, asks) {
357
+ const { started } = await ensureOllama(deps, asks.start);
358
+ try {
359
+ return { values: await prepareModel(deps, model, asks.pull), started };
360
+ } catch (err) {
361
+ if (err instanceof CliError && started)
362
+ throw err.with({ ollama_started: started });
363
+ throw err;
364
+ }
365
+ }
366
+ async function prepareModel(deps, model, pull) {
367
+ let found = await show(deps, model);
368
+ if (!found) {
369
+ if (!await pull(model)) {
370
+ throw new CliError("LOCAL_MODEL_MISSING", `Ollama has no model "${model}".`, {
371
+ check: "model"
372
+ });
373
+ }
374
+ deps.say(`Downloading ${model} with Ollama. A model is several GB; this can take a while.`);
375
+ const pulled = await deps.postJson(`${OLLAMA_URL}/api/pull`, { model, stream: false }, PULL_TIMEOUT_MS);
376
+ found = pulled?.status === 200 ? await show(deps, model) : undefined;
377
+ if (!found) {
378
+ throw new CliError("LOCAL_MODEL_MISSING", `Ollama could not download "${model}".`, {
379
+ check: "model"
380
+ });
381
+ }
382
+ }
383
+ if (!found.capabilities?.includes("tools")) {
384
+ throw new CliError("LOCAL_MODEL_NO_TOOLS", `${model} does not support tool calling, which NimbleBrain's agents need.`, { check: "tools" });
385
+ }
386
+ const name = nimblebrainModelName(model);
387
+ const created = await deps.postJson(`${OLLAMA_URL}/api/create`, { model: name, from: model, parameters: { num_ctx: LOCAL_CONTEXT }, stream: false }, CREATE_TIMEOUT_MS);
388
+ if (created?.status !== 200) {
389
+ throw new CliError("LOCAL_MODEL_MISSING", `Ollama could not prepare ${name} from ${model}.`, {
390
+ check: "model"
391
+ });
392
+ }
393
+ return {
394
+ NB_LOCAL_MODEL_URL: OLLAMA_FROM_CONTAINER,
395
+ NB_LOCAL_MODEL: name,
396
+ NB_LOCAL_MODEL_CONTEXT: String(LOCAL_CONTEXT)
397
+ };
398
+ }
399
+ async function checkLocalModel(deps, model, start) {
400
+ const checks = [];
401
+ const { version, started } = await ensureOllama(deps, start).catch((err) => {
402
+ if (!(err instanceof CliError))
403
+ throw err;
404
+ checks.push({ check: "ollama", ok: false, detail: err.message });
405
+ throw err.with({ check: "ollama", checks });
406
+ });
407
+ checks.push({
408
+ check: "ollama",
409
+ ok: true,
410
+ detail: started ? `${version} (started: ${started})` : version
411
+ });
412
+ const found = await show(deps, model);
413
+ const fail = (check, code, detail) => {
414
+ checks.push({ check, ok: false, detail });
415
+ throw new CliError(code, detail, { check, checks, ollama_started: started });
416
+ };
417
+ if (!found)
418
+ fail("model", "LOCAL_MODEL_MISSING", `Ollama has no model "${model}".`);
419
+ checks.push({ check: "model", ok: true, detail: model });
420
+ if (!found?.capabilities?.includes("tools"))
421
+ fail("tools", "LOCAL_MODEL_NO_TOOLS", `${model} does not support tool calling.`);
422
+ checks.push({ check: "tools", ok: true, detail: "tool calling" });
423
+ const ctx = numCtxOf(found?.parameters);
424
+ if (ctx === undefined || ctx < LOCAL_CONTEXT)
425
+ fail("context", "LOCAL_CONTEXT_SMALL", `${model} has a context window of ${ctx ?? "Ollama's default"}, below ${LOCAL_CONTEXT}.`);
426
+ checks.push({ check: "context", ok: true, detail: `${ctx} tokens` });
427
+ return { checks, started };
428
+ }
429
+
430
+ // src/args.ts
431
+ var COMMAND_SPECS = {
432
+ init: {
433
+ args: [],
434
+ description: "Check this machine, start NimbleBrain, connect your coding agent (default)"
435
+ },
436
+ doctor: {
437
+ args: [],
438
+ description: "Check Docker, Compose, architecture, memory and the port; installs nothing"
439
+ },
440
+ status: { args: [], description: "Version, health, URL and each workspace's MCP URL" },
441
+ key: { args: [], description: "Enter the model key at a hidden prompt" },
442
+ "local-model": {
443
+ args: ["[model]"],
444
+ description: `Run NimbleBrain's agents on a model served by Ollama (default ${DEFAULT_LOCAL_MODEL})`
445
+ },
446
+ telemetry: {
447
+ args: ["[on|off|status]"],
448
+ description: "Whether this install sends anonymous usage data"
449
+ },
450
+ up: { args: [], description: "Start NimbleBrain" },
451
+ down: { args: [], description: "Stop NimbleBrain; data survives down" },
452
+ logs: { args: [], description: "Recent runtime log lines" },
453
+ update: {
454
+ args: [],
455
+ description: "Move to the newest release, keeping data, and refresh the connected agent's nimblebrain skill"
456
+ },
457
+ uninstall: { args: [], description: "Remove NimbleBrain and its data" },
458
+ mcp: {
459
+ args: ["<add|list|remove>"],
460
+ description: "MCP servers in development; see mcp add, list and remove"
461
+ }
462
+ };
463
+ var COMMANDS = Object.keys(COMMAND_SPECS);
464
+ var TELEMETRY_ARGS = ["on", "off", "status"];
223
465
  var AGENTS = ["claude-code", "cursor", "codex", "none"];
224
466
  var DEFAULT_PORT = 27246;
225
- var options = {
226
- json: { type: "boolean" },
227
- yes: { type: "boolean", short: "y" },
228
- agent: { type: "string" },
229
- port: { type: "string" },
230
- home: { type: "string" },
231
- provider: { type: "string" },
232
- "local-model": { type: "string" },
233
- runtime: { type: "string" },
234
- telemetry: { type: "string" },
235
- help: { type: "boolean", short: "h" },
236
- version: { type: "boolean", short: "v" }
467
+ var FLAG_SPECS = {
468
+ json: {
469
+ type: "boolean",
470
+ description: "One JSON object on stdout; progress and notices go to stderr"
471
+ },
472
+ yes: {
473
+ type: "boolean",
474
+ short: "y",
475
+ description: "Take every default; implied when no terminal is attached"
476
+ },
477
+ agent: {
478
+ type: "string",
479
+ takes: "name",
480
+ description: `The coding agent to connect: ${AGENTS.slice(0, -1).join(", ")} or ${AGENTS.at(-1)}`,
481
+ commands: ["init"]
482
+ },
483
+ port: {
484
+ type: "string",
485
+ takes: "n",
486
+ description: `Local port (default ${DEFAULT_PORT})`,
487
+ commands: ["init", "doctor"]
488
+ },
489
+ home: {
490
+ type: "string",
491
+ takes: "dir",
492
+ description: "Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME); a home with another folder name is a separate install"
493
+ },
494
+ provider: {
495
+ type: "string",
496
+ takes: "name",
497
+ description: "The model provider for key (default anthropic)",
498
+ commands: ["key"]
499
+ },
500
+ "local-model": {
501
+ type: "string",
502
+ takes: "model",
503
+ description: "Run on this Ollama model instead of a hosted key",
504
+ commands: ["init"]
505
+ },
506
+ runtime: {
507
+ type: "string",
508
+ takes: "tag",
509
+ description: "The NimbleBrain release to install or update to (default the newest)",
510
+ commands: ["init", "update"]
511
+ },
512
+ telemetry: {
513
+ type: "string",
514
+ takes: "on|off",
515
+ description: "The person's answer to sending anonymous usage data; without it, init asks or leaves it undecided",
516
+ commands: ["init"]
517
+ },
518
+ name: {
519
+ type: "string",
520
+ takes: "name",
521
+ description: "The server name (default from the server's card, else its URL)",
522
+ commands: ["mcp add"]
523
+ },
524
+ workspace: {
525
+ type: "string",
526
+ takes: "id",
527
+ description: "The workspace (default the one init connected, the first in status)",
528
+ commands: ["mcp add", "mcp list", "mcp remove"]
529
+ },
530
+ help: {
531
+ type: "boolean",
532
+ short: "h",
533
+ description: "The commands and flags; with --json, these and every error code as JSON"
534
+ },
535
+ version: { type: "boolean", short: "v", description: "This CLI's version" }
237
536
  };
537
+ var options = Object.fromEntries(Object.entries(FLAG_SPECS).map(([name, f]) => [
538
+ name,
539
+ f.short ? { type: f.type, short: f.short } : { type: f.type }
540
+ ]));
238
541
  function parse(argv) {
239
542
  const { values, positionals } = parseStrict(argv);
240
543
  const json = values.json === true;
@@ -259,7 +562,9 @@ function parse(argv) {
259
562
  provider: values.provider,
260
563
  localModel: values["local-model"],
261
564
  runtime: values.runtime,
262
- telemetry
565
+ telemetry,
566
+ name: values.name,
567
+ workspace: values.workspace
263
568
  };
264
569
  if (values.help)
265
570
  return { kind: "help", flags };
@@ -268,24 +573,49 @@ function parse(argv) {
268
573
  const name = positionals[0] ?? "init";
269
574
  if (name === "help")
270
575
  return { kind: "help", flags };
271
- return { kind: "run", command: command(name, positionals), flags, arg: positionals[1] };
576
+ return {
577
+ kind: "run",
578
+ command: command(name, positionals),
579
+ flags,
580
+ arg: positionals[1],
581
+ operand: positionals[2]
582
+ };
272
583
  }
273
584
  function telemetryFlag(value) {
274
585
  if (value === undefined || value === "on" || value === "off")
275
586
  return value;
276
587
  throw new CliError("USAGE", `--telemetry must be on or off, not "${value}".`);
277
588
  }
589
+ var MCP_SUBCOMMANDS = {
590
+ add: { operand: "url", description: "Add an MCP server you run on this machine to a workspace" },
591
+ list: { operand: null, description: "The servers in a workspace" },
592
+ remove: { operand: "serverName", description: "Remove a server from a workspace" }
593
+ };
278
594
  function command(name, positionals) {
595
+ if (!COMMANDS.includes(name))
596
+ throw new CliError("USAGE", `Unknown command "${name}".`);
597
+ if (name === "mcp")
598
+ return mcpCommand(positionals);
279
599
  const maxArgs = name === "telemetry" || name === "local-model" ? 2 : 1;
280
600
  if (positionals.length > maxArgs)
281
601
  throw new CliError("USAGE", `Unexpected argument "${positionals[maxArgs]}".`);
282
- if (!COMMANDS.includes(name))
283
- throw new CliError("USAGE", `Unknown command "${name}".`);
284
602
  const arg = positionals[1];
285
- if (name === "telemetry" && arg !== undefined && !["on", "off", "status"].includes(arg))
603
+ if (name === "telemetry" && arg !== undefined && !TELEMETRY_ARGS.includes(arg))
286
604
  throw new CliError("USAGE", `telemetry takes on, off or status, not "${arg}".`);
287
605
  return name;
288
606
  }
607
+ function mcpCommand(positionals) {
608
+ const sub = positionals[1];
609
+ if (sub === undefined || !Object.hasOwn(MCP_SUBCOMMANDS, sub))
610
+ throw new CliError("USAGE", `mcp takes add <url>, list or remove <serverName>${sub === undefined ? "" : `, not "${sub}"`}.`);
611
+ const { operand } = MCP_SUBCOMMANDS[sub];
612
+ const maxArgs = operand === null ? 2 : 3;
613
+ if (positionals.length > maxArgs)
614
+ throw new CliError("USAGE", `Unexpected argument "${positionals[maxArgs]}".`);
615
+ if (operand !== null && positionals[2] === undefined)
616
+ throw new CliError("USAGE", `mcp ${sub} needs a ${operand}.`);
617
+ return "mcp";
618
+ }
289
619
  function parseStrict(argv) {
290
620
  try {
291
621
  return parseArgs({ args: argv, options, allowPositionals: true, strict: true });
@@ -298,9 +628,15 @@ function wantsJson(argv) {
298
628
  }
299
629
 
300
630
  // src/compose.ts
301
- import { join as join2 } from "node:path";
302
- var PROJECT = "nimblebrain-local";
303
- var VOLUME = `${PROJECT}_workspace`;
631
+ import { basename, join as join2 } from "node:path";
632
+ var DEFAULT_PROJECT = "nimblebrain-local";
633
+ function projectFor(home) {
634
+ const slug = basename(home).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9]+$/, "");
635
+ if (!slug)
636
+ return "nimblebrain";
637
+ return slug.startsWith("nimblebrain") ? slug : `nimblebrain-${slug}`;
638
+ }
639
+ var volumeOf = (project) => `${project}_workspace`;
304
640
  var RAW = "https://raw.githubusercontent.com/NimbleBrainInc/nimblebrain";
305
641
  async function fetchCompose(deps, tag) {
306
642
  const res = await deps.getText(`${RAW}/${tag}/docker-compose.yml`, 15000);
@@ -325,6 +661,9 @@ function keyVars(composeText) {
325
661
  function asksConsent(composeText) {
326
662
  return composeText.includes("NB_TELEMETRY_CONSENT");
327
663
  }
664
+ function hostLoopback(composeText) {
665
+ return composeText.includes("NB_HOST_LOOPBACK");
666
+ }
328
667
  function providers(composeText) {
329
668
  return Object.fromEntries(keyVars(composeText).map((v) => [
330
669
  v.replace(/_API_KEY$/, "").replace(/_GENERATIVE_AI$/, "").toLowerCase(),
@@ -491,6 +830,75 @@ function gib(bytes) {
491
830
  return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
492
831
  }
493
832
 
833
+ // src/help.ts
834
+ var HELP_COMMAND = {
835
+ name: "help",
836
+ args: [],
837
+ description: "These commands and flags; with --json, these and every error code as JSON"
838
+ };
839
+ function commands() {
840
+ const list = Object.keys(COMMAND_SPECS).flatMap((name) => {
841
+ if (name === "mcp") {
842
+ return Object.entries(MCP_SUBCOMMANDS).map(([sub, spec]) => ({
843
+ name: `mcp ${sub}`,
844
+ args: spec.operand ? [`<${spec.operand}>`] : [],
845
+ description: spec.description
846
+ }));
847
+ }
848
+ const spec = COMMAND_SPECS[name];
849
+ return [{ name, args: [...spec.args], description: spec.description }];
850
+ });
851
+ return [...list, HELP_COMMAND];
852
+ }
853
+ function flags() {
854
+ return Object.entries(FLAG_SPECS).map(([name, spec]) => {
855
+ const f = {
856
+ name: `--${name}`,
857
+ takes: "takes" in spec ? spec.takes : null,
858
+ description: spec.description
859
+ };
860
+ if ("short" in spec)
861
+ f.short = `-${spec.short}`;
862
+ if ("commands" in spec)
863
+ f.commands = [...spec.commands];
864
+ return f;
865
+ });
866
+ }
867
+ function errors() {
868
+ return Object.keys(ERRORS).map((code) => ({
869
+ code,
870
+ fix: ERRORS[code],
871
+ exit: exitCodeOf(code)
872
+ }));
873
+ }
874
+ function describe(version) {
875
+ return { ok: true, cli_version: version, commands: commands(), flags: flags(), errors: errors() };
876
+ }
877
+ function helpText(version) {
878
+ const cmds = commands().map((c) => [[c.name, ...c.args].join(" "), c.description]);
879
+ const fls = flags().map((f) => [
880
+ [f.takes ? `${f.name} <${f.takes}>` : f.name, f.short].filter(Boolean).join(", "),
881
+ f.commands ? `${f.description}; for ${f.commands.join(", ")}` : f.description
882
+ ]);
883
+ const width = Math.max(...[...cmds, ...fls].map(([left]) => left.length)) + 2;
884
+ const row = ([left, right]) => ` ${left.padEnd(width)}${right}`;
885
+ return [
886
+ `nimblebrain ${version}: install and run NimbleBrain on this machine`,
887
+ "",
888
+ "Usage: npx nimblebrain [command] [flags]",
889
+ "",
890
+ "Commands:",
891
+ ...cmds.map(row),
892
+ "",
893
+ "Flags:",
894
+ ...fls.map(row),
895
+ "",
896
+ "Every error code and its fix: npx nimblebrain help --json",
897
+ ""
898
+ ].join(`
899
+ `);
900
+ }
901
+
494
902
  // src/agents.ts
495
903
  import { join as join3 } from "node:path";
496
904
  var SERVER_NAME = "nimblebrain";
@@ -555,6 +963,20 @@ async function installSkill(deps, agent) {
555
963
  "-y"
556
964
  ], { timeoutMs: 120000 });
557
965
  }
966
+ async function refreshSkill(deps, agent) {
967
+ if (!await skillInstalled(deps, agent))
968
+ return "not_installed";
969
+ try {
970
+ const res = await deps.exec("npx", ["-y", "skills", "update", SKILL_NAME, "-g", "-y"], {
971
+ timeoutMs: 120000
972
+ });
973
+ if (res.code !== 0)
974
+ return "failed";
975
+ return /Updated \d+ skill/.test(res.stdout) ? "updated" : "unchanged";
976
+ } catch {
977
+ return "failed";
978
+ }
979
+ }
558
980
  var SKILL_NAME = "nimblebrain";
559
981
  function globalSkillsDir(deps, agent) {
560
982
  if (agent === "claude-code")
@@ -572,102 +994,6 @@ async function skillInstalled(deps, agent) {
572
994
  return await deps.readText(join3(dir, SKILL_NAME, "SKILL.md")) === undefined ? null : SKILL_NAME;
573
995
  }
574
996
 
575
- // src/local-model.ts
576
- var OLLAMA_URL = "http://127.0.0.1:11434";
577
- var OLLAMA_FROM_CONTAINER = "http://host.docker.internal:11434/v1";
578
- var DEFAULT_LOCAL_MODEL = "gemma4:e4b";
579
- var LOCAL_CONTEXT = 32768;
580
- var PULL_TIMEOUT_MS = 60 * 60 * 1000;
581
- var CREATE_TIMEOUT_MS = 2 * 60 * 1000;
582
- function takesLocalModel(composeText) {
583
- return composeText.includes("NB_LOCAL_MODEL_URL");
584
- }
585
- function nimblebrainModelName(model) {
586
- return `nimblebrain-${model.replace(/[^A-Za-z0-9._-]+/g, "-")}`;
587
- }
588
- function localModelOf(envText) {
589
- const line = envText.split(`
590
- `).find((l) => l.startsWith("NB_LOCAL_MODEL="));
591
- const value = line?.slice("NB_LOCAL_MODEL=".length).trim();
592
- return value ? value : undefined;
593
- }
594
- async function show(deps, model) {
595
- const res = await deps.postJson(`${OLLAMA_URL}/api/show`, { model });
596
- return res?.status === 200 ? res.body : undefined;
597
- }
598
- function numCtxOf(parameters) {
599
- const match = parameters?.match(/^num_ctx\s+(\d+)/m);
600
- return match ? Number(match[1]) : undefined;
601
- }
602
- async function requireOllama(deps) {
603
- const res = await deps.getJson(`${OLLAMA_URL}/api/version`);
604
- const version = res?.body?.version;
605
- if (res?.status !== 200 || typeof version !== "string") {
606
- throw new CliError("LOCAL_MODEL_UNREACHABLE", `Ollama does not answer at ${OLLAMA_URL}.`, {
607
- check: "ollama"
608
- });
609
- }
610
- return version;
611
- }
612
- async function setupLocalModel(deps, model, pull) {
613
- await requireOllama(deps);
614
- let found = await show(deps, model);
615
- if (!found) {
616
- if (!await pull(model)) {
617
- throw new CliError("LOCAL_MODEL_MISSING", `Ollama has no model "${model}".`, {
618
- check: "model"
619
- });
620
- }
621
- deps.say(`Downloading ${model} with Ollama. A model is several GB; this can take a while.`);
622
- const pulled = await deps.postJson(`${OLLAMA_URL}/api/pull`, { model, stream: false }, PULL_TIMEOUT_MS);
623
- found = pulled?.status === 200 ? await show(deps, model) : undefined;
624
- if (!found) {
625
- throw new CliError("LOCAL_MODEL_MISSING", `Ollama could not download "${model}".`, {
626
- check: "model"
627
- });
628
- }
629
- }
630
- if (!found.capabilities?.includes("tools")) {
631
- throw new CliError("LOCAL_MODEL_NO_TOOLS", `${model} does not support tool calling, which NimbleBrain's agents need.`, { check: "tools" });
632
- }
633
- const name = nimblebrainModelName(model);
634
- const created = await deps.postJson(`${OLLAMA_URL}/api/create`, { model: name, from: model, parameters: { num_ctx: LOCAL_CONTEXT }, stream: false }, CREATE_TIMEOUT_MS);
635
- if (created?.status !== 200) {
636
- throw new CliError("LOCAL_MODEL_MISSING", `Ollama could not prepare ${name} from ${model}.`, {
637
- check: "model"
638
- });
639
- }
640
- return {
641
- NB_LOCAL_MODEL_URL: OLLAMA_FROM_CONTAINER,
642
- NB_LOCAL_MODEL: name,
643
- NB_LOCAL_MODEL_CONTEXT: String(LOCAL_CONTEXT)
644
- };
645
- }
646
- async function checkLocalModel(deps, model) {
647
- const checks = [];
648
- const version = await requireOllama(deps).catch((err) => {
649
- checks.push({ check: "ollama", ok: false, detail: err.message });
650
- throw new CliError(err.code, err.message, { check: "ollama", checks });
651
- });
652
- checks.push({ check: "ollama", ok: true, detail: version });
653
- const found = await show(deps, model);
654
- const fail = (check, code, detail) => {
655
- checks.push({ check, ok: false, detail });
656
- throw new CliError(code, detail, { check, checks });
657
- };
658
- if (!found)
659
- fail("model", "LOCAL_MODEL_MISSING", `Ollama has no model "${model}".`);
660
- checks.push({ check: "model", ok: true, detail: model });
661
- if (!found?.capabilities?.includes("tools"))
662
- fail("tools", "LOCAL_MODEL_NO_TOOLS", `${model} does not support tool calling.`);
663
- checks.push({ check: "tools", ok: true, detail: "tool calling" });
664
- const ctx = numCtxOf(found?.parameters);
665
- if (ctx === undefined || ctx < LOCAL_CONTEXT)
666
- fail("context", "LOCAL_CONTEXT_SMALL", `${model} has a context window of ${ctx ?? "Ollama's default"}, below ${LOCAL_CONTEXT}.`);
667
- checks.push({ check: "context", ok: true, detail: `${ctx} tokens` });
668
- return checks;
669
- }
670
-
671
997
  // src/release.ts
672
998
  var REFS_URL = "https://github.com/NimbleBrainInc/nimblebrain.git/info/refs?service=git-upload-pack";
673
999
  var VERSION = /^v\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
@@ -688,8 +1014,8 @@ async function runtimeTag(deps, requested) {
688
1014
  }
689
1015
  return tag;
690
1016
  }
691
- async function newestRuntime(deps) {
692
- const res = await deps.getText(REFS_URL, 1e4);
1017
+ async function newestRuntime(deps, timeoutMs = 1e4) {
1018
+ const res = await deps.getText(REFS_URL, timeoutMs);
693
1019
  if (res && res.status !== 200) {
694
1020
  throw new CliError("NETWORK", `GitHub answered ${res.status} when asked for the newest NimbleBrain release. Pass --runtime vX.Y.Z to skip the lookup.`);
695
1021
  }
@@ -747,19 +1073,22 @@ var RELEASED = true;
747
1073
  function telemetryKey(deps) {
748
1074
  return deps.env.NIMBLEBRAIN_TELEMETRY_KEY ?? (RELEASED ? TELEMETRY_KEY : "");
749
1075
  }
1076
+ function doNotTrack(deps) {
1077
+ return deps.env.DO_NOT_TRACK === "1";
1078
+ }
750
1079
  function lockedHere(deps) {
751
- if (deps.env.DO_NOT_TRACK === "1" || deps.env.NB_TELEMETRY_DISABLED === "1")
1080
+ if (doNotTrack(deps) || deps.env.NB_TELEMETRY_DISABLED === "1")
752
1081
  return "do_not_track";
753
1082
  if (!telemetryKey(deps))
754
1083
  return "no_destination";
755
1084
  return;
756
1085
  }
757
- function field(state, locked) {
1086
+ function field(state, cli, locked) {
758
1087
  if (locked)
759
1088
  return { state: state === "undecided" ? "off" : state, locked };
760
1089
  if (state !== "undecided")
761
1090
  return { state };
762
- return { state, ask: QUESTION, set: "npx nimblebrain telemetry on|off" };
1091
+ return { state, ask: QUESTION, set: `${cli} telemetry on|off` };
763
1092
  }
764
1093
  function recorder2(deps, version, id) {
765
1094
  const events = [];
@@ -829,7 +1158,7 @@ var toLines = (events) => `${events.map((e) => JSON.stringify(e)).join(`
829
1158
  `)}
830
1159
  `;
831
1160
  function parseAnswer(answer) {
832
- return /^y/i.test(answer.trim()) ? "on" : "off";
1161
+ return /^n/i.test(answer.trim()) ? "off" : "on";
833
1162
  }
834
1163
  function seededConsent(envText) {
835
1164
  const seed = envText.match(/^NB_TELEMETRY_CONSENT=(on|off)\s*$/m)?.[1];
@@ -840,7 +1169,7 @@ async function currentTelemetry(deps, home, url) {
840
1169
  const rt = await runtimeTelemetry(deps, url);
841
1170
  const state = rt?.consent ?? seededConsent(await deps.readText(join4(home, ".env")) ?? "");
842
1171
  const lock = here ?? (rt?.locked === "operator" || rt?.locked === "no_destination" ? rt.locked : undefined);
843
- return field(state, lock);
1172
+ return field(state, invocation(deps, home), lock);
844
1173
  }
845
1174
  async function settleWaiting(deps, home, version) {
846
1175
  try {
@@ -888,7 +1217,7 @@ async function setRuntimeTelemetry(deps, url, consent) {
888
1217
  // package.json
889
1218
  var package_default = {
890
1219
  name: "nimblebrain",
891
- version: "0.2.1",
1220
+ version: "0.4.0",
892
1221
  description: "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
893
1222
  license: "Apache-2.0",
894
1223
  type: "module",
@@ -935,10 +1264,10 @@ async function status(deps, home) {
935
1264
  if (!install)
936
1265
  throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
937
1266
  const url = `http://127.0.0.1:${install.port}`;
938
- const health = await deps.getJson(`${url}/v1/health`);
939
- const up = health?.status === 200 && health.body?.status === "ok";
1267
+ const up = await isUp(deps, url);
940
1268
  const workspaces = up ? await readWorkspaces(deps, url) : [];
941
- const vars = keyVars(await deps.readText(join5(home, "docker-compose.yml")) ?? "");
1269
+ const composeText = await deps.readText(join5(home, "docker-compose.yml")) ?? "";
1270
+ const vars = keyVars(composeText);
942
1271
  const envText = await deps.readText(join5(home, ".env")) ?? "";
943
1272
  const modelKey = hasKey(envText, vars) ? "set" : "missing";
944
1273
  return {
@@ -953,10 +1282,15 @@ async function status(deps, home) {
953
1282
  skill: install.agent ? await skillInstalled(deps, install.agent) : null
954
1283
  },
955
1284
  model_key: modelKey,
1285
+ host_loopback: hostLoopback(composeText),
956
1286
  local_model: localModelOf(envText) ?? null,
957
1287
  telemetry: await currentTelemetry(deps, home, url)
958
1288
  };
959
1289
  }
1290
+ async function isUp(deps, url) {
1291
+ const health = await deps.getJson(`${url}/v1/health`);
1292
+ return health?.status === 200 && health.body?.status === "ok";
1293
+ }
960
1294
  async function readWorkspaces(deps, url) {
961
1295
  const boot = await deps.getJson(`${url}/v1/bootstrap`);
962
1296
  if (boot?.status !== 200)
@@ -969,25 +1303,31 @@ async function readWorkspaces(deps, url) {
969
1303
  var START_TIMEOUT_MS = 15 * 60000;
970
1304
  var HEALTH_TIMEOUT_MS = 3 * 60000;
971
1305
  var asks = ({ deps, flags }) => deps.interactive && !flags.yes && !flags.json;
1306
+ var yes = (answer) => /^(y|yes)?$/i.test(answer.trim());
1307
+ function confirmOllamaStart(ctx, unasked) {
1308
+ return async (command) => {
1309
+ if (!asks(ctx))
1310
+ return unasked;
1311
+ const login = command.startsWith("brew services") ? " It then also starts at login." : "";
1312
+ return yes(await ctx.deps.prompt(`Ollama isn't running. Start it with \`${command}\`?${login} [Y/n] `));
1313
+ };
1314
+ }
972
1315
  async function init(ctx) {
973
1316
  const { deps, flags, home } = ctx;
974
1317
  if (await readInstall(deps, home))
975
1318
  return { ...await status(deps, home), already: true };
976
- const answer = { consent: await chooseConsent(ctx, false) };
1319
+ const consent = await chooseConsent(ctx);
977
1320
  const rec = recorder2(deps, ctx.version, await reportId(deps, home));
978
1321
  const begun = Date.now();
979
1322
  rec.record("cli.init_started", { agent: flags.agent ?? null, interactive: deps.interactive });
980
1323
  try {
981
- return await install(ctx, answer, rec, begun);
1324
+ return await install(ctx, consent, rec, begun);
982
1325
  } catch (err) {
983
1326
  if (!(err instanceof CliError))
984
1327
  throw err;
985
- if (err.code !== "CANCELLED" || answer.consent !== "undecided")
986
- await settleFailure(rec, home, answer.consent, err);
987
- throw new CliError(err.code, err.message, {
988
- ...err.detail,
989
- telemetry: field(answer.consent, lockedHere(deps))
990
- });
1328
+ if (err.code !== "CANCELLED" || consent !== "undecided")
1329
+ await settleFailure(rec, home, consent, err);
1330
+ throw err.with({ telemetry: field(consent, invocation(deps, home), lockedHere(deps)) });
991
1331
  }
992
1332
  }
993
1333
  async function settleFailure(rec, home, consent, err) {
@@ -997,58 +1337,66 @@ async function settleFailure(rec, home, consent, err) {
997
1337
  }
998
1338
  await rec.settle(home, consent);
999
1339
  }
1000
- async function chooseConsent(ctx, ask) {
1340
+ async function chooseConsent(ctx) {
1001
1341
  if (lockedHere(ctx.deps))
1002
1342
  return "off";
1003
1343
  if (ctx.flags.telemetry)
1004
1344
  return ctx.flags.telemetry;
1005
- if (!ask || !asks(ctx))
1345
+ if (!asks(ctx))
1006
1346
  return "undecided";
1007
- return parseAnswer(await ctx.deps.prompt(`${QUESTION} [y/N] `));
1347
+ const consent = parseAnswer(await ctx.deps.prompt(`${QUESTION} [Y/n] `));
1348
+ const cli = invocation(ctx.deps, ctx.home);
1349
+ 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`);
1350
+ return consent;
1008
1351
  }
1009
- async function install(ctx, answer, rec, begun) {
1352
+ async function install(ctx, consent, rec, begun) {
1010
1353
  const { deps, flags, home } = ctx;
1011
1354
  await doctor(deps, flags.port);
1012
- await guardOurs(deps, home);
1355
+ const project = await guardOurs(deps, home);
1013
1356
  const tag = await runtimeTag(deps, flags.runtime);
1014
1357
  const composeText = await fetchCompose(deps, tag);
1015
1358
  await confirmStart(ctx, tag);
1016
- answer.consent = await chooseConsent(ctx, true);
1017
- const { consent } = answer;
1018
- await writeInstallFiles(deps, home, tag, flags.port, composeText, envValues(deps, rec.id, consent, asksConsent(composeText)));
1359
+ await writeInstallFiles(deps, home, project, tag, flags.port, composeText, envValues(deps, rec.id, consent, asksConsent(composeText)));
1019
1360
  const envText = await deps.readText(paths(home).env) ?? "";
1020
1361
  const hasModel = hasKey(envText, keyVars(composeText)) || localModelOf(envText) !== undefined;
1021
1362
  const local = flags.localModel ?? (!hasModel && asks(ctx) && takesLocalModel(composeText) ? await chooseModelSource(deps) : undefined);
1363
+ let ollamaStarted;
1022
1364
  if (local)
1023
- await useLocalModel(ctx, composeText, local);
1365
+ ollamaStarted = (await useLocalModel(ctx, composeText, local)).started;
1024
1366
  else if (!hasModel && asks(ctx))
1025
1367
  await enterKey(ctx, false);
1026
- deps.say(`Starting NimbleBrain ${tag}. The first start downloads about 2 GB of images.`);
1027
- await start(deps, home, flags.port);
1028
- const state = {
1029
- version: tag.replace(/^v/, ""),
1030
- port: flags.port,
1031
- project: PROJECT
1032
- };
1033
- await writeState(deps, home, state);
1034
- const manual = await connectChosenAgent(ctx, state);
1035
- if (state.agent)
1036
- rec.record("cli.agent_connected", { agent: state.agent });
1037
- const result = { ...await status(deps, home), manual };
1038
- const finalEnv = await deps.readText(paths(home).env) ?? "";
1039
- rec.record("cli.init_completed", {
1040
- duration_ms: Date.now() - begun,
1041
- model_key: result.model_key,
1042
- provider: localModelOf(finalEnv) ? "ollama" : keyProvider(finalEnv, composeText),
1043
- agent: state.agent ?? null
1044
- });
1045
- await rec.settle(home, consent);
1046
- if (result.model_key === "missing" && !result.local_model) {
1047
- throw new CliError("MODEL_KEY_MISSING", "NimbleBrain is running; chat needs a model key.", {
1048
- ...result
1368
+ return carryingStarted(ollamaStarted, async () => {
1369
+ deps.say(`Starting NimbleBrain ${tag}. The first start downloads about 2 GB of images.`);
1370
+ await start(deps, home, flags.port);
1371
+ const state = {
1372
+ version: tag.replace(/^v/, ""),
1373
+ port: flags.port,
1374
+ project
1375
+ };
1376
+ await writeState(deps, home, state);
1377
+ const manual = await connectChosenAgent(ctx, state);
1378
+ if (state.agent)
1379
+ rec.record("cli.agent_connected", { agent: state.agent });
1380
+ const result = {
1381
+ ...await status(deps, home),
1382
+ manual,
1383
+ ollama_started: ollamaStarted
1384
+ };
1385
+ const finalEnv = await deps.readText(paths(home).env) ?? "";
1386
+ rec.record("cli.init_completed", {
1387
+ duration_ms: Date.now() - begun,
1388
+ model_key: result.model_key,
1389
+ provider: localModelOf(finalEnv) ? "ollama" : keyProvider(finalEnv, composeText),
1390
+ agent: state.agent ?? null
1049
1391
  });
1050
- }
1051
- return { ...result };
1392
+ await rec.settle(home, consent);
1393
+ if (result.model_key === "missing" && !result.local_model) {
1394
+ throw new CliError("MODEL_KEY_MISSING", "NimbleBrain is running; chat needs a model key.", {
1395
+ ...result
1396
+ });
1397
+ }
1398
+ return { ...result };
1399
+ });
1052
1400
  }
1053
1401
  async function confirmStart(ctx, tag) {
1054
1402
  if (!asks(ctx))
@@ -1074,10 +1422,25 @@ async function connectChosenAgent(ctx, state) {
1074
1422
  return conn.manual;
1075
1423
  }
1076
1424
  async function up(ctx) {
1425
+ const { deps, home } = ctx;
1077
1426
  const install = await requireInstall(ctx);
1078
- await start(ctx.deps, ctx.home, install.port);
1079
- return { ...await status(ctx.deps, ctx.home) };
1427
+ const local = localModelOf(await deps.readText(paths(home).env) ?? "");
1428
+ const ollama = local ? await ensureOllama(deps, confirmOllamaStart(ctx, true)).catch((err) => {
1429
+ if (err instanceof CliError)
1430
+ return err;
1431
+ throw err;
1432
+ }) : undefined;
1433
+ const started = ollama instanceof CliError ? ollama.detail.ollama_started : ollama?.started;
1434
+ const result = await carryingStarted(started, async () => {
1435
+ await start(deps, home, install.port);
1436
+ return status(deps, home);
1437
+ });
1438
+ if (ollama instanceof CliError) {
1439
+ throw ollama.with({ ...result }, `NimbleBrain is running, but ${lowerFirst(ollama.message)}`);
1440
+ }
1441
+ return { ...result, ollama_started: ollama?.started };
1080
1442
  }
1443
+ var lowerFirst = (s) => s.charAt(0).toLowerCase() + s.slice(1);
1081
1444
  async function down(ctx) {
1082
1445
  await requireInstall(ctx);
1083
1446
  const res = await compose(ctx.deps, ctx.home, ["down"]);
@@ -1105,20 +1468,28 @@ async function update(ctx) {
1105
1468
  const tag = await runtimeTag(deps, ctx.flags.runtime);
1106
1469
  const from = `v${install.version}`;
1107
1470
  const order = compareVersions(tag, from);
1108
- if (order === 0)
1109
- return { ...await status(deps, home), already: true };
1471
+ if (order === 0) {
1472
+ const skill_update = await refreshAgentSkill(deps, install);
1473
+ return { ...await status(deps, home), already: true, ...skill_update };
1474
+ }
1110
1475
  if (order < 0) {
1111
1476
  throw new CliError("USAGE", `${tag} is older than the installed ${from}; NimbleBrain does not move backwards.`);
1112
1477
  }
1113
1478
  const composeText = await fetchCompose(deps, tag);
1114
- await writeInstallFiles(deps, home, tag, install.port, composeText);
1479
+ await writeInstallFiles(deps, home, install.project, tag, install.port, composeText);
1115
1480
  deps.say(`Updating NimbleBrain ${from} → ${tag}.`);
1116
1481
  const pull = await compose(deps, home, ["pull"], START_TIMEOUT_MS);
1117
1482
  if (pull.code !== 0)
1118
1483
  throw startError(pull);
1119
1484
  await start(deps, home, install.port);
1120
1485
  await writeState(deps, home, { ...install, version: tag.replace(/^v/, "") });
1121
- return { ...await status(deps, home), from };
1486
+ const skill_update = await refreshAgentSkill(deps, install);
1487
+ return { ...await status(deps, home), from, ...skill_update };
1488
+ }
1489
+ async function refreshAgentSkill(deps, install) {
1490
+ if (!install.agent || install.agent === "none")
1491
+ return {};
1492
+ return { skill_update: await refreshSkill(deps, install.agent) };
1122
1493
  }
1123
1494
  async function uninstall(ctx) {
1124
1495
  const { deps, flags, home } = ctx;
@@ -1162,7 +1533,7 @@ async function telemetry(ctx) {
1162
1533
  await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", { NB_TELEMETRY_CONSENT: ctx.arg }), 384);
1163
1534
  const rec = recorder2(deps, ctx.version, await reportId(deps, home));
1164
1535
  await rec.settle(home, ctx.arg);
1165
- return { ok: true, telemetry: field(ctx.arg) };
1536
+ return { ok: true, telemetry: field(ctx.arg, invocation(deps, home)) };
1166
1537
  }
1167
1538
  async function key(ctx) {
1168
1539
  if (!ctx.deps.interactive) {
@@ -1199,9 +1570,18 @@ async function localModel(ctx) {
1199
1570
  const install = await requireInstall(ctx);
1200
1571
  const composeText = await ctx.deps.readText(paths(ctx.home).compose) ?? "";
1201
1572
  const model = ctx.arg ?? ctx.flags.localModel ?? DEFAULT_LOCAL_MODEL;
1202
- const name = await useLocalModel(ctx, composeText, model);
1203
- await start(ctx.deps, ctx.home, install.port);
1204
- return { ok: true, local_model: name };
1573
+ const { name, started } = await useLocalModel(ctx, composeText, model);
1574
+ await carryingStarted(started, () => start(ctx.deps, ctx.home, install.port));
1575
+ return { ok: true, local_model: name, ollama_started: started };
1576
+ }
1577
+ async function carryingStarted(started, next) {
1578
+ try {
1579
+ return await next();
1580
+ } catch (err) {
1581
+ if (err instanceof CliError && started)
1582
+ throw err.with({ ollama_started: started });
1583
+ throw err;
1584
+ }
1205
1585
  }
1206
1586
  async function chooseModelSource(deps) {
1207
1587
  deps.say("NimbleBrain's own agents need a model: a hosted one with your API key, or a local one through Ollama (free, slower; https://docs.nimblebrain.ai/config/local-models/).");
@@ -1213,16 +1593,18 @@ async function useLocalModel(ctx, composeText, model) {
1213
1593
  if (!takesLocalModel(composeText)) {
1214
1594
  throw new CliError("RUNTIME_UNSUPPORTED", "This release's runtime takes no local model; a newer release does.");
1215
1595
  }
1216
- const values = await setupLocalModel(deps, model, (m) => confirmPull(ctx, m));
1596
+ const { values, started } = await setupLocalModel(deps, model, {
1597
+ start: confirmOllamaStart(ctx, true),
1598
+ pull: (m) => confirmPull(ctx, m)
1599
+ });
1217
1600
  const p = paths(home);
1218
1601
  await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", values), 384);
1219
- return values.NB_LOCAL_MODEL ?? model;
1602
+ return { name: values.NB_LOCAL_MODEL ?? model, started };
1220
1603
  }
1221
1604
  async function confirmPull(ctx, model) {
1222
1605
  if (!asks(ctx))
1223
1606
  return true;
1224
- const answer = (await ctx.deps.prompt(`Download ${model} with Ollama? It is several GB. [Y/n] `)).trim().toLowerCase();
1225
- return answer === "" || answer === "y" || answer === "yes";
1607
+ return yes(await ctx.deps.prompt(`Download ${model} with Ollama? It is several GB. [Y/n] `));
1226
1608
  }
1227
1609
  async function chooseAgent(deps) {
1228
1610
  deps.say("A coding agent you connect can use NimbleBrain's tools. NimbleBrain's own agents still run on the model key above.");
@@ -1245,13 +1627,13 @@ async function waitHealthy(deps, port) {
1245
1627
  }
1246
1628
  throw new CliError("HEALTH_TIMEOUT", "NimbleBrain did not report healthy within 3 minutes.");
1247
1629
  }
1248
- async function writeInstallFiles(deps, home, tag, port, composeText, extra = {}) {
1630
+ async function writeInstallFiles(deps, home, project, tag, port, composeText, extra = {}) {
1249
1631
  const p = paths(home);
1250
1632
  await deps.writeText(p.compose, composeText);
1251
1633
  if (await deps.readText(p.instance) === undefined)
1252
1634
  await deps.writeText(p.instance, INSTANCE_JSON);
1253
1635
  const env = setEnvLines(await deps.readText(p.env) ?? "", {
1254
- COMPOSE_PROJECT_NAME: PROJECT,
1636
+ COMPOSE_PROJECT_NAME: project,
1255
1637
  NIMBLEBRAIN_TAG: tag,
1256
1638
  NIMBLEBRAIN_WEB_PORT: String(port),
1257
1639
  ...extra
@@ -1269,81 +1651,283 @@ async function requireInstall({ deps, home }) {
1269
1651
  return install;
1270
1652
  }
1271
1653
  async function guardOurs(deps, home) {
1654
+ const project = projectFor(home);
1272
1655
  const env = await deps.readText(paths(home).env);
1273
- if (env?.includes(`COMPOSE_PROJECT_NAME=${PROJECT}`))
1274
- return;
1656
+ const marked = env?.match(/^COMPOSE_PROJECT_NAME=(.*?)\r?$/m)?.[1];
1657
+ if (marked === project || marked === DEFAULT_PROJECT)
1658
+ return marked;
1275
1659
  for (const file of Object.values(paths(home))) {
1276
1660
  if (await deps.readText(file) !== undefined) {
1277
1661
  throw new CliError("NOT_OURS", `${file} already exists and this CLI did not write it.`);
1278
1662
  }
1279
1663
  }
1280
1664
  const projects = await deps.exec("docker", ["compose", "ls", "-a", "--format", "json"]);
1281
- const taken = projects.code === 0 && /"Name"\s*:\s*"nimblebrain-local"/.test(projects.stdout);
1282
- const volumes = await deps.exec("docker", ["volume", "ls", "-q", "--filter", `name=^${VOLUME}$`]);
1665
+ const taken = projects.code === 0 && listsProject(projects.stdout, project);
1666
+ const volumes = await deps.exec("docker", [
1667
+ "volume",
1668
+ "ls",
1669
+ "-q",
1670
+ "--filter",
1671
+ `name=^${volumeOf(project)}$`
1672
+ ]);
1283
1673
  if (taken || volumes.stdout.trim() !== "") {
1284
- throw new CliError("NOT_OURS", `Docker already has a "${PROJECT}" project or volume that this install did not make.`);
1674
+ throw new CliError("NOT_OURS", `Docker already has a "${project}" project or volume that this install did not make.`);
1675
+ }
1676
+ return project;
1677
+ }
1678
+ function listsProject(stdout, project) {
1679
+ try {
1680
+ const list = JSON.parse(stdout);
1681
+ return Array.isArray(list) && list.some((p) => p?.Name === project);
1682
+ } catch {
1683
+ return false;
1285
1684
  }
1286
1685
  }
1287
1686
 
1288
- // src/main.ts
1289
- var HELP = `nimblebrain ${VERSION2}: install and run NimbleBrain on this machine
1290
-
1291
- Usage: npx nimblebrain [command] [flags]
1687
+ // src/mcp.ts
1688
+ async function mcp(ctx) {
1689
+ const sub = ctx.arg;
1690
+ const target = await reach(ctx, sub === "add");
1691
+ if (sub === "add")
1692
+ return add(target, ctx.operand ?? "", ctx.flags.name);
1693
+ if (sub === "list")
1694
+ return list(target);
1695
+ return remove(target, ctx.operand ?? "");
1696
+ }
1697
+ var RUNTIME_CODES = [
1698
+ "DIRECT_URL_NOT_ALLOWED",
1699
+ "URL_NOT_LOOPBACK",
1700
+ "URL_INVALID",
1701
+ "INVALID_SERVER_NAME",
1702
+ "NAME_TAKEN",
1703
+ "NAME_IS_CATALOG_ENTRY"
1704
+ ];
1705
+ var ADD_TIMEOUT_MS = 60000;
1706
+ var CALL_TIMEOUT_MS = 15000;
1707
+ async function reach(ctx, adding) {
1708
+ const { deps, home, flags } = ctx;
1709
+ const install = await readInstall(deps, home);
1710
+ if (!install)
1711
+ throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1712
+ if (adding && !hostLoopback(await deps.readText(paths(home).compose) ?? "")) {
1713
+ throw new CliError("UPDATE_REQUIRED", `NimbleBrain ${install.version} cannot reach a server on this machine.`, { version: install.version });
1714
+ }
1715
+ const url = `http://127.0.0.1:${install.port}`;
1716
+ if (!await isUp(deps, url))
1717
+ throw new CliError("NOT_RUNNING", "NimbleBrain is not running.");
1718
+ const workspaces = await readWorkspaces(deps, url);
1719
+ const ws = flags.workspace ? workspaces.find((w) => w.id === flags.workspace) : workspaces[0];
1720
+ if (!ws) {
1721
+ throw new CliError("WORKSPACE_NOT_FOUND", flags.workspace ? `No workspace "${flags.workspace}" on this install.` : "This install has no workspace.", { workspaces: workspaces.map((w) => w.id) });
1722
+ }
1723
+ return { ctx, url, wsId: ws.id };
1724
+ }
1725
+ async function add(t, serverUrl, name) {
1726
+ const protocol = URL.canParse(serverUrl) ? new URL(serverUrl).protocol : "";
1727
+ if (protocol !== "http:" && protocol !== "https:") {
1728
+ throw new CliError("URL_INVALID", `"${serverUrl}" is not an http or https URL.`);
1729
+ }
1730
+ const install = { kind: "direct-url", url: serverUrl, ...name ? { serverName: name } : {} };
1731
+ const s = await call(t, {
1732
+ action: "install",
1733
+ entry: { id: "direct-url", name: name ?? serverUrl, install }
1734
+ }, ADD_TIMEOUT_MS);
1735
+ return {
1736
+ ok: true,
1737
+ serverName: s.serverName,
1738
+ url: s.url,
1739
+ dialed: s.dialed,
1740
+ placements: s.placements,
1741
+ wsId: s.wsId ?? t.wsId,
1742
+ ...s.warning ? { warning: s.warning } : {},
1743
+ ...s.notice ? { notice: s.notice } : {}
1744
+ };
1745
+ }
1746
+ async function list(t) {
1747
+ const s = await call(t, { action: "list_installed", scope: "workspace" }, CALL_TIMEOUT_MS);
1748
+ const installed = Array.isArray(s.installed) ? s.installed : [];
1749
+ const servers = installed.map((e) => ({
1750
+ serverName: e.serverName,
1751
+ displayName: e.displayName,
1752
+ url: e.url,
1753
+ state: e.state,
1754
+ status: e.status,
1755
+ statusReason: e.statusReason,
1756
+ toolCount: e.toolCount
1757
+ }));
1758
+ return { ok: true, wsId: t.wsId, servers };
1759
+ }
1760
+ async function remove(t, serverName) {
1761
+ const listed = await call(t, { action: "list_installed", scope: "workspace" }, CALL_TIMEOUT_MS);
1762
+ const installed = Array.isArray(listed.installed) ? listed.installed : [];
1763
+ if (!installed.some((e) => e.serverName === serverName)) {
1764
+ throw new CliError("SERVER_NOT_FOUND", `This workspace has no server named "${serverName}".`, {
1765
+ wsId: t.wsId
1766
+ });
1767
+ }
1768
+ await call(t, { action: "uninstall", serverName }, CALL_TIMEOUT_MS);
1769
+ return { ok: true, serverName, wsId: t.wsId };
1770
+ }
1771
+ async function call(t, args, timeoutMs) {
1772
+ const res = await t.ctx.deps.postJson(`${t.url}/v1/workspaces/${encodeURIComponent(t.wsId)}/tools/call`, { server: "nb", tool: "manage_connectors", arguments: args }, timeoutMs);
1773
+ if (!res)
1774
+ throw new CliError("NOT_RUNNING", "NimbleBrain did not answer.");
1775
+ const body = res.body ?? {};
1776
+ if (res.status === 404 && body.error === "workspace_error") {
1777
+ throw new CliError("WORKSPACE_NOT_FOUND", `No workspace "${t.wsId}" on this install.`);
1778
+ }
1779
+ if (res.status < 200 || res.status >= 300) {
1780
+ const why = typeof body.message === "string" ? body.message : `HTTP ${res.status}`;
1781
+ throw new CliError("REQUEST_FAILED", `NimbleBrain refused the request: ${why}`, {
1782
+ status: res.status
1783
+ });
1784
+ }
1785
+ const text = body.content?.find((c) => c.type === "text")?.text;
1786
+ if (body.isError) {
1787
+ const code = body.structuredContent?.error;
1788
+ const known = RUNTIME_CODES.find((c) => c === code);
1789
+ throw new CliError(known ?? "REQUEST_FAILED", text ?? "NimbleBrain refused the request.");
1790
+ }
1791
+ return body.structuredContent ?? {};
1792
+ }
1292
1793
 
1293
- Commands:
1294
- init Check this machine, start NimbleBrain, connect your coding agent (default)
1295
- doctor Check Docker, Compose, architecture, memory and the port; installs nothing
1296
- status Version, health, URL and each workspace's MCP URL
1297
- key Enter the model key at a hidden prompt
1298
- local-model [model] Run NimbleBrain's agents on a model served by Ollama (default gemma4:e4b)
1299
- telemetry [on|off|status] Whether this install sends anonymous usage data
1300
- up, down Start or stop NimbleBrain; data survives down
1301
- logs Recent runtime log lines
1302
- update Move to the newest release, keeping data
1303
- uninstall Remove NimbleBrain and its data
1794
+ // src/updates.ts
1795
+ import { join as join6 } from "node:path";
1796
+ var NPM_LATEST = "https://registry.npmjs.org/nimblebrain/latest";
1797
+ var FRESH_MS = 24 * 60 * 60000;
1798
+ var LOOKUP_TIMEOUT_MS = 5000;
1799
+ var NOTICE_WAIT_MS = 1000;
1800
+ var SEMVER = /^v?\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
1801
+ function cachePath(deps) {
1802
+ const xdg = deps.env.XDG_CACHE_HOME?.trim();
1803
+ const base = xdg?.startsWith("/") ? xdg : join6(deps.home, ".cache");
1804
+ return join6(base, "nimblebrain", "update-check.json");
1805
+ }
1806
+ function updateCheckOff(deps) {
1807
+ const ci = deps.env.CI?.trim().toLowerCase();
1808
+ return ci !== undefined && ci !== "" && ci !== "false" && ci !== "0" || deps.env.NIMBLEBRAIN_NO_UPDATE_CHECK === "1" || doNotTrack(deps);
1809
+ }
1810
+ function startUpdateCheck(deps) {
1811
+ if (updateCheckOff(deps))
1812
+ return;
1813
+ const cached = readCache(deps);
1814
+ let settled = false;
1815
+ const refreshed = cached.then(async (old) => {
1816
+ if (old && Date.now() - old.checked_at < FRESH_MS)
1817
+ return old;
1818
+ return await lookup(deps, old) ?? old;
1819
+ });
1820
+ refreshed.then(() => {
1821
+ settled = true;
1822
+ });
1823
+ return {
1824
+ async known(waitMs) {
1825
+ const old = await cached;
1826
+ if (settled)
1827
+ return refreshed;
1828
+ const deadline = waitMs > 0 ? deps.sleep(waitMs).then(() => old) : Promise.resolve(old);
1829
+ return Promise.race([refreshed, deadline]);
1830
+ }
1831
+ };
1832
+ }
1833
+ async function readCache(deps) {
1834
+ try {
1835
+ const raw = JSON.parse(await deps.readText(cachePath(deps)) ?? "null");
1836
+ if (typeof raw?.checked_at !== "number")
1837
+ return;
1838
+ return {
1839
+ checked_at: raw.checked_at,
1840
+ cli: version(raw.cli),
1841
+ runtime: version(raw.runtime)
1842
+ };
1843
+ } catch {
1844
+ return;
1845
+ }
1846
+ }
1847
+ async function lookup(deps, old) {
1848
+ try {
1849
+ const [npm, runtime] = await Promise.all([
1850
+ deps.getJson(NPM_LATEST, LOOKUP_TIMEOUT_MS),
1851
+ newestRuntime(deps, LOOKUP_TIMEOUT_MS).catch(() => {
1852
+ return;
1853
+ })
1854
+ ]);
1855
+ const cli = npm?.status === 200 ? version(npm.body?.version) : undefined;
1856
+ if (!cli && !runtime)
1857
+ return;
1858
+ const known = {
1859
+ checked_at: Date.now(),
1860
+ cli: cli ?? old?.cli,
1861
+ runtime: runtime ?? old?.runtime
1862
+ };
1863
+ await deps.writeText(cachePath(deps), `${JSON.stringify(known)}
1864
+ `);
1865
+ return known;
1866
+ } catch {
1867
+ return;
1868
+ }
1869
+ }
1870
+ function version(value) {
1871
+ return typeof value === "string" && SEMVER.test(value) ? value : undefined;
1872
+ }
1873
+ function updatesField(known, cliVersion, runtimeVersion) {
1874
+ const updates = {};
1875
+ if (known?.cli)
1876
+ updates.cli = { current: cliVersion, latest: known.cli };
1877
+ if (known?.runtime && runtimeVersion) {
1878
+ updates.runtime = { current: runtimeVersion, latest: known.runtime.replace(/^v/, "") };
1879
+ }
1880
+ return updates.cli || updates.runtime ? updates : undefined;
1881
+ }
1882
+ function noticeLines(updates, withRuntime, run = "npx nimblebrain") {
1883
+ const lines = [];
1884
+ const cli = updates?.cli;
1885
+ if (cli && compareVersions(cli.latest, cli.current) > 0) {
1886
+ lines.push(`nimblebrain ${cli.latest} is available (you have ${cli.current}): npx nimblebrain@latest`);
1887
+ }
1888
+ const rt = updates?.runtime;
1889
+ if (withRuntime && rt && compareVersions(rt.latest, rt.current) > 0) {
1890
+ lines.push(`NimbleBrain v${rt.latest} is available (you have v${rt.current}): ${run} update`);
1891
+ }
1892
+ return lines;
1893
+ }
1304
1894
 
1305
- Flags:
1306
- --json One JSON object on stdout
1307
- --yes, -y Take every default; implied when no terminal is attached
1308
- --agent <name> claude-code, cursor, codex or none
1309
- --port <n> Local port (default 27246)
1310
- --home <dir> Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME)
1311
- --provider <name> The model provider for key (default anthropic)
1312
- --local-model <model> init: run on this Ollama model instead of a hosted key
1313
- --runtime <tag> The NimbleBrain release to install or update to (default the newest)
1314
- --telemetry <on|off> The person's answer to sending anonymous usage data; without it, init asks or leaves it undecided
1315
- --help, --version
1316
- `;
1895
+ // src/main.ts
1896
+ var RUNTIME_NOTICE = ["status", "up", "init"];
1317
1897
  async function run(argv, deps) {
1318
1898
  const json = wantsJson(argv);
1319
1899
  let parsed;
1320
1900
  try {
1321
1901
  parsed = parse(argv);
1322
1902
  } catch (err) {
1323
- return render(toFailure(err), json);
1903
+ return render(toFailure(err), json, BARE_CLI);
1904
+ }
1905
+ if (parsed.kind === "help") {
1906
+ return parsed.flags.json ? render(describe(VERSION2), true, BARE_CLI) : { stdout: helpText(VERSION2), code: 0 };
1324
1907
  }
1325
- if (parsed.kind === "help")
1326
- return { stdout: HELP, code: 0 };
1327
1908
  if (parsed.kind === "version") {
1328
- return parsed.flags.json ? render({ ok: true, version: VERSION2 }, true) : { stdout: `${VERSION2}
1909
+ return parsed.flags.json ? render({ ok: true, version: VERSION2 }, true, BARE_CLI) : { stdout: `${VERSION2}
1329
1910
  `, code: 0 };
1330
1911
  }
1331
- const { command, flags, arg } = parsed;
1912
+ const { command, flags, arg, operand } = parsed;
1913
+ const check = startUpdateCheck(deps);
1332
1914
  const home = installHome(deps, flags.home);
1915
+ const cli = invocation(deps, home);
1333
1916
  let result;
1334
1917
  try {
1335
1918
  switch (command) {
1336
1919
  case "doctor": {
1337
1920
  const install = await readInstall(deps, home);
1338
1921
  const ours = install !== undefined && install.port === flags.port && await isHealthy(deps, flags.port);
1339
- result = { ...await doctorInstall(deps, home, flags.port, ours) };
1922
+ const startOllama = confirmOllamaStart({ deps, flags }, false);
1923
+ result = { ...await doctorInstall(deps, home, flags.port, ours, startOllama) };
1340
1924
  break;
1341
1925
  }
1342
1926
  case "status":
1343
1927
  result = { ...await status(deps, home) };
1344
1928
  break;
1345
1929
  default: {
1346
- const ctx = { deps, flags, home, version: VERSION2, arg };
1930
+ const ctx = { deps, flags, home, version: VERSION2, arg, operand };
1347
1931
  const commands = {
1348
1932
  init,
1349
1933
  up,
@@ -1353,7 +1937,8 @@ async function run(argv, deps) {
1353
1937
  uninstall,
1354
1938
  key,
1355
1939
  telemetry,
1356
- "local-model": localModel
1940
+ "local-model": localModel,
1941
+ mcp
1357
1942
  };
1358
1943
  result = await commands[command](ctx);
1359
1944
  }
@@ -1361,26 +1946,50 @@ async function run(argv, deps) {
1361
1946
  } catch (err) {
1362
1947
  result = toFailure(err);
1363
1948
  }
1949
+ if (!result.ok)
1950
+ result = { ...result, fix: forInstall(result.fix, cli) };
1364
1951
  if (!["init", "telemetry", "uninstall", "doctor"].includes(command)) {
1365
1952
  await settleWaiting(deps, home, VERSION2);
1366
1953
  }
1367
- return render(result, flags.json, command);
1954
+ return answerWithUpdates(result, command, flags.json, check, cli);
1955
+ }
1956
+ async function answerWithUpdates(result, command, json, check, cli) {
1957
+ if (!check)
1958
+ return render(result, json, cli, command);
1959
+ const runtime = isStatusShaped(result) ? result.version : undefined;
1960
+ const updates = updatesField(await check.known(0), VERSION2, runtime);
1961
+ const answer = render(updates && runtime !== undefined ? { ...result, updates } : result, json, cli, command);
1962
+ const notices = async () => {
1963
+ const known = await check.known(NOTICE_WAIT_MS);
1964
+ if (json)
1965
+ return;
1966
+ const lines = noticeLines(updatesField(known, VERSION2, runtime), RUNTIME_NOTICE.includes(command), cli);
1967
+ return lines.length > 0 ? `${lines.join(`
1968
+ `)}
1969
+ ` : undefined;
1970
+ };
1971
+ return { ...answer, notices };
1368
1972
  }
1369
- async function doctorInstall(deps, home, port, ours) {
1973
+ function isStatusShaped(result) {
1974
+ return typeof result.version === "string" && "health" in result && "url" in result && "workspaces" in result;
1975
+ }
1976
+ async function doctorInstall(deps, home, port, ours, startOllama) {
1370
1977
  const machine = await doctor(deps, port, ours);
1371
1978
  const model = localModelOf(await deps.readText(paths(home).env) ?? "");
1372
1979
  if (!model)
1373
1980
  return machine;
1374
1981
  try {
1375
- return { ...machine, checks: [...machine.checks, ...await checkLocalModel(deps, model)] };
1982
+ const local = await checkLocalModel(deps, model, startOllama);
1983
+ return {
1984
+ ...machine,
1985
+ checks: [...machine.checks, ...local.checks],
1986
+ ollama_started: local.started
1987
+ };
1376
1988
  } catch (err) {
1377
1989
  if (!(err instanceof CliError))
1378
1990
  throw err;
1379
1991
  const local = err.detail.checks ?? [];
1380
- throw new CliError(err.code, err.message, {
1381
- ...err.detail,
1382
- checks: [...machine.checks, ...local]
1383
- });
1992
+ throw err.with({ checks: [...machine.checks, ...local] });
1384
1993
  }
1385
1994
  }
1386
1995
  async function isHealthy(deps, port) {
@@ -1392,7 +2001,7 @@ function toFailure(err) {
1392
2001
  return failure(err);
1393
2002
  return failure(new CliError("USAGE", err instanceof Error ? err.message : String(err)));
1394
2003
  }
1395
- function render(result, json, command) {
2004
+ function render(result, json, cli, command) {
1396
2005
  const code = exitCodeFor(result);
1397
2006
  if (json)
1398
2007
  return { stdout: `${JSON.stringify(result)}
@@ -1401,7 +2010,7 @@ function render(result, json, command) {
1401
2010
  return { stdout: `error: ${result.message}
1402
2011
  fix: ${result.fix}
1403
2012
  `, code };
1404
- const lines = isStatus(result) ? statusLines(result, command) : genericLines(result);
2013
+ const lines = isStatus(result) ? statusLines(result, cli, command) : genericLines(result);
1405
2014
  return { stdout: `${lines.join(`
1406
2015
  `)}
1407
2016
  `, code };
@@ -1414,30 +2023,46 @@ var AGENT_NAMES = {
1414
2023
  cursor: "Cursor",
1415
2024
  codex: "Codex"
1416
2025
  };
1417
- function statusLines(r, command) {
2026
+ function statusLines(r, cli, command) {
1418
2027
  const lines = [
1419
2028
  ...changeLines(r),
1420
2029
  ` NimbleBrain ${r.version.startsWith("v") ? r.version : `v${r.version}`}: ${r.health === "ok" ? "running" : "stopped"} at ${r.url}`,
1421
2030
  ...r.workspaces.map((w) => ` workspace ${w.name}: ${w.mcp}`),
1422
- r.local_model ? ` model: ${r.local_model} on Ollama (NimbleBrain's own agents use it)` : ` model key: ${r.model_key === "set" ? "set (NimbleBrain's own agents use it)" : "missing (run npx nimblebrain key)"}`
2031
+ r.local_model ? ` model: ${r.local_model} on Ollama (NimbleBrain's own agents use it)` : ` model key: ${r.model_key === "set" ? "set (NimbleBrain's own agents use it)" : `missing (run ${cli} key)`}`
1423
2032
  ];
1424
2033
  const agent = r.agent.connected;
1425
- if (agent) {
1426
- const name = AGENT_NAMES[agent] ?? agent;
1427
- lines.push(` ${name} can use NimbleBrain's tools (it loads them when its next session starts)`);
1428
- if (!r.agent.skill)
1429
- lines.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain --agent ${agent} -g`);
1430
- } else if (r.manual) {
1431
- lines.push(` agent: not connected; add it by hand: ${r.manual}`);
1432
- }
2034
+ lines.push(...agentLines(r));
2035
+ if (!r.host_loopback)
2036
+ lines.push(` servers on this machine: not reachable until ${cli} update`);
1433
2037
  lines.push(telemetryLine(r.telemetry));
1434
2038
  lines.push(` CLI ${r.cli_version}`);
1435
2039
  if (command === "init" && !r.already && r.health === "ok") {
1436
2040
  const ask = agent ? `, or ask ${AGENT_NAMES[agent] ?? agent} what NimbleBrain can do` : "";
1437
- lines.push("", `Next: open ${r.url}${ask}. Stop it with npx nimblebrain down.`);
2041
+ lines.push("", `Next: open ${r.url}${ask}. Stop it with ${cli} down.`);
1438
2042
  }
1439
2043
  return lines;
1440
2044
  }
2045
+ function agentLines(r) {
2046
+ const agent = r.agent.connected;
2047
+ if (!agent)
2048
+ return r.manual ? [` agent: not connected; add it by hand: ${r.manual}`] : [];
2049
+ const name = AGENT_NAMES[agent] ?? agent;
2050
+ const lines = [
2051
+ ` ${name} can use NimbleBrain's tools (it loads them when its next session starts)`
2052
+ ];
2053
+ const refresh = r.skill_update && SKILL_REFRESH_LINES[r.skill_update];
2054
+ if (refresh)
2055
+ lines.push(` skill: ${refresh}`);
2056
+ if (!r.agent.skill)
2057
+ lines.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain --agent ${agent} -g`);
2058
+ return lines;
2059
+ }
2060
+ var SKILL_REFRESH_LINES = {
2061
+ updated: "updated to the newest nimblebrain skill",
2062
+ unchanged: "the nimblebrain skill is current",
2063
+ failed: "could not refresh the nimblebrain skill; try npx skills update nimblebrain -g",
2064
+ not_installed: undefined
2065
+ };
1441
2066
  function changeLines(r) {
1442
2067
  if (r.already)
1443
2068
  return [" already installed"];
@@ -1453,26 +2078,41 @@ function genericLines(result) {
1453
2078
  function field2(key, value) {
1454
2079
  if (value === undefined || value === null)
1455
2080
  return [];
2081
+ if (key === "servers" && Array.isArray(value)) {
2082
+ if (value.length === 0)
2083
+ return [" no servers in this workspace"];
2084
+ return value.map((s) => ` ${s.serverName}: ${s.url ?? "(no URL)"}${s.status ? ` (${s.status})` : ""}`);
2085
+ }
1456
2086
  if (key === "checks" && Array.isArray(value)) {
1457
2087
  return value.map((c) => ` ${c.ok ? "✓" : "✗"} ${c.check}: ${c.detail}`);
1458
2088
  }
1459
2089
  if (typeof value === "object" && !Array.isArray(value)) {
1460
2090
  return Object.entries(value).flatMap(([k, v]) => field2(`${key} ${k}`, v));
1461
2091
  }
1462
- return [` ${key}: ${Array.isArray(value) ? value.join(", ") : String(value)}`];
2092
+ if (Array.isArray(value)) {
2093
+ const items = value.map((v) => typeof v === "object" ? JSON.stringify(v) : String(v));
2094
+ return [` ${key}: ${items.join(", ")}`];
2095
+ }
2096
+ return [` ${key}: ${String(value)}`];
1463
2097
  }
1464
- function interrupted(argv, exitCode) {
2098
+ function interrupted(argv, exitCode, deps) {
1465
2099
  const err = new CliError("INTERRUPTED", `The CLI stopped before it answered (exit code ${exitCode}).`, { exit_code: exitCode });
1466
- return render(failure(err), wantsJson(argv));
2100
+ let cli = BARE_CLI;
2101
+ try {
2102
+ cli = invocation(deps, installHome(deps, parse(argv).flags.home));
2103
+ } catch {}
2104
+ const result = failure(err);
2105
+ return render({ ...result, fix: forInstall(result.fix, cli) }, wantsJson(argv), cli);
1467
2106
  }
1468
2107
 
1469
2108
  // src/bin.ts
1470
2109
  var argv = process.argv.slice(2);
2110
+ var deps = realDeps();
1471
2111
  var answered = false;
1472
2112
  process.on("exit", (code) => {
1473
2113
  if (answered)
1474
2114
  return;
1475
- const out = interrupted(argv, code);
2115
+ const out = interrupted(argv, code, deps);
1476
2116
  writeSync(1, out.stdout);
1477
2117
  writeSync(2, `nimblebrain: stopped before answering (exit code ${code})
1478
2118
  `);
@@ -1485,7 +2125,10 @@ for (const [signal, n] of [
1485
2125
  ]) {
1486
2126
  process.on(signal, () => process.exit(128 + n));
1487
2127
  }
1488
- var { stdout, code } = await run(argv, realDeps());
1489
- writeSync(1, stdout);
2128
+ var answer = await run(argv, deps);
2129
+ writeSync(1, answer.stdout);
1490
2130
  answered = true;
1491
- process.exitCode = code;
2131
+ var notices = await answer.notices?.();
2132
+ if (notices)
2133
+ writeSync(2, notices);
2134
+ process.exit(answer.code);