captain-tool 0.0.119 → 0.0.121

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 CHANGED
@@ -66,23 +66,44 @@ What does not carry over:
66
66
 
67
67
  ---
68
68
 
69
- ## Installation
69
+ ## Install
70
+
71
+ One command installs captain-tool and connects it to your AI client(s):
70
72
 
71
73
  ```bash
72
- npm install -g captain-tool
74
+ npx captain-tool@latest setup
73
75
  ```
74
76
 
75
- ---
77
+ It sets up Claude Code: it asks "Set up Claude Code? [Y/n]", whether to auto-approve Captain's
78
+ tools, and whether to sign in now, then installs captain-tool globally (so Claude Code keeps a
79
+ path to it that npm does not clean up), registers it, turns on skill proof and adds the
80
+ `/captain-status` command. It ends with "Setup complete. Open Claude Code and say hi to start."
81
+ If the global install needs permissions you don't have, it stops, registers nothing, and prints
82
+ the `npm install -g` command to run yourself. Other clients (Claude Desktop, VS Code, Cursor,
83
+ Windsurf, Codex) are set up by hand: see Manual setup below. `--uninstall` still removes
84
+ Captain from every client an earlier setup configured.
85
+
86
+ In your first chat, Captain checks your status (any message, "Check Captain status and get me
87
+ set up", or `/captain-status`), signs you in, picks your workspace, and offers once to turn how
88
+ you work in Claude Code into Captain flows.
76
89
 
77
- ## Setup (recommended)
90
+ ### Already ran `npm install -g captain-tool`?
78
91
 
79
- Run the interactive setup wizard to automatically configure your AI client(s):
92
+ A global install registers captain with Claude Code on its own, if Claude Code is installed,
93
+ and prints a line saying so. Check with:
80
94
 
81
95
  ```bash
82
- captain-tool setup
96
+ claude mcp list # shows: captain: …/captain-tool
83
97
  ```
84
98
 
85
- The wizard will detect your platform, find the binary, and write the correct MCP config for whichever client(s) you select. Supports all 5 clients above in one step.
99
+ Run `captain-tool setup` for everything else: auto-approval, skill proof, other clients, or
100
+ when the install didn't register (no Claude Code yet, a different server already named
101
+ `captain`, or a package manager or npm setting that skips install scripts, such as
102
+ `ignore-scripts`). After a local (project) or CI install, `captain-tool` isn't on your PATH:
103
+ run `npx captain-tool@latest setup` instead. Registration at install time writes only the server entry,
104
+ and only in `~/.claude.json`; it never changes your permissions. If your `captain` entry
105
+ pointed at a local build of captain-tool, a global install points it back at the installed
106
+ binary.
86
107
 
87
108
  ---
88
109
 
@@ -119,11 +140,17 @@ Restart Claude Desktop to activate.
119
140
 
120
141
  ### Claude Code (CLI)
121
142
 
143
+ **macOS / Linux:**
144
+ ```bash
145
+ claude mcp add -s user captain -- captain-tool
146
+ ```
147
+
148
+ **Windows** (requires `cmd /c` wrapper so the shell can resolve the `.cmd` shim):
122
149
  ```bash
123
- claude mcp add captain -- cmd /c captain-tool
150
+ claude mcp add -s user captain -- cmd /c captain-tool
124
151
  ```
125
152
 
126
- > Registers under the short name `captain` (tool prefix `mcp__captain__`). If you previously added it as `captain-tool`, run `claude mcp remove captain-tool` to avoid a duplicate registration.
153
+ > `-s user` registers it for every folder; without it Claude Code registers it for the current folder only. Registers under the short name `captain` (tool prefix `mcp__captain__`). If you previously added it as `captain-tool`, remove that entry to avoid a duplicate registration: `captain-tool setup` removes it from every folder at once, or run `claude mcp remove captain-tool` in each folder you added it in (a folder-scoped entry can only be removed from its own folder).
127
154
 
128
155
  **Auto-approve captain tools (recommended).** Registration alone does not grant permissions — Claude Code will prompt "Allow captain to …?" on every tool call. The setup wizard (`npx captain-tool setup`) offers to fix this for you; to do it by hand, add one allow rule to `~/.claude/settings.json`:
129
156
 
@@ -135,7 +162,7 @@ claude mcp add captain -- cmd /c captain-tool
135
162
  }
136
163
  ```
137
164
 
138
- `mcp__captain` (no tool suffix) approves every tool from this server. Your own `deny` and `ask` rules always take precedence over this allow rule. Note the rule prefix is the *registration key*: if you registered under a different name, the rule must match it. Old `mcp__captain-tool__*` rules from before the rename match nothing — the wizard sweeps them out of `~/.claude/settings.json`; per-project `.claude/settings.local.json` files can hold more, so clean those by hand if Claude Code still prompts. For scripted installs, `npx captain-tool setup --yes` configures all clients and enables auto-approval without prompting.
165
+ `mcp__captain` (no tool suffix) approves every tool from this server. Your own `deny` and `ask` rules always take precedence over this allow rule. Note the rule prefix is the *registration key*: if you registered under a different name, the rule must match it. Old `mcp__captain-tool__*` rules from before the rename match nothing — the wizard sweeps them out of `~/.claude/settings.json`; per-project `.claude/settings.local.json` files can hold more, so clean those by hand if Claude Code still prompts. For scripted installs, `npx captain-tool setup --yes` sets up Claude Code and enables auto-approval without prompting.
139
166
 
140
167
  ### VS Code + Copilot
141
168
 
@@ -203,11 +230,19 @@ On Windows, use `command = "cmd"` and `args = ["/c", "captain-tool"]`.
203
230
 
204
231
  ## First use
205
232
 
206
- Once connected, ask your AI agent:
233
+ Setup offers to sign you in as its last step: your browser opens, you approve, and you are done.
234
+ To sign in later, or from a script that ran setup with `--yes`, run:
235
+
236
+ ```
237
+ captain-tool login
238
+ ```
239
+
240
+ (`--no-browser` prints the sign-in URL instead of opening it.) Or skip it: your agent asks you to
241
+ sign in the first time you use Captain. Once connected, ask your AI agent:
207
242
 
208
243
  > "Check captain status and get me set up."
209
244
 
210
- It will walk you through logging in and selecting your workspace. After that, you can ask things like:
245
+ It will walk you through anything left, such as signing in and selecting your workspace. After that, you can ask things like:
211
246
 
212
247
  ```
213
248
  Show me all my pipelines.
package/bin/captain-tool CHANGED
@@ -77,6 +77,18 @@ if (process.argv[2] === 'setup') {
77
77
  console.error('Unexpected error:', err);
78
78
  process.exit(1);
79
79
  });
80
+ } else if (process.argv.length === 2 && process.stdin.isTTY) {
81
+ // A person typed `captain-tool` at a terminal. With no arguments the binary is the stdio
82
+ // MCP server an AI client starts, and it would sit waiting on their keyboard. An MCP
83
+ // client always pipes stdin, so this never fires for one. stderr: stdout is the protocol.
84
+ process.stderr.write(
85
+ 'captain-tool is the MCP server your AI client starts; there is nothing to run here.\n' +
86
+ 'To connect it to Claude Code or another client, run:\n' +
87
+ ' npx captain-tool@latest setup\n'
88
+ );
89
+ // No process.exit(): stderr writes can be asynchronous (Windows terminals, pipes), and an
90
+ // exit would drop the hint. Nothing else is pending, so the process ends on its own.
91
+ process.exitCode = 0;
80
92
  } else {
81
93
  const binary = findBinary();
82
94
 
@@ -19,6 +19,7 @@
19
19
  const fs = require('fs');
20
20
  const path = require('path');
21
21
  const os = require('os');
22
+ const crypto = require('crypto');
22
23
  const readline = require('readline');
23
24
 
24
25
  // ── Constants ─────────────────────────────────────────────────────────────────
@@ -61,10 +62,18 @@ const PLATFORMS = [
61
62
  { pkg: '@captain-tool/captain-tool-linux-x64', bin: 'captain-tool' },
62
63
  ];
63
64
 
64
- function findBinary() {
65
+ /**
66
+ * The platform binary's absolute path, or null. `fromDir` resolves the platform package from
67
+ * another install of captain-tool (the global one, after setup installs it from npx) instead
68
+ * of this file's own.
69
+ */
70
+ function findBinary(fromDir) {
65
71
  for (const { pkg, bin } of PLATFORMS) {
66
72
  try {
67
- const pkgJsonPath = require.resolve(`${pkg}/package.json`);
73
+ const pkgJsonPath = require.resolve(
74
+ `${pkg}/package.json`,
75
+ fromDir ? { paths: [fromDir] } : undefined
76
+ );
68
77
  const binPath = path.join(path.dirname(pkgJsonPath), 'bin', bin);
69
78
  fs.accessSync(binPath, fs.constants.X_OK);
70
79
  return binPath;
@@ -216,27 +225,6 @@ function buildEntryFormatB(binaryPath) {
216
225
  };
217
226
  }
218
227
 
219
- // ── Atomic JSON file writer ───────────────────────────────────────────────────
220
-
221
- /**
222
- * Atomically write `data` as formatted JSON to `filePath`.
223
- *
224
- * WHY atomic?
225
- * Config files are read by GUI applications. If we write directly and the
226
- * process crashes mid-write, the app sees a truncated/corrupt file and may
227
- * fail to start. Writing to a .tmp file and then renaming is atomic on all
228
- * supported OS (POSIX rename(2) and Windows MoveFileExW with MOVEFILE_REPLACE_EXISTING
229
- * are both atomic at the filesystem level).
230
- */
231
- function atomicWriteJson(filePath, data) {
232
- const tmpPath = filePath + '.tmp';
233
- const json = JSON.stringify(data, null, 2) + '\n';
234
- // Ensure the parent directory exists (e.g. ~/.cursor/ may not exist yet).
235
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
236
- fs.writeFileSync(tmpPath, json, 'utf8');
237
- fs.renameSync(tmpPath, filePath);
238
- }
239
-
240
228
  // ── Config read helper ────────────────────────────────────────────────────────
241
229
 
242
230
  /**
@@ -244,19 +232,114 @@ function atomicWriteJson(filePath, data) {
244
232
  * does not exist yet (first-time setup).
245
233
  */
246
234
  function readJsonConfig(filePath) {
235
+ const raw = readRaw(filePath);
236
+ // A file that doesn't exist yet is fine: first-time setup creates it.
237
+ // Anything else (permission denied, malformed JSON) throws.
238
+ return raw === null ? {} : JSON.parse(raw);
239
+ }
240
+
241
+ /** The file's text, or null when it does not exist. */
242
+ function readRaw(filePath) {
247
243
  try {
248
- const raw = fs.readFileSync(filePath, 'utf8');
249
- return JSON.parse(raw);
244
+ return fs.readFileSync(filePath, 'utf8');
250
245
  } catch (err) {
251
- if (err.code === 'ENOENT') {
252
- // File doesn't exist yet — that's fine, we'll create it.
253
- return {};
254
- }
255
- // Unexpected error (e.g. permission denied, malformed JSON).
246
+ if (err.code === 'ENOENT') return null;
256
247
  throw err;
257
248
  }
258
249
  }
259
250
 
251
+ /** True for `{…}`: not an array, not null. */
252
+ function isPlainObject(v) {
253
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
254
+ }
255
+
256
+ /**
257
+ * Read a JSON config, let `mutate` change it in place, and write it back atomically, the one
258
+ * read-modify-write every config change here goes through.
259
+ *
260
+ * WHY atomic: config files are read by GUI applications. A process that crashes mid-write
261
+ * would leave a truncated file the app may fail to start with. Writing a .tmp file and
262
+ * renaming it over the config is atomic on every supported OS (POSIX rename(2), Windows
263
+ * MoveFileExW with MOVEFILE_REPLACE_EXISTING).
264
+ *
265
+ * WHY the re-read before the rename: the agent may be running and rewriting the same file
266
+ * (Claude Code rewrites ~/.claude.json while it runs; an install can happen mid-session).
267
+ * Renaming our copy over a file that changed since we read it would drop that change. So
268
+ * the new content is written to a temp file first, the file is read again, and only an
269
+ * unchanged file is replaced; a changed one is merged again from the fresh copy, once, and a
270
+ * file that changes again is reported, not overwritten. A change landing between that
271
+ * re-read and the rename is still possible; the window is one rename.
272
+ *
273
+ * A symlinked config (a dotfiles repo) is written through to its target, so the link stays a
274
+ * link. A config whose JSON is not an object (`[]`, `null`, a string) is refused: setting a
275
+ * key on it would silently write nothing.
276
+ *
277
+ * `mutate` returns false to write nothing; a mutation that leaves the content equal is not
278
+ * written either, so a re-run never churns the file's bytes or mtime. Returns true when the
279
+ * file was written. `hooks.beforeCommit` is a test seam that runs between the temp write and
280
+ * the re-read.
281
+ */
282
+ function updateJsonFile(filePath, mutate, hooks = {}) {
283
+ const target = resolveLink(filePath);
284
+ for (let attempt = 0; attempt < 2; attempt += 1) {
285
+ const raw = readRaw(target);
286
+ const data = raw === null ? {} : JSON.parse(raw);
287
+ if (!isPlainObject(data)) {
288
+ throw new Error(`${filePath} does not hold a JSON object, so captain-tool left it alone.`);
289
+ }
290
+ const before = JSON.stringify(data);
291
+ if (mutate(data) === false || JSON.stringify(data) === before) return false;
292
+
293
+ // A temp file of this call's own: two processes updating the same config must not
294
+ // write, and then rename, each other's prepared content.
295
+ const tmpPath = `${target}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
296
+ fs.mkdirSync(path.dirname(target), { recursive: true });
297
+ // The replacement keeps the config's permissions (~/.claude.json can be 0600 and holds
298
+ // account state); a new file starts private. `mode` applies only when the file is
299
+ // created, and umask can only narrow it, so chmod sets it exactly.
300
+ const mode = existingMode(target) ?? 0o600;
301
+ // Create it exclusively first; from then on it is ours, and every exit path, a failed
302
+ // write (a full disk) included, removes it. A failed create leaves nothing of ours.
303
+ const fd = fs.openSync(tmpPath, 'wx', mode);
304
+ try {
305
+ try {
306
+ fs.writeFileSync(fd, JSON.stringify(data, null, 2) + '\n', 'utf8');
307
+ } finally {
308
+ fs.closeSync(fd);
309
+ }
310
+ fs.chmodSync(tmpPath, mode);
311
+ if (hooks.beforeCommit) hooks.beforeCommit(attempt);
312
+ if (readRaw(target) !== raw) continue;
313
+ fs.renameSync(tmpPath, target);
314
+ return true;
315
+ } finally {
316
+ fs.rmSync(tmpPath, { force: true }); // gone already after a rename
317
+ }
318
+ }
319
+ throw new Error(
320
+ `${filePath} kept changing while captain-tool was updating it, so nothing was written. ` +
321
+ 'Run `captain-tool setup` again.'
322
+ );
323
+ }
324
+
325
+ /** The permission bits of an existing file, or null when it doesn't exist. */
326
+ function existingMode(filePath) {
327
+ try {
328
+ return fs.statSync(filePath).mode & 0o777;
329
+ } catch (_) {
330
+ return null;
331
+ }
332
+ }
333
+
334
+ /** The file a symlink points at (followed to the end), or `filePath` itself. */
335
+ function resolveLink(filePath) {
336
+ try {
337
+ return fs.realpathSync(filePath);
338
+ } catch (_) {
339
+ return filePath; // doesn't exist yet: it is created where asked
340
+ }
341
+ }
342
+
260
343
  // ── Legacy-registration cleanup ───────────────────────────────────────────────
261
344
 
262
345
  /**
@@ -387,11 +470,11 @@ function applyPermissionRule(settings, { addAllowRule = true, sweepLegacy = true
387
470
  * reformats the user's file or churns its mtime for a no-op.
388
471
  */
389
472
  function configurePermissions(permissionsPath, opts) {
390
- const settings = readJsonConfig(permissionsPath);
391
- const result = applyPermissionRule(settings, opts);
392
- if (result.added || result.removed > 0) {
393
- atomicWriteJson(permissionsPath, settings);
394
- }
473
+ let result;
474
+ updateJsonFile(permissionsPath, (settings) => {
475
+ result = applyPermissionRule(settings, opts);
476
+ return result.added || result.removed > 0;
477
+ });
395
478
  return result;
396
479
  }
397
480
 
@@ -430,28 +513,121 @@ function hasUnrelatedLegacyServer(config) {
430
513
  * Returns the absolute path that was written so the caller can print it.
431
514
  */
432
515
  function configureClient(client, binaryPath) {
516
+ return writeClientEntry(client, binaryPath).configPath;
517
+ }
518
+
519
+ /**
520
+ * configureClient's body. `onlyIfOursOrAbsent` (the install-time path) leaves a `captain`
521
+ * entry that is not ours untouched instead of replacing it. Returns
522
+ * { configPath, written, foreign }.
523
+ */
524
+ function writeClientEntry(client, binaryPath, { onlyIfOursOrAbsent = false } = {}) {
433
525
  const configPath = client.configPath(binaryPath);
526
+ const rootKey = client.format === 'A' ? (client.rootKey || 'mcpServers') : 'servers';
527
+ let foreign = false;
434
528
 
435
- // Read the existing config (or start with an empty object).
436
- const config = readJsonConfig(configPath);
529
+ const written = updateJsonFile(configPath, (config) => {
530
+ if (config[rootKey] !== undefined && !isPlainObject(config[rootKey])) {
531
+ throw new Error(`${configPath}: "${rootKey}" is not a JSON object, so captain-tool left it alone.`);
532
+ }
533
+ const existing = config[rootKey] && config[rootKey][SERVER_NAME];
534
+ foreign = Boolean(existing) && !entryIsOurs(existing);
535
+ if (onlyIfOursOrAbsent && foreign) return false;
536
+
537
+ // Heal duplicate registrations in every scope (top-level + per-project) before
538
+ // writing the canonical entry.
539
+ removeLegacyEverywhere(config);
540
+ // Our own `captain` entries in per-folder scopes go too: the user-level one written below
541
+ // covers every folder, and a folder entry would override it there. The earlier README's
542
+ // `claude mcp add captain -- cmd /c captain-tool` (no `-s user`) left exactly such
543
+ // entries, broken outside Windows.
544
+ removeOursFromProjects(config, rootKey);
545
+
546
+ // Format A: { mcpServers: { "captain": { command, args } } }
547
+ // Format B: { servers: { "captain": { type, command, args } } }
548
+ if (!config[rootKey]) config[rootKey] = {};
549
+ config[rootKey][SERVER_NAME] = client.format === 'A'
550
+ ? buildEntryFormatA(binaryPath)
551
+ : buildEntryFormatB(binaryPath);
552
+ return true;
553
+ });
554
+ return { configPath, written, foreign };
555
+ }
437
556
 
438
- // Heal duplicate registrations in every scope (top-level + per-project) before
439
- // writing the canonical entry.
440
- removeLegacyEverywhere(config);
557
+ /**
558
+ * True when npm is installing this package globally. `-g` sets npm_config_global, but
559
+ * `--location=global` (or `global=true` in .npmrc) does not (verified, npm 11.19), so a
560
+ * package installed under npm's global node_modules counts too.
561
+ */
562
+ function isGlobalInstall(env, packageDir) {
563
+ if (env.npm_config_global === 'true') return true;
564
+ if (!env.npm_config_global_prefix || !packageDir) return false;
565
+ const globalRoot = resolveLink(nodeModulesUnder(env.npm_config_global_prefix));
566
+ return path.dirname(resolveLink(packageDir)) === globalRoot;
567
+ }
441
568
 
442
- if (client.format === 'A') {
443
- // Format A: { mcpServers: { "captain": { command, args, env } } }
444
- const rootKey = client.rootKey || 'mcpServers';
445
- if (!config[rootKey]) config[rootKey] = {};
446
- config[rootKey][SERVER_NAME] = buildEntryFormatA(binaryPath);
447
- } else {
448
- // Format B: { servers: { "captain": { type, command, args, env } } }
449
- if (!config.servers) config.servers = {};
450
- config.servers[SERVER_NAME] = buildEntryFormatB(binaryPath);
569
+ /** npm's global node_modules under a global prefix. */
570
+ function nodeModulesUnder(prefix) {
571
+ return process.platform === 'win32'
572
+ ? path.join(prefix, 'node_modules')
573
+ : path.join(prefix, 'lib', 'node_modules');
574
+ }
575
+
576
+ /** Delete `captain` entries that are ours from every `projects[*]` scope. */
577
+ function removeOursFromProjects(config, rootKey) {
578
+ if (!isPlainObject(config.projects)) return;
579
+ for (const proj of Object.values(config.projects)) {
580
+ const servers = isPlainObject(proj) ? proj[rootKey] : undefined;
581
+ if (isPlainObject(servers) && entryIsOurs(servers[SERVER_NAME])) delete servers[SERVER_NAME];
451
582
  }
583
+ }
584
+
585
+ // ── Install-time registration (npm install -g) ────────────────────────────────
586
+
587
+ /** The Claude Code client definition. */
588
+ function claudeCodeClient() {
589
+ return CLIENTS.find((c) => c.rootKey === 'mcpServers' && c.permissionsPath);
590
+ }
452
591
 
453
- atomicWriteJson(configPath, config);
454
- return configPath;
592
+ /**
593
+ * Register captain with Claude Code from the package's install script. The fallback install
594
+ * path: `npx captain-tool@latest setup` is the primary one and asks the user; this one can't
595
+ * ask (npm runs install scripts without a terminal), so it writes only the MCP entry, for
596
+ * Claude Code only, and only when every guard holds. Returns { registered, reason }.
597
+ * Never throws: an install script that fails fails the user's whole `npm install`.
598
+ *
599
+ * Guards, each a `reason` when it stops us:
600
+ * not-global — a local `npm install`: the path would be inside someone's project.
601
+ * npx — `npx captain-tool`: the path is in npm's npx cache, which npm deletes.
602
+ * ci — CI and image builds have no user to use it.
603
+ * setup — setup is running this global install itself and registers afterwards.
604
+ * sudo — `sudo npm install -g`: we'd write a root-owned file into a home.
605
+ * no-binary — no platform binary for this machine.
606
+ * no-claude-code — ~/.claude.json doesn't exist: we never create it (Claude Code creates
607
+ * it on its first run).
608
+ * foreign — a `captain` server that isn't ours is registered; we leave it alone.
609
+ * unreadable — the config isn't JSON, or can't be read or written.
610
+ */
611
+ function registerAtInstall({ env = process.env, binaryPath, packageDir } = {}) {
612
+ if (!isGlobalInstall(env, packageDir)) return { registered: false, reason: 'not-global' };
613
+ if (env.npm_command === 'exec') return { registered: false, reason: 'npx' };
614
+ if (env.CI && env.CI !== 'false' && env.CI !== '0') return { registered: false, reason: 'ci' };
615
+ if (env.CAPTAIN_TOOL_SETUP_RUNNING === '1') return { registered: false, reason: 'setup' };
616
+ if (typeof process.getuid === 'function' && process.getuid() === 0 && env.SUDO_USER) {
617
+ return { registered: false, reason: 'sudo' };
618
+ }
619
+ if (!binaryPath) return { registered: false, reason: 'no-binary' };
620
+ const client = claudeCodeClient();
621
+ if (!fs.existsSync(client.configPath(binaryPath))) {
622
+ return { registered: false, reason: 'no-claude-code' };
623
+ }
624
+ try {
625
+ const { foreign } = writeClientEntry(client, binaryPath, { onlyIfOursOrAbsent: true });
626
+ if (foreign) return { registered: false, reason: 'foreign' };
627
+ return { registered: true, reason: 'registered' };
628
+ } catch (_) {
629
+ return { registered: false, reason: 'unreadable' };
630
+ }
455
631
  }
456
632
 
457
633
  // ── Skill-proof hook (CAP-ADR-0042) ───────────────────────────────────────────
@@ -493,6 +669,67 @@ function runHooks(binary, args) {
493
669
  return { ok: res.status === 0, output };
494
670
  }
495
671
 
672
+ /**
673
+ * Sign in to Captain with `captain-tool login`, which opens the browser and waits for the
674
+ * approval (it drives the same sign-in as the Captain panel, through Captain's local service).
675
+ * Interactive: the person sees the URL and code and answers in the browser, so the child gets
676
+ * this terminal. Returns true when the person is signed in. Never throws: setup's registration
677
+ * stands whatever happens here. `spawn` is injectable for tests.
678
+ */
679
+ function runLogin(binary, spawn = require('child_process').spawnSync) {
680
+ if (!binary) return false;
681
+ const res = spawn(binary, ['login'], { stdio: 'inherit' });
682
+ return !res.error && res.status === 0;
683
+ }
684
+
685
+ /** Setup's last line (user decision, 2026-11-24). */
686
+ const SETUP_DONE = 'Setup complete. Open Claude Code and say hi to start.';
687
+
688
+ /** An answer to a [Y/n] question: Enter or y/yes is yes. */
689
+ function isYes(answer) {
690
+ return answer === '' || /^y(es)?$/i.test(answer);
691
+ }
692
+
693
+ // ── The /captain-status command ─────────────────────────────────────────────────
694
+ // A Claude Code user command (~/.claude/commands/captain-status.md) that runs captain_status,
695
+ // one of the ways a first chat can begin. The marker line tells ours from a file the person
696
+ // wrote: setup never overwrites theirs, and --uninstall removes only ours.
697
+ const STATUS_COMMAND_MARKER = '<!-- written by captain-tool setup -->';
698
+ const STATUS_COMMAND = `---
699
+ description: Check Captain's status and get set up
700
+ ---
701
+ ${STATUS_COMMAND_MARKER}
702
+ Call the captain_status tool and follow its guidance.
703
+ `;
704
+
705
+ function statusCommandPath() {
706
+ return expandPath('~/.claude/commands/captain-status.md');
707
+ }
708
+
709
+ /** Writes the command when it is absent or ours. Returns the path written, or null. */
710
+ function installStatusCommand(filePath = statusCommandPath()) {
711
+ if (fs.existsSync(filePath)) {
712
+ const current = fs.readFileSync(filePath, 'utf8');
713
+ if (!current.includes(STATUS_COMMAND_MARKER)) return null;
714
+ if (current === STATUS_COMMAND) return null;
715
+ }
716
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
717
+ fs.writeFileSync(filePath, STATUS_COMMAND);
718
+ return filePath;
719
+ }
720
+
721
+ /** Removes the command when it is ours. Returns true when a file was removed. */
722
+ function removeStatusCommand(filePath = statusCommandPath()) {
723
+ if (!fs.existsSync(filePath)) return false;
724
+ if (!fs.readFileSync(filePath, 'utf8').includes(STATUS_COMMAND_MARKER)) return false;
725
+ fs.unlinkSync(filePath);
726
+ return true;
727
+ }
728
+
729
+ /** What setup says when it does not sign the person in itself. */
730
+ const SIGN_IN_LATER =
731
+ 'Sign in any time with `captain-tool login`, or your agent will ask the first time you use Captain.';
732
+
496
733
  /** The flags this wizard reads. */
497
734
  function parseFlags(argv) {
498
735
  return {
@@ -510,29 +747,24 @@ function parseFlags(argv) {
510
747
  function uninstallClient(client, binaryPath) {
511
748
  const configPath = client.configPath(binaryPath);
512
749
  if (!fs.existsSync(configPath)) return false;
513
- const config = readJsonConfig(configPath);
514
- let changed = false;
515
- const drop = (root) => {
516
- if (!root || typeof root !== 'object') return;
517
- for (const name of [SERVER_NAME, ...LEGACY_NAMES]) {
518
- if (entryIsOurs(root[name])) {
519
- delete root[name];
520
- changed = true;
750
+ return updateJsonFile(configPath, (config) => {
751
+ const drop = (root) => {
752
+ if (!root || typeof root !== 'object') return;
753
+ for (const name of [SERVER_NAME, ...LEGACY_NAMES]) {
754
+ if (entryIsOurs(root[name])) delete root[name];
521
755
  }
522
- }
523
- };
524
- drop(config.mcpServers);
525
- drop(config.servers);
526
- if (config.projects && typeof config.projects === 'object') {
527
- for (const proj of Object.values(config.projects)) {
528
- if (proj && typeof proj === 'object') {
529
- drop(proj.mcpServers);
530
- drop(proj.servers);
756
+ };
757
+ drop(config.mcpServers);
758
+ drop(config.servers);
759
+ if (config.projects && typeof config.projects === 'object') {
760
+ for (const proj of Object.values(config.projects)) {
761
+ if (proj && typeof proj === 'object') {
762
+ drop(proj.mcpServers);
763
+ drop(proj.servers);
764
+ }
531
765
  }
532
766
  }
533
- }
534
- if (changed) atomicWriteJson(configPath, config);
535
- return changed;
767
+ });
536
768
  }
537
769
 
538
770
  /**
@@ -543,22 +775,24 @@ function uninstallClient(client, binaryPath) {
543
775
  */
544
776
  function removePermissionRule(permissionsPath, { sweepLegacy = true } = {}) {
545
777
  if (!fs.existsSync(permissionsPath)) return 0;
546
- const settings = readJsonConfig(permissionsPath);
547
- const allow = settings.permissions && Array.isArray(settings.permissions.allow)
548
- ? settings.permissions.allow
549
- : null;
550
- if (!allow) return 0;
551
778
  const isOurs = (rule) =>
552
779
  typeof rule === 'string' &&
553
780
  [PERMISSION_RULE, ...(sweepLegacy ? LEGACY_PERMISSION_PREFIXES : [])].some(
554
781
  (p) => rule === p || rule.startsWith(`${p}__`)
555
782
  );
556
- const kept = allow.filter((r) => !isOurs(r));
557
- const removed = allow.length - kept.length;
558
- if (removed > 0) {
783
+ let removed = 0;
784
+ updateJsonFile(permissionsPath, (settings) => {
785
+ const allow = settings.permissions && Array.isArray(settings.permissions.allow)
786
+ ? settings.permissions.allow
787
+ : null;
788
+ removed = 0;
789
+ if (!allow) return false;
790
+ const kept = allow.filter((r) => !isOurs(r));
791
+ removed = allow.length - kept.length;
792
+ if (removed === 0) return false;
559
793
  settings.permissions.allow = kept;
560
- atomicWriteJson(permissionsPath, settings);
561
- }
794
+ return true;
795
+ });
562
796
  return removed;
563
797
  }
564
798
 
@@ -580,6 +814,12 @@ function uninstall(binaryPath, { hooksOnly }) {
580
814
  failed = true;
581
815
  }
582
816
  if (client.permissionsPath) {
817
+ try {
818
+ if (removeStatusCommand()) console.log(`Removed the /captain-status command: ${statusCommandPath()}`);
819
+ } catch (err) {
820
+ console.error(`Could not remove ${statusCommandPath()}: ${err.message}`);
821
+ failed = true;
822
+ }
583
823
  try {
584
824
  // Same promise as the install sweep: an unrelated `captain-tool` server keeps its rules.
585
825
  const sweepLegacy = !hasUnrelatedLegacyServer(readJsonConfig(client.configPath(binaryPath)));
@@ -641,6 +881,69 @@ function abortNoInput() {
641
881
  process.exit(1);
642
882
  }
643
883
 
884
+ // ── npx → global install ──────────────────────────────────────────────────────
885
+
886
+ /** True when `dir` is inside npm's npx cache (`<cache>/_npx/<hash>/…`). */
887
+ function isNpxCacheDir(dir) {
888
+ return dir.split(/[\\/]/).includes('_npx');
889
+ }
890
+
891
+ /**
892
+ * Install this version of captain-tool globally and return its platform binary.
893
+ *
894
+ * WHY: `npx captain-tool@latest setup` is the one command users run, but npx runs us from
895
+ * its cache, which `npm cache clean` deletes and a newer npx run never updates. Registering
896
+ * that path leaves the agent pointing at a binary that later vanishes. So setup installs
897
+ * the same version globally and registers the global copy. CAPTAIN_TOOL_SETUP_RUNNING tells
898
+ * that install's own install script not to register or print its hint: setup does both.
899
+ *
900
+ * Returns { ok: true, binaryPath } or { ok: false, reason, command }.
901
+ */
902
+ function installGlobally({ version, env = process.env } = {}) {
903
+ const { spawnSync } = require('child_process');
904
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
905
+ const shell = process.platform === 'win32';
906
+ const spec = `captain-tool@${version}`;
907
+ const command = `npm install -g ${spec}`;
908
+ const install = spawnSync(npm, ['install', '-g', spec], {
909
+ env: { ...env, CAPTAIN_TOOL_SETUP_RUNNING: '1' },
910
+ stdio: ['ignore', 'inherit', 'inherit'],
911
+ shell,
912
+ });
913
+ const failed = (why) => ({ ok: false, reason: `Could not install captain-tool globally: ${why}`, command });
914
+ if (install.error) return failed(install.error.message);
915
+ if (install.status !== 0) return failed(`npm exited with code ${install.status} (see its output above)`);
916
+ const globalPkg = path.join(globalNodeModules({ env, npm, shell }), 'captain-tool');
917
+ const binaryPath = findBinary(globalPkg);
918
+ if (!binaryPath) {
919
+ // The install worked; re-running it won't help. A version manager that keeps global
920
+ // packages elsewhere (Volta and the like; unverified) lands here.
921
+ return {
922
+ ok: false,
923
+ reason: `captain-tool installed globally, but its binary is not under ${globalPkg}. ` +
924
+ 'Run `captain-tool setup` from that install.',
925
+ command: null,
926
+ };
927
+ }
928
+ return { ok: true, binaryPath };
929
+ }
930
+
931
+ /**
932
+ * npm's global node_modules directory.
933
+ *
934
+ * WHY the env var first: npx gives the processes it runs `npm_config_global_prefix`, and
935
+ * npm's own output redacts anything shaped like a UUID (`npm root -g` printed
936
+ * `/tmp/***\/lib/node_modules` for a prefix under a UUID-named folder, verified on npm
937
+ * 11.19), so parsing it can name a directory that doesn't exist. `npm root -g` is the
938
+ * fallback when setup was not started by npm.
939
+ */
940
+ function globalNodeModules({ env, npm, shell }) {
941
+ if (env.npm_config_global_prefix) return nodeModulesUnder(env.npm_config_global_prefix);
942
+ const { spawnSync } = require('child_process');
943
+ const root = spawnSync(npm, ['root', '-g'], { env, encoding: 'utf8', shell });
944
+ return root.status === 0 ? String(root.stdout || '').trim() : '';
945
+ }
946
+
644
947
  // ── Main ──────────────────────────────────────────────────────────────────────
645
948
 
646
949
  async function main() {
@@ -650,29 +953,17 @@ async function main() {
650
953
  console.log('This wizard registers captain-tool as an MCP server in your AI agent config(s).');
651
954
  console.log('');
652
955
 
956
+ const flags = parseFlags(process.argv);
957
+
653
958
  // Resolve the absolute binary path — same logic as the runner.
654
959
  // If no platform binary is installed we fall back to npx (null triggers the
655
960
  // npx path in resolveCommand / buildEntry*).
656
- const binaryPath = findBinary();
657
- if (binaryPath) {
658
- console.log(`Binary path: ${binaryPath}`);
659
- } else {
660
- const fallback = process.platform === 'win32'
661
- ? 'cmd /c npx captain-tool'
662
- : 'npx captain-tool';
663
- console.warn(
664
- `Warning: no pre-built binary found for this platform.\n` +
665
- `Falling back to: ${fallback}\n` +
666
- `For best performance, install on a supported platform: win32-x64, darwin-x64, darwin-arm64, linux-x64\n`
667
- );
668
- }
669
- console.log('');
961
+ let binaryPath = findBinary();
670
962
 
671
963
  // Non-interactive paths first. `--yes`/`-y` configures every client and
672
964
  // enables auto-approval without prompting (for scripts/CI). Without the
673
965
  // flag, a non-interactive stdin must be rejected up front — see prompt()
674
966
  // for why EOF mid-question would otherwise end as a silent exit 0.
675
- const flags = parseFlags(process.argv);
676
967
  const assumeYes = flags.assumeYes;
677
968
 
678
969
  // `--uninstall` (and `--hooks-only`, which removes only the skill-proof hook and records a
@@ -684,55 +975,32 @@ async function main() {
684
975
  return;
685
976
  }
686
977
 
687
- let selected;
978
+ // Setup configures Claude Code only (user decision, 2026-11-24). The other clients stay in
979
+ // CLIENTS so `--uninstall` still removes Captain from every client an earlier setup wrote.
980
+ const claudeCode = CLIENTS.indexOf(claudeCodeClient());
981
+ let selected = [claudeCode];
688
982
  let wantPermissions = false;
983
+ // `--yes` (scripts, CI) never signs in: a browser sign-in needs a person at the keyboard.
984
+ let wantSignIn = false;
689
985
  if (assumeYes) {
690
- selected = CLIENTS.map((_, i) => i);
691
986
  wantPermissions = true;
692
- console.log('--yes: configuring all clients and enabling auto-approval.');
987
+ console.log('--yes: setting up Claude Code and enabling auto-approval.');
693
988
  console.log('');
694
989
  } else if (!process.stdin.isTTY) {
695
- console.error('stdin is not interactive. Re-run with --yes to configure all clients without prompts.');
990
+ console.error('stdin is not interactive. Re-run with --yes to set up Claude Code without prompts.');
696
991
  process.exit(1);
697
992
  } else {
698
- // Present the client menu.
699
- console.log('Select which agent(s) to configure:');
700
- console.log(' 0. All of the above');
701
- CLIENTS.forEach((client, i) => {
702
- console.log(` ${i + 1}. ${client.name}`);
703
- });
704
- console.log('');
705
-
706
993
  const rl = readline.createInterface({
707
994
  input: process.stdin,
708
995
  output: process.stdout,
709
996
  });
710
997
 
711
- while (true) {
712
- const answer = await prompt(
713
- rl,
714
- `Enter number(s) separated by commas (e.g. "1,3") or 0 for all: `
715
- );
716
- if (answer === null) abortNoInput();
717
-
718
- // Parse the answer into a list of client indices (0-based into CLIENTS).
719
- if (answer === '0') {
720
- selected = CLIENTS.map((_, i) => i);
721
- break;
722
- }
723
-
724
- const indices = answer
725
- .split(',')
726
- .map((s) => parseInt(s.trim(), 10) - 1) // convert 1-based menu to 0-based
727
- .filter((n) => Number.isInteger(n) && n >= 0 && n < CLIENTS.length);
728
-
729
- if (indices.length === 0) {
730
- console.log(`Please enter a number between 0 and ${CLIENTS.length}.`);
731
- continue;
732
- }
733
-
734
- selected = indices;
735
- break;
998
+ const setUp = await prompt(rl, 'Set up Claude Code? [Y/n]: ');
999
+ if (setUp === null) abortNoInput();
1000
+ if (!isYes(setUp)) {
1001
+ rl.close();
1002
+ console.log('Nothing was set up.');
1003
+ return;
736
1004
  }
737
1005
 
738
1006
  // If Claude Code is among the selections, offer to auto-approve captain's
@@ -749,13 +1017,52 @@ async function main() {
749
1017
  `permissions.allow in ${permClient.permissionsPath()} so tool calls never prompt. [Y/n]: `
750
1018
  );
751
1019
  if (answer === null) abortNoInput();
752
- wantPermissions = answer === '' || /^y(es)?$/i.test(answer);
1020
+ wantPermissions = isYes(answer);
753
1021
  }
754
1022
 
1023
+ // Sign in now? Asked here with the other questions, before anything is installed; the
1024
+ // sign-in itself runs last, once the server is registered.
1025
+ const signIn = await prompt(rl, 'Sign in to Captain now? Your browser will open. [Y/n]: ');
1026
+ if (signIn === null) abortNoInput();
1027
+ wantSignIn = isYes(signIn);
1028
+
755
1029
  rl.close();
756
1030
  console.log('');
757
1031
  }
758
1032
 
1033
+ // Run through npx: install globally, then register that copy (see installGlobally). Only
1034
+ // now, once we know what to register: a run that stops at a question installs nothing.
1035
+ if (isNpxCacheDir(__dirname)) {
1036
+ console.log('Installing captain-tool globally, so your AI clients keep a path to it that npm');
1037
+ console.log('does not clean up (npx runs it from a temporary cache)...');
1038
+ const global = installGlobally({ version: require('../package.json').version });
1039
+ if (!global.ok) {
1040
+ console.error(`\n${global.reason}`);
1041
+ console.error('Nothing was registered.');
1042
+ if (global.command) {
1043
+ console.error('Run this yourself, then run `captain-tool setup`:');
1044
+ console.error(` ${global.command}`);
1045
+ }
1046
+ process.exit(1);
1047
+ }
1048
+ binaryPath = global.binaryPath;
1049
+ console.log('');
1050
+ }
1051
+
1052
+ if (binaryPath) {
1053
+ console.log(`Binary path: ${binaryPath}`);
1054
+ } else {
1055
+ const fallback = process.platform === 'win32'
1056
+ ? 'cmd /c npx captain-tool'
1057
+ : 'npx captain-tool';
1058
+ console.warn(
1059
+ `Warning: no pre-built binary found for this platform.\n` +
1060
+ `Falling back to: ${fallback}\n` +
1061
+ `For best performance, install on a supported platform: win32-x64, darwin-x64, darwin-arm64, linux-x64\n`
1062
+ );
1063
+ }
1064
+ console.log('');
1065
+
759
1066
  // Configure each selected client.
760
1067
  let anyFailed = false;
761
1068
  const succeeded = new Set();
@@ -820,6 +1127,13 @@ async function main() {
820
1127
  // whenever Claude Code was configured, whether or not the Captain extension is in use. A
821
1128
  // failure here is a warning: the MCP registration above stands.
822
1129
  if (permIdx !== undefined) {
1130
+ // The /captain-status command: a first chat can start with it (it runs captain_status).
1131
+ try {
1132
+ const written = installStatusCommand();
1133
+ if (written) console.log(`Added the /captain-status command: ${written}`);
1134
+ } catch (err) {
1135
+ console.warn(`Warning: /captain-status command not added: ${err.message}`);
1136
+ }
823
1137
  const bin = hooksBinary(binaryPath);
824
1138
  if (!bin) {
825
1139
  console.warn('Skill-proof hook skipped: no captain-tool binary found. Run `captain-tool hooks install` once captain-tool is installed.');
@@ -839,6 +1153,7 @@ async function main() {
839
1153
  }
840
1154
 
841
1155
  console.log('Setup complete. The captain server is registered and ready to use.');
1156
+
842
1157
  // CAP-ADR-0030: the registered `captain-tool` is a relay to Captain's local service (the
843
1158
  // daemon the Captain extension also runs). The two must be the same release.
844
1159
  console.log('');
@@ -846,6 +1161,23 @@ async function main() {
846
1161
  console.log('not running. If you also use the Captain extension,');
847
1162
  console.log('update captain-tool and the Captain extension together:');
848
1163
  console.log('each refuses the other across a version that changed how agents connect.');
1164
+
1165
+ // Last, because it is interactive and its result is the last thing the person should see.
1166
+ console.log('');
1167
+ if (wantSignIn) {
1168
+ const bin = hooksBinary(binaryPath);
1169
+ if (!bin) {
1170
+ console.warn('Sign-in skipped: no captain-tool binary found.');
1171
+ console.log(SIGN_IN_LATER);
1172
+ } else if (!runLogin(bin)) {
1173
+ console.warn('Not signed in yet.');
1174
+ console.log(SIGN_IN_LATER);
1175
+ }
1176
+ } else {
1177
+ console.log(SIGN_IN_LATER);
1178
+ }
1179
+ console.log('');
1180
+ console.log(SETUP_DONE);
849
1181
  }
850
1182
 
851
1183
  // Only run the interactive wizard when invoked directly. Guarding on
@@ -874,10 +1206,22 @@ module.exports = {
874
1206
  hasUnrelatedLegacyServer,
875
1207
  hooksBinary,
876
1208
  runHooks,
1209
+ runLogin,
1210
+ SIGN_IN_LATER,
1211
+ SETUP_DONE,
1212
+ isYes,
1213
+ STATUS_COMMAND,
1214
+ installStatusCommand,
1215
+ removeStatusCommand,
877
1216
  parseFlags,
878
1217
  uninstallClient,
879
1218
  removePermissionRule,
880
1219
  uninstall,
1220
+ updateJsonFile,
1221
+ registerAtInstall,
1222
+ findBinary,
1223
+ isNpxCacheDir,
1224
+ installGlobally,
881
1225
  // Exported so the npx runner (`captain-tool setup`) can launch the wizard:
882
1226
  // the require.main gate above means a bare require() runs nothing.
883
1227
  main,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "captain-tool",
3
- "version": "0.0.119",
3
+ "version": "0.0.121",
4
4
  "description": "MCP server connecting Claude Desktop and VS Code Copilot to Captain Cloud",
5
5
  "bin": {
6
6
  "captain-tool": "bin/captain-tool",
@@ -11,10 +11,10 @@
11
11
  "test": "node test/setup.test.js"
12
12
  },
13
13
  "optionalDependencies": {
14
- "@captain-tool/captain-tool-win32-x64": "0.0.119",
15
- "@captain-tool/captain-tool-darwin-x64": "0.0.119",
16
- "@captain-tool/captain-tool-darwin-arm64": "0.0.119",
17
- "@captain-tool/captain-tool-linux-x64": "0.0.119"
14
+ "@captain-tool/captain-tool-win32-x64": "0.0.121",
15
+ "@captain-tool/captain-tool-darwin-x64": "0.0.121",
16
+ "@captain-tool/captain-tool-darwin-arm64": "0.0.121",
17
+ "@captain-tool/captain-tool-linux-x64": "0.0.121"
18
18
  },
19
19
  "files": [
20
20
  "bin/",
@@ -4,51 +4,87 @@
4
4
  /**
5
5
  * postinstall.js — runs automatically after `npm install captain-tool`.
6
6
  *
7
- * Checks whether a platform binary was successfully installed (via
8
- * optionalDependencies). If not, prints a friendly warning and exits 0.
7
+ * On a global install (`npm install -g captain-tool`) it registers captain with Claude Code,
8
+ * so the agent finds the server without a second command, and tells the person what it did.
9
+ * This is the fallback install path: `npx captain-tool@latest setup` is the primary one,
10
+ * because it can ask (which clients, auto-approval, skill proof) and this script cannot.
11
+ * What it registers, and when it declines to, is setup's registerAtInstall.
9
12
  *
10
- * WHY exit 0 on failure?
13
+ * WHY exit 0 on every failure?
11
14
  * If postinstall exits non-zero, npm marks the entire install as failed.
12
- * Missing a platform binary is not catastrophic — the user may be on an
13
- * unsupported platform and still want the setup CLI or just the package.json.
14
- * We warn and let them proceed.
15
+ * Not registering is never worth failing the install: the person can still run
16
+ * `captain-tool setup`. We warn and let them proceed.
15
17
  */
16
18
 
17
- const path = require('path');
18
- const fs = require('fs');
19
+ const fs = require('fs');
19
20
 
20
- const PLATFORMS = [
21
- { pkg: '@captain-tool/captain-tool-win32-x64', bin: 'captain-tool.exe' },
22
- { pkg: '@captain-tool/captain-tool-darwin-x64', bin: 'captain-tool' },
23
- { pkg: '@captain-tool/captain-tool-darwin-arm64', bin: 'captain-tool' },
24
- { pkg: '@captain-tool/captain-tool-linux-x64', bin: 'captain-tool' },
25
- ];
26
-
27
- function findBinary() {
28
- for (const { pkg, bin } of PLATFORMS) {
21
+ /**
22
+ * Show `text` to the person running npm.
23
+ *
24
+ * WHY /dev/tty: npm runs install scripts with their output hidden (foreground-scripts is off
25
+ * by default), so stdout reaches no one. The terminal itself still does. With no terminal
26
+ * (CI, scripts) opening it fails and we fall back to stdout, which npm shows only with
27
+ * --foreground-scripts. Windows has no /dev/tty.
28
+ */
29
+ function tellUser(text) {
30
+ if (process.platform !== 'win32') {
29
31
  try {
30
- const pkgJsonPath = require.resolve(`${pkg}/package.json`);
31
- const binPath = path.join(path.dirname(pkgJsonPath), 'bin', bin);
32
- fs.accessSync(binPath, fs.constants.X_OK);
33
- return binPath;
32
+ const fd = fs.openSync('/dev/tty', 'w');
33
+ try {
34
+ fs.writeSync(fd, text);
35
+ } finally {
36
+ fs.closeSync(fd);
37
+ }
38
+ return;
34
39
  } catch (_) {}
35
40
  }
36
- return null;
41
+ process.stdout.write(text);
37
42
  }
38
43
 
39
- const binary = findBinary();
44
+ const SETUP_HINT = 'Run `captain-tool setup` to auto-approve Captain\'s tools, turn on skill proof, or set up other AI clients.';
40
45
 
41
- if (binary) {
42
- console.log(`captain-tool: binary installed at ${binary}`);
43
- console.log('Run `npx captain-tool setup` to register it with your AI agent.');
44
- } else {
45
- // This warning is printed to stderr so it doesn't pollute stdout in scripts.
46
- process.stderr.write(
47
- '\ncaptain-tool: WARNING — no pre-built binary was found for this platform.\n' +
48
- 'Supported platforms: win32-x64, darwin-x64, darwin-arm64, linux-x64\n' +
49
- 'If you believe this is an error, please open an issue:\n' +
50
- ' https://github.com/your-org/captain-tool/issues\n\n'
51
- );
52
- // Exit 0 intentionally — see module comment above.
53
- process.exit(0);
46
+ let result = { registered: false, reason: 'error' };
47
+ try {
48
+ const path = require('path');
49
+ const setup = require('../bin/captain-tool-setup');
50
+ const binaryPath = setup.findBinary();
51
+ if (!binaryPath) {
52
+ // Every install, local or global, hears about this: nothing works without the binary.
53
+ tellUser(
54
+ '\ncaptain-tool: WARNING — no pre-built binary was found for this platform.\n' +
55
+ 'Supported platforms: win32-x64, darwin-x64, darwin-arm64, linux-x64\n' +
56
+ 'If you believe this is an error, please open an issue:\n' +
57
+ ' https://github.com/your-org/captain-tool/issues\n\n'
58
+ );
59
+ }
60
+ result = setup.registerAtInstall({ binaryPath, packageDir: path.join(__dirname, '..') });
61
+ } catch (_) {
62
+ // Fall through: the person is pointed at setup below.
63
+ }
64
+
65
+ switch (result.reason) {
66
+ case 'registered':
67
+ tellUser(`\ncaptain-tool: registered with Claude Code. ${SETUP_HINT}\n\n`);
68
+ break;
69
+ case 'no-binary':
70
+ break; // already told, above
71
+ case 'foreign':
72
+ tellUser(
73
+ '\ncaptain-tool: installed. Claude Code already has a different server named "captain",\n' +
74
+ 'so it was left alone. Run `captain-tool setup` to register captain-tool instead.\n\n'
75
+ );
76
+ break;
77
+ case 'no-claude-code':
78
+ case 'unreadable':
79
+ case 'sudo':
80
+ case 'error':
81
+ tellUser('\ncaptain-tool: installed. Run `captain-tool setup` to connect it to your AI client.\n\n');
82
+ break;
83
+ default:
84
+ // not-global, npx, ci, setup: nobody to tell, or setup is talking to them already.
85
+ break;
54
86
  }
87
+
88
+ // Exit 0 intentionally — see module comment above. exitCode, not process.exit(): the stdout
89
+ // fallback can be asynchronous (pipes, Windows), and an exit would drop the message.
90
+ process.exitCode = 0;