@tacitai/mcp-server 0.7.0 → 0.8.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.
Files changed (73) hide show
  1. package/dist/api-errors.d.ts +102 -0
  2. package/dist/api-errors.js +165 -0
  3. package/dist/autonomy.d.ts +46 -0
  4. package/dist/autonomy.js +118 -0
  5. package/dist/claude-config.d.ts +139 -0
  6. package/dist/claude-config.js +339 -0
  7. package/dist/cli-launch.d.ts +33 -0
  8. package/dist/cli-launch.js +178 -0
  9. package/dist/cli-login.d.ts +34 -0
  10. package/dist/cli-login.js +200 -0
  11. package/dist/cli-mode.d.ts +47 -0
  12. package/dist/cli-mode.js +170 -0
  13. package/dist/cli-profiles.d.ts +37 -0
  14. package/dist/cli-profiles.js +344 -0
  15. package/dist/cli.d.ts +9 -0
  16. package/dist/cli.js +59 -458
  17. package/dist/client.d.ts +90 -52
  18. package/dist/client.js +198 -296
  19. package/dist/credentials.d.ts +81 -0
  20. package/dist/credentials.js +291 -0
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +37 -89
  23. package/dist/oauth.d.ts +1 -1
  24. package/dist/oauth.js +5 -5
  25. package/dist/profile-store.d.ts +96 -0
  26. package/dist/profile-store.js +382 -0
  27. package/dist/prompt.d.ts +32 -0
  28. package/dist/prompt.js +99 -0
  29. package/dist/prompts.d.ts +2 -2
  30. package/dist/prompts.js +3 -3
  31. package/dist/server-mode.d.ts +65 -0
  32. package/dist/server-mode.js +99 -0
  33. package/dist/setup-migrate.d.ts +35 -0
  34. package/dist/setup-migrate.js +204 -0
  35. package/dist/setup.d.ts +41 -66
  36. package/dist/setup.js +361 -531
  37. package/dist/signin.d.ts +108 -0
  38. package/dist/signin.js +595 -0
  39. package/dist/tools/agents.d.ts +6 -4
  40. package/dist/tools/agents.js +15 -4
  41. package/dist/tools/artifacts.d.ts +2 -0
  42. package/dist/tools/artifacts.js +8 -1
  43. package/dist/tools/capture.js +2 -2
  44. package/dist/tools/career.js +2 -2
  45. package/dist/tools/chronicle.js +7 -7
  46. package/dist/tools/crews.js +8 -8
  47. package/dist/tools/errors.d.ts +18 -0
  48. package/dist/tools/errors.js +73 -1
  49. package/dist/tools/exec-route.d.ts +34 -0
  50. package/dist/tools/exec-route.js +101 -27
  51. package/dist/tools/github.js +2 -2
  52. package/dist/tools/gm.js +2 -2
  53. package/dist/tools/iam.js +2 -3
  54. package/dist/tools/kb.js +2 -2
  55. package/dist/tools/lake-structure.js +8 -8
  56. package/dist/tools/lake.js +2 -2
  57. package/dist/tools/onboarding.js +2 -2
  58. package/dist/tools/people.js +7 -7
  59. package/dist/tools/pyramid.js +2 -2
  60. package/dist/tools/recall.js +2 -2
  61. package/dist/tools/secretary.d.ts +1 -0
  62. package/dist/tools/secretary.js +2 -1
  63. package/dist/tools/synthesize.d.ts +37 -0
  64. package/dist/tools/synthesize.js +128 -9
  65. package/dist/tools/voice.d.ts +3 -2
  66. package/dist/tools/voice.js +70 -18
  67. package/dist/tools/wiki.js +2 -2
  68. package/dist/tools/workspaces.js +20 -6
  69. package/dist/version.d.ts +6 -0
  70. package/dist/version.js +18 -0
  71. package/dist/workflow-registry.d.ts +1 -0
  72. package/dist/workflow-registry.js +21 -0
  73. package/package.json +4 -1
package/dist/setup.js CHANGED
@@ -1,587 +1,417 @@
1
1
  /**
2
- * setup — wizard subcommand for @tacit/mcp-server
2
+ * `setup` for @tacitai/mcp-server (MV-1542c step 1.3, P3.1 / P3.2).
3
3
  *
4
- * Usage:
5
- * node dist/index.js setup [--dry-run] [--api-url <url>] [--token <token>] [--profile <name>] [--smoke]
4
+ * npx @tacitai/mcp-server setup [--api-url <url>] [--app-url <url>] [--name <profile>] [--no-browser]
5
+ * [--mode always|on-demand] [--install-cli | --no-install-cli] [--device-label <label>]
6
+ * [--all-configs] [--smoke] [--dry-run]
6
7
  *
7
- * Contract (§2.1 of sparc_specification.md, Phase-2 QE resolutions + W5 device-auth):
8
- * F1 smoke — calls tacit_synthesize via getClient()/postSSE; exits non-zero on empty/error.
9
- * F2 token — when token is obtained (device-auth or --token), writes it directly to mcp.json
10
- * (file is 0600). Falls back to env-var placeholder "${TACIT_TOKEN_*}" when token
11
- * came from the environment.
12
- * Merge — deep-merges ONLY mcpServers[profile]; all other keys preserved.
13
- * Idempotent — same --api-url + --profile → byte-identical mcp.json.
14
- * Secrets — token written to mcp.json (0600) when obtained via device-auth or --token;
15
- * NEVER printed to stdout/stderr (dry-run output is redacted).
8
+ * Steps (each failing step stops; nothing later runs on a partial sign-in):
9
+ * 1 targets 2 exported-credential warning 3 signIn 4 profile 5 load mode 6 install `tacit`
10
+ * 7 old-entry migration 8 registration (+ --all-configs) 9 summary (then --smoke)
16
11
  *
17
- * W5 additions:
18
- * --profile <name> — profile name (default: 'tacit'); drives env-var name + mcp.json key.
19
- * Device-auth flow — when --token is NOT provided and token env var is absent, opens browser
20
- * to ${apiUrl}/auth/device, waits for localhost:9123 callback, exchanges
21
- * code for token, derives profile from workspace_name (unless --profile set).
22
- * Metadata file — writes ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
23
- *
24
- * Security invariants:
25
- * - Token is NEVER logged or written to disk.
26
- * - Authorization header value excluded from all logging paths.
27
- * - State nonce generated from crypto.randomBytes (never user-provided).
28
- * - Tampered state in device-auth callback → exit 1 (S-10/AC-13).
12
+ * The only place a token is stored is the 0600 profile. The Claude Code entry names the profile and
13
+ * holds no credential; no token reaches argv, env, stdout or a log line. `~/.claude/mcp.json` is never
14
+ * written. Exit codes: 0 done, 1 failed, 2 state / PKCE check or denial, 3 signed in and profile saved
15
+ * but Claude Code registration or a needed `tacit` install did not complete.
29
16
  */
30
- import * as fs from 'fs';
31
- import * as path from 'path';
32
- import * as os from 'os';
33
- import * as http from 'http';
34
- import * as crypto from 'crypto';
35
- import * as readline from 'readline';
36
- import { execFile } from 'child_process';
17
+ import * as os from 'node:os';
18
+ import * as readline from 'node:readline';
37
19
  import { TacitClient, TacitApiError } from './client.js';
38
- function parseArgs(argv) {
39
- const opts = {
40
- dryRun: false,
41
- apiUrl: null,
42
- token: null,
43
- smoke: false,
44
- profile: 'tacit',
45
- profileExplicit: false,
46
- };
47
- for (let i = 0; i < argv.length; i++) {
48
- const arg = argv[i];
49
- if (arg === '--dry-run') {
50
- opts.dryRun = true;
51
- }
52
- else if (arg === '--smoke') {
53
- opts.smoke = true;
54
- }
55
- else if (arg === '--api-url') {
56
- const next = argv[i + 1];
57
- if (!next || next.startsWith('--')) {
58
- process.stderr.write('Error: --api-url requires a value\n');
59
- process.exit(1);
60
- }
61
- opts.apiUrl = next;
62
- i++;
63
- }
64
- else if (arg === '--token') {
65
- const next = argv[i + 1];
66
- if (!next || next.startsWith('--')) {
67
- process.stderr.write('Error: --token requires a value\n');
68
- process.exit(1);
69
- }
70
- opts.token = next;
71
- i++;
72
- }
73
- else if (arg === '--profile') {
74
- const next = argv[i + 1];
75
- if (!next || next.startsWith('--')) {
76
- process.stderr.write('Error: --profile requires a value\n');
77
- process.exit(1);
78
- }
79
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(next)) {
80
- process.stderr.write(`Error: invalid profile name '${next}'. Names must be lowercase alphanumeric with hyphens.\n`);
81
- process.exit(1);
82
- }
83
- opts.profile = next;
84
- opts.profileExplicit = true;
85
- i++;
86
- }
87
- }
88
- return opts;
89
- }
90
- // ─── Profile / env-var helpers ────────────────────────────────────────────────
91
- /**
92
- * Derive the environment variable name for a given profile name.
93
- *
94
- * AC-3, AC-4, AC-10:
95
- * 'tacit' → 'TACIT_TOKEN'
96
- * 'tacit-acme' → 'TACIT_TOKEN_ACME'
97
- * 'my-workspace' → 'TACIT_TOKEN_MY_WORKSPACE'
98
- */
99
- export function profileToEnvVar(profile) {
100
- // Strip leading 'tacit-' prefix if present
101
- const stripped = profile.startsWith('tacit-') ? profile.slice(6) : profile;
102
- // Special case: default profile ('tacit') → stripped = '' → 'TACIT_TOKEN'
103
- if (stripped === '' || stripped === 'tacit') {
104
- return 'TACIT_TOKEN';
105
- }
106
- return 'TACIT_TOKEN_' + stripped.replace(/-/g, '_').toUpperCase();
107
- }
108
- /**
109
- * Derive a profile name from a workspace_name returned by device-auth exchange.
110
- * AC-12: lowercased, spaces→hyphens, non-alphanumeric-hyphen stripped.
111
- */
20
+ import { ENTRY_NAME, PACKAGE_NAME, activeConfigFolder, findOnPath, genericEntryJson, listConfigFolders, registerUserEntry, removeUserEntry, run, scanLegacyEntries, userEntryState, } from './claude-config.js';
21
+ import { ProfileError, getDefault, getDeviceLabel, isUsableProfileName, pickProfileSlug, setDefault, tryReadProfile, writeProfile, } from './profile-store.js';
22
+ import { PromptError, promptHidden } from './prompt.js';
23
+ import { SignInError, signIn } from './signin.js';
24
+ import { migrateLegacyEntries } from './setup-migrate.js';
25
+ import { revokeUnsaved } from './cli-profiles.js';
26
+ import { readPackageVersion } from './version.js';
27
+ const DEFAULT_API_URL = 'https://api-beta.tacitai.app';
28
+ const EXPORTED_NAMES = ['TACIT_TOKEN', 'TACIT_WORKSPACE_ID', 'TACIT_API_URL', 'TACIT_SESSION_TOKEN', 'TACIT_PROFILE'];
29
+ export const TOKEN_REMOVED_MESSAGE = '--token was removed: a token on the command line is visible to other users. Sign in with setup, or put TACIT_TOKEN in the environment for --smoke.';
30
+ // ─── Helpers kept for cli.ts ─────────────────────────────────────────────────
31
+ /** workspace_name to profile slug (AC-12). */
112
32
  export function workspaceNameToProfile(name) {
113
33
  const slug = name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/^-+/, '');
114
- if (!slug || !/^[a-z0-9]/.test(slug))
115
- return 'workspace';
116
- return slug.slice(0, 64);
117
- }
118
- function claudeDir() {
119
- return path.join(os.homedir(), '.claude');
34
+ return !slug || !/^[a-z0-9]/.test(slug) ? 'workspace' : slug.slice(0, 64);
120
35
  }
121
- function mcpJsonPath() {
122
- return path.join(claudeDir(), 'mcp.json');
123
- }
124
- function readExistingConfig() {
125
- const p = mcpJsonPath();
126
- if (!fs.existsSync(p)) {
127
- return {};
128
- }
129
- try {
130
- const raw = fs.readFileSync(p, 'utf-8');
131
- return JSON.parse(raw);
132
- }
133
- catch {
134
- // Non-parseable file — start fresh but preserve as-is would corrupt; warn and start fresh.
135
- process.stderr.write(`Warning: ~/.claude/mcp.json could not be parsed; will overwrite with merged config.\n`);
136
- return {};
137
- }
138
- }
139
- /**
140
- * Web app URL for shareable links: api.* → app.*, localhost API → localhost:5174.
141
- */
36
+ /** Web app URL for shareable links: api.* to app.*, localhost API to localhost:5174. */
142
37
  export function deriveAppUrl(apiUrl) {
143
38
  const url = new URL(apiUrl);
144
39
  url.username = '';
145
40
  url.password = '';
146
41
  if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {
147
42
  url.port = '5174';
148
- url.pathname = '/';
149
- return url.toString().replace(/\/$/, '');
150
43
  }
151
- url.hostname = url.hostname.replace(/^api[-.]/, (m) => m === 'api.' ? 'app.' : '');
44
+ else {
45
+ url.hostname = url.hostname.replace(/^api[-.]/, (m) => (m === 'api.' ? 'app.' : ''));
46
+ }
152
47
  url.pathname = '/';
153
48
  return url.toString().replace(/\/$/, '');
154
49
  }
155
- /**
156
- * Build the MCP server entry for a given profile.
157
- *
158
- * When `token` is provided (device-auth or --token), the actual token is written
159
- * to mcp.json so the user doesn't need to set an env var. mcp.json is written
160
- * with mode 0600 (owner-only), consistent with how CLI tools store auth tokens
161
- * (e.g. ~/.npmrc). When `token` is null, the env-var placeholder is written
162
- * so Claude Code expands ${VAR} at launch.
163
- */
164
- function buildProfileEntry(apiUrl, envVarName, token) {
50
+ export class UsageError extends Error {
51
+ }
52
+ const VALUE_FLAGS = ['--api-url', '--app-url', '--name', '--mode', '--device-label'];
53
+ export function parseArgs(argv) {
54
+ const o = { noBrowser: false, install: 'ask', allConfigs: false, smoke: false, dryRun: false };
55
+ for (let i = 0; i < argv.length; i++) {
56
+ const [flag, inline] = argv[i].startsWith('--') && argv[i].includes('=') ? [argv[i].slice(0, argv[i].indexOf('=')), argv[i].slice(argv[i].indexOf('=') + 1)] : [argv[i], undefined];
57
+ if (flag === '--token')
58
+ throw new UsageError(TOKEN_REMOVED_MESSAGE);
59
+ if (flag === '--profile')
60
+ throw new UsageError('--profile was renamed --name.');
61
+ let value;
62
+ if (VALUE_FLAGS.includes(flag)) {
63
+ value = inline ?? argv[++i];
64
+ if (value === undefined || value === '' || (inline === undefined && value.startsWith('--')))
65
+ throw new UsageError(`${flag} requires a value`);
66
+ }
67
+ switch (flag) {
68
+ case '--api-url':
69
+ o.apiUrl = value;
70
+ break;
71
+ case '--app-url':
72
+ o.appUrl = value;
73
+ break;
74
+ case '--name':
75
+ if (!isUsableProfileName(value))
76
+ throw new UsageError(`Invalid profile name '${value}'. Use lowercase letters, digits and hyphens, and not a command word.`);
77
+ o.name = value;
78
+ break;
79
+ case '--mode':
80
+ if (value !== 'always' && value !== 'on-demand')
81
+ throw new UsageError('--mode must be always or on-demand');
82
+ o.mode = value;
83
+ break;
84
+ case '--device-label':
85
+ if (!/^[A-Za-z0-9 ._-]{1,64}$/.test(value))
86
+ throw new UsageError('--device-label may use letters, digits, space, . _ - (1 to 64 characters)');
87
+ o.deviceLabel = value;
88
+ break;
89
+ case '--no-browser':
90
+ o.noBrowser = true;
91
+ break;
92
+ case '--install-cli':
93
+ case '--no-install-cli': {
94
+ const want = flag === '--install-cli' ? 'yes' : 'no';
95
+ if (o.install !== 'ask' && o.install !== want)
96
+ throw new UsageError('--install-cli and --no-install-cli cannot be used together');
97
+ o.install = want;
98
+ break;
99
+ }
100
+ case '--all-configs':
101
+ o.allConfigs = true;
102
+ break;
103
+ case '--smoke':
104
+ o.smoke = true;
105
+ break;
106
+ case '--dry-run':
107
+ o.dryRun = true;
108
+ break;
109
+ default: throw new UsageError(`Unknown option ${flag}`);
110
+ }
111
+ }
112
+ if (o.smoke && o.dryRun)
113
+ throw new UsageError('--smoke cannot be combined with --dry-run');
114
+ return o;
115
+ }
116
+ // ─── I/O ─────────────────────────────────────────────────────────────────────
117
+ function ask(question) {
118
+ return new Promise((resolve) => {
119
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
120
+ let answered = false;
121
+ rl.on('close', () => { if (!answered)
122
+ resolve(''); });
123
+ rl.question(question, (a) => { answered = true; rl.close(); resolve(a.trim()); });
124
+ });
125
+ }
126
+ export function defaultIo() {
165
127
  return {
166
- command: 'npx',
167
- args: ['-y', '@tacitai/mcp-server'],
168
- env: {
169
- TACIT_TOKEN: token ?? `\${${envVarName}}`,
170
- TACIT_API_URL: apiUrl,
171
- TACIT_APP_URL: deriveAppUrl(apiUrl),
128
+ isTTY: Boolean(process.stdin.isTTY),
129
+ log: (line) => { process.stderr.write(line + '\n'); },
130
+ promptLine: ask,
131
+ promptHidden: (q) => promptHidden(q, { output: process.stderr }),
132
+ async choose(question, items, defaultIdx) {
133
+ process.stderr.write(`${question}\n${items.map((t, i) => ` ${i + 1}) ${t}`).join('\n')}\n`);
134
+ for (let n = 0; n < 3; n++) {
135
+ const a = await ask(`Choose 1-${items.length} [${defaultIdx + 1}]: `);
136
+ if (a === '')
137
+ return defaultIdx;
138
+ const k = Number(a);
139
+ if (Number.isInteger(k) && k >= 1 && k <= items.length)
140
+ return k - 1;
141
+ }
142
+ return defaultIdx;
172
143
  },
173
- };
174
- }
175
- /**
176
- * Deep-merge ONLY the mcpServers[profileName] key; all other keys preserved.
177
- */
178
- function mergeConfig(existing, profileName, entry) {
179
- const servers = existing.mcpServers ?? {};
180
- const merged = {
181
- ...existing,
182
- mcpServers: {
183
- ...servers,
184
- [profileName]: entry,
144
+ async confirm(question, defaultYes) {
145
+ const a = (await ask(question)).toLowerCase();
146
+ return a === '' ? defaultYes : a === 'y' || a === 'yes';
185
147
  },
186
148
  };
187
- return merged;
188
- }
189
- function configToBytes(cfg) {
190
- return JSON.stringify(cfg, null, 2) + '\n';
191
149
  }
192
- // ─── Metadata file ────────────────────────────────────────────────────────────
193
- /**
194
- * Write ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
195
- * Token plaintext is NEVER written here — metadata only.
196
- */
197
- export function writeProfileMetadata(profile, expiresAt, apiUrl) {
198
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(profile)) {
199
- process.stderr.write(`[TACIT] Invalid profile name '${profile}' — skipping metadata write.\n`);
200
- return;
201
- }
202
- const metaDir = path.join(os.homedir(), '.tacit', 'profiles');
203
- fs.mkdirSync(metaDir, { recursive: true, mode: 0o700 });
150
+ const tilde = (p) => (p === os.homedir() ? '~' : p.startsWith(os.homedir() + '/') ? '~' + p.slice(os.homedir().length) : p);
151
+ // ─── Steps ───────────────────────────────────────────────────────────────────
152
+ async function fetchPersonId(apiUrl, token, fetchFn) {
204
153
  try {
205
- fs.chmodSync(metaDir, 0o700);
154
+ const res = await fetchFn(`${apiUrl}/api/v1/auth/whoami`, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(10_000) });
155
+ if (!res.ok)
156
+ return null;
157
+ const who = (await res.json());
158
+ return typeof who.person_id === 'string' && who.person_id ? who.person_id : null;
206
159
  }
207
- catch { /* unsupported OS */ }
208
- const filePath = path.join(metaDir, `${profile}.json`);
209
- // v2 non-clobber: if a login profile exists, update expires_at and api_url in place
210
- if (fs.existsSync(filePath)) {
211
- try {
212
- const existing = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
213
- if (existing.version === 2) {
214
- existing.expires_at = expiresAt;
215
- existing.api_url = apiUrl;
216
- fs.writeFileSync(filePath, JSON.stringify(existing, null, 2), { mode: 0o600 });
217
- return;
218
- }
219
- }
220
- catch { /* corrupt file, overwrite */ }
160
+ catch {
161
+ return null;
221
162
  }
222
- fs.writeFileSync(filePath, JSON.stringify({ expires_at: expiresAt, api_url: apiUrl }, null, 2), { mode: 0o600 });
223
163
  }
224
- // ─── Device-auth flow ─────────────────────────────────────────────────────────
225
- const DEVICE_AUTH_CALLBACK_PORT = 9123;
226
- const DEVICE_AUTH_TIMEOUT_MS = 120_000;
227
- /**
228
- * Opens a browser to the device-auth URL and waits for the OAuth callback.
229
- * Returns the token, expiry, and workspace name from the exchange response.
230
- *
231
- * Security:
232
- * - State nonce is generated via crypto.randomBytes (never user-provided).
233
- * - Tampered state → exit 1 (S-10 / AC-13).
234
- * - Token plaintext is NEVER logged.
235
- *
236
- * Error paths:
237
- * - /auth/device returns 404 → reject immediately (pre-flight probe).
238
- * - Port 9123 occupied → reject (caller falls back to loginFlow).
239
- * - 120s timeout → reject (caller falls back to loginFlow).
240
- * - Browser open fails → print URL to stdout for manual copy-paste (AC-16 fallback).
241
- */
242
- export async function deviceAuthFlow(apiUrl) {
243
- // Pre-flight: check if /auth/device exists before opening a browser to it.
164
+ /** `npm i -g @tacitai/mcp-server@<own version>`. Only called after an explicit Yes / --install-cli. */
165
+ async function installCli(env, out, err) {
166
+ const version = readPackageVersion();
167
+ const fail = (why) => {
168
+ err(`Could not install the tacit command (${why}).`);
169
+ err(`Use it without installing: npx -p ${PACKAGE_NAME} tacit <command>`);
170
+ return false;
171
+ };
172
+ if (version === 'unknown')
173
+ return fail('this package has no version');
174
+ out(`Installing the tacit command (npm i -g ${PACKAGE_NAME}@${version})...`);
175
+ const r = await run('npm', ['i', '-g', `${PACKAGE_NAME}@${version}`], { env, timeoutMs: 180_000 });
176
+ for (const line of `${r.stdout}\n${r.stderr}`.split('\n').map((l) => l.trim()).filter(Boolean).slice(-8))
177
+ out(` ${line}`);
178
+ if (r.missing)
179
+ return fail('npm was not found');
180
+ if (r.code !== 0)
181
+ return fail(`npm exited with ${String(r.code)}`);
182
+ out('Installed the tacit command.');
183
+ return true;
184
+ }
185
+ async function runSmoke(apiUrl, token, out, err) {
186
+ const client = new TacitClient({ apiUrl, token });
187
+ let body = '';
244
188
  try {
245
- const probe = await fetch(`${apiUrl}/auth/device`, { method: 'HEAD', redirect: 'manual' });
246
- if (probe.status === 404) {
247
- throw new Error('device-auth endpoint not available');
248
- }
189
+ for await (const chunk of client.postSSE('/api/v1/mind/synthesize/stream', { query: 'What is in this knowledge base?' }))
190
+ body += chunk;
249
191
  }
250
- catch (err) {
251
- if (err instanceof Error && err.message === 'device-auth endpoint not available')
252
- throw err;
253
- // Network error (e.g., no connectivity) — let device auth attempt anyway.
192
+ catch (e) {
193
+ err(`SMOKE_SYNTH_FAIL: ${e instanceof TacitApiError ? `API error ${e.statusCode}` : e instanceof Error ? e.message : String(e)}`);
194
+ return 1;
254
195
  }
255
- // 1. Generate a cryptographically random state nonce (32 bytes, hex).
256
- const stateNonce = crypto.randomBytes(32).toString('hex');
257
- return new Promise((resolve, reject) => {
258
- let server = null;
259
- let timeoutHandle = null;
260
- const cleanup = () => {
261
- if (timeoutHandle)
262
- clearTimeout(timeoutHandle);
263
- if (server) {
264
- server.close(() => { });
265
- }
266
- };
267
- // 2. Start localhost:9123 HTTP server for callback.
268
- server = http.createServer(async (req, res) => {
269
- const reqUrl = req.url ?? '';
270
- if (!reqUrl.startsWith('/callback')) {
271
- res.writeHead(404);
272
- res.end('Not found');
273
- return;
274
- }
275
- const parsedUrl = new URL(reqUrl, `http://localhost:${DEVICE_AUTH_CALLBACK_PORT}`);
276
- const returnedState = parsedUrl.searchParams.get('state') ?? '';
277
- const code = parsedUrl.searchParams.get('code') ?? '';
278
- // 6a. Verify state nonce — tampered state → exit 1 (S-10/AC-13).
279
- if (returnedState !== stateNonce) {
280
- res.writeHead(400, { 'Content-Type': 'text/plain' });
281
- res.end('Invalid state parameter.');
282
- cleanup();
283
- reject(new Error('CSRF state mismatch: state nonce did not match. Aborting device auth.'));
284
- return;
285
- }
286
- if (!code) {
287
- res.writeHead(400, { 'Content-Type': 'text/plain' });
288
- res.end('Missing code parameter.');
289
- cleanup();
290
- reject(new Error('Device auth callback missing code parameter.'));
291
- return;
292
- }
293
- // 6c. Exchange code for token.
294
- try {
295
- res.writeHead(200, { 'Content-Type': 'text/html' });
296
- res.end('<html><body><h1>Authentication complete. You may close this tab.</h1></body></html>');
297
- const exchangeRes = await fetch(`${apiUrl}/api/v1/auth/device-exchange`, {
298
- method: 'POST',
299
- headers: { 'Content-Type': 'application/json' },
300
- body: JSON.stringify({ code }),
301
- });
302
- if (!exchangeRes.ok) {
303
- const errBody = await exchangeRes.text().catch(() => '');
304
- cleanup();
305
- reject(new Error(`Device auth exchange failed (${exchangeRes.status}): ${errBody}`));
306
- return;
307
- }
308
- const data = await exchangeRes.json();
309
- const token = typeof data['token'] === 'string' ? data['token'] : '';
310
- const expiresAt = typeof data['expires_at'] === 'string' ? data['expires_at'] : '';
311
- const workspaceName = typeof data['workspace_name'] === 'string' ? data['workspace_name'] : 'tacit';
312
- if (!token) {
313
- cleanup();
314
- reject(new Error('Device auth exchange returned empty token.'));
315
- return;
316
- }
317
- cleanup();
318
- resolve({ token, expiresAt, workspaceName });
319
- }
320
- catch (err) {
321
- cleanup();
322
- reject(err);
323
- }
324
- });
325
- server.on('error', (err) => {
326
- cleanup();
327
- reject(err);
328
- });
329
- server.listen(DEVICE_AUTH_CALLBACK_PORT, '127.0.0.1', () => {
330
- // 3. Build device URL.
331
- const callbackUrl = `http://localhost:${DEVICE_AUTH_CALLBACK_PORT}/callback`;
332
- const deviceUrl = `${apiUrl}/auth/device?callback=${encodeURIComponent(callbackUrl)}&state=${stateNonce}`;
333
- // 4. Try to open the browser.
334
- // Use execFile with an argument array (not exec) to avoid shell injection
335
- // — deviceUrl is built from user-supplied --api-url and must not be
336
- // interpolated into a shell command string.
337
- const platform = process.platform;
338
- const [openBin, openArgs] = platform === 'win32'
339
- ? ['cmd', ['/c', 'start', '', deviceUrl]]
340
- : platform === 'darwin'
341
- ? ['open', [deviceUrl]]
342
- : ['xdg-open', [deviceUrl]];
343
- execFile(openBin, openArgs, (err) => {
344
- if (err) {
345
- // AC-16 fallback: print URL for manual copy-paste.
346
- process.stdout.write(`Could not open browser automatically.\n` +
347
- `Open this URL in your browser to authenticate:\n` +
348
- ` ${deviceUrl}\n`);
349
- }
350
- else {
351
- process.stdout.write(`Opening browser for authentication...\n` +
352
- `If the browser does not open, visit:\n` +
353
- ` ${deviceUrl}\n`);
354
- }
355
- });
356
- // 5. Timeout guard (AC-15). Reject so main() falls back to loginFlow.
357
- timeoutHandle = setTimeout(() => {
358
- cleanup();
359
- reject(new Error(`device-auth timed out after ${DEVICE_AUTH_TIMEOUT_MS / 1000}s`));
360
- }, DEVICE_AUTH_TIMEOUT_MS);
361
- });
362
- });
196
+ if (!body) {
197
+ err('SMOKE_SYNTH_FAIL: empty response body');
198
+ return 1;
199
+ }
200
+ out(`SMOKE_SYNTH_OK:${body.length}`);
201
+ return 0;
363
202
  }
364
- function prompt(question, hidden = false) {
365
- return new Promise((resolve) => {
366
- const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
367
- if (hidden && process.stdin.isTTY) {
368
- process.stderr.write(question);
369
- const stdin = process.stdin;
370
- stdin.setRawMode(true);
371
- stdin.resume();
372
- stdin.setEncoding('utf-8');
373
- let input = '';
374
- const onData = (ch) => {
375
- if (ch === '\n' || ch === '\r' || ch === '\u0004') {
376
- stdin.setRawMode(false);
377
- stdin.pause();
378
- stdin.removeListener('data', onData);
379
- rl.close();
380
- process.stderr.write('\n');
381
- resolve(input);
382
- }
383
- else if (ch === '\u007F' || ch === '\b') {
384
- if (input.length > 0)
385
- input = input.slice(0, -1);
386
- }
387
- else if (ch === '\u0003') {
388
- process.exit(1);
389
- }
390
- else {
391
- input += ch;
392
- }
393
- };
394
- stdin.on('data', onData);
203
+ async function offerAllConfigs(folder, io, env, out, err) {
204
+ const others = listConfigFolders(env).filter((f) => f.configFile !== folder.configFile);
205
+ if (others.length === 0) {
206
+ out('No other Claude Code config folders found.');
207
+ return true;
208
+ }
209
+ if (!io.isTTY) {
210
+ out('--all-configs needs a terminal to ask per folder; nothing else was changed.');
211
+ return true;
212
+ }
213
+ let ok = true;
214
+ for (const f of others) {
215
+ if (!(await io.confirm(`Add the TACIT entry to ${tilde(f.dir)}? (y/N) `, false))) {
216
+ out(`Left ${tilde(f.dir)} unchanged.`);
217
+ continue;
395
218
  }
219
+ const r = await registerUserEntry(f, { env });
220
+ if (r.status === 'added')
221
+ out(`Registered the TACIT entry in ${tilde(f.configFile)}.`);
222
+ else if (r.status === 'already')
223
+ out(`${tilde(f.configFile)} already has the TACIT entry.`);
224
+ else if (r.status === 'foreign')
225
+ out(`${tilde(f.configFile)} has a different tacit entry; left as it is (setup lists old entries above).`);
396
226
  else {
397
- rl.question(question, (answer) => {
398
- rl.close();
399
- resolve(answer.trim());
400
- });
227
+ ok = false;
228
+ err(`Could not register in ${tilde(f.dir)} (${r.detail ?? r.status}).`);
401
229
  }
402
- });
230
+ }
231
+ return ok;
232
+ }
233
+ function planLines(o, apiUrl, folder, count) {
234
+ return [
235
+ `(dry-run) Would sign in to ${apiUrl} using ${o.noBrowser ? 'email and password' : 'the browser'}.`,
236
+ `(dry-run) Would save profile ${o.name ?? '<named after your workspace>'} in ~/.tacit/profiles (token stored there only).`,
237
+ `(dry-run) Would load TACIT ${o.mode === 'on-demand' ? 'only when you start Claude Code with the tacit command' : 'in every session'}; config folder ${tilde(folder.dir)}.`,
238
+ ...(o.mode === 'on-demand' ? [] : [`(dry-run) Would register: claude mcp add-json --scope user ${ENTRY_NAME} '${genericEntryJson()}'`]),
239
+ `(dry-run) Old token-bearing entries it would offer to migrate: ${count}.`,
240
+ ];
403
241
  }
404
- async function loginFlow(apiUrl) {
405
- process.stderr.write('\n Log in with your TACIT credentials.\n\n');
406
- const email = await prompt(' Email: ');
407
- const pin = await prompt(' PIN: ', true);
408
- if (!email || !pin) {
409
- process.stderr.write('Error: email and PIN are required.\n');
410
- process.exit(1);
242
+ // ─── Main ────────────────────────────────────────────────────────────────────
243
+ /** Runs setup and returns the exit code (0, 1, 2 or 3). */
244
+ export async function runSetup(argv, deps = {}) {
245
+ const env = deps.env ?? process.env;
246
+ const out = deps.out ?? ((l) => { process.stdout.write(l + '\n'); });
247
+ const err = deps.err ?? ((l) => { process.stderr.write(l + '\n'); });
248
+ const fetchFn = deps.fetchFn ?? fetch;
249
+ const io = deps.io ?? defaultIo();
250
+ const cwd = deps.cwd ?? process.cwd();
251
+ let o;
252
+ let apiUrl;
253
+ try {
254
+ o = parseArgs(argv);
255
+ apiUrl = (o.apiUrl ?? env['TACIT_API_URL'] ?? DEFAULT_API_URL).replace(/\/+$/, '');
256
+ new URL(apiUrl);
411
257
  }
412
- const loginUrl = apiUrl.endsWith('/api/v1')
413
- ? `${apiUrl}/auth/login`
414
- : `${apiUrl}/api/v1/auth/login`;
415
- const res = await fetch(loginUrl, {
416
- method: 'POST',
417
- headers: { 'Content-Type': 'application/json' },
418
- body: JSON.stringify({ email, pin }),
419
- });
420
- if (!res.ok) {
421
- const body = await res.text().catch(() => '');
422
- if (res.status === 401) {
423
- process.stderr.write('\n Login failed — check your email and PIN.\n');
424
- }
425
- else {
426
- const isHtml = body.trimStart().startsWith('<!') || body.trimStart().startsWith('<html');
427
- const detail = isHtml
428
- ? `The server returned an HTML page instead of a JSON response.\n This usually means --api-url points to the web app, not the API.\n Try without --api-url (the default is correct for most users),\n or use the API URL (e.g. https://api-beta.tacitai.app).`
429
- : body.slice(0, 200);
430
- process.stderr.write(`\n Login failed (${res.status}): ${detail}\n`);
431
- }
432
- process.exit(1);
258
+ catch (e) {
259
+ err(e instanceof UsageError ? e.message : 'The API URL must be a full http(s) URL.');
260
+ return 1;
433
261
  }
434
- const data = await res.json();
435
- const token = typeof data['session_token'] === 'string' ? data['session_token'] : '';
436
- const workspaceName = typeof data['workspace_name'] === 'string' ? data['workspace_name'] : '';
437
- if (!token) {
438
- process.stderr.write('Error: login returned no session token.\n');
439
- process.exit(1);
262
+ const appUrl = (o.appUrl ?? deriveAppUrl(apiUrl)).replace(/\/+$/, '');
263
+ const folder = activeConfigFolder(env);
264
+ out(`Signing in to ${new URL(apiUrl).host}.`);
265
+ out(`Claude Code config folder: ${tilde(folder.dir)}`);
266
+ const exported = EXPORTED_NAMES.filter((n) => (env[n] ?? '') !== '');
267
+ if (exported.length > 0) {
268
+ err(`Warning: ${exported.join(', ')} ${exported.length === 1 ? 'is' : 'are'} exported in this shell. A complete TACIT_TOKEN + TACIT_API_URL + TACIT_WORKSPACE_ID set overrides saved logins.`);
440
269
  }
441
- return { token, workspaceName };
442
- }
443
- // ─── Smoke synthesis ──────────────────────────────────────────────────────────
444
- const SMOKE_QUERY = 'What is in this knowledge base?';
445
- async function runSmoke(apiUrl, token) {
446
- const client = new TacitClient({
447
- apiUrl,
448
- token: token ?? process.env['TACIT_TOKEN'] ?? '',
449
- });
450
- let body = '';
270
+ const folders = listConfigFolders(env);
271
+ if (o.dryRun) {
272
+ const entries = await scanLegacyEntries(folders, cwd);
273
+ for (const l of planLines(o, apiUrl, folder, entries.length))
274
+ out(l);
275
+ return 0;
276
+ }
277
+ // 3. sign in
278
+ let issued;
451
279
  try {
452
- // F1: use existing postSSE path (NOT a raw fetch).
453
- for await (const chunk of client.postSSE('/api/v1/mind/synthesize/stream', {
454
- query: SMOKE_QUERY,
455
- })) {
456
- body += chunk;
280
+ issued = await (deps.signInFn ?? signIn)({ apiUrl, appUrl, mode: o.noBrowser ? 'pin' : 'auto', deviceLabel: o.deviceLabel ?? getDeviceLabel(), io, fetchFn, env });
281
+ }
282
+ catch (e) {
283
+ if (e instanceof SignInError) {
284
+ if (!e.reported)
285
+ err(e.message);
286
+ return e.exitCode;
457
287
  }
288
+ err(e instanceof PromptError || e instanceof ProfileError ? e.message : 'Sign-in failed.');
289
+ return 1;
458
290
  }
459
- catch (err) {
460
- const msg = err instanceof TacitApiError
461
- ? `API error ${err.statusCode}: ${err.body}`
462
- : err instanceof Error ? err.message : String(err);
463
- process.stderr.write(`SMOKE_SYNTH_FAIL: ${msg}\n`);
464
- process.exit(1);
291
+ // 4. profile (the only place the token is stored)
292
+ let profile;
293
+ try {
294
+ const identity = { api_url: apiUrl, workspace_id: issued.workspaceId, identity_email: issued.identityEmail };
295
+ let existing;
296
+ if (o.name) {
297
+ profile = o.name;
298
+ existing = tryReadProfile(profile);
299
+ if (existing && (existing.api_url !== apiUrl || existing.workspace_id !== issued.workspaceId || (existing.identity_email ?? '').toLowerCase() !== issued.identityEmail.toLowerCase())) {
300
+ const left = await revokeUnsaved(apiUrl, issued.token, fetchFn);
301
+ err(`Profile ${profile} already holds a different login. The login just issued was not saved${left ? ` (it expires ${issued.expiresAt.slice(0, 10)})` : ' and was signed out'}. Choose another --name, or run: tacit rm ${profile}`);
302
+ if (left)
303
+ err(left);
304
+ return 1;
305
+ }
306
+ }
307
+ else {
308
+ profile = pickProfileSlug(issued.workspaceName, identity).slug;
309
+ existing = tryReadProfile(profile);
310
+ }
311
+ writeProfile(profile, {
312
+ version: 2, workspace_id: issued.workspaceId, workspace_name: issued.workspaceName, api_url: apiUrl, app_url: appUrl,
313
+ token: issued.token, created_at: new Date().toISOString(), expires_at: issued.expiresAt, identity_email: issued.identityEmail,
314
+ token_id: issued.tokenId, device_label: issued.deviceLabel, credential_kind: 'iam_token',
315
+ ...(existing?.claude_config_dir ? { claude_config_dir: existing.claude_config_dir } : {}),
316
+ });
317
+ if (getDefault() === null)
318
+ setDefault(profile);
465
319
  }
466
- if (!body || body.length === 0) {
467
- process.stderr.write('SMOKE_SYNTH_FAIL: empty response body\n');
468
- process.exit(1);
320
+ catch (e) {
321
+ err(e instanceof ProfileError ? e.message : 'Could not save the login.');
322
+ const left = await revokeUnsaved(apiUrl, issued.token, fetchFn);
323
+ err(left ?? 'The login just issued was signed out.');
324
+ return 1;
469
325
  }
470
- // Print charcount for oracle D6 verification.
471
- process.stdout.write(`SMOKE_SYNTH_OK:${body.length}\n`);
472
- process.exit(0);
473
- }
474
- // ─── Main export ──────────────────────────────────────────────────────────────
475
- export async function setup(argv) {
476
- const opts = parseArgs(argv);
477
- // Resolve api-url: flag > env > default.
478
- let apiUrl = opts.apiUrl ?? process.env['TACIT_API_URL'] ?? 'https://api-beta.tacitai.app';
479
- // Auto-correct common mistake: frontend URL (beta.tacitai.app) → API URL (api-beta.tacitai.app).
326
+ out(`Saved your login as profile ${profile} (${issued.workspaceName}).`);
327
+ if (getDefault() !== profile)
328
+ out(`Default profile stays ${getDefault() ?? '(none)'}. To use this one: tacit use ${profile}`);
329
+ let code = 0;
480
330
  try {
481
- const parsed = new URL(apiUrl);
482
- if (/^(?!api[-.]).*\.tacitai\.app$/.test(parsed.hostname)) {
483
- const corrected = `${parsed.protocol}//api-${parsed.hostname}`;
484
- process.stderr.write(`\n Note: ${apiUrl} looks like the web app URL.\n Using API URL instead: ${corrected}\n\n`);
485
- apiUrl = corrected;
331
+ // 5. load mode
332
+ let mode;
333
+ if (o.mode)
334
+ mode = o.mode;
335
+ else if (!io.isTTY) {
336
+ mode = 'always';
337
+ out('No terminal: TACIT will load in every Claude Code session. Change it later with: tacit mode on-demand');
486
338
  }
487
- }
488
- catch { /* invalid URL — let it fail naturally downstream */ }
489
- // Determine profile and token.
490
- let profile = opts.profile;
491
- let token = opts.token;
492
- let expiresAt = '';
493
- // Check env var for this profile (to support existing token path).
494
- const envVarNameForProfile = profileToEnvVar(profile);
495
- const envToken = process.env[envVarNameForProfile] ?? process.env['TACIT_TOKEN'] ?? null;
496
- if (!token && !envToken && !opts.dryRun) {
497
- // Neither --token nor env set and not a dry-run → authenticate interactively.
498
- // Try device-auth (browser flow) first; fall back to login prompt.
499
- let authenticated = false;
500
- try {
501
- const deviceResult = await deviceAuthFlow(apiUrl);
502
- token = deviceResult.token;
503
- expiresAt = deviceResult.expiresAt;
504
- if (!opts.profileExplicit && deviceResult.workspaceName) {
505
- profile = workspaceNameToProfile(deviceResult.workspaceName);
339
+ else
340
+ mode = (await io.choose('How should TACIT load in Claude Code?', ['Every session', 'Only when I start Claude Code with the tacit command'], 0)) === 1 ? 'on-demand' : 'always';
341
+ // 6. install the tacit command
342
+ if (findOnPath('tacit', env) === null) {
343
+ const wanted = o.install === 'yes' || (o.install === 'ask' && io.isTTY && (await io.confirm('Install the tacit command? (Y/n) ', true)));
344
+ if (wanted) {
345
+ if (!(await installCli(env, out, err)))
346
+ code = 3;
347
+ }
348
+ else if (mode === 'on-demand') {
349
+ err(`The tacit command is needed for on-demand mode. Install it with: npm i -g ${PACKAGE_NAME}, or run: tacit mode always`);
350
+ code = 3;
506
351
  }
507
- authenticated = true;
508
352
  }
509
- catch {
510
- // Device-auth not available — fall back to login prompt.
353
+ // 7. migrate old entries
354
+ const entries = await scanLegacyEntries(folders, cwd);
355
+ if (entries.length > 0) {
356
+ const personId = await fetchPersonId(apiUrl, issued.token, fetchFn);
357
+ await migrateLegacyEntries(entries, { io, out, env, fetchFn, apiUrl, workspaceId: issued.workspaceId, profile, personId });
511
358
  }
512
- if (!authenticated) {
513
- const loginResult = await loginFlow(apiUrl);
514
- token = loginResult.token;
515
- if (!opts.profileExplicit && loginResult.workspaceName) {
516
- profile = workspaceNameToProfile(loginResult.workspaceName);
359
+ // 8. registration
360
+ if (mode === 'on-demand') {
361
+ if (userEntryState(folder) === 'generic' && io.isTTY && (await io.confirm('Remove it so TACIT stops loading in every session? (y/N) ', false))) {
362
+ const r = await removeUserEntry(folder, { env });
363
+ if (r.status === 'removed')
364
+ out(`Removed the TACIT entry from ${tilde(folder.configFile)}.`);
365
+ else {
366
+ err(`Could not remove the entry (${r.detail ?? r.status}).`);
367
+ code = 3;
368
+ }
517
369
  }
370
+ if (o.allConfigs)
371
+ out('--all-configs registers nothing in on-demand mode.');
518
372
  }
519
- }
520
- // Final env-var name derived from (possibly updated) profile.
521
- const envVarName = profileToEnvVar(profile);
522
- // Pass the actual token when we have it (device-auth or --token);
523
- // fall back to env-var placeholder when the token came from the environment.
524
- const resolvedToken = token ?? null;
525
- const profileEntry = buildProfileEntry(apiUrl, envVarName, resolvedToken);
526
- // D10: emit confirmation string BEFORE writing (also printed in dry-run).
527
- process.stdout.write(`\n Registering MCP server "${profile}" with Claude Code...\n`);
528
- if (opts.dryRun) {
529
- process.stdout.write(' (dry-run) Would register:\n');
530
- const redactedEntry = buildProfileEntry(apiUrl, envVarName, null);
531
- process.stdout.write(` ${JSON.stringify(redactedEntry, null, 2)}\n`);
532
- process.exit(0);
533
- return;
534
- }
535
- // Register via `claude mcp add-json` — the only way Claude Code discovers MCP servers.
536
- // Writing ~/.claude/mcp.json directly does NOT work (Claude Code ignores that file).
537
- const jsonConfig = JSON.stringify(profileEntry);
538
- const registered = await new Promise((resolve) => {
539
- execFile('claude', ['mcp', 'add-json', '--scope', 'user', profile, jsonConfig], {
540
- timeout: 15_000,
541
- }, (err, stdout, stderr) => {
542
- if (err) {
543
- process.stderr.write(`\n Warning: could not register via "claude mcp add-json".\n`);
544
- process.stderr.write(` ${stderr || err.message}\n`);
545
- resolve(false);
373
+ else {
374
+ let r = await registerUserEntry(folder, { env });
375
+ if (r.status === 'foreign') {
376
+ if (io.isTTY && (await io.confirm(`The "${ENTRY_NAME}" entry in ${tilde(folder.configFile)} is not the standard one. Replace it? (y/N) `, false))) {
377
+ r = await registerUserEntry(folder, { env, replaceForeign: true });
378
+ }
379
+ else
380
+ err(`The "${ENTRY_NAME}" entry in ${tilde(folder.configFile)} was left as it is, so TACIT may not load the way setup saved it.`);
546
381
  }
547
- else {
548
- resolve(true);
382
+ if (r.status === 'added') {
383
+ out(`Registered the TACIT entry in ${tilde(folder.configFile)}:`);
384
+ out(` ${genericEntryJson()}`);
549
385
  }
550
- });
551
- });
552
- // Fallback: also write ~/.claude/mcp.json for environments without `claude` CLI.
553
- const dir = claudeDir();
554
- if (!fs.existsSync(dir)) {
555
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
556
- }
557
- const existing = readExistingConfig();
558
- const merged = mergeConfig(existing, profile, profileEntry);
559
- const output = configToBytes(merged);
560
- const dest = mcpJsonPath();
561
- fs.writeFileSync(dest, output, { encoding: 'utf-8', mode: 0o600 });
562
- fs.chmodSync(dest, 0o600);
563
- // AC-12: write ~/.tacit/profiles/<profile>.json metadata (token NOT included).
564
- if (expiresAt) {
565
- writeProfileMetadata(profile, expiresAt, apiUrl);
566
- }
567
- if (registered) {
568
- process.stdout.write(`\n Done! Start a new Claude Code session to connect.\n`);
569
- }
570
- else if (resolvedToken) {
571
- process.stdout.write(`\n Config written to ~/.claude/mcp.json (fallback).\n` +
572
- ` If Claude Code doesn't pick it up, run:\n` +
573
- ` claude mcp add-json --scope user ${profile} '${jsonConfig}'\n` +
574
- ` Then start a new Claude Code session.\n`);
575
- }
576
- else {
577
- process.stdout.write(`\n Setup complete. Add this to your shell profile:\n` +
578
- ` export ${envVarName}=<your-token>\n` +
579
- `\n Then start a new Claude Code session to connect.\n`);
386
+ else if (r.status === 'already')
387
+ out(`The TACIT entry is already registered in ${tilde(folder.configFile)}.`);
388
+ else if (r.status === 'no-claude') {
389
+ err(`Claude Code was not found. Your login is saved as profile ${profile}. After installing Claude Code, run: tacit mode always`);
390
+ code = 3;
391
+ }
392
+ else if (r.status === 'failed') {
393
+ err(`Could not register the TACIT entry (${r.detail ?? 'claude mcp add-json failed'}). Your login is saved as profile ${profile}.`);
394
+ code = 3;
395
+ }
396
+ if (o.allConfigs && r.status !== 'no-claude' && !(await offerAllConfigs(folder, io, env, out, err)))
397
+ code = 3;
398
+ }
399
+ // 9. summary
400
+ out('');
401
+ out(`Profile ${profile}`);
402
+ out(`Workspace ${issued.workspaceName}`);
403
+ out(`Signed in as ${issued.identityEmail} (expires ${issued.expiresAt.slice(0, 10)})`);
404
+ out(`Config ${tilde(folder.configFile)} (${mode === 'always' ? 'every session' : 'on demand'})`);
405
+ out(mode === 'always' ? 'Start Claude Code with: claude' : `Start Claude Code with: tacit ${profile}`);
580
406
  }
581
- if (opts.smoke) {
582
- await runSmoke(apiUrl, token);
583
- // runSmoke calls process.exit internally; return here for type safety.
584
- return;
407
+ catch (e) {
408
+ err(`${e instanceof PromptError ? e.message : 'Setup stopped.'} Your login is saved as profile ${profile}.`);
409
+ return 3;
585
410
  }
586
- process.exit(0);
411
+ if (code === 0 && o.smoke)
412
+ return runSmoke(apiUrl, issued.token, out, err);
413
+ return code;
414
+ }
415
+ export async function setup(argv) {
416
+ process.exit(await runSetup(argv));
587
417
  }