@agent-deck/shared 2.5.0 → 2.5.2

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.
@@ -0,0 +1,758 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MUSE_SCHEMA_VERSION = exports.CURSOR_MCP_RECOVERY_HINT = void 0;
7
+ exports.buildMcpUrl = buildMcpUrl;
8
+ exports.resolveMuseGlobalConfigDir = resolveMuseGlobalConfigDir;
9
+ exports.resolveConfigPath = resolveConfigPath;
10
+ exports.buildCodexAgentDeckEntry = buildCodexAgentDeckEntry;
11
+ exports.buildGlobalFallbackHttpEntry = buildGlobalFallbackHttpEntry;
12
+ exports.buildAgentDeckEntry = buildAgentDeckEntry;
13
+ exports.isHttpAgentDeckEntry = isHttpAgentDeckEntry;
14
+ exports.readHttpWorkspaceHeader = readHttpWorkspaceHeader;
15
+ exports.isLegacyBareHttpAgentDeckEntry = isLegacyBareHttpAgentDeckEntry;
16
+ exports.isMcpLaunchEntry = isMcpLaunchEntry;
17
+ exports.isLegacyClaudeLaunchEntry = isLegacyClaudeLaunchEntry;
18
+ exports.isLegacyMuseLaunchEntry = isLegacyMuseLaunchEntry;
19
+ exports.readJsonFile = readJsonFile;
20
+ exports.mergeMuseServerConfig = mergeMuseServerConfig;
21
+ exports.mergeMcpServerConfig = mergeMcpServerConfig;
22
+ exports.writeJsonFile = writeJsonFile;
23
+ exports.readTextFile = readTextFile;
24
+ exports.writeTextFile = writeTextFile;
25
+ exports.escapeTomlBasicString = escapeTomlBasicString;
26
+ exports.formatCodexMcpSection = formatCodexMcpSection;
27
+ exports.formatCodexGlobalFallbackSection = formatCodexGlobalFallbackSection;
28
+ exports.codexTomlHasAgentDeckEntry = codexTomlHasAgentDeckEntry;
29
+ exports.codexTomlHasLauncherEntry = codexTomlHasLauncherEntry;
30
+ exports.mergeCodexTomlConfig = mergeCodexTomlConfig;
31
+ exports.writePerFolderMcpEntries = writePerFolderMcpEntries;
32
+ /**
33
+ * NOT-597: moved from `packages/cli/src/mcp-config.ts` so the daemon
34
+ * (backend approval path) and `agent-deck use` share one writer for
35
+ * per-folder MCP entries. The CLI re-exports this module; new code
36
+ * imports from `@agent-deck/shared`.
37
+ */
38
+ const node_fs_1 = __importDefault(require("node:fs"));
39
+ const node_os_1 = __importDefault(require("node:os"));
40
+ const node_path_1 = __importDefault(require("node:path"));
41
+ const strip_ansi_1 = require("./strip-ansi");
42
+ /** Shared recovery sentence for Cursor MCP diagnostics and docs (NOT-50, pure-MCP form NOT-567). */
43
+ exports.CURSOR_MCP_RECOVERY_HINT = 'If Agent Deck tools are missing in Cursor, run `agent-deck setup --client cursor`, approve the project agent-deck server, run `agent-deck use <deck>` in the folder, then reload MCP.';
44
+ /** Muse user settings require this exact schema version (NOT-387). */
45
+ exports.MUSE_SCHEMA_VERSION = 1;
46
+ function buildMcpUrl({ host, mcpPort }) {
47
+ return `http://${host}:${mcpPort}/mcp`;
48
+ }
49
+ /** Muse honors XDG_CONFIG_HOME for its user settings; otherwise ~/.config. */
50
+ function resolveMuseGlobalConfigDir(home = node_os_1.default.homedir()) {
51
+ const xdg = process.env.XDG_CONFIG_HOME?.trim();
52
+ return xdg ? xdg : node_path_1.default.join(home, '.config');
53
+ }
54
+ function resolveConfigPath(client, scope, cwd = process.cwd()) {
55
+ const home = node_os_1.default.homedir();
56
+ switch (client) {
57
+ case 'cursor':
58
+ return scope === 'project'
59
+ ? node_path_1.default.join(cwd, '.cursor', 'mcp.json')
60
+ : node_path_1.default.join(home, '.cursor', 'mcp.json');
61
+ case 'claude':
62
+ return scope === 'project'
63
+ ? node_path_1.default.join(cwd, '.mcp.json')
64
+ : node_path_1.default.join(home, '.claude.json');
65
+ case 'claude-desktop':
66
+ if (process.platform === 'darwin') {
67
+ return node_path_1.default.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
68
+ }
69
+ if (process.platform === 'win32') {
70
+ return node_path_1.default.join(process.env.APPDATA ?? home, 'Claude', 'claude_desktop_config.json');
71
+ }
72
+ return node_path_1.default.join(home, '.config', 'Claude', 'claude_desktop_config.json');
73
+ case 'muse':
74
+ if (scope === 'project') {
75
+ return node_path_1.default.join(cwd, '.mcp.json');
76
+ }
77
+ return node_path_1.default.join(resolveMuseGlobalConfigDir(home), 'muse', 'settings.json');
78
+ case 'codex':
79
+ return scope === 'project'
80
+ ? node_path_1.default.join(cwd, '.codex', 'config.toml')
81
+ : node_path_1.default.join(home, '.codex', 'config.toml');
82
+ default:
83
+ throw new Error(`Unsupported client: ${client}`);
84
+ }
85
+ }
86
+ /**
87
+ * Pure-HTTP entry for a Codex project config (`<folder>/.codex/config.toml`).
88
+ * The daemon resolves the deck from `.agent-deck/use.json` — no deck id here.
89
+ */
90
+ function buildCodexAgentDeckEntry(endpoint, options) {
91
+ return {
92
+ url: buildMcpUrl(endpoint),
93
+ http_headers: {
94
+ 'x-agent-deck-workspace': node_path_1.default.resolve(options.workspaceRoot),
95
+ },
96
+ };
97
+ }
98
+ /**
99
+ * Global headerless HTTP fallback entry (NOT-565, design §4): folders with
100
+ * no assignment connect everywhere over pure MCP and land in the existing
101
+ * unassigned (explain-only) session. No headers, no executable lookup.
102
+ * Per-folder entries written by `agent-deck use` use the same server name,
103
+ * so they shadow this fallback where an assignment exists.
104
+ */
105
+ function buildGlobalFallbackHttpEntry(endpoint) {
106
+ return {
107
+ type: 'http',
108
+ url: buildMcpUrl(endpoint),
109
+ };
110
+ }
111
+ /**
112
+ * MCP client entry for the agent-deck server. Codex, Claude, Cursor, and
113
+ * Muse connect over pure HTTP (NOT-563/565/567/570/571): the workspace
114
+ * header names the folder and the daemon resolves the deck from
115
+ * `.agent-deck/use.json` — no deck id in tracked config, no executable
116
+ * lookup.
117
+ *
118
+ * A `workspaceRoot` selects the per-folder HTTP form; without one the
119
+ * client gets the global headerless HTTP fallback (NOT-565/567/570).
120
+ * Claude Desktop still uses the trusted local launcher, which reads the
121
+ * folder assignment at runtime. The retired Muse launcher shape (NOT-387:
122
+ * command/args/env only, no type or workspace pin) is never built —
123
+ * legacy entries are detected with {@link isLegacyMuseLaunchEntry} and
124
+ * converted by the upgrade path (NOT-572).
125
+ */
126
+ function buildAgentDeckEntry(client, endpoint, options) {
127
+ if (client === 'codex') {
128
+ if (!options?.workspaceRoot) {
129
+ throw new Error('buildAgentDeckEntry(codex) requires options.workspaceRoot for the x-agent-deck-workspace header');
130
+ }
131
+ return buildCodexAgentDeckEntry(endpoint, { workspaceRoot: options.workspaceRoot });
132
+ }
133
+ if (client === 'claude-desktop') {
134
+ return {
135
+ command: 'agent-deck',
136
+ args: ['mcp-launch'],
137
+ };
138
+ }
139
+ if (client === 'muse' || client === 'claude') {
140
+ // NOT-571: Muse writes the identical entry Claude writes (NOT-563) —
141
+ // the same <folder>/.mcp.json, the same shape — so the two clients no
142
+ // longer overwrite each other's agent-deck entry.
143
+ if (options?.workspaceRoot) {
144
+ // Per-folder pure-MCP entry: the daemon resolves the deck from
145
+ // `.agent-deck/use.json` — no deck id in the file.
146
+ return {
147
+ type: 'http',
148
+ url: buildMcpUrl(endpoint),
149
+ headers: {
150
+ 'x-agent-deck-workspace': node_path_1.default.resolve(options.workspaceRoot),
151
+ },
152
+ };
153
+ }
154
+ // Global setup fallback: headerless pure HTTP, no launcher and no
155
+ // executable lookup. (The per-folder form above already returned, so
156
+ // no workspaceRoot is in scope here.)
157
+ return buildGlobalFallbackHttpEntry(endpoint);
158
+ }
159
+ if (client === 'cursor') {
160
+ if (options?.workspaceRoot) {
161
+ // NOT-567 per-folder pure-MCP entry: the daemon resolves the deck
162
+ // from `.agent-deck/use.json` — no deck id in the file. Cursor
163
+ // does not interpolate `${workspaceFolder}` in header values, so
164
+ // the absolute folder path is written out.
165
+ return {
166
+ url: buildMcpUrl(endpoint),
167
+ headers: {
168
+ 'x-agent-deck-workspace': node_path_1.default.resolve(options.workspaceRoot),
169
+ },
170
+ };
171
+ }
172
+ // NOT-567 global setup fallback: headerless pure HTTP, no launcher
173
+ // and no executable lookup. Unassigned folders connect through it
174
+ // and land in the explain-only session.
175
+ return {
176
+ url: buildMcpUrl(endpoint),
177
+ };
178
+ }
179
+ throw new Error(`Unsupported client: ${client}`);
180
+ }
181
+ /**
182
+ * Pure-MCP HTTP entry (NOT-567): a `url` with no `command` — the
183
+ * per-folder entry carrying the workspace header, or the headerless
184
+ * global fallback. No executable lookup on the connection path.
185
+ */
186
+ function isHttpAgentDeckEntry(entry) {
187
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
188
+ return false;
189
+ }
190
+ const record = entry;
191
+ return typeof record.url === 'string' && typeof record.command !== 'string';
192
+ }
193
+ /**
194
+ * Raw `x-agent-deck-workspace` header value from a pure-MCP HTTP entry
195
+ * (NOT-567). Returned as-is: Cursor sends header values literally, so a
196
+ * value carrying `${...}` interpolation is for the caller to flag, never
197
+ * to resolve.
198
+ */
199
+ function readHttpWorkspaceHeader(entry) {
200
+ if (!isHttpAgentDeckEntry(entry)) {
201
+ return undefined;
202
+ }
203
+ const headers = entry.headers;
204
+ if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
205
+ return undefined;
206
+ }
207
+ const workspaceRoot = headers['x-agent-deck-workspace'];
208
+ return typeof workspaceRoot === 'string' && workspaceRoot.length > 0 ? workspaceRoot : undefined;
209
+ }
210
+ /**
211
+ * Pre-1.7 Cursor/HTTP entries used bare `url` with no deck-assignment
212
+ * launcher. Same url-without-command shape as {@link isHttpAgentDeckEntry};
213
+ * kept under this name for the Claude legacy paths.
214
+ */
215
+ function isLegacyBareHttpAgentDeckEntry(entry) {
216
+ return isHttpAgentDeckEntry(entry);
217
+ }
218
+ function isMcpLaunchEntry(entry) {
219
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
220
+ return false;
221
+ }
222
+ const record = entry;
223
+ if (typeof record.command !== 'string') {
224
+ return false;
225
+ }
226
+ const commandName = record.command.replaceAll('\\', '/').split('/').pop();
227
+ if (commandName !== 'agent-deck' && commandName !== 'agent-deck.cmd') {
228
+ return false;
229
+ }
230
+ const args = record.args;
231
+ return Array.isArray(args) && args.length === 1 && args[0] === 'mcp-launch';
232
+ }
233
+ /**
234
+ * True when a JSON `agent-deck` entry is a legacy Claude Code launcher
235
+ * entry (NOT-566): an `agent-deck mcp-launch` entry carrying
236
+ * `type: 'stdio'` or an `AGENT_DECK_WORKSPACE` env pin. Every launcher
237
+ * entry `use`/`setup --client claude` ever wrote carries at least one of
238
+ * those markers — project entries carry both, global entries the type.
239
+ *
240
+ * Muse-shaped launcher entries carry the same command/args but never
241
+ * `type` or the workspace pin, so they never match here; they match
242
+ * {@link isLegacyMuseLaunchEntry} instead, and the upgrade rewrite
243
+ * handles each marker with its own conversion (NOT-572).
244
+ */
245
+ function isLegacyClaudeLaunchEntry(entry) {
246
+ if (!isMcpLaunchEntry(entry)) {
247
+ return false;
248
+ }
249
+ const record = entry;
250
+ if (record.type === 'stdio') {
251
+ return true;
252
+ }
253
+ const env = record.env;
254
+ if (!env || typeof env !== 'object' || Array.isArray(env)) {
255
+ return false;
256
+ }
257
+ const workspaceRoot = env.AGENT_DECK_WORKSPACE;
258
+ return typeof workspaceRoot === 'string' && workspaceRoot.length > 0;
259
+ }
260
+ /**
261
+ * True when a JSON `agent-deck` entry is a legacy Muse launcher entry
262
+ * (NOT-387 shape, retired NOT-572): an `agent-deck mcp-launch` entry
263
+ * with neither Claude marker — no `type: 'stdio'`, no
264
+ * `AGENT_DECK_WORKSPACE` env pin. Every launcher entry older
265
+ * `use --client muse` and `setup --client muse --scope project` wrote
266
+ * has exactly this shape (command/args/env only). Nothing builds it;
267
+ * the upgrade path converts it to the HTTP shape (or removes it when
268
+ * the folder has no assignment), and setup/use only detect it for
269
+ * legacy warnings.
270
+ */
271
+ function isLegacyMuseLaunchEntry(entry) {
272
+ return isMcpLaunchEntry(entry) && !isLegacyClaudeLaunchEntry(entry);
273
+ }
274
+ function readJsonFile(filePath) {
275
+ if (!node_fs_1.default.existsSync(filePath)) {
276
+ return {};
277
+ }
278
+ const raw = (0, strip_ansi_1.sanitizeJsonText)(node_fs_1.default.readFileSync(filePath, 'utf8').trim());
279
+ if (!raw) {
280
+ return {};
281
+ }
282
+ const parsed = JSON.parse(raw);
283
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
284
+ throw new Error(`Expected JSON object in ${filePath}`);
285
+ }
286
+ return parsed;
287
+ }
288
+ /**
289
+ * Merge into Muse global settings: sets schema_version when absent, rejects
290
+ * an incompatible existing schema version with an actionable error (caller
291
+ * must leave the file untouched), and preserves every unrelated root key
292
+ * and MCP server. Project .mcp.json uses the plain merge — it has no
293
+ * schema_version and is shared with Claude Code.
294
+ */
295
+ function mergeMuseServerConfig(existing, entry, configPath) {
296
+ const schemaVersion = existing.schema_version;
297
+ if (schemaVersion !== undefined && schemaVersion !== exports.MUSE_SCHEMA_VERSION) {
298
+ throw new Error(`Unsupported schema_version in ${configPath}: expected ${exports.MUSE_SCHEMA_VERSION}, found ${JSON.stringify(schemaVersion)}. ` +
299
+ 'Update Muse or fix the file manually, then re-run setup.');
300
+ }
301
+ return {
302
+ ...mergeMcpServerConfig(existing, entry),
303
+ schema_version: exports.MUSE_SCHEMA_VERSION,
304
+ };
305
+ }
306
+ function mergeMcpServerConfig(existing, entry) {
307
+ const currentServers = existing.mcpServers;
308
+ const mcpServers = currentServers && typeof currentServers === 'object' && !Array.isArray(currentServers)
309
+ ? { ...currentServers }
310
+ : {};
311
+ mcpServers['agent-deck'] = entry;
312
+ return {
313
+ ...existing,
314
+ mcpServers,
315
+ };
316
+ }
317
+ function writeJsonFile(filePath, data) {
318
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(filePath), { recursive: true });
319
+ node_fs_1.default.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
320
+ }
321
+ function readTextFile(filePath) {
322
+ if (!node_fs_1.default.existsSync(filePath)) {
323
+ return '';
324
+ }
325
+ return node_fs_1.default.readFileSync(filePath, 'utf8');
326
+ }
327
+ function writeTextFile(filePath, text) {
328
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(filePath), { recursive: true });
329
+ node_fs_1.default.writeFileSync(filePath, text, 'utf8');
330
+ }
331
+ /**
332
+ * Matches our managed Codex section headers: the `[mcp_servers.agent-deck]`
333
+ * parent plus any `[mcp_servers.agent-deck.<sub>]` sub-table (the layout
334
+ * `codex mcp add --env` writes). Bare or quoted key, whitespace-tolerant,
335
+ * with any trailing comment. Never matches a merely prefixed sibling such
336
+ * as `[mcp_servers.agent-deck-env]`.
337
+ */
338
+ const CODEX_AGENT_DECK_SECTION_RE = /^\s*\[\s*mcp_servers\s*\.\s*("agent-deck"|'agent-deck'|agent-deck)\s*(\.\s*[^\]#]+)?\]\s*(?:#.*)?$/;
339
+ /** Matches a bare `[mcp_servers]` section header holding dotted/inline keys. */
340
+ const CODEX_MCP_SERVERS_SECTION_RE = /^\s*\[\s*("mcp_servers"|'mcp_servers'|mcp_servers)\s*\]\s*(?:#.*)?$/;
341
+ /** Matches an `agent-deck` key definition start inside `[mcp_servers]`. */
342
+ const CODEX_MCP_SERVERS_AGENT_DECK_KEY_RE = /^\s*("agent-deck"|'agent-deck'|agent-deck)\s*(?=[.=])/;
343
+ function isTomlSectionHeader(line) {
344
+ return line.trimStart().startsWith('[');
345
+ }
346
+ /**
347
+ * Net `{`/`[` minus `}`/`]` depth change of one TOML line, ignoring string
348
+ * literals and `#` comments so braces inside values never unbalance the
349
+ * scan. Used to skip multi-line inline tables when removing stale keys.
350
+ */
351
+ function tomlBracketDelta(line) {
352
+ let code = '';
353
+ let i = 0;
354
+ while (i < line.length) {
355
+ const ch = line[i];
356
+ if (ch === '"') {
357
+ i += 1;
358
+ while (i < line.length && line[i] !== '"') {
359
+ i += line[i] === '\\' ? 2 : 1;
360
+ }
361
+ i += 1;
362
+ }
363
+ else if (ch === "'") {
364
+ i += 1;
365
+ while (i < line.length && line[i] !== "'") {
366
+ i += 1;
367
+ }
368
+ i += 1;
369
+ }
370
+ else if (ch === '#') {
371
+ break;
372
+ }
373
+ else {
374
+ code += ch;
375
+ i += 1;
376
+ }
377
+ }
378
+ let delta = 0;
379
+ for (const c of code) {
380
+ if (c === '{' || c === '[') {
381
+ delta += 1;
382
+ }
383
+ else if (c === '}' || c === ']') {
384
+ delta -= 1;
385
+ }
386
+ }
387
+ return delta;
388
+ }
389
+ function escapeTomlBasicString(value) {
390
+ return value
391
+ .replaceAll('\\', '\\\\')
392
+ .replaceAll('"', '\\"')
393
+ .replaceAll('\n', '\\n')
394
+ .replaceAll('\r', '\\r')
395
+ .replaceAll('\t', '\\t');
396
+ }
397
+ /**
398
+ * Canonical `[mcp_servers.agent-deck]` TOML block (NOT-563). No trailing
399
+ * newline — the merge helper owns file framing.
400
+ */
401
+ function formatCodexMcpSection(entry) {
402
+ const headers = Object.entries(entry.http_headers)
403
+ .map(([name, value]) => `"${escapeTomlBasicString(name)}" = "${escapeTomlBasicString(value)}"`)
404
+ .join(', ');
405
+ return [
406
+ '[mcp_servers.agent-deck]',
407
+ `url = "${escapeTomlBasicString(entry.url)}"`,
408
+ `http_headers = { ${headers} }`,
409
+ ].join('\n');
410
+ }
411
+ /**
412
+ * Canonical headerless `[mcp_servers.agent-deck]` TOML block: the global
413
+ * unassigned-folder fallback (NOT-565, design §4). Same-name per-folder
414
+ * entries written by `agent-deck use` shadow it. No trailing newline —
415
+ * the merge helper owns file framing.
416
+ */
417
+ function formatCodexGlobalFallbackSection(endpoint) {
418
+ return [
419
+ '[mcp_servers.agent-deck]',
420
+ `url = "${escapeTomlBasicString(buildMcpUrl(endpoint))}"`,
421
+ ].join('\n');
422
+ }
423
+ /**
424
+ * True when Codex TOML defines any `agent-deck` server entry (NOT-574):
425
+ * a managed `[mcp_servers.agent-deck]` section (or sub-table) in any
426
+ * transport, or a dotted/inline `agent-deck` key under a bare
427
+ * `[mcp_servers]` section. Other servers never match; a merely prefixed
428
+ * sibling such as `[mcp_servers.agent-deck-env]` never matches.
429
+ */
430
+ function codexTomlHasAgentDeckEntry(existingText) {
431
+ if (!existingText.includes('agent-deck')) {
432
+ return false;
433
+ }
434
+ const lines = existingText.split('\n');
435
+ const headerKind = new Map();
436
+ for (const [index, line] of lines.entries()) {
437
+ if (!isTomlSectionHeader(line)) {
438
+ continue;
439
+ }
440
+ if (CODEX_AGENT_DECK_SECTION_RE.test(line)) {
441
+ return true;
442
+ }
443
+ if (CODEX_MCP_SERVERS_SECTION_RE.test(line)) {
444
+ headerKind.set(index, 'servers');
445
+ }
446
+ else {
447
+ headerKind.set(index, 'other');
448
+ }
449
+ }
450
+ const headerIdxs = [...headerKind.keys()];
451
+ const rangeEnd = (headerIdx) => {
452
+ for (const candidate of headerIdxs) {
453
+ if (candidate > headerIdx) {
454
+ return candidate;
455
+ }
456
+ }
457
+ return lines.length;
458
+ };
459
+ for (const [headerIdx, kind] of headerKind) {
460
+ if (kind !== 'servers') {
461
+ continue;
462
+ }
463
+ const end = rangeEnd(headerIdx);
464
+ let depth = 0;
465
+ let index = headerIdx + 1;
466
+ while (index < end) {
467
+ const line = lines[index];
468
+ if (depth === 0 && CODEX_MCP_SERVERS_AGENT_DECK_KEY_RE.test(line)) {
469
+ return true;
470
+ }
471
+ depth += tomlBracketDelta(line);
472
+ if (depth < 0) {
473
+ depth = 0;
474
+ }
475
+ index += 1;
476
+ }
477
+ }
478
+ return false;
479
+ }
480
+ /**
481
+ * True when Codex TOML defines the `agent-deck` server through the legacy
482
+ * stdio launcher (NOT-566): a managed `[mcp_servers.agent-deck]` section
483
+ * (or sub-table) whose body mentions `mcp-launch`, or a dotted/inline
484
+ * `agent-deck` key under a bare `[mcp_servers]` section mentioning it.
485
+ * Pure-HTTP sections, custom entries, and other servers never match —
486
+ * only what the legacy-upgrade rewrite owns.
487
+ */
488
+ function codexTomlHasLauncherEntry(existingText) {
489
+ if (!existingText.includes('mcp-launch')) {
490
+ return false;
491
+ }
492
+ const lines = existingText.split('\n');
493
+ const headerKind = new Map();
494
+ for (const [index, line] of lines.entries()) {
495
+ if (!isTomlSectionHeader(line)) {
496
+ continue;
497
+ }
498
+ if (CODEX_AGENT_DECK_SECTION_RE.test(line)) {
499
+ headerKind.set(index, 'managed');
500
+ }
501
+ else if (CODEX_MCP_SERVERS_SECTION_RE.test(line)) {
502
+ headerKind.set(index, 'servers');
503
+ }
504
+ else {
505
+ headerKind.set(index, 'other');
506
+ }
507
+ }
508
+ const headerIdxs = [...headerKind.keys()];
509
+ const rangeEnd = (headerIdx) => {
510
+ for (const candidate of headerIdxs) {
511
+ if (candidate > headerIdx) {
512
+ return candidate;
513
+ }
514
+ }
515
+ return lines.length;
516
+ };
517
+ for (const [headerIdx, kind] of headerKind) {
518
+ const end = rangeEnd(headerIdx);
519
+ if (kind === 'managed') {
520
+ for (let index = headerIdx + 1; index < end; index += 1) {
521
+ if (lines[index].includes('mcp-launch')) {
522
+ return true;
523
+ }
524
+ }
525
+ continue;
526
+ }
527
+ if (kind !== 'servers') {
528
+ continue;
529
+ }
530
+ // Dotted/inline agent-deck definitions, same top-level-key rule as
531
+ // the merge: a nested `agent-deck` key inside another server's inline
532
+ // table belongs to that server, not to us.
533
+ let depth = 0;
534
+ let index = headerIdx + 1;
535
+ while (index < end) {
536
+ const line = lines[index];
537
+ if (depth === 0 && CODEX_MCP_SERVERS_AGENT_DECK_KEY_RE.test(line)) {
538
+ let block = line;
539
+ depth += tomlBracketDelta(line);
540
+ index += 1;
541
+ while (depth > 0 && index < end) {
542
+ block += `\n${lines[index]}`;
543
+ depth += tomlBracketDelta(lines[index]);
544
+ index += 1;
545
+ }
546
+ depth = 0;
547
+ if (block.includes('mcp-launch')) {
548
+ return true;
549
+ }
550
+ continue;
551
+ }
552
+ depth += tomlBracketDelta(line);
553
+ if (depth < 0) {
554
+ depth = 0;
555
+ }
556
+ index += 1;
557
+ }
558
+ }
559
+ return false;
560
+ }
561
+ /**
562
+ * Merge our managed section into existing Codex TOML, preserving every
563
+ * unrelated byte. Stale agent-deck content in any form is removed first:
564
+ * the parent section, every `[mcp_servers.agent-deck.<sub>]` sub-table
565
+ * wherever it sits, and dotted/inline `agent-deck` keys under a bare
566
+ * `[mcp_servers]` section (multi-line inline tables included). The first
567
+ * managed section is replaced in place with its header normalized to the
568
+ * bare form; otherwise the section is appended after a blank separator.
569
+ * Idempotent: merging twice yields byte-identical text. The result ends
570
+ * with exactly one newline when the section is the last content.
571
+ */
572
+ function mergeCodexTomlConfig(existingText, section) {
573
+ const lines = existingText.split('\n');
574
+ const headerKind = new Map();
575
+ for (const [index, line] of lines.entries()) {
576
+ if (!isTomlSectionHeader(line)) {
577
+ continue;
578
+ }
579
+ if (CODEX_AGENT_DECK_SECTION_RE.test(line)) {
580
+ headerKind.set(index, 'managed');
581
+ }
582
+ else if (CODEX_MCP_SERVERS_SECTION_RE.test(line)) {
583
+ headerKind.set(index, 'servers');
584
+ }
585
+ else {
586
+ headerKind.set(index, 'other');
587
+ }
588
+ }
589
+ const headerIdxs = [...headerKind.keys()];
590
+ const rangeEnd = (headerIdx) => {
591
+ for (const candidate of headerIdxs) {
592
+ if (candidate > headerIdx) {
593
+ return candidate;
594
+ }
595
+ }
596
+ return lines.length;
597
+ };
598
+ // Dotted/inline agent-deck definitions inside bare [mcp_servers] bodies.
599
+ // Only top-level keys count, so a nested `agent-deck` key inside another
600
+ // server's inline table is left alone.
601
+ const removed = new Set();
602
+ for (const [headerIdx, kind] of headerKind) {
603
+ if (kind !== 'servers') {
604
+ continue;
605
+ }
606
+ const end = rangeEnd(headerIdx);
607
+ let depth = 0;
608
+ let index = headerIdx + 1;
609
+ while (index < end) {
610
+ const line = lines[index];
611
+ if (depth === 0 && CODEX_MCP_SERVERS_AGENT_DECK_KEY_RE.test(line)) {
612
+ depth += tomlBracketDelta(line);
613
+ removed.add(index);
614
+ index += 1;
615
+ while (depth > 0 && index < end) {
616
+ depth += tomlBracketDelta(lines[index]);
617
+ removed.add(index);
618
+ index += 1;
619
+ }
620
+ depth = 0;
621
+ continue;
622
+ }
623
+ depth += tomlBracketDelta(line);
624
+ if (depth < 0) {
625
+ depth = 0;
626
+ }
627
+ index += 1;
628
+ }
629
+ // A removed key block takes one following blank separator with it when
630
+ // it sits right after the header or between blank lines, so no doubled
631
+ // blank line is left behind.
632
+ for (let i = headerIdx + 1; i < end; i += 1) {
633
+ if (!removed.has(i) || (i > headerIdx + 1 && removed.has(i - 1))) {
634
+ continue;
635
+ }
636
+ let blockEnd = i;
637
+ while (blockEnd + 1 < end && removed.has(blockEnd + 1)) {
638
+ blockEnd += 1;
639
+ }
640
+ const after = blockEnd + 1;
641
+ const beforeIsSeparator = i === headerIdx + 1 || lines[i - 1].trim() === '';
642
+ if (after < end && !removed.has(after) && lines[after].trim() === '' && beforeIsSeparator) {
643
+ removed.add(after);
644
+ }
645
+ i = blockEnd;
646
+ }
647
+ }
648
+ const managedHeaders = headerIdxs.filter((index) => headerKind.get(index) === 'managed');
649
+ const appendSection = (text) => {
650
+ let framed = text;
651
+ if (framed !== '' && !framed.endsWith('\n')) {
652
+ framed += '\n';
653
+ }
654
+ if (framed !== '' && !framed.endsWith('\n\n')) {
655
+ framed += '\n';
656
+ }
657
+ return `${framed}${section}\n`;
658
+ };
659
+ if (managedHeaders.length === 0) {
660
+ if (removed.size === 0) {
661
+ return appendSection(existingText);
662
+ }
663
+ // Only dotted/inline definitions: drop them, then append. Inserting a
664
+ // section header mid-body would reparent the remaining [mcp_servers]
665
+ // keys under agent-deck.
666
+ return appendSection(lines.filter((_, index) => !removed.has(index)).join('\n'));
667
+ }
668
+ for (const headerIdx of managedHeaders) {
669
+ const end = rangeEnd(headerIdx);
670
+ for (let index = headerIdx; index < end; index += 1) {
671
+ removed.add(index);
672
+ }
673
+ }
674
+ const first = managedHeaders[0];
675
+ const firstEnd = rangeEnd(first);
676
+ let nextKept = firstEnd;
677
+ while (nextKept < lines.length && removed.has(nextKept)) {
678
+ nextKept += 1;
679
+ }
680
+ // Keep one blank separator before the next surviving content when the
681
+ // removed block had any: trailing blanks of the replaced range or blanks
682
+ // in the gap up to the next kept line.
683
+ let hadSeparator = false;
684
+ for (let index = firstEnd - 1; index > first; index -= 1) {
685
+ if (lines[index].trim() === '') {
686
+ hadSeparator = true;
687
+ }
688
+ else {
689
+ break;
690
+ }
691
+ }
692
+ if (!hadSeparator) {
693
+ for (let index = firstEnd; index < nextKept; index += 1) {
694
+ if (lines[index].trim() === '') {
695
+ hadSeparator = true;
696
+ break;
697
+ }
698
+ }
699
+ }
700
+ const out = [];
701
+ for (let index = 0; index < first; index += 1) {
702
+ if (!removed.has(index)) {
703
+ out.push(lines[index]);
704
+ }
705
+ }
706
+ out.push(...section.split('\n'));
707
+ const rest = [];
708
+ for (let index = nextKept; index < lines.length; index += 1) {
709
+ if (!removed.has(index)) {
710
+ rest.push(lines[index]);
711
+ }
712
+ }
713
+ if (hadSeparator && rest.some((line) => line.trim() !== '')) {
714
+ out.push('');
715
+ }
716
+ out.push(...rest);
717
+ const merged = out.join('\n');
718
+ return merged.endsWith('\n') ? merged : `${merged}\n`;
719
+ }
720
+ /**
721
+ * NOT-597: shared per-folder writer used by `agent-deck use` and by the
722
+ * daemon's human-approved assignment path. Writes only inside
723
+ * `workspaceRoot` (project scope): JSON entries via
724
+ * `mergeMcpServerConfig`, Codex TOML via `mergeCodexTomlConfig`.
725
+ * Callers pass the explicit client list; `use` maps its `--client` flag,
726
+ * the daemon passes cursor+claude+codex so later sessions start assigned
727
+ * regardless of host. Never touches the global headerless fallback —
728
+ * that is `setup`'s job.
729
+ */
730
+ function writePerFolderMcpEntries(workspaceRoot, endpoint, clients) {
731
+ const written = [];
732
+ const root = node_path_1.default.resolve(workspaceRoot);
733
+ for (const client of clients) {
734
+ if (client === 'claude-desktop') {
735
+ // Claude Desktop uses the launcher (no per-folder HTTP entry).
736
+ continue;
737
+ }
738
+ // NOT-571: `muse` writes the same headed `.mcp.json` entry Claude
739
+ // writes (same file, same shape) — idempotent when both are passed.
740
+ const configPath = resolveConfigPath(client, 'project', root);
741
+ const resolved = node_path_1.default.resolve(configPath);
742
+ if (resolved !== root && !resolved.startsWith(`${root}${node_path_1.default.sep}`)) {
743
+ throw new Error(`Refusing to write MCP config outside the workspace: ${configPath}`);
744
+ }
745
+ if (client === 'codex') {
746
+ const section = formatCodexMcpSection(buildCodexAgentDeckEntry(endpoint, { workspaceRoot: root }));
747
+ writeTextFile(configPath, mergeCodexTomlConfig(readTextFile(configPath), section));
748
+ written.push({ client, path: configPath });
749
+ continue;
750
+ }
751
+ const entry = buildAgentDeckEntry(client, endpoint, { workspaceRoot: root });
752
+ const merged = mergeMcpServerConfig(readJsonFile(configPath), entry);
753
+ writeJsonFile(configPath, merged);
754
+ written.push({ client, path: configPath });
755
+ }
756
+ return written;
757
+ }
758
+ //# sourceMappingURL=mcp-config.js.map