cueapril 0.0.0-stage → 1.2.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.
package/agents.mjs ADDED
@@ -0,0 +1,996 @@
1
+ // Detects coding agents and gives each a user-level CueApril MCP entry.
2
+ //
3
+ // Claude Code claude mcp remove/add-json --scope user (argument array, no shell); the
4
+ // entry's headersHelper prints claude-code-headers.json beside the credentials
5
+ // Codex [mcp_servers.cueapril] in ~/.codex/config.toml ($CODEX_HOME)
6
+ // Gemini CLI mcpServers.cueapril in ~/.gemini/settings.json ($GEMINI_CLI_HOME/.gemini)
7
+ // Cursor mcpServers.cueapril in ~/.cursor/mcp.json
8
+ //
9
+ // Configuration is only ever written at user level, never inside a repository.
10
+ // Edited files are backed up to <file>.cueapril.bak first and end up 0600
11
+ // because they hold the key. Only the cueapril entries change: the TOML editor
12
+ // keeps every other byte, the JSON editor every other key. The key is never put
13
+ // on a command line: Claude Code's own config is changed only through its CLI
14
+ // (it locks and merges ~/.claude.json itself), with an entry that names a
15
+ // helper command instead of the key.
16
+ import {
17
+ BOM,
18
+ CliError,
19
+ assertOutsideRepository,
20
+ atomicWriteFile,
21
+ defaultDeps,
22
+ displayPath,
23
+ exists,
24
+ homeDir,
25
+ isExecutable,
26
+ lstatIfExists,
27
+ pathFor,
28
+ readFileIfExists,
29
+ redact,
30
+ runCommand,
31
+ safeText,
32
+ which,
33
+ } from './io.mjs';
34
+ import { assertPrivateConfigFile, configDir, maskKey } from './key-store.mjs';
35
+
36
+ export const AGENT_IDS = Object.freeze(['claude', 'codex', 'gemini', 'cursor']);
37
+ export const AGENT_NAMES = Object.freeze({
38
+ claude: 'Claude Code',
39
+ codex: 'Codex',
40
+ gemini: 'Gemini CLI',
41
+ cursor: 'Cursor',
42
+ });
43
+ export const SERVER_NAME = 'cueapril';
44
+ export const BACKUP_SUFFIX = '.cueapril.bak';
45
+ /** Codex's default MCP tool timeout; the wait tool returns within 50 s. */
46
+ export const CODEX_TOOL_TIMEOUT_SEC = 60;
47
+ const PLACEHOLDER_KEY_TEXT = '<key from cueapril login>';
48
+
49
+ // Secret-bearing parts of a plan live here, outside the plan objects, so a
50
+ // plan can be printed or serialised without ever exposing the key.
51
+ const payloads = new WeakMap();
52
+
53
+ export function mcpUrl(baseUrl) {
54
+ return `${baseUrl}/mcp`;
55
+ }
56
+
57
+ function stripBom(text) {
58
+ return text.startsWith(BOM) ? text.slice(BOM.length) : text;
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // Detection
63
+
64
+ function codexHome(io) {
65
+ const p = pathFor(io);
66
+ const configured = typeof io.env.CODEX_HOME === 'string' ? io.env.CODEX_HOME.trim() : '';
67
+ return configured && p.isAbsolute(configured) ? configured : p.join(homeDir(io), '.codex');
68
+ }
69
+
70
+ function geminiDir(io) {
71
+ const p = pathFor(io);
72
+ const configured = typeof io.env.GEMINI_CLI_HOME === 'string' ? io.env.GEMINI_CLI_HOME.trim() : '';
73
+ return p.join(configured && p.isAbsolute(configured) ? configured : homeDir(io), '.gemini');
74
+ }
75
+
76
+ export function claudeJsonPath(io) {
77
+ const p = pathFor(io);
78
+ const configured = typeof io.env.CLAUDE_CONFIG_DIR === 'string' ? io.env.CLAUDE_CONFIG_DIR.trim() : '';
79
+ return p.join(configured && p.isAbsolute(configured) ? configured : homeDir(io), '.claude.json');
80
+ }
81
+
82
+ /** Config file each agent's CueApril entry lives in (Claude Code's is written by its CLI). */
83
+ export function agentConfigPath(id, deps = {}) {
84
+ const io = defaultDeps(deps);
85
+ const p = pathFor(io);
86
+ if (id === 'claude') return claudeJsonPath(io);
87
+ if (id === 'codex') return p.join(codexHome(io), 'config.toml');
88
+ if (id === 'gemini') return p.join(geminiDir(io), 'settings.json');
89
+ if (id === 'cursor') return p.join(homeDir(io), '.cursor', 'mcp.json');
90
+ throw new CliError(`Unknown agent "${safeText(id, 40)}".`);
91
+ }
92
+
93
+ function versionOf(name) {
94
+ const match = /^anthropic\.claude-code-(\d+)\.(\d+)\.(\d+)/.exec(name);
95
+ return match ? match.slice(1).map(Number) : null;
96
+ }
97
+
98
+ function compareVersions(a, b) {
99
+ for (let i = 0; i < 3; i += 1) if (a[i] !== b[i]) return a[i] - b[i];
100
+ return 0;
101
+ }
102
+
103
+ /**
104
+ * Finds the claude CLI: PATH first, then the standard install locations, then
105
+ * the newest native binary shipped inside an editor extension.
106
+ */
107
+ export async function findClaudeBinary(deps = {}) {
108
+ const io = defaultDeps(deps);
109
+ const onPath = await which(io, 'claude');
110
+ if (onPath) return onPath;
111
+ const p = pathFor(io);
112
+ const home = homeDir(io);
113
+ const exe = io.platform === 'win32' ? '.exe' : '';
114
+ for (const candidate of [
115
+ p.join(home, '.local', 'bin', `claude${exe}`),
116
+ p.join(home, '.claude', 'local', `claude${exe}`),
117
+ p.join(home, '.claude', 'local', 'node_modules', '.bin', 'claude'),
118
+ ]) {
119
+ if (await isExecutable(io, candidate)) return candidate;
120
+ }
121
+ let best = null;
122
+ for (const editor of ['.vscode', '.vscode-insiders', '.cursor', '.windsurf', '.vscode-server']) {
123
+ const dir = p.join(home, editor, 'extensions');
124
+ let entries = [];
125
+ try {
126
+ entries = await io.fs.readdir(dir);
127
+ } catch {
128
+ continue;
129
+ }
130
+ for (const entry of entries) {
131
+ const version = versionOf(String(entry));
132
+ if (!version) continue;
133
+ const candidate = p.join(dir, String(entry), 'resources', 'native-binary', `claude${exe}`);
134
+ if ((!best || compareVersions(version, best.version) > 0) && (await isExecutable(io, candidate))) {
135
+ best = { version, path: candidate };
136
+ }
137
+ }
138
+ }
139
+ return best ? best.path : null;
140
+ }
141
+
142
+ /**
143
+ * Lists the supported agents and whether each is installed:
144
+ * [{ id, name, detected, evidence: [...], binary?, configPath }].
145
+ */
146
+ export async function detectAgents(deps = {}) {
147
+ const io = defaultDeps(deps);
148
+ const p = pathFor(io);
149
+ const home = homeDir(io);
150
+ const show = (target) => displayPath(io, target);
151
+ const results = [];
152
+
153
+ // ~/.claude alone is weak evidence: installing the cueapril-qa skill creates
154
+ // ~/.claude/skills. Claude Code itself leaves ~/.claude.json and other state.
155
+ const claudeBinary = await findClaudeBinary(io);
156
+ const claudeEvidence = [];
157
+ if (claudeBinary) claudeEvidence.push(`claude at ${show(claudeBinary)}`);
158
+ if (await exists(io, claudeJsonPath(io))) claudeEvidence.push(show(claudeJsonPath(io)));
159
+ const claudeDir = p.join(home, '.claude');
160
+ const claudeState = await io.fs.readdir(claudeDir).catch(() => []);
161
+ if (claudeState.some((entry) => String(entry) !== 'skills' && !String(entry).startsWith('.'))) {
162
+ claudeEvidence.push(show(claudeDir));
163
+ }
164
+ results.push({
165
+ id: 'claude',
166
+ name: AGENT_NAMES.claude,
167
+ detected: claudeEvidence.length > 0,
168
+ evidence: claudeEvidence,
169
+ binary: claudeBinary,
170
+ configPath: claudeJsonPath(io),
171
+ });
172
+
173
+ for (const [id, command, dir] of [
174
+ ['codex', 'codex', codexHome(io)],
175
+ ['gemini', 'gemini', geminiDir(io)],
176
+ ]) {
177
+ const evidence = [];
178
+ const binary = await which(io, command);
179
+ if (binary) evidence.push(`${command} at ${show(binary)}`);
180
+ if (await exists(io, dir)) evidence.push(show(dir));
181
+ results.push({
182
+ id,
183
+ name: AGENT_NAMES[id],
184
+ detected: evidence.length > 0,
185
+ evidence,
186
+ binary,
187
+ configPath: agentConfigPath(id, io),
188
+ });
189
+ }
190
+
191
+ const cursorDir = p.join(home, '.cursor');
192
+ const cursorFound = await exists(io, cursorDir);
193
+ results.push({
194
+ id: 'cursor',
195
+ name: AGENT_NAMES.cursor,
196
+ detected: cursorFound,
197
+ evidence: cursorFound ? [show(cursorDir)] : [],
198
+ binary: null,
199
+ configPath: agentConfigPath('cursor', io),
200
+ });
201
+ return results;
202
+ }
203
+
204
+ /** Parses --agents: auto (default), none, or a comma list of agent ids. */
205
+ export function parseAgentList(raw) {
206
+ const text = String(raw ?? 'auto').trim().toLowerCase();
207
+ if (text === '' || text === 'auto') return 'auto';
208
+ if (text === 'none') return [];
209
+ const ids = [...new Set(text.split(',').map((part) => part.trim()).filter(Boolean))];
210
+ const aliases = { 'claude-code': 'claude', 'gemini-cli': 'gemini' };
211
+ const resolved = ids.map((id) => aliases[id] ?? id);
212
+ const unknown = resolved.filter((id) => !AGENT_IDS.includes(id));
213
+ if (unknown.length) {
214
+ throw new CliError(`Unknown agent "${safeText(unknown[0], 40)}". Use auto, none or a list of: ${AGENT_IDS.join(', ')}.`);
215
+ }
216
+ return resolved;
217
+ }
218
+
219
+ // ---------------------------------------------------------------------------
220
+ // TOML scanning for Codex. This is not a full TOML parser: it finds table
221
+ // headers and key/value starts while tracking strings, comments and brackets,
222
+ // so a header-like line inside a multi-line string or array is never taken
223
+ // for a table. Anything it cannot read makes the edit fail closed.
224
+
225
+ export class TomlScanError extends Error {
226
+ constructor(message, line) {
227
+ super(`line ${line}: ${message}`);
228
+ this.name = 'TomlScanError';
229
+ this.line = line;
230
+ }
231
+ }
232
+
233
+ function splitLines(text) {
234
+ const lines = [];
235
+ let start = 0;
236
+ while (start < text.length) {
237
+ const newline = text.indexOf('\n', start);
238
+ if (newline === -1) {
239
+ lines.push({ body: text.slice(start), eol: '' });
240
+ break;
241
+ }
242
+ const crlf = newline > start && text[newline - 1] === '\r';
243
+ lines.push({ body: text.slice(start, crlf ? newline - 1 : newline), eol: crlf ? '\r\n' : '\n' });
244
+ start = newline + 1;
245
+ }
246
+ return lines;
247
+ }
248
+
249
+ function skipSpace(text, index) {
250
+ let i = index;
251
+ while (text[i] === ' ' || text[i] === '\t') i += 1;
252
+ return i;
253
+ }
254
+
255
+ const ESCAPES = { b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', e: '\u001b', '"': '"', '\\': '\\' };
256
+
257
+ function readBasicString(text, index) {
258
+ let out = '';
259
+ let i = index + 1;
260
+ while (i < text.length) {
261
+ const char = text[i];
262
+ if (char === '"') return { value: out, end: i + 1 };
263
+ if (char === '\\') {
264
+ const next = text[i + 1];
265
+ if (next in ESCAPES) {
266
+ out += ESCAPES[next];
267
+ i += 2;
268
+ continue;
269
+ }
270
+ const length = next === 'u' ? 4 : next === 'U' ? 8 : next === 'x' ? 2 : 0;
271
+ const hex = text.slice(i + 2, i + 2 + length);
272
+ if (!length || hex.length !== length || !/^[0-9A-Fa-f]+$/.test(hex)) return null;
273
+ try {
274
+ out += String.fromCodePoint(parseInt(hex, 16));
275
+ } catch {
276
+ return null;
277
+ }
278
+ i += 2 + length;
279
+ continue;
280
+ }
281
+ out += char;
282
+ i += 1;
283
+ }
284
+ return null;
285
+ }
286
+
287
+ function readKeyPath(text, index) {
288
+ const parts = [];
289
+ let i = index;
290
+ for (;;) {
291
+ i = skipSpace(text, i);
292
+ if (text[i] === '"') {
293
+ const string = readBasicString(text, i);
294
+ if (!string) return null;
295
+ parts.push(string.value);
296
+ i = string.end;
297
+ } else if (text[i] === "'") {
298
+ const end = text.indexOf("'", i + 1);
299
+ if (end === -1) return null;
300
+ parts.push(text.slice(i + 1, end));
301
+ i = end + 1;
302
+ } else {
303
+ const start = i;
304
+ while (i < text.length && /[A-Za-z0-9_-]/.test(text[i])) i += 1;
305
+ if (i === start) return null;
306
+ parts.push(text.slice(start, i));
307
+ }
308
+ i = skipSpace(text, i);
309
+ if (text[i] !== '.') return { parts, end: i };
310
+ i += 1;
311
+ }
312
+ }
313
+
314
+ function closeRun(text, index, quote) {
315
+ let end = index;
316
+ while (text[end] === quote) end += 1;
317
+ return end - index <= 5 ? end : -1;
318
+ }
319
+
320
+ function scanValue(text, index, startState, startDepth, line) {
321
+ let state = startState;
322
+ let depth = startDepth;
323
+ let i = index;
324
+ while (i < text.length) {
325
+ const char = text[i];
326
+ if (state === 'basic-ml') {
327
+ if (char === '\\') {
328
+ i += 2;
329
+ } else if (text.startsWith('"""', i)) {
330
+ i = closeRun(text, i, '"');
331
+ if (i < 0) throw new TomlScanError('too many quotes closing a string', line);
332
+ state = null;
333
+ } else {
334
+ i += 1;
335
+ }
336
+ continue;
337
+ }
338
+ if (state === 'literal-ml') {
339
+ if (text.startsWith("'''", i)) {
340
+ i = closeRun(text, i, "'");
341
+ if (i < 0) throw new TomlScanError('too many quotes closing a string', line);
342
+ state = null;
343
+ } else {
344
+ i += 1;
345
+ }
346
+ continue;
347
+ }
348
+ if (char === '#') break;
349
+ if (char === '"') {
350
+ if (text.startsWith('"""', i)) {
351
+ state = 'basic-ml';
352
+ i += 3;
353
+ continue;
354
+ }
355
+ const string = readBasicString(text, i);
356
+ if (!string) throw new TomlScanError('unterminated string', line);
357
+ i = string.end;
358
+ continue;
359
+ }
360
+ if (char === "'") {
361
+ if (text.startsWith("'''", i)) {
362
+ state = 'literal-ml';
363
+ i += 3;
364
+ continue;
365
+ }
366
+ const end = text.indexOf("'", i + 1);
367
+ if (end === -1) throw new TomlScanError('unterminated string', line);
368
+ i = end + 1;
369
+ continue;
370
+ }
371
+ if (char === '[' || char === '{') depth += 1;
372
+ if (char === ']' || char === '}') {
373
+ depth -= 1;
374
+ if (depth < 0) throw new TomlScanError('unbalanced brackets', line);
375
+ }
376
+ i += 1;
377
+ }
378
+ return { state, depth };
379
+ }
380
+
381
+ /**
382
+ * Classifies each line as header, kv (a key/value start), cont (inside a
383
+ * multi-line value), comment or blank. Records keep the exact line text and
384
+ * line ending so unchanged lines can be written back byte for byte.
385
+ */
386
+ export function scanToml(text) {
387
+ const records = [];
388
+ let state = null;
389
+ let depth = 0;
390
+ let table = [];
391
+ splitLines(text).forEach((line, index) => {
392
+ const number = index + 1;
393
+ const record = { body: line.body, eol: line.eol, kind: '', table, path: null, isArray: false };
394
+ if (state || depth > 0) {
395
+ record.kind = 'cont';
396
+ ({ state, depth } = scanValue(line.body, 0, state, depth, number));
397
+ } else {
398
+ const start = skipSpace(line.body, 0);
399
+ const first = line.body[start];
400
+ if (first === undefined) {
401
+ record.kind = 'blank';
402
+ } else if (first === '#') {
403
+ record.kind = 'comment';
404
+ } else if (first === '[') {
405
+ const isArray = line.body[start + 1] === '[';
406
+ const key = readKeyPath(line.body, start + (isArray ? 2 : 1));
407
+ if (!key) throw new TomlScanError('unreadable table header', number);
408
+ let i = key.end;
409
+ if (isArray ? !line.body.startsWith(']]', i) : line.body[i] !== ']') {
410
+ throw new TomlScanError('unreadable table header', number);
411
+ }
412
+ i = skipSpace(line.body, i + (isArray ? 2 : 1));
413
+ if (i < line.body.length && line.body[i] !== '#') {
414
+ throw new TomlScanError('unexpected text after a table header', number);
415
+ }
416
+ table = key.parts;
417
+ Object.assign(record, { kind: 'header', table, path: key.parts, isArray });
418
+ } else {
419
+ const key = readKeyPath(line.body, start);
420
+ if (!key || line.body[key.end] !== '=') throw new TomlScanError('expected "key = value"', number);
421
+ Object.assign(record, { kind: 'kv', path: key.parts });
422
+ ({ state, depth } = scanValue(line.body, key.end + 1, null, 0, number));
423
+ }
424
+ }
425
+ records.push(record);
426
+ });
427
+ if (state || depth > 0) throw new TomlScanError('a value is not closed at the end of the file', records.length);
428
+ return records;
429
+ }
430
+
431
+ function startsWithPath(path, prefix) {
432
+ return path.length >= prefix.length && prefix.every((part, i) => path[i] === part);
433
+ }
434
+
435
+ export function tomlString(value) {
436
+ const escaped = String(value)
437
+ .replace(/\\/g, '\\\\')
438
+ .replace(/"/g, '\\"')
439
+ .replace(/[\u0000-\u001f\u007f]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
440
+ return `"${escaped}"`;
441
+ }
442
+
443
+ /** The two Codex tables CueApril owns, in Codex's config.toml syntax. */
444
+ export function codexBlock(baseUrl, key, eol = '\n') {
445
+ return (
446
+ [
447
+ `[mcp_servers.${SERVER_NAME}]`,
448
+ '# Added by `cueapril init`. This table holds a secret key: keep this file private.',
449
+ `url = ${tomlString(mcpUrl(baseUrl))}`,
450
+ `http_headers = { Authorization = ${tomlString(`Bearer ${key}`)} }`,
451
+ `tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC}`,
452
+ '',
453
+ `[mcp_servers.${SERVER_NAME}.tools.cueapril_start_assessment]`,
454
+ 'approval_mode = "approve"',
455
+ ].join(eol) + eol
456
+ );
457
+ }
458
+
459
+ function sectionsOf(records) {
460
+ const sections = [];
461
+ records.forEach((record, index) => {
462
+ if (record.kind === 'header') sections.push({ start: index, path: record.path, isArray: record.isArray });
463
+ });
464
+ sections.forEach((section, n) => {
465
+ section.end = n + 1 < sections.length ? sections[n + 1].start : records.length;
466
+ section.coreEnd = section.start;
467
+ for (let i = section.start + 1; i < section.end; i += 1) {
468
+ if (records[i].kind === 'kv' || records[i].kind === 'cont') section.coreEnd = i;
469
+ }
470
+ section.ours = startsWithPath(section.path, ['mcp_servers', SERVER_NAME]);
471
+ });
472
+ return sections;
473
+ }
474
+
475
+ /** True when config.toml defines any CueApril server entry, in any syntax. */
476
+ export function codexHasServer(text) {
477
+ const records = scanToml(stripBom(text));
478
+ return records.some(
479
+ (record) =>
480
+ (record.kind === 'header' && startsWithPath(record.path, ['mcp_servers', SERVER_NAME])) ||
481
+ (record.kind === 'kv' && startsWithPath([...record.table, ...record.path], ['mcp_servers', SERVER_NAME])),
482
+ );
483
+ }
484
+
485
+ /**
486
+ * Replaces (or appends) the cueapril tables in a Codex config.toml. Every
487
+ * byte outside those tables is preserved: comments and blank lines after the
488
+ * last cueapril key stay with whatever follows. cueapril entries written as
489
+ * dotted keys or inline tables are removed too, so the result never defines
490
+ * the server twice. Returns { content, action: create | update | unchanged }.
491
+ */
492
+ export function editCodexConfig(text, { baseUrl, key }) {
493
+ if (text === null || text === undefined) return { content: codexBlock(baseUrl, key), action: 'create' };
494
+ const bom = text.startsWith(BOM) ? BOM : '';
495
+ const body = text.slice(bom.length);
496
+ const eol = /\r\n/.test(body) ? '\r\n' : '\n';
497
+ const block = codexBlock(baseUrl, key, eol);
498
+ const records = scanToml(body);
499
+ const sections = sectionsOf(records);
500
+ const owner = new Array(records.length).fill(null);
501
+ for (const section of sections) for (let i = section.start; i < section.end; i += 1) owner[i] = section;
502
+
503
+ for (const section of sections) {
504
+ if (section.isArray && section.path.length === 1 && section.path[0] === 'mcp_servers') {
505
+ throw new CliError('config.toml declares [[mcp_servers]] as an array, which CueApril cannot extend safely.');
506
+ }
507
+ }
508
+ const remove = new Set();
509
+ records.forEach((record, index) => {
510
+ if (record.kind !== 'kv' || owner[index]?.ours) return;
511
+ const full = [...record.table, ...record.path];
512
+ if (full.length === 1 && full[0] === 'mcp_servers') {
513
+ throw new CliError('config.toml writes mcp_servers as an inline table, which CueApril cannot extend safely.');
514
+ }
515
+ if (startsWithPath(full, ['mcp_servers', SERVER_NAME])) {
516
+ remove.add(index);
517
+ for (let next = index + 1; next < records.length && records[next].kind === 'cont'; next += 1) remove.add(next);
518
+ }
519
+ });
520
+
521
+ const runs = [];
522
+ sections.forEach((section, n) => {
523
+ if (!section.ours) return;
524
+ const last = runs.at(-1);
525
+ if (last && last.lastSection === n - 1) {
526
+ last.coreEnd = section.coreEnd;
527
+ last.lastSection = n;
528
+ } else {
529
+ runs.push({ start: section.start, coreEnd: section.coreEnd, lastSection: n });
530
+ }
531
+ });
532
+
533
+ const out = [];
534
+ let inserted = false;
535
+ for (let i = 0; i < records.length; i += 1) {
536
+ const run = runs.find((candidate) => candidate.start === i);
537
+ if (run) {
538
+ if (!inserted) out.push(block);
539
+ inserted = true;
540
+ i = run.coreEnd;
541
+ continue;
542
+ }
543
+ if (!remove.has(i)) out.push(records[i].body + records[i].eol);
544
+ }
545
+ let result = out.join('');
546
+ if (!inserted) {
547
+ if (result && !result.endsWith('\n')) result += eol;
548
+ const lastLineBlank = result === '' || /(^|\n)[ \t]*\r?\n$/.test(result);
549
+ if (!lastLineBlank) result += eol;
550
+ result += block;
551
+ }
552
+ const content = bom + result;
553
+ return { content, action: content === text ? 'unchanged' : 'update' };
554
+ }
555
+
556
+ // ---------------------------------------------------------------------------
557
+ // JSON settings (Gemini CLI, Cursor)
558
+
559
+ function canonicalJson(value) {
560
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
561
+ if (value && typeof value === 'object') {
562
+ return `{${Object.keys(value)
563
+ .sort()
564
+ .map((name) => `${JSON.stringify(name)}:${canonicalJson(value[name])}`)
565
+ .join(',')}}`;
566
+ }
567
+ return JSON.stringify(value);
568
+ }
569
+
570
+ export function sameJson(a, b) {
571
+ return canonicalJson(a) === canonicalJson(b);
572
+ }
573
+
574
+ function detectIndent(body) {
575
+ const match = /\n([ \t]+)["}\]]/.exec(body);
576
+ if (!match) return 2;
577
+ return match[1].includes('\t') ? '\t' : Math.min(8, match[1].length);
578
+ }
579
+
580
+ export function geminiEntry(baseUrl, key) {
581
+ return { url: mcpUrl(baseUrl), type: 'http', headers: { Authorization: `Bearer ${key}` } };
582
+ }
583
+
584
+ export function cursorEntry(baseUrl, key) {
585
+ return { url: mcpUrl(baseUrl), headers: { Authorization: `Bearer ${key}` } };
586
+ }
587
+
588
+ /**
589
+ * Sets mcpServers.cueapril in a JSON settings file, keeping every other key
590
+ * in place. Refuses files that are not plain JSON objects (for example JSON
591
+ * with comments) instead of rewriting them.
592
+ */
593
+ export function editJsonMcp(text, entry, { label = 'The settings file' } = {}) {
594
+ if (text === null || text === undefined) {
595
+ return { content: `${JSON.stringify({ mcpServers: { [SERVER_NAME]: entry } }, null, 2)}\n`, action: 'create' };
596
+ }
597
+ const bom = text.startsWith(BOM) ? BOM : '';
598
+ const body = text.slice(bom.length);
599
+ let data = {};
600
+ if (body.trim()) {
601
+ try {
602
+ data = JSON.parse(body);
603
+ } catch {
604
+ throw new CliError(
605
+ `${label} is not plain JSON (it may contain comments), so CueApril did not change it. Add the cueapril entry by hand.`,
606
+ );
607
+ }
608
+ }
609
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
610
+ throw new CliError(`${label} does not hold a JSON object, so CueApril did not change it.`);
611
+ }
612
+ const servers = data.mcpServers;
613
+ if (servers !== undefined && (!servers || typeof servers !== 'object' || Array.isArray(servers))) {
614
+ throw new CliError(`${label} has an mcpServers value that is not an object, so CueApril did not change it.`);
615
+ }
616
+ if (servers && Object.hasOwn(servers, SERVER_NAME) && sameJson(servers[SERVER_NAME], entry)) {
617
+ return { content: text, action: 'unchanged' };
618
+ }
619
+ const next = { ...data, mcpServers: { ...(servers ?? {}), [SERVER_NAME]: entry } };
620
+ const eol = /\r\n/.test(body) ? '\r\n' : '\n';
621
+ const trailing = !body.trim() || /\n\s*$/.test(body);
622
+ const json = JSON.stringify(next, null, detectIndent(body)).replace(/\n/g, eol);
623
+ return { content: `${bom}${json}${trailing ? eol : ''}`, action: 'update' };
624
+ }
625
+
626
+ function jsonEntryState(text, entry) {
627
+ if (text === null) return 'missing';
628
+ let data;
629
+ try {
630
+ data = JSON.parse(stripBom(text) || '{}');
631
+ } catch {
632
+ return 'unreadable';
633
+ }
634
+ const current = data?.mcpServers?.[SERVER_NAME];
635
+ if (!current) return 'missing';
636
+ return sameJson(current, entry) ? 'current' : 'different';
637
+ }
638
+
639
+ // ---------------------------------------------------------------------------
640
+ // Claude Code
641
+ //
642
+ // `claude mcp add` and `add-json` take headers only as arguments, so a key
643
+ // passed that way is visible in process listings and exec audit logs while
644
+ // claude runs. Instead the user entry names a headersHelper, which Claude Code
645
+ // runs through a shell (/bin/sh, or cmd.exe on Windows) each time it connects:
646
+ // it prints the 0600 headers file below, written atomically by init. The key
647
+ // is then in neither argv nor ~/.claude.json, and a new key needs no claude run.
648
+
649
+ /** Holds {"Authorization":"Bearer <key>"} for Claude Code's headersHelper; 0600, beside the credentials. */
650
+ export const CLAUDE_HEADERS_FILE = 'claude-code-headers.json';
651
+
652
+ export function claudeHeadersPath(deps = {}) {
653
+ const io = defaultDeps(deps);
654
+ return pathFor(io).join(configDir(io), CLAUDE_HEADERS_FILE);
655
+ }
656
+
657
+ function shellQuote(text) {
658
+ return `'${String(text).replace(/'/g, `'\\''`)}'`;
659
+ }
660
+
661
+ /**
662
+ * The headersHelper command that prints the headers file, quoted for the shell
663
+ * Claude Code runs it in. Null when the path cannot be quoted safely there.
664
+ */
665
+ export function claudeHeadersHelper(file, platform = process.platform) {
666
+ if (/[\u0000-\u001f\u007f]/.test(file)) return null;
667
+ if (platform === 'win32') return /["%]/.test(file) ? null : `type "${file}"`;
668
+ return `cat ${shellQuote(file)}`;
669
+ }
670
+
671
+ export function claudeHeadersContent(key) {
672
+ return `${JSON.stringify({ Authorization: `Bearer ${key}` })}\n`;
673
+ }
674
+
675
+ /** The user-scope entry init registers with `claude mcp add-json`: the URL and the helper, never the key. */
676
+ export function claudeEntry(baseUrl, helper) {
677
+ return { type: 'http', url: mcpUrl(baseUrl), headersHelper: helper };
678
+ }
679
+
680
+ export async function readClaudeUserEntry(deps = {}) {
681
+ const io = defaultDeps(deps);
682
+ const text = await readFileIfExists(io, claudeJsonPath(io)).catch(() => null);
683
+ if (!text) return null;
684
+ try {
685
+ const entry = JSON.parse(text)?.mcpServers?.[SERVER_NAME];
686
+ return entry && typeof entry === 'object' ? entry : null;
687
+ } catch {
688
+ return null;
689
+ }
690
+ }
691
+
692
+ function storesAuthorization(entry) {
693
+ const headers = entry?.headers;
694
+ return Boolean(headers && typeof headers === 'object' && Object.keys(headers).some((name) => name.toLowerCase() === 'authorization'));
695
+ }
696
+
697
+ /** True when the user entry is the one init registers: this URL, this helper and no key of its own. */
698
+ export function claudeEntryRegistered(entry, baseUrl, helper) {
699
+ return Boolean(
700
+ helper &&
701
+ entry &&
702
+ (entry.type === 'http' || entry.type === 'streamable-http') &&
703
+ entry.url === mcpUrl(baseUrl) &&
704
+ entry.headersHelper === helper &&
705
+ !storesAuthorization(entry),
706
+ );
707
+ }
708
+
709
+ /** An entry from an earlier init that keeps this key in its header. It works; init replaces it. */
710
+ export function claudeEntryMatches(entry, baseUrl, key) {
711
+ return Boolean(
712
+ entry &&
713
+ (entry.type === 'http' || entry.type === 'streamable-http') &&
714
+ entry.url === mcpUrl(baseUrl) &&
715
+ entry.headers?.Authorization === `Bearer ${key}`,
716
+ );
717
+ }
718
+
719
+ /** True when Claude Code would send this key to this server. */
720
+ async function claudeEntryCurrent(io, entry, baseUrl, key) {
721
+ if (claudeEntryMatches(entry, baseUrl, key)) return true;
722
+ const file = claudeHeadersPath(io);
723
+ if (!claudeEntryRegistered(entry, baseUrl, claudeHeadersHelper(file, io.platform))) return false;
724
+ return (await readFileIfExists(io, file).catch(() => null)) === claudeHeadersContent(key);
725
+ }
726
+
727
+ /**
728
+ * The command that runs the claude CLI without a shell. On Windows an npm
729
+ * .cmd shim is bypassed by running its cli.js with Node directly.
730
+ */
731
+ async function claudeInvocation(io, binary) {
732
+ if (!binary) return null;
733
+ if (io.platform === 'win32' && /\.(cmd|bat)$/i.test(binary)) {
734
+ const p = pathFor(io);
735
+ for (const script of ['cli.js', 'cli.mjs']) {
736
+ const candidate = p.join(p.dirname(binary), 'node_modules', '@anthropic-ai', 'claude-code', script);
737
+ if (await exists(io, candidate)) return { command: io.execPath ?? process.execPath, prefix: [candidate] };
738
+ }
739
+ return null;
740
+ }
741
+ return { command: binary, prefix: [] };
742
+ }
743
+
744
+ // ---------------------------------------------------------------------------
745
+ // Planning and applying
746
+
747
+ function placeholderAware(key) {
748
+ return key ? maskKey(key) : PLACEHOLDER_KEY_TEXT;
749
+ }
750
+
751
+ async function guardTarget(io, file) {
752
+ await assertOutsideRepository(io, file);
753
+ const p = pathFor(io);
754
+ for (const target of [p.dirname(file), file]) {
755
+ const stat = await lstatIfExists(io, target);
756
+ if (stat?.isSymbolicLink()) {
757
+ throw new CliError(
758
+ `${displayPath(io, target)} is a symbolic link; CueApril will not write a secret key through it. Add the cueapril entry by hand.`,
759
+ );
760
+ }
761
+ }
762
+ }
763
+
764
+ function fileEditor(id, baseUrl) {
765
+ if (id === 'codex') return (text, key) => editCodexConfig(text, { baseUrl, key });
766
+ const entry = id === 'gemini' ? geminiEntry : cursorEntry;
767
+ return (text, key) => editJsonMcp(text, entry(baseUrl, key), { label: `${AGENT_NAMES[id]} settings` });
768
+ }
769
+
770
+ function filePreview(id, baseUrl, key) {
771
+ const shown = placeholderAware(key);
772
+ if (id === 'codex') return codexBlock(baseUrl, shown).trimEnd();
773
+ const entry = id === 'gemini' ? geminiEntry(baseUrl, shown) : cursorEntry(baseUrl, shown);
774
+ return JSON.stringify({ mcpServers: { [SERVER_NAME]: entry } }, null, 2);
775
+ }
776
+
777
+ async function planFile(io, agent, { baseUrl, key }) {
778
+ const file = agent.configPath ?? agentConfigPath(agent.id, io);
779
+ const item = {
780
+ agent: agent.id,
781
+ name: AGENT_NAMES[agent.id],
782
+ kind: 'file',
783
+ path: file,
784
+ displayPath: displayPath(io, file),
785
+ preview: filePreview(agent.id, baseUrl, key),
786
+ placeholder: !key,
787
+ };
788
+ try {
789
+ await guardTarget(io, file);
790
+ const original = await readFileIfExists(io, file);
791
+ const edit = fileEditor(agent.id, baseUrl);
792
+ const result = edit(original, key ?? 'cueapril_sk_placeholder');
793
+ item.action = key ? result.action : original === null ? 'create' : 'update';
794
+ if (item.action === 'update') item.backupPath = `${file}${BACKUP_SUFFIX}`;
795
+ if (key) payloads.set(item, { original, content: result.content, edit, key });
796
+ } catch (error) {
797
+ item.action = 'error';
798
+ const reason =
799
+ error instanceof TomlScanError
800
+ ? `${item.displayPath} could not be read safely (${error.message}), so CueApril did not change it.`
801
+ : error.message;
802
+ item.message = safeText(redact(reason, key ? [key] : []), 400);
803
+ }
804
+ return item;
805
+ }
806
+
807
+ async function planClaude(io, agent, { baseUrl, key }) {
808
+ const headersFile = claudeHeadersPath(io);
809
+ const helper = claudeHeadersHelper(headersFile, io.platform);
810
+ const removeArgs = ['mcp', 'remove', SERVER_NAME, '--scope', 'user'];
811
+ const addArgs = ['mcp', 'add-json', '--scope', 'user', SERVER_NAME, JSON.stringify(claudeEntry(baseUrl, helper))];
812
+ const item = {
813
+ agent: 'claude',
814
+ name: AGENT_NAMES.claude,
815
+ kind: 'command',
816
+ path: claudeJsonPath(io),
817
+ displayPath: displayPath(io, claudeJsonPath(io)),
818
+ headersPath: displayPath(io, headersFile),
819
+ // Nothing secret is on these command lines; the key goes only into the headers file.
820
+ commands: [`claude ${removeArgs.join(' ')}`, `claude ${addArgs.slice(0, -1).join(' ')} ${shellQuote(addArgs.at(-1))}`],
821
+ placeholder: !key,
822
+ };
823
+ try {
824
+ if (!helper) {
825
+ throw new CliError(
826
+ `${item.headersPath} cannot be named safely in a Claude Code headersHelper command. Set XDG_CONFIG_HOME to a plainer directory, or add the cueapril entry by hand.`,
827
+ );
828
+ }
829
+ await assertPrivateConfigFile(io, headersFile);
830
+ } catch (error) {
831
+ // The commands would register a helper for a file that must not be written.
832
+ Object.assign(item, { action: 'error', message: safeText(redact(error.message, key ? [key] : []), 400), commands: [] });
833
+ return item;
834
+ }
835
+ const content = key ? claudeHeadersContent(key) : null;
836
+ if (claudeEntryRegistered(await readClaudeUserEntry(io), baseUrl, helper)) {
837
+ // Registered already: a new key changes only the headers file, and claude is not run.
838
+ const current = await readFileIfExists(io, headersFile).catch(() => null);
839
+ if (key && current === content) {
840
+ item.action = 'unchanged';
841
+ return item;
842
+ }
843
+ Object.assign(item, { action: current === null ? 'create' : 'update', path: headersFile, displayPath: item.headersPath, commands: [] });
844
+ if (key) payloads.set(item, { key, headersFile, content });
845
+ return item;
846
+ }
847
+ const binary = agent.binary === undefined ? await findClaudeBinary(io) : agent.binary;
848
+ const invocation = await claudeInvocation(io, binary);
849
+ if (!invocation) {
850
+ item.action = 'error';
851
+ item.message = binary
852
+ ? 'Claude Code is installed through a script CueApril cannot run without a shell. Install the native claude CLI, then run `cueapril init --agents claude` again.'
853
+ : 'Claude Code was detected but the claude command was not found. Run `cueapril init --agents claude` from a terminal where `claude` works.';
854
+ return item;
855
+ }
856
+ item.action = 'configure';
857
+ item.binary = binary;
858
+ if (key) payloads.set(item, { ...invocation, removeArgs, addArgs, key, headersFile, content });
859
+ return item;
860
+ }
861
+
862
+ /**
863
+ * Plans the MCP changes for the given agents (ids, or records from
864
+ * detectAgents). Without a key (a dry run before login) the plan shows a
865
+ * placeholder and cannot be applied. Plan items are safe to print or
866
+ * serialise: they never contain the key.
867
+ */
868
+ export async function planAgentChanges({ agents, baseUrl, key } = {}, deps = {}) {
869
+ const io = defaultDeps(deps);
870
+ if (!baseUrl) throw new CliError('planAgentChanges needs a baseUrl.');
871
+ const detected = await detectAgents(io);
872
+ const byId = new Map(detected.map((agent) => [agent.id, agent]));
873
+ const wanted = (agents ?? []).map((agent) => (typeof agent === 'string' ? agent : agent.id));
874
+ const plan = [];
875
+ for (const id of wanted) {
876
+ if (!AGENT_IDS.includes(id)) throw new CliError(`Unknown agent "${safeText(id, 40)}".`);
877
+ const agent = byId.get(id);
878
+ plan.push(id === 'claude' ? await planClaude(io, agent, { baseUrl, key }) : await planFile(io, agent, { baseUrl, key }));
879
+ }
880
+ return plan;
881
+ }
882
+
883
+ async function applyFile(io, item, payload) {
884
+ await guardTarget(io, item.path);
885
+ const current = await readFileIfExists(io, item.path);
886
+ let content = payload.content;
887
+ let action = item.action;
888
+ if (current !== payload.original) {
889
+ // The file changed after planning: redo the edit on what is there now.
890
+ const result = payload.edit(current, payload.key);
891
+ content = result.content;
892
+ action = result.action;
893
+ }
894
+ if (action === 'unchanged') return { status: 'unchanged' };
895
+ let backupPath = null;
896
+ if (current !== null) {
897
+ backupPath = `${item.path}${BACKUP_SUFFIX}`;
898
+ await atomicWriteFile(io, backupPath, current, { mode: 0o600 });
899
+ }
900
+ await atomicWriteFile(io, item.path, content, { mode: 0o600 });
901
+ return { status: current === null ? 'created' : 'updated', backupPath };
902
+ }
903
+
904
+ async function applyClaude(io, item, payload) {
905
+ const { command, prefix, removeArgs, addArgs, key, headersFile, content } = payload;
906
+ await assertPrivateConfigFile(io, headersFile);
907
+ const before = await readFileIfExists(io, headersFile).catch(() => null);
908
+ const headersChanged = before !== content;
909
+ if (headersChanged) await atomicWriteFile(io, headersFile, content, { mode: 0o600, dirMode: 0o700 });
910
+ if (!command) return { status: !headersChanged ? 'unchanged' : before === null ? 'created' : 'updated' };
911
+ // A missing entry makes remove fail; that is expected and ignored.
912
+ await runCommand(io, command, [...prefix, ...removeArgs], { timeoutMs: 30_000 });
913
+ const result = await runCommand(io, command, [...prefix, ...addArgs], { timeoutMs: 60_000 });
914
+ if (result.error || result.code !== 0) {
915
+ const detail = safeText(redact(result.stderr || result.stdout || result.error?.message || '', [key]), 300);
916
+ return { status: 'failed', message: `claude mcp add-json failed${detail ? `: ${detail}` : ''}` };
917
+ }
918
+ return { status: 'configured', headersPath: displayPath(io, headersFile), headersChanged };
919
+ }
920
+
921
+ /**
922
+ * Applies a plan from planAgentChanges. Never throws for one agent's failure:
923
+ * each result is { agent, name, status, path?, backupPath?, message? } with
924
+ * status created, updated, configured, unchanged, failed or skipped.
925
+ */
926
+ export async function applyAgentChanges(plan, deps = {}) {
927
+ const io = defaultDeps(deps);
928
+ const results = [];
929
+ for (const item of plan ?? []) {
930
+ const base = { agent: item.agent, name: item.name, path: item.displayPath ?? item.path };
931
+ if (item.action === 'unchanged') {
932
+ results.push({ ...base, status: 'unchanged' });
933
+ continue;
934
+ }
935
+ if (item.action === 'error') {
936
+ results.push({ ...base, status: 'failed', message: item.message });
937
+ continue;
938
+ }
939
+ const payload = payloads.get(item);
940
+ if (!payload) {
941
+ results.push({ ...base, status: 'skipped', message: 'No key was available, so nothing was written.' });
942
+ continue;
943
+ }
944
+ try {
945
+ const outcome = item.kind === 'command' ? await applyClaude(io, item, payload) : await applyFile(io, item, payload);
946
+ results.push({
947
+ ...base,
948
+ ...outcome,
949
+ ...(outcome.backupPath ? { backupPath: displayPath(io, outcome.backupPath) } : {}),
950
+ });
951
+ } catch (error) {
952
+ results.push({ ...base, status: 'failed', message: safeText(redact(error.message, [payload.key]), 400) });
953
+ }
954
+ }
955
+ return results;
956
+ }
957
+
958
+ /**
959
+ * Reads each detected agent's configuration and reports whether it has a
960
+ * CueApril entry: current (this URL and key), different, missing or unreadable.
961
+ */
962
+ export async function inspectAgents(deps = {}, { baseUrl, key } = {}) {
963
+ const io = defaultDeps(deps);
964
+ const agents = await detectAgents(io);
965
+ const results = [];
966
+ for (const agent of agents) {
967
+ const result = {
968
+ id: agent.id,
969
+ name: agent.name,
970
+ detected: agent.detected,
971
+ path: displayPath(io, agent.configPath),
972
+ state: 'missing',
973
+ };
974
+ try {
975
+ if (agent.id === 'claude') {
976
+ const entry = await readClaudeUserEntry(io);
977
+ result.state = !entry ? 'missing' : key && (await claudeEntryCurrent(io, entry, baseUrl, key)) ? 'current' : 'different';
978
+ } else if (agent.id === 'codex') {
979
+ const text = await readFileIfExists(io, agent.configPath);
980
+ if (text !== null && codexHasServer(text)) {
981
+ result.state = key && editCodexConfig(text, { baseUrl, key }).action === 'unchanged' ? 'current' : 'different';
982
+ }
983
+ } else {
984
+ const text = await readFileIfExists(io, agent.configPath);
985
+ const entry = agent.id === 'gemini' ? geminiEntry(baseUrl, key ?? '') : cursorEntry(baseUrl, key ?? '');
986
+ result.state = jsonEntryState(text, entry);
987
+ if (result.state === 'current' && !key) result.state = 'different';
988
+ }
989
+ } catch (error) {
990
+ result.state = 'unreadable';
991
+ result.message = safeText(redact(error.message, key ? [key] : []), 300);
992
+ }
993
+ results.push(result);
994
+ }
995
+ return results;
996
+ }