@tacitai/mcp-server 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) 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 +88 -52
  18. package/dist/client.js +195 -295
  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 +4 -4
  40. package/dist/tools/artifacts.d.ts +2 -0
  41. package/dist/tools/artifacts.js +8 -1
  42. package/dist/tools/errors.d.ts +12 -0
  43. package/dist/tools/errors.js +65 -0
  44. package/dist/tools/exec-route.d.ts +34 -0
  45. package/dist/tools/exec-route.js +101 -27
  46. package/dist/tools/iam.js +2 -3
  47. package/dist/tools/secretary.d.ts +1 -0
  48. package/dist/tools/secretary.js +2 -1
  49. package/dist/tools/synthesize.d.ts +37 -0
  50. package/dist/tools/synthesize.js +126 -7
  51. package/dist/tools/voice.d.ts +3 -2
  52. package/dist/tools/voice.js +70 -18
  53. package/dist/tools/workspaces.js +7 -4
  54. package/dist/version.d.ts +6 -0
  55. package/dist/version.js +18 -0
  56. package/dist/workflow-registry.d.ts +1 -0
  57. package/dist/workflow-registry.js +21 -0
  58. package/package.json +4 -1
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Claude Code config: token-free registration, clash detection, legacy scan (MV-1542c step 1.3).
3
+ *
4
+ * The only thing this module ever registers is an entry that names a profile, never a credential:
5
+ *
6
+ * {"type":"stdio","command":"npx","args":["-y","@tacitai/mcp-server"],"env":{"TACIT_PROFILE":"${TACIT_PROFILE:-}"}}
7
+ *
8
+ * Rules (FEAT-267, design rules 6 and 7):
9
+ * - Claude Code is driven through `claude mcp add-json|remove`, started with execFile (no shell),
10
+ * remove first, then add (`add-json` exits 1 on an existing name).
11
+ * - `~/.claude/mcp.json` is never written (Claude Code does not read it).
12
+ * - The config folder is `CLAUDE_CONFIG_DIR` when set, else `~` (its file is `<folder>/.claude.json`).
13
+ * - `.claude.json` is read, never edited here (a running `claude` can write the same file).
14
+ * - A token read from an old entry stays in memory in `LegacyEntry.token`; it is never put in argv,
15
+ * env, a message or a log line.
16
+ */
17
+ import * as fs from 'node:fs';
18
+ import * as os from 'node:os';
19
+ import * as path from 'node:path';
20
+ import { execFile } from 'node:child_process';
21
+ export const ENTRY_NAME = 'tacit';
22
+ export const PACKAGE_NAME = '@tacitai/mcp-server';
23
+ export const GENERIC_ENTRY = {
24
+ type: 'stdio', command: 'npx', args: ['-y', PACKAGE_NAME], env: { TACIT_PROFILE: '${TACIT_PROFILE:-}' },
25
+ };
26
+ export function genericEntryJson() { return JSON.stringify(GENERIC_ENTRY); }
27
+ /** On-demand launch (P6.1): inline `--mcp-config` value that names the profile literally. Never a token. */
28
+ export function onDemandMcpConfig(profile) {
29
+ return JSON.stringify({ mcpServers: { [ENTRY_NAME]: { ...GENERIC_ENTRY, env: { TACIT_PROFILE: profile } } } });
30
+ }
31
+ function canonical(v) {
32
+ if (Array.isArray(v))
33
+ return `[${v.map(canonical).join(',')}]`;
34
+ if (v && typeof v === 'object') {
35
+ const o = v;
36
+ return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(',')}}`;
37
+ }
38
+ return JSON.stringify(v);
39
+ }
40
+ export function folderFor(dir) {
41
+ const home = os.homedir();
42
+ if (dir === null || path.resolve(dir) === home) {
43
+ return { dir: home, configFile: path.join(home, '.claude.json'), isDefault: true, backupsDir: path.join(home, '.claude', 'backups') };
44
+ }
45
+ const abs = path.resolve(dir);
46
+ return { dir: abs, configFile: path.join(abs, '.claude.json'), isDefault: false, backupsDir: path.join(abs, 'backups') };
47
+ }
48
+ export function activeConfigFolder(env = process.env) {
49
+ const dir = env['CLAUDE_CONFIG_DIR'];
50
+ return folderFor(dir && dir.trim() ? dir : null);
51
+ }
52
+ function realOwnedDir(p) {
53
+ try {
54
+ const st = fs.lstatSync(p);
55
+ if (st.isSymbolicLink() || !st.isDirectory())
56
+ return false;
57
+ return process.platform === 'win32' || typeof process.getuid !== 'function' || st.uid === process.getuid();
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
63
+ /**
64
+ * Every Claude config folder on this machine: the active one first, then `~` (when `~/.claude.json`
65
+ * exists), `~/.claude` (when it holds a `.claude.json`) and each real `~/.claude-*` directory the user owns.
66
+ */
67
+ export function listConfigFolders(env = process.env) {
68
+ const home = os.homedir();
69
+ const out = [activeConfigFolder(env)];
70
+ const add = (f) => { if (!out.some((o) => o.configFile === f.configFile))
71
+ out.push(f); };
72
+ if (fs.existsSync(path.join(home, '.claude.json')))
73
+ add(folderFor(null));
74
+ const dotClaude = path.join(home, '.claude');
75
+ if (realOwnedDir(dotClaude) && fs.existsSync(path.join(dotClaude, '.claude.json')))
76
+ add(folderFor(dotClaude));
77
+ let names = [];
78
+ try {
79
+ names = fs.readdirSync(home);
80
+ }
81
+ catch { /* unreadable home */ }
82
+ for (const n of names.filter((x) => x.startsWith('.claude-')).sort()) {
83
+ if (realOwnedDir(path.join(home, n)))
84
+ add(folderFor(path.join(home, n)));
85
+ }
86
+ return out;
87
+ }
88
+ export function readClaudeJson(file) {
89
+ try {
90
+ const v = JSON.parse(fs.readFileSync(file, 'utf8'));
91
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ function servers(v) {
98
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
99
+ }
100
+ /** State of the user-scope `tacit` entry in a folder's `.claude.json`. */
101
+ export function userEntryState(folder) {
102
+ const entry = servers(readClaudeJson(folder.configFile)?.['mcpServers'])[ENTRY_NAME];
103
+ if (entry === undefined)
104
+ return 'absent';
105
+ return canonical(entry) === canonical(GENERIC_ENTRY) ? 'generic' : 'foreign';
106
+ }
107
+ /** Mode is derived from the entry, never stored (P3.4). */
108
+ export function loadMode(folder) {
109
+ const s = userEntryState(folder);
110
+ return s === 'generic' ? 'always' : s === 'absent' ? 'on-demand' : 'conflict';
111
+ }
112
+ export function envFor(folder, base = process.env) {
113
+ const env = { ...base };
114
+ if (folder) {
115
+ if (folder.isDefault)
116
+ delete env['CLAUDE_CONFIG_DIR'];
117
+ else
118
+ env['CLAUDE_CONFIG_DIR'] = folder.dir;
119
+ }
120
+ return env;
121
+ }
122
+ /** execFile, never a shell. `missing` is true when the program is not on PATH. */
123
+ export function run(command, args, opts = {}) {
124
+ return new Promise((resolve) => {
125
+ execFile(command, args, {
126
+ env: envFor(opts.folder, opts.env), cwd: opts.cwd, timeout: opts.timeoutMs ?? 20_000,
127
+ maxBuffer: 4 * 1024 * 1024, encoding: 'utf8',
128
+ }, (err, stdout, stderr) => {
129
+ const e = err;
130
+ resolve({
131
+ code: e === null ? 0 : typeof e.code === 'number' ? e.code : null,
132
+ stdout: String(stdout ?? ''), stderr: String(stderr ?? ''), missing: e?.code === 'ENOENT',
133
+ });
134
+ });
135
+ });
136
+ }
137
+ export function findOnPath(command, env = process.env) {
138
+ for (const dir of (env['PATH'] ?? '').split(path.delimiter).filter(Boolean)) {
139
+ const p = path.join(dir, command);
140
+ try {
141
+ fs.accessSync(p, fs.constants.X_OK);
142
+ if (fs.statSync(p).isFile())
143
+ return p;
144
+ }
145
+ catch { /* next */ }
146
+ }
147
+ return null;
148
+ }
149
+ function brief(r) {
150
+ return (r.stderr || r.stdout || `exit ${String(r.code)}`).trim().split('\n').slice(-2).join(' ').slice(0, 300);
151
+ }
152
+ /**
153
+ * Register the generic token-free user entry. An existing generic entry is left alone ('already'); a
154
+ * foreign one is never overwritten unless the caller got consent (`replaceForeign`). Remove, then add.
155
+ */
156
+ export async function registerUserEntry(folder, opts = {}) {
157
+ const state = userEntryState(folder);
158
+ if (state === 'generic')
159
+ return { status: 'already' };
160
+ if (state === 'foreign' && !opts.replaceForeign)
161
+ return { status: 'foreign' };
162
+ const rm = await run('claude', ['mcp', 'remove', ENTRY_NAME, '-s', 'user'], { folder, env: opts.env });
163
+ if (rm.missing)
164
+ return { status: 'no-claude' };
165
+ const add = await run('claude', ['mcp', 'add-json', '--scope', 'user', ENTRY_NAME, genericEntryJson()], { folder, env: opts.env });
166
+ if (add.missing)
167
+ return { status: 'no-claude' };
168
+ return add.code === 0 ? { status: 'added' } : { status: 'failed', detail: brief(add) };
169
+ }
170
+ export async function removeUserEntry(folder, opts = {}) {
171
+ if (userEntryState(folder) === 'absent')
172
+ return { status: 'absent' };
173
+ const rm = await run('claude', ['mcp', 'remove', ENTRY_NAME, '-s', 'user'], { folder, env: opts.env });
174
+ if (rm.missing)
175
+ return { status: 'no-claude' };
176
+ return rm.code === 0 ? { status: 'removed' } : { status: 'failed', detail: brief(rm) };
177
+ }
178
+ /** Remove-then-add one named entry (migration). `entry` must be token-free. Local scope runs in `cwd`. */
179
+ export async function replaceEntry(folder, name, scope, entry, opts = {}) {
180
+ const o = { folder, cwd: scope === 'local' ? opts.cwd : undefined, env: opts.env };
181
+ const rm = await run('claude', ['mcp', 'remove', name, '-s', scope], o);
182
+ if (rm.missing)
183
+ return { status: 'no-claude' };
184
+ const add = await run('claude', ['mcp', 'add-json', '--scope', scope, name, JSON.stringify(entry)], o);
185
+ return add.code === 0 ? { status: 'added' } : { status: 'failed', detail: brief(add) };
186
+ }
187
+ /** `claude --help` probe (P6.1 step 4). */
188
+ export async function probeClaude(opts = {}) {
189
+ const r = await run('claude', ['--help'], { env: opts.env, timeoutMs: 10_000 });
190
+ if (r.missing)
191
+ return { ok: false, missing: true, supportsMcpConfig: false, subcommands: [], reason: 'not found' };
192
+ if (r.code !== 0)
193
+ return { ok: false, missing: false, supportsMcpConfig: false, subcommands: [], reason: brief(r) };
194
+ const after = r.stdout.split(/^Commands:\s*$/m)[1] ?? '';
195
+ const subcommands = [...after.matchAll(/^ {2}([a-z][\w-]*)/gm)].map((m) => m[1]);
196
+ return { ok: true, missing: false, supportsMcpConfig: /--mcp-config\b/.test(r.stdout), subcommands };
197
+ }
198
+ function ancestors(start, stopAt) {
199
+ const out = [];
200
+ let cur = start;
201
+ for (;;) {
202
+ out.push(cur);
203
+ const parent = path.dirname(cur);
204
+ if (parent === cur || (stopAt !== null && cur === stopAt))
205
+ break;
206
+ cur = parent;
207
+ }
208
+ return out;
209
+ }
210
+ function pathVariants(cwd) {
211
+ let real = cwd;
212
+ try {
213
+ real = fs.realpathSync(cwd);
214
+ }
215
+ catch { /* keep as given */ }
216
+ return [...new Set([...ancestors(cwd, null), ...ancestors(real, null)])];
217
+ }
218
+ /**
219
+ * A server named `tacit` that would load next to ours: local-scope entries for the cwd and each ancestor
220
+ * (both the given and the realpath form), and `.mcp.json` in the cwd and each ancestor up to `$HOME`.
221
+ */
222
+ export function findClashes(cwd, folder) {
223
+ const out = [];
224
+ const home = os.homedir();
225
+ const projects = servers(readClaudeJson(folder.configFile)?.['projects']);
226
+ for (const p of pathVariants(cwd)) {
227
+ if (servers(projects[p]?.['mcpServers'])[ENTRY_NAME] !== undefined)
228
+ out.push({ scope: 'local', file: folder.configFile, path: p });
229
+ }
230
+ const seen = new Set();
231
+ for (const base of pathVariants(cwd)) {
232
+ const isInHome = base === home || base.startsWith(home + path.sep);
233
+ if (!isInHome && base !== cwd)
234
+ continue;
235
+ const file = path.join(base, '.mcp.json');
236
+ if (seen.has(file))
237
+ continue;
238
+ seen.add(file);
239
+ if (servers(readClaudeJson(file)?.['mcpServers'])[ENTRY_NAME] !== undefined)
240
+ out.push({ scope: 'project', file, path: base });
241
+ }
242
+ return out;
243
+ }
244
+ /** Shape only, for reporting; the value is never printed. */
245
+ export function tokenShape(t) {
246
+ if (/^tk_[0-9a-f]{32}$/.test(t))
247
+ return 'iam';
248
+ if (/^tk_[A-Za-z0-9]+_[A-Za-z0-9]+$/.test(t))
249
+ return 'api_key';
250
+ const parts = t.split('.');
251
+ if (parts.length === 3)
252
+ return 'jwt';
253
+ if (parts.length === 2)
254
+ return 'hmac';
255
+ if (/^[A-Za-z0-9_-]{43,44}$/.test(t))
256
+ return 'legacy';
257
+ return 'unknown';
258
+ }
259
+ function matchesTacitServer(entry) {
260
+ const args = Array.isArray(entry['args']) ? entry['args'].filter((a) => typeof a === 'string') : [];
261
+ return args.some((a) => a.includes(PACKAGE_NAME) || a.split(/[\\/]/).includes('tacit-mcp-server'));
262
+ }
263
+ function literalToken(entry) {
264
+ const env = entry['env'];
265
+ const t = env && typeof env === 'object' ? env['TACIT_TOKEN'] : undefined;
266
+ return typeof t === 'string' && t !== '' && !t.startsWith('${') ? t : null;
267
+ }
268
+ async function isGitTracked(file) {
269
+ const r = await run('git', ['ls-files', '--error-unmatch', path.basename(file)], { cwd: path.dirname(file), timeoutMs: 5000 });
270
+ return r.code === 0;
271
+ }
272
+ function toLegacy(scope, folder, file, name, entry, projectPath) {
273
+ if (!entry || typeof entry !== 'object' || !matchesTacitServer(entry))
274
+ return null;
275
+ const token = literalToken(entry);
276
+ if (token === null)
277
+ return null;
278
+ const env = entry['env'];
279
+ const str = (k) => (typeof env[k] === 'string' && env[k] !== '' ? env[k] : undefined);
280
+ return { scope, folder, file, projectPath, name, entry, token, shape: tokenShape(token),
281
+ apiUrl: str('TACIT_API_URL'), workspaceId: str('TACIT_WORKSPACE_ID'), gitTracked: false };
282
+ }
283
+ /**
284
+ * Every token-bearing TACIT server in: user and local scope of each folder, the `.mcp.json` of the cwd and
285
+ * its ancestors up to `$HOME`, and the legacy `~/.claude/mcp.json`. Read only.
286
+ */
287
+ export async function scanLegacyEntries(folders, cwd) {
288
+ const found = [];
289
+ const push = (e) => { if (e)
290
+ found.push(e); };
291
+ for (const folder of folders) {
292
+ const json = readClaudeJson(folder.configFile);
293
+ if (!json)
294
+ continue;
295
+ for (const [name, e] of Object.entries(servers(json['mcpServers'])))
296
+ push(toLegacy('user', folder, folder.configFile, name, e));
297
+ for (const [projectPath, p] of Object.entries(servers(json['projects']))) {
298
+ for (const [name, e] of Object.entries(servers(p?.['mcpServers'])))
299
+ push(toLegacy('local', folder, folder.configFile, name, e, projectPath));
300
+ }
301
+ }
302
+ const home = os.homedir();
303
+ const active = folders[0] ?? folderFor(null);
304
+ const mcpJsons = new Set();
305
+ for (const base of ancestors(cwd, home))
306
+ mcpJsons.add(path.join(base, '.mcp.json'));
307
+ for (const file of mcpJsons) {
308
+ for (const [name, e] of Object.entries(servers(readClaudeJson(file)?.['mcpServers']))) {
309
+ const l = toLegacy('project', active, file, name, e, path.dirname(file));
310
+ if (l) {
311
+ l.gitTracked = await isGitTracked(file);
312
+ push(l);
313
+ }
314
+ }
315
+ }
316
+ const legacyFile = path.join(home, '.claude', 'mcp.json');
317
+ for (const [name, e] of Object.entries(servers(readClaudeJson(legacyFile)?.['mcpServers'])))
318
+ push(toLegacy('legacy-file', active, legacyFile, name, e));
319
+ return found;
320
+ }
321
+ /** Backup files Claude Code keeps that still contain a `TACIT_TOKEN` key. */
322
+ export function countBackupsWithToken(folder) {
323
+ let names = [];
324
+ try {
325
+ names = fs.readdirSync(folder.backupsDir);
326
+ }
327
+ catch {
328
+ return { total: 0, withToken: 0 };
329
+ }
330
+ let withToken = 0;
331
+ for (const n of names) {
332
+ try {
333
+ if (fs.readFileSync(path.join(folder.backupsDir, n), 'utf8').includes('"TACIT_TOKEN"'))
334
+ withToken++;
335
+ }
336
+ catch { /* skip */ }
337
+ }
338
+ return { total: names.length, withToken };
339
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `tacit <name> [claude args...]` and the bare-`tacit` picker (MV-1542c step 1.6, P6.1).
3
+ *
4
+ * Launching only SELECTS a stored profile by name: `TACIT_PROFILE=<name>` goes to the child and the MCP
5
+ * server (credentials.ts) loads it. The server decides what the token can reach; nothing here widens access.
6
+ *
7
+ * Order (each failing step stops, `claude` is never started on a refusal):
8
+ * 1 safe-load the profile, refuse an expired one 2 child env: strip the five credential variables
9
+ * 3 config folder (profile claude_config_dir) 4 probe `claude --help`
10
+ * 5 clash check (a second `tacit` server) 6 mode: always -> `claude ...`;
11
+ * on-demand -> `claude ... --mcp-config <json>` last
12
+ *
13
+ * `claude` is started with spawn + an argv array, never a shell. No token is ever in argv or in the child
14
+ * environment: the child gets `TACIT_PROFILE` and nothing else of ours.
15
+ */
16
+ import { spawn, type SpawnOptions } from 'node:child_process';
17
+ import { type CliContext } from './cli-mode.js';
18
+ import type { SignInIo } from './signin.js';
19
+ /** The variables `tacit <name>` removes from the child so a shell export cannot win over the saved login. */
20
+ export declare const STRIPPED_ENV: readonly ["TACIT_TOKEN", "TACIT_WORKSPACE_ID", "TACIT_API_URL", "TACIT_APP_URL", "TACIT_SESSION_TOKEN"];
21
+ export interface LaunchContext extends CliContext {
22
+ spawnFn?: (command: string, args: string[], options: SpawnOptions) => ReturnType<typeof spawn>;
23
+ now?: () => number;
24
+ }
25
+ /** D-50: the environment for the child (and for `tacit status --name`): credentials out, profile in. */
26
+ export declare function launchEnv(base: NodeJS.ProcessEnv, name: string): {
27
+ env: NodeJS.ProcessEnv;
28
+ ignored: string[];
29
+ };
30
+ /** Returns the exit code. Never throws for an expected refusal. */
31
+ export declare function launch(name: string, extraArgs: string[], ctx: LaunchContext): Promise<number>;
32
+ /** Bare `tacit`: pick a saved login, then launch it. Needs a terminal. */
33
+ export declare function pickAndLaunch(ctx: LaunchContext, io: SignInIo): Promise<number>;
@@ -0,0 +1,178 @@
1
+ /**
2
+ * `tacit <name> [claude args...]` and the bare-`tacit` picker (MV-1542c step 1.6, P6.1).
3
+ *
4
+ * Launching only SELECTS a stored profile by name: `TACIT_PROFILE=<name>` goes to the child and the MCP
5
+ * server (credentials.ts) loads it. The server decides what the token can reach; nothing here widens access.
6
+ *
7
+ * Order (each failing step stops, `claude` is never started on a refusal):
8
+ * 1 safe-load the profile, refuse an expired one 2 child env: strip the five credential variables
9
+ * 3 config folder (profile claude_config_dir) 4 probe `claude --help`
10
+ * 5 clash check (a second `tacit` server) 6 mode: always -> `claude ...`;
11
+ * on-demand -> `claude ... --mcp-config <json>` last
12
+ *
13
+ * `claude` is started with spawn + an argv array, never a shell. No token is ever in argv or in the child
14
+ * environment: the child gets `TACIT_PROFILE` and nothing else of ours.
15
+ */
16
+ import { spawn } from 'node:child_process';
17
+ import * as os from 'node:os';
18
+ import { ENTRY_NAME, findClashes, loadMode, onDemandMcpConfig, probeClaude, userEntryState, } from './claude-config.js';
19
+ import { expiredProfile } from './api-errors.js';
20
+ import { CLAUDE_NOT_FOUND, folderForProfile, legacyEntryMessage } from './cli-mode.js';
21
+ import { ProfileError, getDefault, listProfiles, readProfile } from './profile-store.js';
22
+ /** The variables `tacit <name>` removes from the child so a shell export cannot win over the saved login. */
23
+ export const STRIPPED_ENV = [
24
+ 'TACIT_TOKEN', 'TACIT_WORKSPACE_ID', 'TACIT_API_URL', 'TACIT_APP_URL', 'TACIT_SESSION_TOKEN',
25
+ ];
26
+ const EXPIRY_NOTICE_DAYS = 14;
27
+ const DAY_MS = 86_400_000;
28
+ /** D-50: the environment for the child (and for `tacit status --name`): credentials out, profile in. */
29
+ export function launchEnv(base, name) {
30
+ const env = { ...base };
31
+ const ignored = STRIPPED_ENV.filter((k) => (base[k] ?? '') !== '');
32
+ for (const k of STRIPPED_ENV)
33
+ delete env[k];
34
+ env['TACIT_PROFILE'] = name;
35
+ return { env, ignored: [...ignored] };
36
+ }
37
+ function dateOf(ms) {
38
+ return new Date(ms).toISOString().slice(0, 10);
39
+ }
40
+ function workspaceOf(p) {
41
+ return p.workspace_name ?? p.workspace_id;
42
+ }
43
+ /** Signal exit becomes 128 + signal number, like a shell reports it. */
44
+ function exitCodeOf(code, signal) {
45
+ if (code !== null)
46
+ return code;
47
+ return signal ? 128 + (os.constants.signals[signal] ?? 0) : 1;
48
+ }
49
+ function runChild(args, env, ctx) {
50
+ return new Promise((resolve) => {
51
+ const start = ctx.spawnFn ?? spawn;
52
+ const ignore = () => { };
53
+ let settled = false;
54
+ const finish = (code) => {
55
+ if (settled)
56
+ return;
57
+ settled = true;
58
+ process.off('SIGINT', ignore);
59
+ process.off('SIGTERM', ignore);
60
+ resolve(code);
61
+ };
62
+ // The terminal sends Ctrl-C to the whole foreground group; `claude` handles it, this process waits.
63
+ process.on('SIGINT', ignore);
64
+ process.on('SIGTERM', ignore);
65
+ const child = start('claude', args, { stdio: 'inherit', env, cwd: ctx.cwd });
66
+ child.on('error', (err) => {
67
+ ctx.err(err.code === 'ENOENT' ? CLAUDE_NOT_FOUND : `Failed to launch claude: ${err.message}`);
68
+ finish(1);
69
+ });
70
+ child.on('exit', (code, signal) => { finish(exitCodeOf(code, signal)); });
71
+ });
72
+ }
73
+ function clashMessage(name, c) {
74
+ return `A server named "${ENTRY_NAME}" is already configured in ${c.file} (${c.scope}). ` +
75
+ `tacit ${name} would load a second one or connect a different workspace. ` +
76
+ `Remove it with: claude mcp remove ${ENTRY_NAME} -s ${c.scope} or run claude from another folder.`;
77
+ }
78
+ /** Returns the exit code. Never throws for an expected refusal. */
79
+ export async function launch(name, extraArgs, ctx) {
80
+ const now = (ctx.now ?? Date.now)();
81
+ // 1. profile
82
+ let profile;
83
+ try {
84
+ profile = readProfile(name);
85
+ }
86
+ catch (err) {
87
+ if (err instanceof ProfileError) {
88
+ ctx.err(err.message);
89
+ return 1;
90
+ }
91
+ throw err;
92
+ }
93
+ if (profile.expires_at) {
94
+ const expiresMs = Date.parse(profile.expires_at);
95
+ if (!Number.isNaN(expiresMs)) {
96
+ if (now > expiresMs) {
97
+ ctx.err(expiredProfile(workspaceOf(profile), dateOf(expiresMs)));
98
+ return 1;
99
+ }
100
+ const daysLeft = Math.floor((expiresMs - now) / DAY_MS);
101
+ if (daysLeft < EXPIRY_NOTICE_DAYS) {
102
+ ctx.err(`[TACIT] Your login for ${workspaceOf(profile)} expires in ${daysLeft} day${daysLeft === 1 ? '' : 's'}. Run: tacit login`);
103
+ }
104
+ }
105
+ }
106
+ // 3. config folder (before the env so CLAUDE_CONFIG_DIR is part of it)
107
+ const where = folderForProfile(name, profile, ctx.env);
108
+ if ('error' in where) {
109
+ ctx.err(where.error);
110
+ return 1;
111
+ }
112
+ const folder = where.folder;
113
+ // 2. child environment
114
+ const { env: childBase, ignored } = launchEnv(ctx.env, name);
115
+ const env = { ...childBase };
116
+ if (folder.isDefault)
117
+ delete env['CLAUDE_CONFIG_DIR'];
118
+ else
119
+ env['CLAUDE_CONFIG_DIR'] = folder.dir;
120
+ if (ignored.length > 0) {
121
+ ctx.err(`Ignoring ${ignored.join('/')} from your shell: tacit ${name} uses the saved login.`);
122
+ }
123
+ // 4. probe
124
+ const probe = await probeClaude({ env });
125
+ if (probe.missing) {
126
+ ctx.err(CLAUDE_NOT_FOUND);
127
+ return 1;
128
+ }
129
+ if (!probe.ok) {
130
+ ctx.err(`Could not run "claude --help" (${probe.reason ?? 'unknown error'}).`);
131
+ return 1;
132
+ }
133
+ // `tacit <name> mcp list`: a Claude subcommand goes through untouched, with the profile selected.
134
+ if (extraArgs[0] !== undefined && probe.subcommands.includes(extraArgs[0])) {
135
+ return runChild(extraArgs, env, ctx);
136
+ }
137
+ // 5. clash (always) and legacy entry
138
+ const clashes = findClashes(ctx.cwd, folder);
139
+ if (clashes.length > 0) {
140
+ for (const c of clashes)
141
+ ctx.err(clashMessage(name, c));
142
+ return 1;
143
+ }
144
+ if (userEntryState(folder) === 'foreign') {
145
+ ctx.err(legacyEntryMessage(folder));
146
+ return 1;
147
+ }
148
+ // 6. mode
149
+ if (loadMode(folder) === 'always')
150
+ return runChild(extraArgs, env, ctx);
151
+ if (!probe.supportsMcpConfig) {
152
+ ctx.err('Claude Code is too old for on-demand mode. Update it, or run: tacit mode always');
153
+ return 1;
154
+ }
155
+ // --mcp-config is variadic, so it goes last. The JSON names the profile; it never holds a token.
156
+ return runChild([...extraArgs, '--mcp-config', onDemandMcpConfig(name)], env, ctx);
157
+ }
158
+ /** Bare `tacit`: pick a saved login, then launch it. Needs a terminal. */
159
+ export async function pickAndLaunch(ctx, io) {
160
+ if (!io.isTTY) {
161
+ ctx.err('Usage: tacit <profile-name> | tacit login | tacit ls');
162
+ return 1;
163
+ }
164
+ const profiles = listProfiles();
165
+ if (profiles.length === 0) {
166
+ ctx.err('No saved logins. Run: npx @tacitai/mcp-server setup');
167
+ return 1;
168
+ }
169
+ const defaultName = getDefault();
170
+ const items = profiles.map((p) => `${p.data.workspace_name ?? p.name} (${p.name})${p.name === defaultName ? ' *' : ''}`);
171
+ const defIdx = Math.max(0, profiles.findIndex((p) => p.name === defaultName));
172
+ const idx = await io.choose('Workspaces:', items, defIdx);
173
+ if (!Number.isInteger(idx) || idx < 0 || idx >= profiles.length) {
174
+ ctx.err('Invalid selection.');
175
+ return 1;
176
+ }
177
+ return launch(profiles[idx].name, [], ctx);
178
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * `tacit login` (MV-1542c step 1.6, P6.3, S-4).
3
+ *
4
+ * tacit login [--api-url <url>] [--app-url <url>] [--name <profile>] [--no-browser]
5
+ * [--device-label <label>] [--claude-config-dir <abs>] [--revoke-old]
6
+ *
7
+ * Same `signIn` as `setup` (device flow, or email + password). It writes the profile and nothing else: no Claude
8
+ * Code config is touched. Only the user-approved login is stored, in the 0600 profile.
9
+ *
10
+ * Re-login of a profile known up front (`--name p`, or "yes" to the renew prompt when exactly one profile
11
+ * matches the server) sends that profile's `token_id` as `rotate_token_id` on the password path, so the server
12
+ * supersedes exactly that row (and answers 403 TOKEN_NOT_OWNED for a row that is not this identity's).
13
+ * `--revoke-old` then signs the replaced login out at once instead of letting it lapse after its 48 h
14
+ * overlap; it presents the OLD token to its own server's self-revoke route, which revokes only that row.
15
+ */
16
+ import { type CliContext } from './cli-mode.js';
17
+ import { type IssuedCredential, type SignInIo, type SignInOptions } from './signin.js';
18
+ export interface LoginContext extends CliContext {
19
+ io?: SignInIo;
20
+ signInFn?: (opts: SignInOptions) => Promise<IssuedCredential>;
21
+ fetchFn?: typeof fetch;
22
+ }
23
+ export interface LoginOptions {
24
+ apiUrl?: string;
25
+ appUrl?: string;
26
+ name?: string;
27
+ noBrowser: boolean;
28
+ deviceLabel?: string;
29
+ claudeConfigDir?: string;
30
+ revokeOld: boolean;
31
+ }
32
+ export declare function parseLoginArgs(argv: string[]): LoginOptions;
33
+ /** Returns the exit code. */
34
+ export declare function runLogin(argv: string[], ctx: LoginContext): Promise<number>;