nimblebrain 0.0.1 → 0.1.1

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.
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # nimblebrain
2
+
3
+ Install and run [NimbleBrain](https://github.com/NimbleBrainInc/nimblebrain), the
4
+ open-source runtime for agents and MCP apps, on your own machine, and connect your
5
+ coding agent to it.
6
+
7
+ ```bash
8
+ npx nimblebrain
9
+ ```
10
+
11
+ It checks the machine, starts NimbleBrain in Docker at `http://127.0.0.1:27246`, and
12
+ connects your coding agent to a workspace over MCP. Run it again any time: on a
13
+ machine that already has NimbleBrain it reports what is there.
14
+
15
+ You need Docker with Compose v2, about 2 GB of memory for Docker, and Node.js 20 or
16
+ later.
17
+
18
+ ## Commands
19
+
20
+ | Command | Does |
21
+ |---|---|
22
+ | `init` (default) | Check the machine, start NimbleBrain, connect your coding agent |
23
+ | `doctor` | Check Docker, Compose, architecture, memory and the port; installs nothing |
24
+ | `status` | Version, health, URL and each workspace's MCP URL |
25
+ | `key` | Enter the model key at a hidden prompt |
26
+ | `up` / `down` | Start or stop it; data survives `down` |
27
+ | `logs` | Recent log lines |
28
+ | `update` | Move to the newest release, keeping data |
29
+ | `uninstall` | Remove it and its data |
30
+ | `telemetry [on\|off\|status]` | Whether this install sends anonymous usage data |
31
+
32
+ `--json` makes every command answer one JSON object, `{"ok": true, ...}` or
33
+ `{"ok": false, "error": "<CODE>", "fix": "..."}`, for scripts and coding agents.
34
+ `--yes` takes every default. `--agent claude-code|cursor|codex|none` names the agent to
35
+ connect.
36
+
37
+ ## Usage data
38
+
39
+ Nothing is sent until you say yes. `init` asks once in your terminal; run by a coding
40
+ agent, it sends nothing and hands the agent the question to ask you, which it answers
41
+ with `npx nimblebrain telemetry on` or `off`. `DO_NOT_TRACK=1` keeps it off. What is
42
+ sent and what never is: [Telemetry](https://docs.nimblebrain.ai/using/telemetry/).
43
+
44
+ Docs: [docs.nimblebrain.ai](https://docs.nimblebrain.ai)
@@ -0,0 +1,1295 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/bin.ts
4
+ import { writeSync } from "node:fs";
5
+
6
+ // src/deps.ts
7
+ import { spawn } from "node:child_process";
8
+ import { chmod, mkdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
9
+ import { createServer } from "node:net";
10
+ import { homedir } from "node:os";
11
+ import { dirname, join } from "node:path";
12
+ function realDeps() {
13
+ return {
14
+ exec(cmd, args, opts = {}) {
15
+ return new Promise((resolve) => {
16
+ let stdout = "";
17
+ let stderr = "";
18
+ let missing = false;
19
+ const child = spawn(cmd, args, {
20
+ stdio: ["ignore", "pipe", "pipe"],
21
+ timeout: opts.timeoutMs ?? 30000,
22
+ cwd: opts.cwd,
23
+ env: opts.env
24
+ });
25
+ child.stdout.on("data", (d) => {
26
+ stdout += d.toString();
27
+ });
28
+ child.stderr.on("data", (d) => {
29
+ stderr += d.toString();
30
+ });
31
+ child.on("error", (err) => {
32
+ if (err.code === "ENOENT")
33
+ missing = true;
34
+ });
35
+ child.on("close", (code) => resolve({ code, stdout, stderr, missing }));
36
+ });
37
+ },
38
+ portFree(port) {
39
+ return new Promise((resolve) => {
40
+ const server = createServer();
41
+ server.once("error", () => resolve(false));
42
+ server.once("listening", () => server.close(() => resolve(true)));
43
+ server.listen(port, "127.0.0.1");
44
+ });
45
+ },
46
+ getJson: async (url, timeoutMs = 3000) => asJson(await request(url, { headers: { "user-agent": "nimblebrain-cli" } }, timeoutMs)),
47
+ getText: (url, timeoutMs = 1e4) => request(url, { headers: { "user-agent": "nimblebrain-cli" } }, timeoutMs),
48
+ postJson: async (url, body, timeoutMs = 5000) => asJson(await request(url, {
49
+ method: "POST",
50
+ headers: { "user-agent": "nimblebrain-cli", "content-type": "application/json" },
51
+ body: JSON.stringify(body)
52
+ }, timeoutMs)),
53
+ async readText(path) {
54
+ try {
55
+ return await readFile(path, "utf8");
56
+ } catch {
57
+ return;
58
+ }
59
+ },
60
+ async writeText(path, text, mode = 420) {
61
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
62
+ await writeFile(path, text, { mode });
63
+ await chmod(path, mode);
64
+ },
65
+ async remove(path) {
66
+ try {
67
+ await rmdir(path);
68
+ } catch (err) {
69
+ if (err.code === "ENOTDIR")
70
+ await rm(path, { force: true });
71
+ }
72
+ },
73
+ prompt: (question, opts = {}) => opts.hidden ? hiddenPrompt(question) : visiblePrompt(question),
74
+ interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
75
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
76
+ say: (line) => {
77
+ process.stderr.write(`${line}
78
+ `);
79
+ },
80
+ env: process.env,
81
+ home: homedir()
82
+ };
83
+ }
84
+ async function request(url, init, timeoutMs) {
85
+ const abort = new AbortController;
86
+ const timer = setTimeout(() => abort.abort(), timeoutMs);
87
+ try {
88
+ const res = await fetch(url, { ...init, signal: abort.signal });
89
+ return { status: res.status, body: await res.text() };
90
+ } catch {
91
+ return;
92
+ } finally {
93
+ clearTimeout(timer);
94
+ }
95
+ }
96
+ function asJson(res) {
97
+ if (!res)
98
+ return;
99
+ try {
100
+ return { status: res.status, body: JSON.parse(res.body) };
101
+ } catch {
102
+ return res;
103
+ }
104
+ }
105
+ async function visiblePrompt(question) {
106
+ const { createInterface } = await import("node:readline/promises");
107
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
108
+ try {
109
+ return (await rl.question(question)).trim();
110
+ } finally {
111
+ rl.close();
112
+ }
113
+ }
114
+ function hiddenPrompt(question) {
115
+ return new Promise((resolve, reject) => {
116
+ const stdin = process.stdin;
117
+ process.stderr.write(question);
118
+ let value = "";
119
+ stdin.setRawMode(true);
120
+ stdin.resume();
121
+ stdin.setEncoding("utf8");
122
+ const done = (fn) => {
123
+ stdin.setRawMode(false);
124
+ stdin.pause();
125
+ stdin.removeListener("data", onData);
126
+ process.stderr.write(`
127
+ `);
128
+ fn();
129
+ };
130
+ const onData = (chunk) => {
131
+ const step = typeHidden(value, chunk);
132
+ value = step.value;
133
+ if (step.end === "enter")
134
+ done(() => resolve(value.trim()));
135
+ if (step.end === "cancel")
136
+ done(() => reject(new Error("Cancelled.")));
137
+ };
138
+ stdin.on("data", onData);
139
+ });
140
+ }
141
+ function typeHidden(value, chunk) {
142
+ let v = value;
143
+ for (const ch of chunk) {
144
+ if (ch === "\r" || ch === `
145
+ `)
146
+ return { value: v, end: "enter" };
147
+ if (ch === "\x03")
148
+ return { value: v, end: "cancel" };
149
+ v = ch === "" || ch === "\b" ? v.slice(0, -1) : v + ch;
150
+ }
151
+ return { value: v };
152
+ }
153
+ function installHome(deps, flag) {
154
+ return flag ?? deps.env.NIMBLEBRAIN_HOME ?? join(deps.home, ".nimblebrain-local");
155
+ }
156
+
157
+ // src/args.ts
158
+ import { parseArgs } from "node:util";
159
+
160
+ // src/result.ts
161
+ var ERRORS = {
162
+ USAGE: "Run `npx nimblebrain --help` for the commands and flags.",
163
+ DOCKER_MISSING: "Install Docker Desktop or Docker Engine (https://docs.docker.com/get-docker/), then run this again.",
164
+ DOCKER_NOT_RUNNING: "Start Docker Desktop (or the Docker service), then run this again.",
165
+ DOCKER_PERMISSION: "Let this user use Docker (https://docs.docker.com/engine/install/linux-postinstall/), sign in again, then run this again.",
166
+ COMPOSE_MISSING: "Install Docker Compose v2 (https://docs.docker.com/compose/install/) or update Docker Desktop, then run this again.",
167
+ ARCH_UNSUPPORTED: "NimbleBrain publishes no image for this CPU architecture.",
168
+ LOW_MEMORY: "Give Docker at least 2 GB of memory in its settings, then run this again.",
169
+ PORT_IN_USE: "Stop whatever holds the port, or pass --port with a free one.",
170
+ 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.",
172
+ NETWORK: "Check the network connection, then run the same command again.",
173
+ MODEL_KEY_MISSING: "Run `npx nimblebrain key` in your own terminal to enter a model key.",
174
+ HEALTH_TIMEOUT: "Run `npx nimblebrain logs` and look at the last error line.",
175
+ AGENT_UNSUPPORTED: "Pass --agent claude-code, cursor, codex or none.",
176
+ START_FAILED: "Run `npx nimblebrain logs` and look at the last error line, then run this again.",
177
+ NEEDS_TERMINAL: "A person runs this in their own terminal; it asks for input no agent should give.",
178
+ CANCELLED: "Nothing was changed. Run the command again to go ahead.",
179
+ RUNTIME_UNSUPPORTED: "Pass a newer runtime with --runtime, or leave it out to install the newest release.",
180
+ NOT_RUNNING: "Run `npx nimblebrain up`, then run this again.",
181
+ TELEMETRY_LOCKED: "Nothing to change: DO_NOT_TRACK or the install's configuration decides telemetry here.",
182
+ INTERRUPTED: "Run `npx nimblebrain status` to see what is in place, then run the same command again."
183
+ };
184
+
185
+ class CliError extends Error {
186
+ code;
187
+ fix;
188
+ detail;
189
+ constructor(code, message, detail = {}) {
190
+ super(message ?? code);
191
+ this.code = code;
192
+ this.fix = ERRORS[code];
193
+ this.detail = detail;
194
+ }
195
+ }
196
+ function failure(err) {
197
+ return { ...err.detail, ok: false, error: err.code, message: err.message, fix: err.fix };
198
+ }
199
+ function exitCodeFor(result) {
200
+ if (result.ok)
201
+ return 0;
202
+ return result.error === "USAGE" ? 2 : 1;
203
+ }
204
+
205
+ // src/args.ts
206
+ var COMMANDS = [
207
+ "init",
208
+ "doctor",
209
+ "status",
210
+ "key",
211
+ "up",
212
+ "down",
213
+ "logs",
214
+ "update",
215
+ "uninstall",
216
+ "telemetry"
217
+ ];
218
+ var AGENTS = ["claude-code", "cursor", "codex", "none"];
219
+ var DEFAULT_PORT = 27246;
220
+ var options = {
221
+ json: { type: "boolean" },
222
+ yes: { type: "boolean", short: "y" },
223
+ agent: { type: "string" },
224
+ port: { type: "string" },
225
+ home: { type: "string" },
226
+ provider: { type: "string" },
227
+ runtime: { type: "string" },
228
+ telemetry: { type: "string" },
229
+ help: { type: "boolean", short: "h" },
230
+ version: { type: "boolean", short: "v" }
231
+ };
232
+ function parse(argv) {
233
+ const { values, positionals } = parseStrict(argv);
234
+ const json = values.json === true;
235
+ const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
236
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
237
+ throw new CliError("USAGE", `--port must be a port number, not "${values.port}".`);
238
+ }
239
+ let agent;
240
+ if (values.agent !== undefined) {
241
+ if (!AGENTS.includes(values.agent)) {
242
+ throw new CliError("AGENT_UNSUPPORTED", `Unknown agent "${values.agent}".`);
243
+ }
244
+ agent = values.agent;
245
+ }
246
+ const telemetry = telemetryFlag(values.telemetry);
247
+ const flags = {
248
+ json,
249
+ yes: values.yes === true,
250
+ agent,
251
+ port,
252
+ home: values.home,
253
+ provider: values.provider,
254
+ runtime: values.runtime,
255
+ telemetry
256
+ };
257
+ if (values.help)
258
+ return { kind: "help", flags };
259
+ if (values.version)
260
+ return { kind: "version", flags };
261
+ const name = positionals[0] ?? "init";
262
+ if (name === "help")
263
+ return { kind: "help", flags };
264
+ return { kind: "run", command: command(name, positionals), flags, arg: positionals[1] };
265
+ }
266
+ function telemetryFlag(value) {
267
+ if (value === undefined || value === "on" || value === "off")
268
+ return value;
269
+ throw new CliError("USAGE", `--telemetry must be on or off, not "${value}".`);
270
+ }
271
+ function command(name, positionals) {
272
+ const maxArgs = name === "telemetry" ? 2 : 1;
273
+ if (positionals.length > maxArgs)
274
+ throw new CliError("USAGE", `Unexpected argument "${positionals[maxArgs]}".`);
275
+ if (!COMMANDS.includes(name))
276
+ throw new CliError("USAGE", `Unknown command "${name}".`);
277
+ const arg = positionals[1];
278
+ if (name === "telemetry" && arg !== undefined && !["on", "off", "status"].includes(arg))
279
+ throw new CliError("USAGE", `telemetry takes on, off or status, not "${arg}".`);
280
+ return name;
281
+ }
282
+ function parseStrict(argv) {
283
+ try {
284
+ return parseArgs({ args: argv, options, allowPositionals: true, strict: true });
285
+ } catch (err) {
286
+ throw new CliError("USAGE", err instanceof Error ? err.message : String(err));
287
+ }
288
+ }
289
+ function wantsJson(argv) {
290
+ return argv.includes("--json");
291
+ }
292
+
293
+ // src/doctor.ts
294
+ var SUPPORTED_ARCH = ["x86_64", "amd64", "aarch64", "arm64"];
295
+ var MIN_MEMORY = 2 * 1024 ** 3;
296
+ async function doctor(deps, port, portInUseByUs = false) {
297
+ const log = recorder();
298
+ await checkDocker(deps, log);
299
+ const facts = await checkDaemon(deps, log);
300
+ await checkCompose(deps, log);
301
+ checkArch(facts.arch, log);
302
+ checkMemory(facts.memory, log);
303
+ await checkPort(deps, port, portInUseByUs, log);
304
+ return { ok: true, checks: log.checks, arch: facts.arch };
305
+ }
306
+ function recorder() {
307
+ const checks = [];
308
+ return {
309
+ checks,
310
+ pass: (check, detail) => {
311
+ checks.push({ check, ok: true, detail });
312
+ },
313
+ fail: (check, code, detail) => {
314
+ checks.push({ check, ok: false, detail });
315
+ throw new CliError(code, detail, { check, checks });
316
+ }
317
+ };
318
+ }
319
+ async function checkDocker(deps, log) {
320
+ const version = await deps.exec("docker", ["--version"]);
321
+ if (version.missing)
322
+ log.fail("docker", "DOCKER_MISSING", "Docker is not installed.");
323
+ log.pass("docker", version.stdout.trim());
324
+ }
325
+ async function checkDaemon(deps, log) {
326
+ const info = await deps.exec("docker", ["info", "--format", "{{json .}}"]);
327
+ if (info.code !== 0) {
328
+ if (/permission denied/i.test(`${info.stderr}
329
+ ${info.stdout}`)) {
330
+ log.fail("docker-daemon", "DOCKER_PERMISSION", "This user may not use Docker.");
331
+ }
332
+ log.fail("docker-daemon", "DOCKER_NOT_RUNNING", "Docker is installed but not running.");
333
+ }
334
+ log.pass("docker-daemon", "running");
335
+ return parseInfo(info.stdout);
336
+ }
337
+ async function checkCompose(deps, log) {
338
+ const compose = await deps.exec("docker", ["compose", "version", "--short"]);
339
+ const major = Number.parseInt(compose.stdout.trim().replace(/^v/, ""), 10);
340
+ if (compose.code !== 0 || !(major >= 2)) {
341
+ log.fail("compose", "COMPOSE_MISSING", "Docker Compose v2 is not available.");
342
+ }
343
+ log.pass("compose", compose.stdout.trim());
344
+ }
345
+ function checkArch(arch, log) {
346
+ if (!SUPPORTED_ARCH.includes(arch)) {
347
+ log.fail("arch", "ARCH_UNSUPPORTED", `No NimbleBrain image is published for ${arch || "this architecture"}.`);
348
+ }
349
+ log.pass("arch", arch);
350
+ }
351
+ function checkMemory(memory, log) {
352
+ if (memory > 0 && memory < MIN_MEMORY) {
353
+ log.fail("memory", "LOW_MEMORY", `Docker has ${gib(memory)} of memory; NimbleBrain needs 2 GB.`);
354
+ }
355
+ log.pass("memory", memory > 0 ? gib(memory) : "unknown");
356
+ }
357
+ async function checkPort(deps, port, ours, log) {
358
+ if (ours)
359
+ return log.pass("port", `${port} (this install)`);
360
+ if (!await deps.portFree(port))
361
+ log.fail("port", "PORT_IN_USE", `Port ${port} is in use.`);
362
+ log.pass("port", String(port));
363
+ }
364
+ function parseInfo(stdout) {
365
+ try {
366
+ const info = JSON.parse(stdout);
367
+ return {
368
+ arch: typeof info.Architecture === "string" ? info.Architecture : "",
369
+ memory: typeof info.MemTotal === "number" ? info.MemTotal : 0
370
+ };
371
+ } catch {
372
+ return { arch: "", memory: 0 };
373
+ }
374
+ }
375
+ function gib(bytes) {
376
+ return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
377
+ }
378
+
379
+ // src/agents.ts
380
+ import { join as join2 } from "node:path";
381
+ var SERVER_NAME = "nimblebrain";
382
+ async function connectAgent(deps, agent, mcpUrl) {
383
+ if (agent === "none")
384
+ return { connected: null };
385
+ const manual = manualSettings(agent, mcpUrl);
386
+ try {
387
+ if (agent === "claude-code") {
388
+ await deps.exec("claude", ["mcp", "remove", "-s", "user", SERVER_NAME]);
389
+ const res = await deps.exec("claude", [
390
+ "mcp",
391
+ "add",
392
+ "--transport",
393
+ "http",
394
+ "-s",
395
+ "user",
396
+ SERVER_NAME,
397
+ mcpUrl
398
+ ]);
399
+ return res.code === 0 ? { connected: agent } : { connected: null, manual };
400
+ }
401
+ if (agent === "codex") {
402
+ await deps.exec("codex", ["mcp", "remove", SERVER_NAME]);
403
+ const res = await deps.exec("codex", ["mcp", "add", SERVER_NAME, "--url", mcpUrl]);
404
+ return res.code === 0 ? { connected: agent } : { connected: null, manual };
405
+ }
406
+ await connectCursor(deps, mcpUrl);
407
+ return { connected: agent };
408
+ } catch {
409
+ return { connected: null, manual };
410
+ }
411
+ }
412
+ async function connectCursor(deps, mcpUrl) {
413
+ const path = join2(deps.home, ".cursor", "mcp.json");
414
+ const text = await deps.readText(path);
415
+ const config = text ? JSON.parse(text) : {};
416
+ config.mcpServers = { ...config.mcpServers ?? {}, [SERVER_NAME]: { url: mcpUrl } };
417
+ await deps.writeText(path, `${JSON.stringify(config, null, 2)}
418
+ `, 384);
419
+ }
420
+ function manualSettings(agent, mcpUrl) {
421
+ if (agent === "claude-code")
422
+ return `claude mcp add --transport http -s user ${SERVER_NAME} ${mcpUrl}`;
423
+ if (agent === "codex")
424
+ return `codex mcp add ${SERVER_NAME} --url ${mcpUrl}`;
425
+ return `Add to ~/.cursor/mcp.json: {"mcpServers":{"${SERVER_NAME}":{"url":"${mcpUrl}"}}}`;
426
+ }
427
+ async function installSkill(deps, agent) {
428
+ if (agent === "none")
429
+ return null;
430
+ const res = await deps.exec("npx", [
431
+ "-y",
432
+ "skills",
433
+ "add",
434
+ "nimblebraininc/skills",
435
+ "--skill",
436
+ "nimblebrain",
437
+ "--agent",
438
+ agent,
439
+ "-g",
440
+ "-y"
441
+ ], { timeoutMs: 120000 });
442
+ return res.code === 0 ? "nimblebrain" : null;
443
+ }
444
+
445
+ // src/compose.ts
446
+ import { join as join3 } from "node:path";
447
+ var PROJECT = "nimblebrain-local";
448
+ var VOLUME = `${PROJECT}_workspace`;
449
+ var RAW = "https://raw.githubusercontent.com/NimbleBrainInc/nimblebrain";
450
+ async function fetchCompose(deps, tag) {
451
+ const res = await deps.getText(`${RAW}/${tag}/docker-compose.yml`, 15000);
452
+ if (!res)
453
+ throw new CliError("NETWORK", `Could not download the Compose file for ${tag}.`);
454
+ if (res.status === 404) {
455
+ throw new CliError("RUNTIME_UNSUPPORTED", `NimbleBrain ${tag} has no Compose file to install.`);
456
+ }
457
+ if (res.status !== 200) {
458
+ throw new CliError("NETWORK", `Downloading the Compose file for ${tag} answered ${res.status}.`);
459
+ }
460
+ if (!res.body.includes("${NIMBLEBRAIN_TAG") || !res.body.includes("NIMBLEBRAIN_WEB_PORT")) {
461
+ throw new CliError("RUNTIME_UNSUPPORTED", `NimbleBrain ${tag}'s Compose file does not take its image tag and port from .env.`);
462
+ }
463
+ return res.body;
464
+ }
465
+ function keyVars(composeText) {
466
+ return [
467
+ ...new Set([...composeText.matchAll(/\b([A-Z][A-Z0-9_]*_API_KEY)=\$\{\1\b/g)].map((m) => m[1] ?? ""))
468
+ ];
469
+ }
470
+ function asksConsent(composeText) {
471
+ return composeText.includes("NB_TELEMETRY_CONSENT");
472
+ }
473
+ function providers(composeText) {
474
+ return Object.fromEntries(keyVars(composeText).map((v) => [
475
+ v.replace(/_API_KEY$/, "").replace(/_GENERATIVE_AI$/, "").toLowerCase(),
476
+ v
477
+ ]));
478
+ }
479
+ function composeEnv(deps, vars) {
480
+ const env = { ...deps.env };
481
+ for (const v of [
482
+ ...vars,
483
+ "NIMBLEBRAIN_TAG",
484
+ "NIMBLEBRAIN_WEB_PORT",
485
+ "COMPOSE_PROJECT_NAME",
486
+ "NB_TELEMETRY_KEY",
487
+ "NB_TELEMETRY_ID",
488
+ "NB_TELEMETRY_CONSENT"
489
+ ]) {
490
+ delete env[v];
491
+ }
492
+ return env;
493
+ }
494
+ async function compose(deps, home, args, timeoutMs = 120000) {
495
+ const vars = keyVars(await deps.readText(paths(home).compose) ?? "");
496
+ return deps.exec("docker", ["compose", ...args], {
497
+ cwd: home,
498
+ env: composeEnv(deps, vars),
499
+ timeoutMs
500
+ });
501
+ }
502
+ function startError(res) {
503
+ const text = `${res.stderr}
504
+ ${res.stdout}`;
505
+ const last = text.trim().split(`
506
+ `).filter((l) => l.trim()).pop() ?? "Compose failed.";
507
+ if (/no such host|timeout|TLS handshake|connection refused|network is unreachable/i.test(text)) {
508
+ return new CliError("NETWORK", last);
509
+ }
510
+ if (/port is already allocated|address already in use/i.test(text)) {
511
+ return new CliError("PORT_IN_USE", last);
512
+ }
513
+ return new CliError("START_FAILED", last);
514
+ }
515
+ function setEnvLines(text, values) {
516
+ const lines = text === "" ? [] : text.replace(/\n$/, "").split(`
517
+ `);
518
+ const seen = new Set;
519
+ const out = lines.map((line) => {
520
+ const name = line.match(/^([A-Z][A-Z0-9_]*)=/)?.[1];
521
+ if (name && name in values) {
522
+ seen.add(name);
523
+ return `${name}=${values[name]}`;
524
+ }
525
+ return line;
526
+ });
527
+ for (const [name, value] of Object.entries(values))
528
+ if (!seen.has(name))
529
+ out.push(`${name}=${value}`);
530
+ return `${out.join(`
531
+ `)}
532
+ `;
533
+ }
534
+ function hasKey(envText, vars) {
535
+ return vars.some((v) => new RegExp(`^${v}=\\S`, "m").test(envText));
536
+ }
537
+ var paths = (home) => ({
538
+ compose: join3(home, "docker-compose.yml"),
539
+ env: join3(home, ".env"),
540
+ instance: join3(home, "instance.json"),
541
+ install: join3(home, "install.json")
542
+ });
543
+ var INSTANCE_JSON = `${JSON.stringify({ auth: { adapter: "dev" } }, null, 2)}
544
+ `;
545
+
546
+ // src/release.ts
547
+ var REFS_URL = "https://github.com/NimbleBrainInc/nimblebrain.git/info/refs?service=git-upload-pack";
548
+ var VERSION = /^v\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
549
+ var MIN_RUNTIME = "v0.73.0";
550
+ async function runtimeTag(deps, requested) {
551
+ const pinned = requested ?? deps.env.NIMBLEBRAIN_TAG;
552
+ let tag;
553
+ if (pinned) {
554
+ if (!VERSION.test(pinned)) {
555
+ throw new CliError("USAGE", `"${pinned}" is not a runtime release tag like v1.2.3.`);
556
+ }
557
+ tag = pinned;
558
+ } else {
559
+ tag = await newestRuntime(deps);
560
+ }
561
+ if (compareVersions(tag, MIN_RUNTIME) < 0) {
562
+ throw new CliError("RUNTIME_UNSUPPORTED", `This CLI installs NimbleBrain ${MIN_RUNTIME} or newer, not ${tag}.`);
563
+ }
564
+ return tag;
565
+ }
566
+ async function newestRuntime(deps) {
567
+ const res = await deps.getText(REFS_URL, 1e4);
568
+ if (res && res.status !== 200) {
569
+ throw new CliError("NETWORK", `GitHub answered ${res.status} when asked for the newest NimbleBrain release. Pass --runtime vX.Y.Z to skip the lookup.`);
570
+ }
571
+ const names = [...(res?.body ?? "").matchAll(/refs\/tags\/([^\s\0^]+)/g)].map((m) => m[1] ?? "");
572
+ const newest = newestRelease(names);
573
+ if (!newest)
574
+ throw new CliError("NETWORK", "Could not find the newest NimbleBrain release.");
575
+ return newest;
576
+ }
577
+ function newestRelease(tags) {
578
+ const plain = tags.filter((t) => /^v\d+\.\d+\.\d+$/.test(t));
579
+ return plain.sort(compareVersions).pop();
580
+ }
581
+ function compareVersions(a, b) {
582
+ const [coreA = "", preA] = a.replace(/^v/, "").split(/-(.*)/s);
583
+ const [coreB = "", preB] = b.replace(/^v/, "").split(/-(.*)/s);
584
+ const core = compareIdentifiers(coreA.split("."), coreB.split("."));
585
+ if (core !== 0 || !preA && !preB)
586
+ return core;
587
+ if (!preA || !preB)
588
+ return preA ? -1 : 1;
589
+ return compareIdentifiers(preA.split("."), preB.split("."));
590
+ }
591
+ function compareIdentifiers(a, b) {
592
+ for (let i = 0;i < Math.min(a.length, b.length); i++) {
593
+ const order = compareIdentifier(a[i] ?? "", b[i] ?? "");
594
+ if (order !== 0)
595
+ return order;
596
+ }
597
+ return a.length - b.length;
598
+ }
599
+ function compareIdentifier(x, y) {
600
+ if (x === y)
601
+ return 0;
602
+ const xn = /^\d+$/.test(x);
603
+ const yn = /^\d+$/.test(y);
604
+ if (xn && yn)
605
+ return Number(x) - Number(y);
606
+ if (xn !== yn)
607
+ return xn ? -1 : 1;
608
+ return x < y ? -1 : 1;
609
+ }
610
+
611
+ // src/status.ts
612
+ import { join as join5 } from "node:path";
613
+
614
+ // src/telemetry.ts
615
+ import { randomUUID } from "node:crypto";
616
+ import { join as join4 } from "node:path";
617
+ var TELEMETRY_KEY = "phc_qKmpYhdDtcFYZchu3KAKFFmYHG88nfUDPCFqxoAmbS7E";
618
+ var ENDPOINT = "https://us.i.posthog.com/batch/";
619
+ var QUESTION = "Help improve NimbleBrain by sending anonymous usage data? No prompts, content, names or keys are sent.";
620
+ var reportPath = (home) => join4(home, "telemetry-report.jsonl");
621
+ var RELEASED = true;
622
+ function telemetryKey(deps) {
623
+ return deps.env.NIMBLEBRAIN_TELEMETRY_KEY ?? (RELEASED ? TELEMETRY_KEY : "");
624
+ }
625
+ function lockedHere(deps) {
626
+ if (deps.env.DO_NOT_TRACK === "1" || deps.env.NB_TELEMETRY_DISABLED === "1")
627
+ return "do_not_track";
628
+ if (!telemetryKey(deps))
629
+ return "no_destination";
630
+ return;
631
+ }
632
+ function field(state, locked) {
633
+ if (locked)
634
+ return { state: state === "undecided" ? "off" : state, locked };
635
+ if (state !== "undecided")
636
+ return { state };
637
+ return { state, ask: QUESTION, set: "npx nimblebrain telemetry on|off" };
638
+ }
639
+ function recorder2(deps, version, id) {
640
+ const events = [];
641
+ const self = {
642
+ id: id ?? randomUUID(),
643
+ record(event, properties = {}) {
644
+ if (lockedHere(deps))
645
+ return;
646
+ events.push({
647
+ event,
648
+ distinct_id: self.id,
649
+ timestamp: new Date().toISOString(),
650
+ properties: {
651
+ cli_version: version,
652
+ os: process.platform,
653
+ arch: process.arch,
654
+ node_version: process.version,
655
+ ...properties
656
+ }
657
+ });
658
+ },
659
+ async settle(home, consent) {
660
+ try {
661
+ if (consent === "off" || lockedHere(deps)) {
662
+ await deps.remove(reportPath(home));
663
+ return;
664
+ }
665
+ const waiting = await readReport(deps, home);
666
+ const batch = [...waiting, ...events].map((e) => ({ ...e, distinct_id: self.id }));
667
+ if (consent === "on")
668
+ await send(deps, home, batch);
669
+ else if (events.length > 0)
670
+ await deps.writeText(reportPath(home), toLines(batch), 384);
671
+ } catch {} finally {
672
+ events.length = 0;
673
+ }
674
+ }
675
+ };
676
+ return self;
677
+ }
678
+ async function send(deps, home, batch) {
679
+ if (batch.length === 0)
680
+ return;
681
+ const res = await deps.postJson(ENDPOINT, { api_key: telemetryKey(deps), batch });
682
+ if (res && res.status < 300)
683
+ await deps.remove(reportPath(home));
684
+ else
685
+ await deps.writeText(reportPath(home), toLines(batch), 384);
686
+ }
687
+ async function reportId(deps, home) {
688
+ return (await readReport(deps, home))[0]?.distinct_id;
689
+ }
690
+ async function readReport(deps, home) {
691
+ const text = await deps.readText(reportPath(home));
692
+ if (!text)
693
+ return [];
694
+ return text.split(`
695
+ `).filter((l) => l.trim()).flatMap((l) => {
696
+ try {
697
+ return [JSON.parse(l)];
698
+ } catch {
699
+ return [];
700
+ }
701
+ });
702
+ }
703
+ var toLines = (events) => `${events.map((e) => JSON.stringify(e)).join(`
704
+ `)}
705
+ `;
706
+ function parseAnswer(answer) {
707
+ return /^y/i.test(answer.trim()) ? "on" : "off";
708
+ }
709
+ function seededConsent(envText) {
710
+ const seed = envText.match(/^NB_TELEMETRY_CONSENT=(on|off)\s*$/m)?.[1];
711
+ return seed === "on" || seed === "off" ? seed : "undecided";
712
+ }
713
+ async function currentTelemetry(deps, home, url) {
714
+ const here = lockedHere(deps);
715
+ const rt = await runtimeTelemetry(deps, url);
716
+ const state = rt?.consent ?? seededConsent(await deps.readText(join4(home, ".env")) ?? "");
717
+ const lock = here ?? (rt?.locked === "operator" || rt?.locked === "no_destination" ? rt.locked : undefined);
718
+ return field(state, lock);
719
+ }
720
+ async function settleWaiting(deps, home, version) {
721
+ try {
722
+ const id = await reportId(deps, home);
723
+ if (!id)
724
+ return;
725
+ const install = JSON.parse(await deps.readText(join4(home, "install.json")) ?? "{}");
726
+ if (typeof install.port !== "number")
727
+ return;
728
+ const t = await currentTelemetry(deps, home, `http://127.0.0.1:${install.port}`);
729
+ await recorder2(deps, version, id).settle(home, t.locked ? "off" : t.state);
730
+ } catch {}
731
+ }
732
+ function envValues(deps, id, consent, asksFirst) {
733
+ const values = {
734
+ NB_TELEMETRY_ID: id,
735
+ NB_TELEMETRY_KEY: asksFirst ? telemetryKey(deps) : ""
736
+ };
737
+ if (consent !== "undecided")
738
+ values.NB_TELEMETRY_CONSENT = consent;
739
+ return values;
740
+ }
741
+ async function runtimeTelemetry(deps, url) {
742
+ const res = await deps.postJson(`${url}/v1/tools/call`, {
743
+ server: "nb",
744
+ tool: "workspace_info",
745
+ arguments: {}
746
+ });
747
+ const t = res?.body?.structuredContent?.telemetry;
748
+ if (t?.consent !== "on" && t?.consent !== "off" && t?.consent !== "undecided")
749
+ return;
750
+ return { consent: t.consent, locked: typeof t.locked === "string" ? t.locked : undefined };
751
+ }
752
+ async function setRuntimeTelemetry(deps, url, consent) {
753
+ const res = await deps.postJson(`${url}/v1/tools/call`, {
754
+ server: "nb",
755
+ tool: "set_telemetry",
756
+ arguments: { consent }
757
+ });
758
+ const body = res?.body;
759
+ if (!res || res.status >= 300 || body?.isError) {
760
+ throw new CliError("TELEMETRY_LOCKED", body?.content?.[0]?.text ?? "NimbleBrain did not accept the answer.");
761
+ }
762
+ }
763
+ // package.json
764
+ var package_default = {
765
+ name: "nimblebrain",
766
+ version: "0.1.1",
767
+ description: "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
768
+ license: "Apache-2.0",
769
+ type: "module",
770
+ repository: {
771
+ type: "git",
772
+ url: "git+https://github.com/NimbleBrainInc/nimblebrain.git",
773
+ directory: "packages/cli"
774
+ },
775
+ homepage: "https://nimblebrain.ai/developers",
776
+ bin: {
777
+ nimblebrain: "dist/nimblebrain.js"
778
+ },
779
+ files: ["dist"],
780
+ engines: {
781
+ node: ">=20"
782
+ },
783
+ scripts: {
784
+ build: "bun build src/bin.ts --target=node --outfile=dist/nimblebrain.js --banner='#!/usr/bin/env node'",
785
+ "build:release": "bun run build --define NIMBLEBRAIN_CLI_RELEASE=true",
786
+ test: "bun test --no-env-file test/"
787
+ }
788
+ };
789
+
790
+ // src/version.ts
791
+ var VERSION2 = package_default.version;
792
+
793
+ // src/status.ts
794
+ async function readInstall(deps, home) {
795
+ const text = await deps.readText(join5(home, "install.json"));
796
+ if (text === undefined)
797
+ return;
798
+ try {
799
+ const state = JSON.parse(text);
800
+ if (typeof state.version !== "string" || typeof state.port !== "number" || typeof state.project !== "string") {
801
+ return;
802
+ }
803
+ return state;
804
+ } catch {
805
+ return;
806
+ }
807
+ }
808
+ async function status(deps, home) {
809
+ const install = await readInstall(deps, home);
810
+ if (!install)
811
+ throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
812
+ const url = `http://127.0.0.1:${install.port}`;
813
+ const health = await deps.getJson(`${url}/v1/health`);
814
+ const up = health?.status === 200 && health.body?.status === "ok";
815
+ const workspaces = up ? await readWorkspaces(deps, url) : [];
816
+ const vars = keyVars(await deps.readText(join5(home, "docker-compose.yml")) ?? "");
817
+ const modelKey = hasKey(await deps.readText(join5(home, ".env")) ?? "", vars) ? "set" : "missing";
818
+ return {
819
+ ok: true,
820
+ version: install.version,
821
+ cli_version: VERSION2,
822
+ health: up ? "ok" : "down",
823
+ url,
824
+ workspaces,
825
+ agent: { connected: install.agent ?? null, skill: install.skill ?? null },
826
+ model_key: modelKey,
827
+ telemetry: await currentTelemetry(deps, home, url)
828
+ };
829
+ }
830
+ async function readWorkspaces(deps, url) {
831
+ const boot = await deps.getJson(`${url}/v1/bootstrap`);
832
+ if (boot?.status !== 200)
833
+ return [];
834
+ const body = boot.body;
835
+ return (body.workspaces ?? []).filter((w) => typeof w.id === "string" && typeof w.name === "string").map((w) => ({ id: w.id, name: w.name, mcp: `${url}/mcp/${w.id}` }));
836
+ }
837
+
838
+ // src/lifecycle.ts
839
+ var START_TIMEOUT_MS = 15 * 60000;
840
+ var HEALTH_TIMEOUT_MS = 3 * 60000;
841
+ var asks = ({ deps, flags }) => deps.interactive && !flags.yes && !flags.json;
842
+ async function init(ctx) {
843
+ const { deps, flags, home } = ctx;
844
+ if (await readInstall(deps, home))
845
+ return { ...await status(deps, home), already: true };
846
+ const answer = { consent: await chooseConsent(ctx, false) };
847
+ const rec = recorder2(deps, ctx.version, await reportId(deps, home));
848
+ const begun = Date.now();
849
+ rec.record("cli.init_started", { agent: flags.agent ?? null, interactive: deps.interactive });
850
+ try {
851
+ return await install(ctx, answer, rec, begun);
852
+ } catch (err) {
853
+ if (!(err instanceof CliError))
854
+ throw err;
855
+ if (err.code !== "CANCELLED" || answer.consent !== "undecided")
856
+ await settleFailure(rec, home, answer.consent, err);
857
+ throw new CliError(err.code, err.message, {
858
+ ...err.detail,
859
+ telemetry: field(answer.consent, lockedHere(deps))
860
+ });
861
+ }
862
+ }
863
+ async function settleFailure(rec, home, consent, err) {
864
+ if (err.code !== "MODEL_KEY_MISSING") {
865
+ const check = typeof err.detail.check === "string" ? err.detail.check : undefined;
866
+ rec.record(check ? "cli.doctor_failed" : "cli.init_failed", { error: err.code, check });
867
+ }
868
+ await rec.settle(home, consent);
869
+ }
870
+ async function chooseConsent(ctx, ask) {
871
+ if (lockedHere(ctx.deps))
872
+ return "off";
873
+ if (ctx.flags.telemetry)
874
+ return ctx.flags.telemetry;
875
+ if (!ask || !asks(ctx))
876
+ return "undecided";
877
+ return parseAnswer(await ctx.deps.prompt(`${QUESTION} [y/N] `));
878
+ }
879
+ async function install(ctx, answer, rec, begun) {
880
+ const { deps, flags, home } = ctx;
881
+ await doctor(deps, flags.port);
882
+ await guardOurs(deps, home);
883
+ const tag = await runtimeTag(deps, flags.runtime);
884
+ const composeText = await fetchCompose(deps, tag);
885
+ await confirmStart(ctx, tag);
886
+ answer.consent = await chooseConsent(ctx, true);
887
+ const { consent } = answer;
888
+ await writeInstallFiles(deps, home, tag, flags.port, composeText, envValues(deps, rec.id, consent, asksConsent(composeText)));
889
+ if (!hasKey(await deps.readText(paths(home).env) ?? "", keyVars(composeText)) && asks(ctx))
890
+ await enterKey(ctx, false);
891
+ deps.say(`Starting NimbleBrain ${tag}. The first start downloads about 2 GB of images.`);
892
+ await start(deps, home, flags.port);
893
+ const state = {
894
+ version: tag.replace(/^v/, ""),
895
+ port: flags.port,
896
+ project: PROJECT
897
+ };
898
+ await writeState(deps, home, state);
899
+ const manual = await connectChosenAgent(ctx, state);
900
+ if (state.agent)
901
+ rec.record("cli.agent_connected", { agent: state.agent });
902
+ const result = { ...await status(deps, home), manual };
903
+ rec.record("cli.init_completed", {
904
+ duration_ms: Date.now() - begun,
905
+ model_key: result.model_key
906
+ });
907
+ await rec.settle(home, consent);
908
+ if (result.model_key === "missing") {
909
+ throw new CliError("MODEL_KEY_MISSING", "NimbleBrain is running; chat needs a model key.", {
910
+ ...result
911
+ });
912
+ }
913
+ return { ...result };
914
+ }
915
+ async function confirmStart(ctx, tag) {
916
+ if (!asks(ctx))
917
+ return;
918
+ const answer = await ctx.deps.prompt(`Start NimbleBrain ${tag} at http://127.0.0.1:${ctx.flags.port}? [Y/n] `);
919
+ if (/^n/i.test(answer))
920
+ throw new CliError("CANCELLED", "Nothing was installed.");
921
+ }
922
+ async function connectChosenAgent(ctx, state) {
923
+ const { deps, flags, home } = ctx;
924
+ const agent = flags.agent ?? (asks(ctx) ? await chooseAgent(deps) : undefined);
925
+ if (!agent || agent === "none")
926
+ return;
927
+ const first = (await status(deps, home)).workspaces[0];
928
+ if (!first)
929
+ return;
930
+ const conn = await connectAgent(deps, agent, first.mcp);
931
+ if (conn.connected) {
932
+ state.agent = conn.connected;
933
+ state.skill = await installSkill(deps, conn.connected) ?? undefined;
934
+ await writeState(deps, home, state);
935
+ }
936
+ return conn.manual;
937
+ }
938
+ async function up(ctx) {
939
+ const install = await requireInstall(ctx);
940
+ await start(ctx.deps, ctx.home, install.port);
941
+ return { ...await status(ctx.deps, ctx.home) };
942
+ }
943
+ async function down(ctx) {
944
+ await requireInstall(ctx);
945
+ const res = await compose(ctx.deps, ctx.home, ["down"]);
946
+ if (res.code !== 0)
947
+ throw startError(res);
948
+ return { ok: true, health: "down" };
949
+ }
950
+ async function logs(ctx) {
951
+ await requireInstall(ctx);
952
+ const res = await compose(ctx.deps, ctx.home, [
953
+ "logs",
954
+ "--no-color",
955
+ "--tail",
956
+ "100",
957
+ "platform"
958
+ ]);
959
+ if (res.code !== 0)
960
+ throw startError(res);
961
+ return { ok: true, lines: res.stdout.split(`
962
+ `).filter((l) => l.trim()) };
963
+ }
964
+ async function update(ctx) {
965
+ const { deps, home } = ctx;
966
+ const install = await requireInstall(ctx);
967
+ const tag = await runtimeTag(deps, ctx.flags.runtime);
968
+ const from = `v${install.version}`;
969
+ const order = compareVersions(tag, from);
970
+ if (order === 0)
971
+ return { ...await status(deps, home), already: true };
972
+ if (order < 0) {
973
+ throw new CliError("USAGE", `${tag} is older than the installed ${from}; NimbleBrain does not move backwards.`);
974
+ }
975
+ const composeText = await fetchCompose(deps, tag);
976
+ await writeInstallFiles(deps, home, tag, install.port, composeText);
977
+ deps.say(`Updating NimbleBrain ${from} → ${tag}.`);
978
+ const pull = await compose(deps, home, ["pull"], START_TIMEOUT_MS);
979
+ if (pull.code !== 0)
980
+ throw startError(pull);
981
+ await start(deps, home, install.port);
982
+ await writeState(deps, home, { ...install, version: tag.replace(/^v/, "") });
983
+ return { ...await status(deps, home), from };
984
+ }
985
+ async function uninstall(ctx) {
986
+ const { deps, flags, home } = ctx;
987
+ const install = await requireInstall(ctx);
988
+ if (!flags.yes) {
989
+ if (!deps.interactive || flags.json) {
990
+ throw new CliError("CANCELLED", "Removing deletes every conversation; pass --yes to confirm.");
991
+ }
992
+ const answer = await deps.prompt("Remove NimbleBrain and every conversation in it? [y/N] ");
993
+ if (!/^y/i.test(answer))
994
+ throw new CliError("CANCELLED", "Nothing was removed.");
995
+ }
996
+ const res = await compose(deps, home, ["down", "-v", "--rmi", "all"], START_TIMEOUT_MS);
997
+ if (res.code !== 0)
998
+ throw startError(res);
999
+ if (install.agent === "claude-code")
1000
+ await deps.exec("claude", ["mcp", "remove", "-s", "user", SERVER_NAME]);
1001
+ if (install.agent === "codex")
1002
+ await deps.exec("codex", ["mcp", "remove", SERVER_NAME]);
1003
+ for (const file of [...Object.values(paths(home)), reportPath(home)])
1004
+ await deps.remove(file);
1005
+ await deps.remove(home);
1006
+ return { ok: true, removed: true };
1007
+ }
1008
+ async function telemetry(ctx) {
1009
+ const { deps, home } = ctx;
1010
+ const install = await requireInstall(ctx);
1011
+ const url = `http://127.0.0.1:${install.port}`;
1012
+ if (ctx.arg !== "on" && ctx.arg !== "off") {
1013
+ return { ok: true, telemetry: (await status(deps, home)).telemetry };
1014
+ }
1015
+ const here = lockedHere(deps);
1016
+ if (here) {
1017
+ 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.");
1018
+ }
1019
+ const rt = await runtimeTelemetry(deps, url);
1020
+ if (!rt)
1021
+ throw new CliError("NOT_RUNNING", "NimbleBrain is not running, so it cannot record the answer.");
1022
+ await setRuntimeTelemetry(deps, url, ctx.arg);
1023
+ const p = paths(home);
1024
+ await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", { NB_TELEMETRY_CONSENT: ctx.arg }), 384);
1025
+ const rec = recorder2(deps, ctx.version, await reportId(deps, home));
1026
+ await rec.settle(home, ctx.arg);
1027
+ return { ok: true, telemetry: field(ctx.arg) };
1028
+ }
1029
+ async function key(ctx) {
1030
+ if (!ctx.deps.interactive) {
1031
+ throw new CliError("NEEDS_TERMINAL", "`key` asks for a model key at a hidden prompt.");
1032
+ }
1033
+ await requireInstall(ctx);
1034
+ return enterKey(ctx, true);
1035
+ }
1036
+ async function enterKey(ctx, restart) {
1037
+ const { deps, flags, home } = ctx;
1038
+ const offered = providers(await deps.readText(paths(home).compose) ?? "");
1039
+ const names = Object.keys(offered);
1040
+ let provider = flags.provider;
1041
+ deps.say("NimbleBrain's own agents run on a model key you give it, billed by that provider.");
1042
+ if (!provider) {
1043
+ const answer = await deps.prompt(`Model provider (${names.join(", ")}) [anthropic]: `);
1044
+ provider = answer || "anthropic";
1045
+ }
1046
+ const variable = offered[provider];
1047
+ if (!variable)
1048
+ throw new CliError("USAGE", `Unknown provider "${provider}"; one of ${names.join(", ")}.`);
1049
+ const value = await deps.prompt(`${variable} (nothing is shown as you type): `, { hidden: true });
1050
+ if (!value)
1051
+ throw new CliError("CANCELLED", "No key was entered.");
1052
+ const p = paths(home);
1053
+ await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", { [variable]: value }), 384);
1054
+ if (restart) {
1055
+ const install = await readInstall(deps, home);
1056
+ await start(deps, home, install?.port ?? flags.port);
1057
+ }
1058
+ return { ok: true, provider, model_key: "set" };
1059
+ }
1060
+ async function chooseAgent(deps) {
1061
+ deps.say("A coding agent you connect can use NimbleBrain's tools. NimbleBrain's own agents still run on the model key above.");
1062
+ const answer = await deps.prompt(`Connect a coding agent? (${AGENTS.join(", ")}) [none]: `);
1063
+ return AGENTS.includes(answer) ? answer : "none";
1064
+ }
1065
+ async function start(deps, home, port) {
1066
+ const res = await compose(deps, home, ["up", "-d", "--no-build"], START_TIMEOUT_MS);
1067
+ if (res.code !== 0)
1068
+ throw startError(res);
1069
+ await waitHealthy(deps, port);
1070
+ }
1071
+ async function waitHealthy(deps, port) {
1072
+ const url = `http://127.0.0.1:${port}/v1/health`;
1073
+ for (let waited = 0;waited <= HEALTH_TIMEOUT_MS; waited += 2000) {
1074
+ const res = await deps.getJson(url);
1075
+ if (res?.status === 200)
1076
+ return;
1077
+ await deps.sleep(2000);
1078
+ }
1079
+ throw new CliError("HEALTH_TIMEOUT", "NimbleBrain did not report healthy within 3 minutes.");
1080
+ }
1081
+ async function writeInstallFiles(deps, home, tag, port, composeText, extra = {}) {
1082
+ const p = paths(home);
1083
+ await deps.writeText(p.compose, composeText);
1084
+ if (await deps.readText(p.instance) === undefined)
1085
+ await deps.writeText(p.instance, INSTANCE_JSON);
1086
+ const env = setEnvLines(await deps.readText(p.env) ?? "", {
1087
+ COMPOSE_PROJECT_NAME: PROJECT,
1088
+ NIMBLEBRAIN_TAG: tag,
1089
+ NIMBLEBRAIN_WEB_PORT: String(port),
1090
+ ...extra
1091
+ });
1092
+ await deps.writeText(p.env, env, 384);
1093
+ }
1094
+ async function writeState(deps, home, state) {
1095
+ await deps.writeText(paths(home).install, `${JSON.stringify(state, null, 2)}
1096
+ `);
1097
+ }
1098
+ async function requireInstall({ deps, home }) {
1099
+ const install = await readInstall(deps, home);
1100
+ if (!install)
1101
+ throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1102
+ return install;
1103
+ }
1104
+ async function guardOurs(deps, home) {
1105
+ const env = await deps.readText(paths(home).env);
1106
+ if (env?.includes(`COMPOSE_PROJECT_NAME=${PROJECT}`))
1107
+ return;
1108
+ for (const file of Object.values(paths(home))) {
1109
+ if (await deps.readText(file) !== undefined) {
1110
+ throw new CliError("NOT_OURS", `${file} already exists and this CLI did not write it.`);
1111
+ }
1112
+ }
1113
+ const projects = await deps.exec("docker", ["compose", "ls", "-a", "--format", "json"]);
1114
+ const taken = projects.code === 0 && /"Name"\s*:\s*"nimblebrain-local"/.test(projects.stdout);
1115
+ const volumes = await deps.exec("docker", ["volume", "ls", "-q", "--filter", `name=^${VOLUME}$`]);
1116
+ if (taken || volumes.stdout.trim() !== "") {
1117
+ throw new CliError("NOT_OURS", `Docker already has a "${PROJECT}" project or volume that this install did not make.`);
1118
+ }
1119
+ }
1120
+
1121
+ // src/main.ts
1122
+ var HELP = `nimblebrain ${VERSION2}: install and run NimbleBrain on this machine
1123
+
1124
+ Usage: npx nimblebrain [command] [flags]
1125
+
1126
+ Commands:
1127
+ init Check this machine, start NimbleBrain, connect your coding agent (default)
1128
+ doctor Check Docker, Compose, architecture, memory and the port; installs nothing
1129
+ status Version, health, URL and each workspace's MCP URL
1130
+ key Enter the model key at a hidden prompt
1131
+ telemetry [on|off|status] Whether this install sends anonymous usage data
1132
+ up, down Start or stop NimbleBrain; data survives down
1133
+ logs Recent runtime log lines
1134
+ update Move to the newest release, keeping data
1135
+ uninstall Remove NimbleBrain and its data
1136
+
1137
+ Flags:
1138
+ --json One JSON object on stdout
1139
+ --yes, -y Take every default; implied when no terminal is attached
1140
+ --agent <name> claude-code, cursor, codex or none
1141
+ --port <n> Local port (default 27246)
1142
+ --home <dir> Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME)
1143
+ --provider <name> The model provider for key (default anthropic)
1144
+ --runtime <tag> The NimbleBrain release to install or update to (default the newest)
1145
+ --telemetry <on|off> The person's answer to sending anonymous usage data; without it, init asks or leaves it undecided
1146
+ --help, --version
1147
+ `;
1148
+ async function run(argv, deps) {
1149
+ const json = wantsJson(argv);
1150
+ let parsed;
1151
+ try {
1152
+ parsed = parse(argv);
1153
+ } catch (err) {
1154
+ return render(toFailure(err), json);
1155
+ }
1156
+ if (parsed.kind === "help")
1157
+ return { stdout: HELP, code: 0 };
1158
+ if (parsed.kind === "version") {
1159
+ return parsed.flags.json ? render({ ok: true, version: VERSION2 }, true) : { stdout: `${VERSION2}
1160
+ `, code: 0 };
1161
+ }
1162
+ const { command, flags, arg } = parsed;
1163
+ const home = installHome(deps, flags.home);
1164
+ let result;
1165
+ try {
1166
+ switch (command) {
1167
+ case "doctor": {
1168
+ const install = await readInstall(deps, home);
1169
+ const ours = install !== undefined && install.port === flags.port && await isHealthy(deps, flags.port);
1170
+ result = { ...await doctor(deps, flags.port, ours) };
1171
+ break;
1172
+ }
1173
+ case "status":
1174
+ result = { ...await status(deps, home) };
1175
+ break;
1176
+ default: {
1177
+ const ctx = { deps, flags, home, version: VERSION2, arg };
1178
+ const commands = { init, up, down, logs, update, uninstall, key, telemetry };
1179
+ result = await commands[command](ctx);
1180
+ }
1181
+ }
1182
+ } catch (err) {
1183
+ result = toFailure(err);
1184
+ }
1185
+ if (!["init", "telemetry", "uninstall", "doctor"].includes(command)) {
1186
+ await settleWaiting(deps, home, VERSION2);
1187
+ }
1188
+ return render(result, flags.json, command);
1189
+ }
1190
+ async function isHealthy(deps, port) {
1191
+ const res = await deps.getJson(`http://127.0.0.1:${port}/v1/health`);
1192
+ return res?.status === 200;
1193
+ }
1194
+ function toFailure(err) {
1195
+ if (err instanceof CliError)
1196
+ return failure(err);
1197
+ return failure(new CliError("USAGE", err instanceof Error ? err.message : String(err)));
1198
+ }
1199
+ function render(result, json, command) {
1200
+ const code = exitCodeFor(result);
1201
+ if (json)
1202
+ return { stdout: `${JSON.stringify(result)}
1203
+ `, code };
1204
+ if (!result.ok)
1205
+ return { stdout: `error: ${result.message}
1206
+ fix: ${result.fix}
1207
+ `, code };
1208
+ const lines = isStatus(result) ? statusLines(result, command) : genericLines(result);
1209
+ return { stdout: `${lines.join(`
1210
+ `)}
1211
+ `, code };
1212
+ }
1213
+ function isStatus(result) {
1214
+ return "health" in result && "url" in result && "workspaces" in result;
1215
+ }
1216
+ var AGENT_NAMES = {
1217
+ "claude-code": "Claude Code",
1218
+ cursor: "Cursor",
1219
+ codex: "Codex"
1220
+ };
1221
+ function statusLines(r, command) {
1222
+ const lines = [
1223
+ ...changeLines(r),
1224
+ ` NimbleBrain ${r.version.startsWith("v") ? r.version : `v${r.version}`}: ${r.health === "ok" ? "running" : "stopped"} at ${r.url}`,
1225
+ ...r.workspaces.map((w) => ` workspace ${w.name}: ${w.mcp}`),
1226
+ ` model key: ${r.model_key === "set" ? "set (NimbleBrain's own agents use it)" : "missing (run npx nimblebrain key)"}`
1227
+ ];
1228
+ const agent = r.agent.connected;
1229
+ if (agent) {
1230
+ const name = AGENT_NAMES[agent] ?? agent;
1231
+ lines.push(` ${name} can use NimbleBrain's tools (it loads them when its next session starts)`);
1232
+ if (!r.agent.skill)
1233
+ lines.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain`);
1234
+ } else if (r.manual) {
1235
+ lines.push(` agent: not connected; add it by hand: ${r.manual}`);
1236
+ }
1237
+ lines.push(telemetryLine(r.telemetry));
1238
+ lines.push(` CLI ${r.cli_version}`);
1239
+ if (command === "init" && !r.already && r.health === "ok") {
1240
+ const ask = agent ? `, or ask ${AGENT_NAMES[agent] ?? agent} what NimbleBrain can do` : "";
1241
+ lines.push("", `Next: open ${r.url}${ask}. Stop it with npx nimblebrain down.`);
1242
+ }
1243
+ return lines;
1244
+ }
1245
+ function changeLines(r) {
1246
+ if (r.already)
1247
+ return [" already installed"];
1248
+ return r.from ? [` updated from ${r.from}`] : [];
1249
+ }
1250
+ function telemetryLine(t) {
1251
+ const how = t.locked ? ` (${t.locked})` : t.set ? ` (answer with ${t.set})` : "";
1252
+ return ` telemetry: ${t.state}${how}`;
1253
+ }
1254
+ function genericLines(result) {
1255
+ return Object.entries(result).filter(([key]) => key !== "ok").flatMap(([key, value]) => field2(key, value));
1256
+ }
1257
+ function field2(key, value) {
1258
+ if (value === undefined || value === null)
1259
+ return [];
1260
+ if (key === "checks" && Array.isArray(value)) {
1261
+ return value.map((c) => ` ${c.ok ? "✓" : "✗"} ${c.check}: ${c.detail}`);
1262
+ }
1263
+ if (typeof value === "object" && !Array.isArray(value)) {
1264
+ return Object.entries(value).flatMap(([k, v]) => field2(`${key} ${k}`, v));
1265
+ }
1266
+ return [` ${key}: ${Array.isArray(value) ? value.join(", ") : String(value)}`];
1267
+ }
1268
+ function interrupted(argv, exitCode) {
1269
+ const err = new CliError("INTERRUPTED", `The CLI stopped before it answered (exit code ${exitCode}).`, { exit_code: exitCode });
1270
+ return render(failure(err), wantsJson(argv));
1271
+ }
1272
+
1273
+ // src/bin.ts
1274
+ var argv = process.argv.slice(2);
1275
+ var answered = false;
1276
+ process.on("exit", (code) => {
1277
+ if (answered)
1278
+ return;
1279
+ const out = interrupted(argv, code);
1280
+ writeSync(1, out.stdout);
1281
+ writeSync(2, `nimblebrain: stopped before answering (exit code ${code})
1282
+ `);
1283
+ process.exitCode = out.code;
1284
+ });
1285
+ for (const [signal, n] of [
1286
+ ["SIGINT", 2],
1287
+ ["SIGTERM", 15],
1288
+ ["SIGHUP", 1]
1289
+ ]) {
1290
+ process.on(signal, () => process.exit(128 + n));
1291
+ }
1292
+ var { stdout, code } = await run(argv, realDeps());
1293
+ writeSync(1, stdout);
1294
+ answered = true;
1295
+ process.exitCode = code;
package/package.json CHANGED
@@ -1,16 +1,25 @@
1
1
  {
2
2
  "name": "nimblebrain",
3
- "version": "0.0.1",
4
- "description": "NimbleBrain SDK (coming soon)",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
3
+ "version": "0.1.1",
4
+ "description": "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/NimbleBrainInc/nimblebrain.git",
10
+ "directory": "packages/cli"
11
+ },
12
+ "homepage": "https://nimblebrain.ai/developers",
13
+ "bin": {
14
+ "nimblebrain": "dist/nimblebrain.js"
15
+ },
7
16
  "files": ["dist"],
8
- "scripts": {
9
- "build": "tsc"
17
+ "engines": {
18
+ "node": ">=20"
10
19
  },
11
- "license": "MIT",
12
- "keywords": ["nimblebrain", "ai", "mcp"],
13
- "devDependencies": {
14
- "typescript": "^5.7.0"
20
+ "scripts": {
21
+ "build": "bun build src/bin.ts --target=node --outfile=dist/nimblebrain.js --banner='#!/usr/bin/env node'",
22
+ "build:release": "bun run build --define NIMBLEBRAIN_CLI_RELEASE=true",
23
+ "test": "bun test --no-env-file test/"
15
24
  }
16
25
  }
package/dist/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const VERSION = "0.0.1";
package/dist/index.js DELETED
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VERSION = void 0;
4
- exports.VERSION = "0.0.1";