@joripspace/cli 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/mcp-config.js CHANGED
@@ -1,981 +1,981 @@
1
- const crypto = require('node:crypto');
2
- const fs = require('node:fs');
3
- const os = require('node:os');
4
- const path = require('node:path');
5
- const { isDeepStrictEqual } = require('node:util');
6
- const { applyEdits, getNodeValue, modify, parseTree, printParseErrorCode } = require('jsonc-parser');
7
- const { parse: parseToml, stringify: stringifyToml } = require('smol-toml');
8
-
9
- const JORIPSPACE_MCP_URL = 'https://api.joripspace.com/mcp';
10
- const JORIPSPACE_SERVER_ID = 'joripspace';
11
-
12
- const JSON_AGENT_PROFILES = Object.freeze({
13
- claude: { containerKey: 'mcpServers', allowJsonc: false },
14
- cursor: { containerKey: 'mcpServers', allowJsonc: false },
15
- antigravity: { containerKey: 'mcpServers', allowJsonc: false },
16
- });
17
-
18
- const MCP_AGENT_ADAPTERS = Object.freeze([
19
- {
20
- id: 'codex',
21
- surfaces: ['desktop', 'cli', 'ide'],
22
- resolveConfig: ({ homeDir }) => ({ path: path.join(homeDir, '.codex', 'config.toml') }),
23
- detect: ({ homeDir, existsSync, commandExists }) =>
24
- existsSync(path.join(homeDir, '.codex')) || commandExists('codex'),
25
- merge: mergeCodexConfig,
26
- nextAction: { kind: 'command', argv: ['codex', 'mcp', 'login', JORIPSPACE_SERVER_ID] },
27
- },
28
- {
29
- id: 'claude-code',
30
- surfaces: ['desktop-code-tab', 'cli'],
31
- resolveConfig: ({ homeDir }) => ({ path: path.join(homeDir, '.claude.json') }),
32
- detect: ({ homeDir, existsSync, commandExists }) =>
33
- existsSync(path.join(homeDir, '.claude.json')) ||
34
- existsSync(path.join(homeDir, '.claude')) ||
35
- commandExists('claude'),
36
- merge: (filePath) => mergeJsonMcpConfig(filePath, 'claude'),
37
- nextAction: { kind: 'in-app-command', command: '/mcp' },
38
- },
39
- {
40
- id: 'cursor',
41
- surfaces: ['ide', 'cli'],
42
- resolveConfig: ({ homeDir }) => ({ path: path.join(homeDir, '.cursor', 'mcp.json') }),
43
- detect: ({ homeDir, existsSync, commandExists }) =>
44
- existsSync(path.join(homeDir, '.cursor')) || commandExists('cursor') || commandExists('cursor-agent'),
45
- merge: (filePath) => mergeJsonMcpConfig(filePath, 'cursor'),
46
- nextAction: {
47
- kind: 'in-app-navigation',
48
- instruction: 'Open Customize > MCPs and complete authentication for the JoripSpace server.',
49
- },
50
- },
51
- {
52
- id: 'antigravity',
53
- surfaces: ['ide', 'cli'],
54
- resolveConfig: ({ homeDir }) => ({
55
- path: path.join(homeDir, '.gemini', 'config', 'mcp_config.json'),
56
- }),
57
- detect: ({ homeDir, existsSync, commandExists }) =>
58
- existsSync(path.join(homeDir, '.gemini', 'config', 'mcp_config.json')) ||
59
- existsSync(path.join(homeDir, '.gemini', 'antigravity')) ||
60
- existsSync(path.join(homeDir, '.gemini', 'antigravity-cli')) ||
61
- commandExists('agy'),
62
- merge: (filePath) => mergeJsonMcpConfig(filePath, 'antigravity'),
63
- nextAction: {
64
- kind: 'in-app-navigation',
65
- instruction: 'Open Agent Settings > Customizations and authenticate the JoripSpace server.',
66
- },
67
- },
68
- {
69
- id: 'opencode',
70
- surfaces: ['desktop', 'cli'],
71
- resolveConfig: resolveOpenCodeConfig,
72
- detect: ({ selection, existsSync, commandExists }) =>
73
- existsSync(path.dirname(selection.path)) || commandExists('opencode'),
74
- merge: mergeOpenCodeConfig,
75
- nextAction: {
76
- kind: 'command',
77
- argv: ['opencode', 'mcp', 'auth', JORIPSPACE_SERVER_ID],
78
- },
79
- },
80
- ]);
81
-
82
- function configureUserMcpServers(options = {}) {
83
- const homeDir = path.resolve(options.homeDir || os.homedir());
84
- const env = options.env || process.env;
85
- const existsSync = options.existsSync || fs.existsSync;
86
- const commandExists = options.commandExists || ((command) => defaultCommandExists(command, env));
87
- const context = { homeDir, env, existsSync, commandExists };
88
-
89
- return MCP_AGENT_ADAPTERS.map((adapter) => {
90
- let selection;
91
- try {
92
- selection = adapter.resolveConfig(context);
93
- } catch (error) {
94
- return agentErrorResult(adapter, null, error, false);
95
- }
96
-
97
- let detected;
98
- try {
99
- detected = Boolean(adapter.detect({ ...context, selection }));
100
- } catch (error) {
101
- return agentErrorResult(adapter, selection.path, error, false);
102
- }
103
-
104
- const common = {
105
- id: adapter.id,
106
- detected,
107
- path: selection.path,
108
- surfaces: [...adapter.surfaces],
109
- next_action: cloneSerializable(adapter.nextAction),
110
- };
111
- if (!detected) {
112
- return {
113
- ...common,
114
- status: 'not_detected',
115
- registration: 'not_detected',
116
- changed: false,
117
- auth_status: 'not_applicable',
118
- activation: 'not_registered',
119
- };
120
- }
121
- if (selection.error) {
122
- return {
123
- ...common,
124
- status: 'skipped',
125
- registration: 'skipped',
126
- changed: false,
127
- auth_status: 'not_applicable',
128
- activation: 'not_registered',
129
- error: selection.error,
130
- error_code: selection.errorCode || 'ambiguous_config',
131
- };
132
- }
133
-
134
- try {
135
- const result = adapter.merge(selection.path);
136
- return {
137
- ...common,
138
- ...result,
139
- registration:
140
- result.registration ||
141
- (result.status === 'configured' ? (result.changed ? 'updated' : 'unchanged') : result.status),
142
- auth_status: result.status === 'configured' ? 'not_checked' : 'not_applicable',
143
- activation: result.status === 'configured' ? 'next_session' : 'not_registered',
144
- };
145
- } catch (error) {
146
- return agentErrorResult(adapter, selection.path, error, true);
147
- }
148
- });
149
- }
150
-
151
- function agentErrorResult(adapter, filePath, error, detected) {
152
- return {
153
- id: adapter.id,
154
- detected,
155
- status: 'error',
156
- registration: 'error',
157
- changed: false,
158
- path: filePath,
159
- surfaces: [...adapter.surfaces],
160
- auth_status: 'not_applicable',
161
- activation: 'not_registered',
162
- next_action: cloneSerializable(adapter.nextAction),
163
- error: error instanceof Error ? error.message : String(error),
164
- ...(error && typeof error === 'object' && error.code ? { error_code: String(error.code) } : {}),
165
- };
166
- }
167
-
168
- function resolveOpenCodeConfig({ homeDir, env, existsSync }) {
169
- const xdgConfigHome = String(env?.XDG_CONFIG_HOME || '').trim();
170
- const directory = path.join(
171
- xdgConfigHome ? path.resolve(xdgConfigHome) : path.join(homeDir, '.config'),
172
- 'opencode'
173
- );
174
- const jsonPath = path.join(directory, 'opencode.json');
175
- const jsoncPath = path.join(directory, 'opencode.jsonc');
176
- const hasJson = existsSync(jsonPath);
177
- const hasJsonc = existsSync(jsoncPath);
178
- if (hasJson && hasJsonc) {
179
- return {
180
- path: jsonPath,
181
- error:
182
- 'both OpenCode global config files exist; neither was changed because their precedence is ambiguous',
183
- errorCode: 'ambiguous_opencode_config',
184
- };
185
- }
186
- return { path: hasJsonc ? jsoncPath : jsonPath };
187
- }
188
-
189
- function mergeJsonMcpConfig(filePath, agent = 'claude') {
190
- if (agent === 'opencode') return mergeOpenCodeConfig(filePath);
191
- const profile = JSON_AGENT_PROFILES[agent];
192
- if (!profile) throw new Error(`unsupported MCP JSON adapter: ${agent}`);
193
- const existed = fs.existsSync(filePath);
194
- const source = existed ? fs.readFileSync(filePath, 'utf8') : '';
195
- const allowJsonc = profile.allowJsonc && path.extname(filePath).toLowerCase() === '.jsonc';
196
- let config = {};
197
-
198
- if (existed) {
199
- const parsed = parseJsonConfigSource(source, { allowJsonc });
200
- if (!parsed.ok) return skippedConfig(filePath, parsed.error, parsed.errorCode);
201
- config = parsed.value;
202
- }
203
- if (!isPlainObject(config)) {
204
- return skippedConfig(
205
- filePath,
206
- 'existing MCP configuration must be a JSON object; it was left unchanged',
207
- 'invalid_json_root'
208
- );
209
- }
210
- const container = config[profile.containerKey];
211
- if (container !== undefined && !isPlainObject(container)) {
212
- return skippedConfig(
213
- filePath,
214
- `existing ${profile.containerKey} value is not an object; it was left unchanged`,
215
- 'invalid_mcp_container'
216
- );
217
- }
218
-
219
- const existingServer = isPlainObject(container?.[JORIPSPACE_SERVER_ID])
220
- ? container[JORIPSPACE_SERVER_ID]
221
- : {};
222
- const server = buildJsonServer(agent, existingServer);
223
- if (isDeepStrictEqual(existingServer, server)) {
224
- return {
225
- status: 'configured',
226
- registration: 'unchanged',
227
- changed: false,
228
- path: filePath,
229
- };
230
- }
231
-
232
- let nextSource;
233
- if (!existed) {
234
- nextSource = `${JSON.stringify(
235
- { [profile.containerKey]: { [JORIPSPACE_SERVER_ID]: server } },
236
- null,
237
- 2
238
- )}\n`;
239
- } else {
240
- const edits = modify(source, [profile.containerKey, JORIPSPACE_SERVER_ID], server, {
241
- formattingOptions: jsonFormattingOptions(source),
242
- });
243
- nextSource = applyEdits(source, edits);
244
- }
245
-
246
- const candidate = parseJsonConfigSource(nextSource, { allowJsonc });
247
- if (!candidate.ok) {
248
- throw codedError(
249
- 'MCP_CONFIG_GENERATION_FAILED',
250
- 'generated MCP configuration did not pass JSON validation'
251
- );
252
- }
253
- if (
254
- !isDeepStrictEqual(candidate.value?.[profile.containerKey]?.[JORIPSPACE_SERVER_ID], server) ||
255
- !isDeepStrictEqual(
256
- withoutJsonServer(config, profile.containerKey),
257
- withoutJsonServer(candidate.value, profile.containerKey)
258
- )
259
- ) {
260
- throw codedError(
261
- 'MCP_CONFIG_GENERATION_FAILED',
262
- 'generated MCP configuration did not preserve unrelated settings'
263
- );
264
- }
265
-
266
- writeTextAtomically(filePath, nextSource, { expectedSource: existed ? source : null });
267
- return {
268
- status: 'configured',
269
- registration: existed ? 'updated' : 'created',
270
- changed: true,
271
- path: filePath,
272
- };
273
- }
274
-
275
- function mergeOpenCodeConfig(filePath) {
276
- const existed = fs.existsSync(filePath);
277
- const source = existed ? fs.readFileSync(filePath, 'utf8') : '';
278
- const allowJsonc = path.extname(filePath).toLowerCase() === '.jsonc';
279
- let config = {};
280
-
281
- if (existed) {
282
- const parsed = parseJsonConfigSource(source, { allowJsonc });
283
- if (!parsed.ok) return skippedConfig(filePath, parsed.error, parsed.errorCode);
284
- config = parsed.value;
285
- }
286
- if (!isPlainObject(config)) {
287
- return skippedConfig(
288
- filePath,
289
- 'existing OpenCode configuration must be a JSON object; it was left unchanged',
290
- 'invalid_json_root'
291
- );
292
- }
293
-
294
- if (config.mcp !== undefined && !isPlainObject(config.mcp)) {
295
- return skippedConfig(
296
- filePath,
297
- 'existing OpenCode mcp value is not an object; it was left unchanged',
298
- 'invalid_mcp_container'
299
- );
300
- }
301
-
302
- const serverPath = ['mcp', JORIPSPACE_SERVER_ID];
303
- const existingServer = getJsonPath(config, serverPath);
304
- if (existingServer !== undefined && !isPlainObject(existingServer)) {
305
- return skippedConfig(
306
- filePath,
307
- 'existing OpenCode JoripSpace configuration is not an object; it was left unchanged',
308
- 'invalid_joripspace_server'
309
- );
310
- }
311
-
312
- const server = buildOpenCodeServer(existingServer || {});
313
- if (isDeepStrictEqual(existingServer, server)) {
314
- return {
315
- status: 'configured',
316
- registration: 'unchanged',
317
- changed: false,
318
- path: filePath,
319
- };
320
- }
321
-
322
- let nextSource;
323
- if (!existed) {
324
- nextSource = `${JSON.stringify({ mcp: { [JORIPSPACE_SERVER_ID]: server } }, null, 2)}\n`;
325
- } else {
326
- const edits = modify(source, serverPath, server, {
327
- formattingOptions: jsonFormattingOptions(source),
328
- });
329
- nextSource = applyEdits(source, edits);
330
- }
331
-
332
- const candidate = parseJsonConfigSource(nextSource, { allowJsonc });
333
- if (!candidate.ok) {
334
- throw codedError(
335
- 'MCP_CONFIG_GENERATION_FAILED',
336
- 'generated OpenCode MCP configuration did not pass JSON validation'
337
- );
338
- }
339
- if (
340
- !isDeepStrictEqual(getJsonPath(candidate.value, serverPath), server) ||
341
- !isDeepStrictEqual(withoutJsonPath(config, serverPath), withoutJsonPath(candidate.value, serverPath))
342
- ) {
343
- throw codedError(
344
- 'MCP_CONFIG_GENERATION_FAILED',
345
- 'generated OpenCode MCP configuration did not preserve unrelated settings'
346
- );
347
- }
348
-
349
- writeTextAtomically(filePath, nextSource, { expectedSource: existed ? source : null });
350
- return {
351
- status: 'configured',
352
- registration: existed ? 'updated' : 'created',
353
- changed: true,
354
- path: filePath,
355
- };
356
- }
357
-
358
- function buildOpenCodeServer(value) {
359
- const existing = isPlainObject(value) ? value : {};
360
- const safe = {};
361
- if (isFiniteNonNegativeNumber(existing.timeout)) safe.timeout = existing.timeout;
362
- return { type: 'remote', url: JORIPSPACE_MCP_URL, enabled: true, ...safe };
363
- }
364
-
365
- function buildJsonServer(agent, value) {
366
- const existing = isPlainObject(value) ? value : {};
367
- const safe = {};
368
- if (isFiniteNonNegativeNumber(existing.timeout)) safe.timeout = existing.timeout;
369
- if (agent === 'claude' && typeof existing.alwaysLoad === 'boolean') {
370
- safe.alwaysLoad = existing.alwaysLoad;
371
- }
372
- if (agent === 'antigravity') {
373
- if (typeof existing.disabled === 'boolean') safe.disabled = existing.disabled;
374
- if (isStringArray(existing.disabledTools)) safe.disabledTools = [...existing.disabledTools];
375
- }
376
-
377
- if (agent === 'antigravity') return { serverUrl: JORIPSPACE_MCP_URL, ...safe };
378
- if (agent === 'cursor') return { url: JORIPSPACE_MCP_URL, ...safe };
379
- return { type: 'http', url: JORIPSPACE_MCP_URL, ...safe };
380
- }
381
-
382
- function mergeCodexConfig(filePath) {
383
- const existed = fs.existsSync(filePath);
384
- const source = existed ? fs.readFileSync(filePath, 'utf8') : '';
385
- const parsed = parseTomlConfigSource(source);
386
- if (!parsed.ok) return skippedConfig(filePath, parsed.error, parsed.errorCode);
387
- const config = parsed.value;
388
- if (config.mcp_servers !== undefined && !isPlainObject(config.mcp_servers)) {
389
- return skippedConfig(
390
- filePath,
391
- 'existing mcp_servers value is not a TOML table; it was left unchanged',
392
- 'invalid_mcp_container'
393
- );
394
- }
395
- const existingServer = config.mcp_servers?.[JORIPSPACE_SERVER_ID];
396
- if (existingServer !== undefined && !isPlainObject(existingServer)) {
397
- return skippedConfig(
398
- filePath,
399
- 'existing Codex JoripSpace configuration is not a TOML table; it was left unchanged',
400
- 'invalid_joripspace_server'
401
- );
402
- }
403
-
404
- const removed = removeTomlTableTree(source, ['mcp_servers', JORIPSPACE_SERVER_ID]);
405
- if (existingServer !== undefined && !removed.found) {
406
- return skippedConfig(
407
- filePath,
408
- 'existing Codex JoripSpace configuration uses a TOML representation that cannot be edited safely; it was left unchanged',
409
- 'unsupported_toml_representation'
410
- );
411
- }
412
- const base = parseTomlConfigSource(removed.source);
413
- if (!base.ok || base.value.mcp_servers?.[JORIPSPACE_SERVER_ID] !== undefined) {
414
- return skippedConfig(
415
- filePath,
416
- 'existing Codex JoripSpace configuration could not be isolated safely; it was left unchanged',
417
- 'unsupported_toml_representation'
418
- );
419
- }
420
-
421
- const server = buildCodexServer(existingServer || {});
422
- const block = stringifyToml({ mcp_servers: { [JORIPSPACE_SERVER_ID]: server } }).trimEnd();
423
- const nextSource = appendTomlBlock(removed.source, block, detectEol(source));
424
- const candidate = parseTomlConfigSource(nextSource);
425
- if (!candidate.ok) {
426
- throw codedError(
427
- 'MCP_CONFIG_GENERATION_FAILED',
428
- 'generated Codex MCP configuration did not pass TOML validation'
429
- );
430
- }
431
- if (
432
- !isDeepStrictEqual(candidate.value.mcp_servers?.[JORIPSPACE_SERVER_ID], server) ||
433
- !isDeepStrictEqual(withoutTomlServer(config), withoutTomlServer(candidate.value))
434
- ) {
435
- throw codedError(
436
- 'MCP_CONFIG_GENERATION_FAILED',
437
- 'generated Codex MCP configuration did not preserve unrelated settings'
438
- );
439
- }
440
- if (nextSource === source) {
441
- return {
442
- status: 'configured',
443
- registration: 'unchanged',
444
- changed: false,
445
- path: filePath,
446
- };
447
- }
448
-
449
- writeTextAtomically(filePath, nextSource, { expectedSource: existed ? source : null });
450
- return {
451
- status: 'configured',
452
- registration: existed ? 'updated' : 'created',
453
- changed: true,
454
- path: filePath,
455
- };
456
- }
457
-
458
- function buildCodexServer(value) {
459
- const safe = isPlainObject(value) ? value : {};
460
- const server = {
461
- url: JORIPSPACE_MCP_URL,
462
- auth: 'oauth',
463
- enabled: true,
464
- required: false,
465
- };
466
- for (const key of ['startup_timeout_ms', 'startup_timeout_sec', 'tool_timeout_sec']) {
467
- if (isFiniteNonNegativeNumber(safe[key])) server[key] = safe[key];
468
- }
469
- for (const key of ['enabled_tools', 'disabled_tools']) {
470
- if (isStringArray(safe[key])) server[key] = [...safe[key]];
471
- }
472
- if (
473
- typeof safe.default_tools_approval_mode === 'string' &&
474
- ['auto', 'prompt', 'writes', 'approve'].includes(safe.default_tools_approval_mode)
475
- ) {
476
- server.default_tools_approval_mode = safe.default_tools_approval_mode;
477
- }
478
- if (isPlainObject(safe.tools)) {
479
- const tools = {};
480
- for (const [toolName, toolConfig] of Object.entries(safe.tools)) {
481
- if (
482
- isPlainObject(toolConfig) &&
483
- typeof toolConfig.approval_mode === 'string' &&
484
- ['auto', 'prompt', 'writes', 'approve'].includes(toolConfig.approval_mode)
485
- ) {
486
- tools[toolName] = { approval_mode: toolConfig.approval_mode };
487
- }
488
- }
489
- if (Object.keys(tools).length) server.tools = tools;
490
- }
491
- return server;
492
- }
493
-
494
- function sanitizeJoripspaceServer(value) {
495
- const blockedExactKeys = new Set([
496
- '__proto__',
497
- 'args',
498
- 'auth',
499
- 'authprovidertype',
500
- 'binary',
501
- 'callback',
502
- 'clientid',
503
- 'command',
504
- 'constructor',
505
- 'cwd',
506
- 'env',
507
- 'environment',
508
- 'executable',
509
- 'helper',
510
- 'oauth',
511
- 'process',
512
- 'prototype',
513
- 'script',
514
- 'workingdirectory',
515
- ]);
516
- const scrub = (input) => {
517
- if (Array.isArray(input)) return input.map(scrub);
518
- if (!isPlainObject(input)) return input;
519
- const output = {};
520
- for (const [key, nested] of Object.entries(input)) {
521
- const normalized = normalizeConfigKey(key);
522
- if (
523
- blockedExactKeys.has(normalized) ||
524
- normalized.startsWith('auth') ||
525
- normalized.includes('oauth') ||
526
- normalized.includes('header') ||
527
- normalized.includes('callback') ||
528
- normalized.includes('helper') ||
529
- /(token|secret|password|authorization|cookie|apikey|credential|bearer)/.test(normalized)
530
- ) {
531
- continue;
532
- }
533
- output[key] = scrub(nested);
534
- }
535
- return output;
536
- };
537
- return scrub(value);
538
- }
539
-
540
- function parseJsonConfigSource(source, { allowJsonc }) {
541
- const errors = [];
542
- const root = parseTree(source, errors, {
543
- allowTrailingComma: allowJsonc,
544
- disallowComments: !allowJsonc,
545
- });
546
- if (errors.length || !root) {
547
- const code = errors[0] ? printParseErrorCode(errors[0].error) : 'InvalidSymbol';
548
- return {
549
- ok: false,
550
- value: null,
551
- error: `existing MCP configuration is not valid ${allowJsonc ? 'JSONC' : 'JSON'} (${code}); it was left unchanged`,
552
- errorCode: allowJsonc ? 'invalid_jsonc' : 'invalid_json',
553
- };
554
- }
555
- const duplicate = findDuplicateJsonProperty(root);
556
- if (duplicate) {
557
- return {
558
- ok: false,
559
- value: null,
560
- error: `existing MCP configuration contains duplicate key ${duplicate}; it was left unchanged`,
561
- errorCode: 'duplicate_json_key',
562
- };
563
- }
564
- return { ok: true, value: toPlainJsonValue(getNodeValue(root)) };
565
- }
566
-
567
- function findDuplicateJsonProperty(node, currentPath = []) {
568
- if (node.type === 'object') {
569
- const seen = new Set();
570
- for (const property of node.children || []) {
571
- const key = property.children?.[0]?.value;
572
- const valueNode = property.children?.[1];
573
- if (typeof key !== 'string') continue;
574
- const nextPath = [...currentPath, key];
575
- if (seen.has(key)) return JSON.stringify(nextPath.join('.'));
576
- seen.add(key);
577
- const nested = valueNode ? findDuplicateJsonProperty(valueNode, nextPath) : null;
578
- if (nested) return nested;
579
- }
580
- } else if (node.type === 'array') {
581
- for (let index = 0; index < (node.children || []).length; index += 1) {
582
- const nested = findDuplicateJsonProperty(node.children[index], [...currentPath, String(index)]);
583
- if (nested) return nested;
584
- }
585
- }
586
- return null;
587
- }
588
-
589
- function parseTomlConfigSource(source) {
590
- try {
591
- const value = parseToml(String(source || ''));
592
- if (!isPlainObject(value)) throw new Error('root is not a table');
593
- return { ok: true, value };
594
- } catch {
595
- return {
596
- ok: false,
597
- value: null,
598
- error: 'existing Codex configuration is not valid TOML; it was left unchanged',
599
- errorCode: 'invalid_toml',
600
- };
601
- }
602
- }
603
-
604
- function removeTomlTableTree(source, targetPath) {
605
- const lines = String(source || '').match(/[^\n]*\n|[^\n]+$/g) || [];
606
- const kept = [];
607
- let multilineState = null;
608
- let skipping = false;
609
- let found = false;
610
-
611
- for (const line of lines) {
612
- if (!multilineState && /^\s*\[/.test(line)) {
613
- const headerPath = parseTomlHeaderPath(line);
614
- if (headerPath) {
615
- skipping = pathStartsWith(headerPath, targetPath);
616
- if (skipping) found = true;
617
- } else if (/^\s*\[\[?/.test(line)) {
618
- skipping = false;
619
- }
620
- }
621
- if (!skipping) kept.push(line);
622
- multilineState = advanceTomlMultilineState(line, multilineState);
623
- }
624
- return { source: kept.join(''), found };
625
- }
626
-
627
- function parseTomlHeaderPath(line) {
628
- const header = String(line || '').replace(/\r?\n$/, '');
629
- try {
630
- const parsed = parseToml(`${header}\n__joripspace_header_probe__ = true\n`);
631
- return findTomlProbePath(parsed);
632
- } catch {
633
- return null;
634
- }
635
- }
636
-
637
- function findTomlProbePath(value, currentPath = []) {
638
- if (isPlainObject(value)) {
639
- if (value.__joripspace_header_probe__ === true) return currentPath;
640
- for (const [key, nested] of Object.entries(value)) {
641
- const found = findTomlProbePath(nested, [...currentPath, key]);
642
- if (found) return found;
643
- }
644
- } else if (Array.isArray(value)) {
645
- for (const nested of value) {
646
- const found = findTomlProbePath(nested, currentPath);
647
- if (found) return found;
648
- }
649
- }
650
- return null;
651
- }
652
-
653
- function advanceTomlMultilineState(line, initialState) {
654
- let state = initialState;
655
- let index = 0;
656
- while (index < line.length) {
657
- if (state === 'basic') {
658
- const end = line.indexOf('"""', index);
659
- if (end < 0) return state;
660
- if (isEscapedAt(line, end)) {
661
- index = end + 1;
662
- continue;
663
- }
664
- state = null;
665
- index = end + 3;
666
- continue;
667
- }
668
- if (state === 'literal') {
669
- const end = line.indexOf("'''", index);
670
- if (end < 0) return state;
671
- state = null;
672
- index = end + 3;
673
- continue;
674
- }
675
-
676
- const character = line[index];
677
- if (character === '#') break;
678
- if (line.startsWith('"""', index)) {
679
- state = 'basic';
680
- index += 3;
681
- continue;
682
- }
683
- if (line.startsWith("'''", index)) {
684
- state = 'literal';
685
- index += 3;
686
- continue;
687
- }
688
- if (character === '"') {
689
- index += 1;
690
- while (index < line.length) {
691
- if (line[index] === '"' && !isEscapedAt(line, index)) {
692
- index += 1;
693
- break;
694
- }
695
- index += 1;
696
- }
697
- continue;
698
- }
699
- if (character === "'") {
700
- const end = line.indexOf("'", index + 1);
701
- index = end < 0 ? line.length : end + 1;
702
- continue;
703
- }
704
- index += 1;
705
- }
706
- return state;
707
- }
708
-
709
- function isEscapedAt(source, index) {
710
- let slashCount = 0;
711
- for (let cursor = index - 1; cursor >= 0 && source[cursor] === '\\'; cursor -= 1) {
712
- slashCount += 1;
713
- }
714
- return slashCount % 2 === 1;
715
- }
716
-
717
- function pathStartsWith(value, prefix) {
718
- return prefix.every((segment, index) => value[index] === segment);
719
- }
720
-
721
- function appendTomlBlock(source, block, eol = '\n') {
722
- const normalizedBlock = String(block || '')
723
- .trimEnd()
724
- .replace(/\r?\n/g, eol);
725
- let prefix = String(source || '');
726
- if (!prefix) return `${normalizedBlock}${eol}`;
727
- if (!prefix.endsWith('\n')) prefix += eol;
728
- if (!prefix.endsWith(`${eol}${eol}`)) prefix += eol;
729
- return `${prefix}${normalizedBlock}${eol}`;
730
- }
731
-
732
- function replaceTomlTable(source, tableName, replacement) {
733
- return replaceTomlTableTree(source, tableName, replacement);
734
- }
735
-
736
- function replaceTomlTableTree(source, tableName, replacement) {
737
- const removed = removeTomlTableTree(String(source || ''), String(tableName).split('.'));
738
- return appendTomlBlock(removed.source, replacement, detectEol(source));
739
- }
740
-
741
- function withoutJsonServer(config, containerKey) {
742
- const copy = { ...config };
743
- if (isPlainObject(copy[containerKey])) {
744
- const container = { ...copy[containerKey] };
745
- delete container[JORIPSPACE_SERVER_ID];
746
- if (Object.keys(container).length) copy[containerKey] = container;
747
- else delete copy[containerKey];
748
- }
749
- return copy;
750
- }
751
-
752
- function getJsonPath(value, segments) {
753
- let current = value;
754
- for (const segment of segments) {
755
- if (!isPlainObject(current)) return undefined;
756
- current = current[segment];
757
- }
758
- return current;
759
- }
760
-
761
- function withoutJsonPath(value, segments) {
762
- if (!isPlainObject(value)) return value;
763
- const [segment, ...remaining] = segments;
764
- const copy = { ...value };
765
- if (segment === undefined) return copy;
766
- if (remaining.length === 0) {
767
- delete copy[segment];
768
- return copy;
769
- }
770
- if (isPlainObject(copy[segment])) {
771
- const nested = withoutJsonPath(copy[segment], remaining);
772
- if (Object.keys(nested).length === 0) delete copy[segment];
773
- else copy[segment] = nested;
774
- }
775
- return copy;
776
- }
777
-
778
- function withoutTomlServer(config) {
779
- const copy = { ...config };
780
- if (isPlainObject(copy.mcp_servers)) {
781
- const servers = { ...copy.mcp_servers };
782
- delete servers[JORIPSPACE_SERVER_ID];
783
- if (Object.keys(servers).length) copy.mcp_servers = servers;
784
- else delete copy.mcp_servers;
785
- }
786
- return copy;
787
- }
788
-
789
- function jsonFormattingOptions(source) {
790
- const eol = detectEol(source);
791
- const indentation = /\r?\n([ \t]+)["}]/.exec(source)?.[1] || ' ';
792
- if (indentation.includes('\t')) return { insertSpaces: false, tabSize: 1, eol };
793
- return { insertSpaces: true, tabSize: Math.max(1, indentation.length), eol };
794
- }
795
-
796
- function detectEol(source) {
797
- return String(source || '').includes('\r\n') ? '\r\n' : '\n';
798
- }
799
-
800
- function writeTextAtomically(filePath, source, options = {}) {
801
- const directory = path.dirname(filePath);
802
- fs.mkdirSync(directory, { recursive: true });
803
- const hasExpected = Object.prototype.hasOwnProperty.call(options, 'expectedSource');
804
- const expectedSource = hasExpected ? options.expectedSource : readTextIfExists(filePath);
805
- if (readTextIfExists(filePath) !== expectedSource) throw concurrentConfigError();
806
-
807
- let mode = 0o600;
808
- try {
809
- mode = fs.statSync(filePath).mode & 0o777;
810
- } catch (error) {
811
- if (error?.code !== 'ENOENT') throw error;
812
- }
813
- const temporaryPath = `${filePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
814
- let descriptor;
815
- let temporaryExists = false;
816
- try {
817
- descriptor = fs.openSync(temporaryPath, 'wx', mode);
818
- temporaryExists = true;
819
- fs.writeFileSync(descriptor, source, 'utf8');
820
- fs.fsyncSync(descriptor);
821
- fs.closeSync(descriptor);
822
- descriptor = undefined;
823
- try {
824
- fs.chmodSync(temporaryPath, mode);
825
- } catch (error) {
826
- if (process.platform !== 'win32') throw error;
827
- }
828
-
829
- if (typeof options.beforeCommit === 'function') options.beforeCommit();
830
- if (readTextIfExists(filePath) !== expectedSource) throw concurrentConfigError();
831
- fs.renameSync(temporaryPath, filePath);
832
- temporaryExists = false;
833
- fsyncDirectory(directory);
834
- if (fs.readFileSync(filePath, 'utf8') !== source) {
835
- throw codedError('MCP_CONFIG_WRITE_VERIFY_FAILED', 'MCP configuration write verification failed');
836
- }
837
- } finally {
838
- if (descriptor !== undefined) {
839
- try {
840
- fs.closeSync(descriptor);
841
- } catch {}
842
- }
843
- if (temporaryExists) {
844
- try {
845
- fs.rmSync(temporaryPath, { force: true });
846
- } catch {}
847
- }
848
- }
849
- }
850
-
851
- function fsyncDirectory(directory) {
852
- if (process.platform === 'win32') return;
853
- let descriptor;
854
- try {
855
- descriptor = fs.openSync(directory, 'r');
856
- fs.fsyncSync(descriptor);
857
- } catch (error) {
858
- if (!['EINVAL', 'ENOTSUP', 'EISDIR'].includes(error?.code)) throw error;
859
- } finally {
860
- if (descriptor !== undefined) fs.closeSync(descriptor);
861
- }
862
- }
863
-
864
- function readTextIfExists(filePath) {
865
- try {
866
- return fs.readFileSync(filePath, 'utf8');
867
- } catch (error) {
868
- if (error?.code === 'ENOENT') return null;
869
- throw error;
870
- }
871
- }
872
-
873
- function concurrentConfigError() {
874
- return codedError('MCP_CONFIG_CONFLICT', 'MCP configuration changed concurrently; it was not overwritten');
875
- }
876
-
877
- function codedError(code, message) {
878
- const error = new Error(message);
879
- error.code = code;
880
- return error;
881
- }
882
-
883
- function skippedConfig(filePath, error, errorCode) {
884
- return {
885
- status: 'skipped',
886
- registration: 'skipped',
887
- changed: false,
888
- path: filePath,
889
- error,
890
- error_code: errorCode,
891
- };
892
- }
893
-
894
- function defaultCommandExists(command, env = process.env) {
895
- const pathValue = String(env.PATH || env.Path || env.path || '');
896
- if (!pathValue) return false;
897
- const pathEntries = pathValue
898
- .split(path.delimiter)
899
- .map((entry) => entry.trim().replace(/^"|"$/g, ''))
900
- .filter(Boolean);
901
- const extensions =
902
- process.platform === 'win32'
903
- ? commandHasExtension(command)
904
- ? ['']
905
- : String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD')
906
- .split(';')
907
- .filter(Boolean)
908
- : [''];
909
-
910
- for (const directory of pathEntries) {
911
- for (const extension of extensions) {
912
- const candidate = path.join(directory, `${command}${extension}`);
913
- try {
914
- const stats = fs.statSync(candidate);
915
- if (!stats.isFile()) continue;
916
- if (process.platform === 'win32' || (stats.mode & 0o111) !== 0) return true;
917
- } catch (error) {
918
- if (!['ENOENT', 'ENOTDIR', 'EACCES'].includes(error?.code)) throw error;
919
- }
920
- }
921
- }
922
- return false;
923
- }
924
-
925
- function commandHasExtension(command) {
926
- return path.extname(command) !== '';
927
- }
928
-
929
- function normalizeConfigKey(key) {
930
- return String(key)
931
- .toLowerCase()
932
- .replace(/[^a-z0-9_]/g, '')
933
- .replace(/_/g, '');
934
- }
935
-
936
- function toPlainJsonValue(value) {
937
- if (Array.isArray(value)) return value.map(toPlainJsonValue);
938
- if (!value || typeof value !== 'object') return value;
939
- const output = {};
940
- for (const [key, nested] of Object.entries(value)) {
941
- Object.defineProperty(output, key, {
942
- value: toPlainJsonValue(nested),
943
- enumerable: true,
944
- configurable: true,
945
- writable: true,
946
- });
947
- }
948
- return output;
949
- }
950
-
951
- function isPlainObject(value) {
952
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
953
- const prototype = Object.getPrototypeOf(value);
954
- return prototype === Object.prototype || prototype === null;
955
- }
956
-
957
- function isFiniteNonNegativeNumber(value) {
958
- return typeof value === 'number' && Number.isFinite(value) && value >= 0;
959
- }
960
-
961
- function isStringArray(value) {
962
- return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
963
- }
964
-
965
- function cloneSerializable(value) {
966
- return value == null ? value : JSON.parse(JSON.stringify(value));
967
- }
968
-
969
- module.exports = {
970
- JORIPSPACE_MCP_URL,
971
- MCP_AGENT_ADAPTERS,
972
- configureUserMcpServers,
973
- defaultCommandExists,
974
- mergeCodexConfig,
975
- mergeJsonMcpConfig,
976
- mergeOpenCodeConfig,
977
- replaceTomlTable,
978
- replaceTomlTableTree,
979
- sanitizeJoripspaceServer,
980
- writeTextAtomically,
981
- };
1
+ const crypto = require('node:crypto');
2
+ const fs = require('node:fs');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+ const { isDeepStrictEqual } = require('node:util');
6
+ const { applyEdits, getNodeValue, modify, parseTree, printParseErrorCode } = require('jsonc-parser');
7
+ const { parse: parseToml, stringify: stringifyToml } = require('smol-toml');
8
+
9
+ const JORIPSPACE_MCP_URL = 'https://api.joripspace.com/mcp';
10
+ const JORIPSPACE_SERVER_ID = 'joripspace';
11
+
12
+ const JSON_AGENT_PROFILES = Object.freeze({
13
+ claude: { containerKey: 'mcpServers', allowJsonc: false },
14
+ cursor: { containerKey: 'mcpServers', allowJsonc: false },
15
+ antigravity: { containerKey: 'mcpServers', allowJsonc: false },
16
+ });
17
+
18
+ const MCP_AGENT_ADAPTERS = Object.freeze([
19
+ {
20
+ id: 'codex',
21
+ surfaces: ['desktop', 'cli', 'ide'],
22
+ resolveConfig: ({ homeDir }) => ({ path: path.join(homeDir, '.codex', 'config.toml') }),
23
+ detect: ({ homeDir, existsSync, commandExists }) =>
24
+ existsSync(path.join(homeDir, '.codex')) || commandExists('codex'),
25
+ merge: mergeCodexConfig,
26
+ nextAction: { kind: 'command', argv: ['codex', 'mcp', 'login', JORIPSPACE_SERVER_ID] },
27
+ },
28
+ {
29
+ id: 'claude-code',
30
+ surfaces: ['desktop-code-tab', 'cli'],
31
+ resolveConfig: ({ homeDir }) => ({ path: path.join(homeDir, '.claude.json') }),
32
+ detect: ({ homeDir, existsSync, commandExists }) =>
33
+ existsSync(path.join(homeDir, '.claude.json')) ||
34
+ existsSync(path.join(homeDir, '.claude')) ||
35
+ commandExists('claude'),
36
+ merge: (filePath) => mergeJsonMcpConfig(filePath, 'claude'),
37
+ nextAction: { kind: 'in-app-command', command: '/mcp' },
38
+ },
39
+ {
40
+ id: 'cursor',
41
+ surfaces: ['ide', 'cli'],
42
+ resolveConfig: ({ homeDir }) => ({ path: path.join(homeDir, '.cursor', 'mcp.json') }),
43
+ detect: ({ homeDir, existsSync, commandExists }) =>
44
+ existsSync(path.join(homeDir, '.cursor')) || commandExists('cursor') || commandExists('cursor-agent'),
45
+ merge: (filePath) => mergeJsonMcpConfig(filePath, 'cursor'),
46
+ nextAction: {
47
+ kind: 'in-app-navigation',
48
+ instruction: 'Open Customize > MCPs and complete authentication for the JoripSpace server.',
49
+ },
50
+ },
51
+ {
52
+ id: 'antigravity',
53
+ surfaces: ['ide', 'cli'],
54
+ resolveConfig: ({ homeDir }) => ({
55
+ path: path.join(homeDir, '.gemini', 'config', 'mcp_config.json'),
56
+ }),
57
+ detect: ({ homeDir, existsSync, commandExists }) =>
58
+ existsSync(path.join(homeDir, '.gemini', 'config', 'mcp_config.json')) ||
59
+ existsSync(path.join(homeDir, '.gemini', 'antigravity')) ||
60
+ existsSync(path.join(homeDir, '.gemini', 'antigravity-cli')) ||
61
+ commandExists('agy'),
62
+ merge: (filePath) => mergeJsonMcpConfig(filePath, 'antigravity'),
63
+ nextAction: {
64
+ kind: 'in-app-navigation',
65
+ instruction: 'Open Agent Settings > Customizations and authenticate the JoripSpace server.',
66
+ },
67
+ },
68
+ {
69
+ id: 'opencode',
70
+ surfaces: ['desktop', 'cli'],
71
+ resolveConfig: resolveOpenCodeConfig,
72
+ detect: ({ selection, existsSync, commandExists }) =>
73
+ existsSync(path.dirname(selection.path)) || commandExists('opencode'),
74
+ merge: mergeOpenCodeConfig,
75
+ nextAction: {
76
+ kind: 'command',
77
+ argv: ['opencode', 'mcp', 'auth', JORIPSPACE_SERVER_ID],
78
+ },
79
+ },
80
+ ]);
81
+
82
+ function configureUserMcpServers(options = {}) {
83
+ const homeDir = path.resolve(options.homeDir || os.homedir());
84
+ const env = options.env || process.env;
85
+ const existsSync = options.existsSync || fs.existsSync;
86
+ const commandExists = options.commandExists || ((command) => defaultCommandExists(command, env));
87
+ const context = { homeDir, env, existsSync, commandExists };
88
+
89
+ return MCP_AGENT_ADAPTERS.map((adapter) => {
90
+ let selection;
91
+ try {
92
+ selection = adapter.resolveConfig(context);
93
+ } catch (error) {
94
+ return agentErrorResult(adapter, null, error, false);
95
+ }
96
+
97
+ let detected;
98
+ try {
99
+ detected = Boolean(adapter.detect({ ...context, selection }));
100
+ } catch (error) {
101
+ return agentErrorResult(adapter, selection.path, error, false);
102
+ }
103
+
104
+ const common = {
105
+ id: adapter.id,
106
+ detected,
107
+ path: selection.path,
108
+ surfaces: [...adapter.surfaces],
109
+ next_action: cloneSerializable(adapter.nextAction),
110
+ };
111
+ if (!detected) {
112
+ return {
113
+ ...common,
114
+ status: 'not_detected',
115
+ registration: 'not_detected',
116
+ changed: false,
117
+ auth_status: 'not_applicable',
118
+ activation: 'not_registered',
119
+ };
120
+ }
121
+ if (selection.error) {
122
+ return {
123
+ ...common,
124
+ status: 'skipped',
125
+ registration: 'skipped',
126
+ changed: false,
127
+ auth_status: 'not_applicable',
128
+ activation: 'not_registered',
129
+ error: selection.error,
130
+ error_code: selection.errorCode || 'ambiguous_config',
131
+ };
132
+ }
133
+
134
+ try {
135
+ const result = adapter.merge(selection.path);
136
+ return {
137
+ ...common,
138
+ ...result,
139
+ registration:
140
+ result.registration ||
141
+ (result.status === 'configured' ? (result.changed ? 'updated' : 'unchanged') : result.status),
142
+ auth_status: result.status === 'configured' ? 'not_checked' : 'not_applicable',
143
+ activation: result.status === 'configured' ? 'next_session' : 'not_registered',
144
+ };
145
+ } catch (error) {
146
+ return agentErrorResult(adapter, selection.path, error, true);
147
+ }
148
+ });
149
+ }
150
+
151
+ function agentErrorResult(adapter, filePath, error, detected) {
152
+ return {
153
+ id: adapter.id,
154
+ detected,
155
+ status: 'error',
156
+ registration: 'error',
157
+ changed: false,
158
+ path: filePath,
159
+ surfaces: [...adapter.surfaces],
160
+ auth_status: 'not_applicable',
161
+ activation: 'not_registered',
162
+ next_action: cloneSerializable(adapter.nextAction),
163
+ error: error instanceof Error ? error.message : String(error),
164
+ ...(error && typeof error === 'object' && error.code ? { error_code: String(error.code) } : {}),
165
+ };
166
+ }
167
+
168
+ function resolveOpenCodeConfig({ homeDir, env, existsSync }) {
169
+ const xdgConfigHome = String(env?.XDG_CONFIG_HOME || '').trim();
170
+ const directory = path.join(
171
+ xdgConfigHome ? path.resolve(xdgConfigHome) : path.join(homeDir, '.config'),
172
+ 'opencode'
173
+ );
174
+ const jsonPath = path.join(directory, 'opencode.json');
175
+ const jsoncPath = path.join(directory, 'opencode.jsonc');
176
+ const hasJson = existsSync(jsonPath);
177
+ const hasJsonc = existsSync(jsoncPath);
178
+ if (hasJson && hasJsonc) {
179
+ return {
180
+ path: jsonPath,
181
+ error:
182
+ 'both OpenCode global config files exist; neither was changed because their precedence is ambiguous',
183
+ errorCode: 'ambiguous_opencode_config',
184
+ };
185
+ }
186
+ return { path: hasJsonc ? jsoncPath : jsonPath };
187
+ }
188
+
189
+ function mergeJsonMcpConfig(filePath, agent = 'claude') {
190
+ if (agent === 'opencode') return mergeOpenCodeConfig(filePath);
191
+ const profile = JSON_AGENT_PROFILES[agent];
192
+ if (!profile) throw new Error(`unsupported MCP JSON adapter: ${agent}`);
193
+ const existed = fs.existsSync(filePath);
194
+ const source = existed ? fs.readFileSync(filePath, 'utf8') : '';
195
+ const allowJsonc = profile.allowJsonc && path.extname(filePath).toLowerCase() === '.jsonc';
196
+ let config = {};
197
+
198
+ if (existed) {
199
+ const parsed = parseJsonConfigSource(source, { allowJsonc });
200
+ if (!parsed.ok) return skippedConfig(filePath, parsed.error, parsed.errorCode);
201
+ config = parsed.value;
202
+ }
203
+ if (!isPlainObject(config)) {
204
+ return skippedConfig(
205
+ filePath,
206
+ 'existing MCP configuration must be a JSON object; it was left unchanged',
207
+ 'invalid_json_root'
208
+ );
209
+ }
210
+ const container = config[profile.containerKey];
211
+ if (container !== undefined && !isPlainObject(container)) {
212
+ return skippedConfig(
213
+ filePath,
214
+ `existing ${profile.containerKey} value is not an object; it was left unchanged`,
215
+ 'invalid_mcp_container'
216
+ );
217
+ }
218
+
219
+ const existingServer = isPlainObject(container?.[JORIPSPACE_SERVER_ID])
220
+ ? container[JORIPSPACE_SERVER_ID]
221
+ : {};
222
+ const server = buildJsonServer(agent, existingServer);
223
+ if (isDeepStrictEqual(existingServer, server)) {
224
+ return {
225
+ status: 'configured',
226
+ registration: 'unchanged',
227
+ changed: false,
228
+ path: filePath,
229
+ };
230
+ }
231
+
232
+ let nextSource;
233
+ if (!existed) {
234
+ nextSource = `${JSON.stringify(
235
+ { [profile.containerKey]: { [JORIPSPACE_SERVER_ID]: server } },
236
+ null,
237
+ 2
238
+ )}\n`;
239
+ } else {
240
+ const edits = modify(source, [profile.containerKey, JORIPSPACE_SERVER_ID], server, {
241
+ formattingOptions: jsonFormattingOptions(source),
242
+ });
243
+ nextSource = applyEdits(source, edits);
244
+ }
245
+
246
+ const candidate = parseJsonConfigSource(nextSource, { allowJsonc });
247
+ if (!candidate.ok) {
248
+ throw codedError(
249
+ 'MCP_CONFIG_GENERATION_FAILED',
250
+ 'generated MCP configuration did not pass JSON validation'
251
+ );
252
+ }
253
+ if (
254
+ !isDeepStrictEqual(candidate.value?.[profile.containerKey]?.[JORIPSPACE_SERVER_ID], server) ||
255
+ !isDeepStrictEqual(
256
+ withoutJsonServer(config, profile.containerKey),
257
+ withoutJsonServer(candidate.value, profile.containerKey)
258
+ )
259
+ ) {
260
+ throw codedError(
261
+ 'MCP_CONFIG_GENERATION_FAILED',
262
+ 'generated MCP configuration did not preserve unrelated settings'
263
+ );
264
+ }
265
+
266
+ writeTextAtomically(filePath, nextSource, { expectedSource: existed ? source : null });
267
+ return {
268
+ status: 'configured',
269
+ registration: existed ? 'updated' : 'created',
270
+ changed: true,
271
+ path: filePath,
272
+ };
273
+ }
274
+
275
+ function mergeOpenCodeConfig(filePath) {
276
+ const existed = fs.existsSync(filePath);
277
+ const source = existed ? fs.readFileSync(filePath, 'utf8') : '';
278
+ const allowJsonc = path.extname(filePath).toLowerCase() === '.jsonc';
279
+ let config = {};
280
+
281
+ if (existed) {
282
+ const parsed = parseJsonConfigSource(source, { allowJsonc });
283
+ if (!parsed.ok) return skippedConfig(filePath, parsed.error, parsed.errorCode);
284
+ config = parsed.value;
285
+ }
286
+ if (!isPlainObject(config)) {
287
+ return skippedConfig(
288
+ filePath,
289
+ 'existing OpenCode configuration must be a JSON object; it was left unchanged',
290
+ 'invalid_json_root'
291
+ );
292
+ }
293
+
294
+ if (config.mcp !== undefined && !isPlainObject(config.mcp)) {
295
+ return skippedConfig(
296
+ filePath,
297
+ 'existing OpenCode mcp value is not an object; it was left unchanged',
298
+ 'invalid_mcp_container'
299
+ );
300
+ }
301
+
302
+ const serverPath = ['mcp', JORIPSPACE_SERVER_ID];
303
+ const existingServer = getJsonPath(config, serverPath);
304
+ if (existingServer !== undefined && !isPlainObject(existingServer)) {
305
+ return skippedConfig(
306
+ filePath,
307
+ 'existing OpenCode JoripSpace configuration is not an object; it was left unchanged',
308
+ 'invalid_joripspace_server'
309
+ );
310
+ }
311
+
312
+ const server = buildOpenCodeServer(existingServer || {});
313
+ if (isDeepStrictEqual(existingServer, server)) {
314
+ return {
315
+ status: 'configured',
316
+ registration: 'unchanged',
317
+ changed: false,
318
+ path: filePath,
319
+ };
320
+ }
321
+
322
+ let nextSource;
323
+ if (!existed) {
324
+ nextSource = `${JSON.stringify({ mcp: { [JORIPSPACE_SERVER_ID]: server } }, null, 2)}\n`;
325
+ } else {
326
+ const edits = modify(source, serverPath, server, {
327
+ formattingOptions: jsonFormattingOptions(source),
328
+ });
329
+ nextSource = applyEdits(source, edits);
330
+ }
331
+
332
+ const candidate = parseJsonConfigSource(nextSource, { allowJsonc });
333
+ if (!candidate.ok) {
334
+ throw codedError(
335
+ 'MCP_CONFIG_GENERATION_FAILED',
336
+ 'generated OpenCode MCP configuration did not pass JSON validation'
337
+ );
338
+ }
339
+ if (
340
+ !isDeepStrictEqual(getJsonPath(candidate.value, serverPath), server) ||
341
+ !isDeepStrictEqual(withoutJsonPath(config, serverPath), withoutJsonPath(candidate.value, serverPath))
342
+ ) {
343
+ throw codedError(
344
+ 'MCP_CONFIG_GENERATION_FAILED',
345
+ 'generated OpenCode MCP configuration did not preserve unrelated settings'
346
+ );
347
+ }
348
+
349
+ writeTextAtomically(filePath, nextSource, { expectedSource: existed ? source : null });
350
+ return {
351
+ status: 'configured',
352
+ registration: existed ? 'updated' : 'created',
353
+ changed: true,
354
+ path: filePath,
355
+ };
356
+ }
357
+
358
+ function buildOpenCodeServer(value) {
359
+ const existing = isPlainObject(value) ? value : {};
360
+ const safe = {};
361
+ if (isFiniteNonNegativeNumber(existing.timeout)) safe.timeout = existing.timeout;
362
+ return { type: 'remote', url: JORIPSPACE_MCP_URL, enabled: true, ...safe };
363
+ }
364
+
365
+ function buildJsonServer(agent, value) {
366
+ const existing = isPlainObject(value) ? value : {};
367
+ const safe = {};
368
+ if (isFiniteNonNegativeNumber(existing.timeout)) safe.timeout = existing.timeout;
369
+ if (agent === 'claude' && typeof existing.alwaysLoad === 'boolean') {
370
+ safe.alwaysLoad = existing.alwaysLoad;
371
+ }
372
+ if (agent === 'antigravity') {
373
+ if (typeof existing.disabled === 'boolean') safe.disabled = existing.disabled;
374
+ if (isStringArray(existing.disabledTools)) safe.disabledTools = [...existing.disabledTools];
375
+ }
376
+
377
+ if (agent === 'antigravity') return { serverUrl: JORIPSPACE_MCP_URL, ...safe };
378
+ if (agent === 'cursor') return { url: JORIPSPACE_MCP_URL, ...safe };
379
+ return { type: 'http', url: JORIPSPACE_MCP_URL, ...safe };
380
+ }
381
+
382
+ function mergeCodexConfig(filePath) {
383
+ const existed = fs.existsSync(filePath);
384
+ const source = existed ? fs.readFileSync(filePath, 'utf8') : '';
385
+ const parsed = parseTomlConfigSource(source);
386
+ if (!parsed.ok) return skippedConfig(filePath, parsed.error, parsed.errorCode);
387
+ const config = parsed.value;
388
+ if (config.mcp_servers !== undefined && !isPlainObject(config.mcp_servers)) {
389
+ return skippedConfig(
390
+ filePath,
391
+ 'existing mcp_servers value is not a TOML table; it was left unchanged',
392
+ 'invalid_mcp_container'
393
+ );
394
+ }
395
+ const existingServer = config.mcp_servers?.[JORIPSPACE_SERVER_ID];
396
+ if (existingServer !== undefined && !isPlainObject(existingServer)) {
397
+ return skippedConfig(
398
+ filePath,
399
+ 'existing Codex JoripSpace configuration is not a TOML table; it was left unchanged',
400
+ 'invalid_joripspace_server'
401
+ );
402
+ }
403
+
404
+ const removed = removeTomlTableTree(source, ['mcp_servers', JORIPSPACE_SERVER_ID]);
405
+ if (existingServer !== undefined && !removed.found) {
406
+ return skippedConfig(
407
+ filePath,
408
+ 'existing Codex JoripSpace configuration uses a TOML representation that cannot be edited safely; it was left unchanged',
409
+ 'unsupported_toml_representation'
410
+ );
411
+ }
412
+ const base = parseTomlConfigSource(removed.source);
413
+ if (!base.ok || base.value.mcp_servers?.[JORIPSPACE_SERVER_ID] !== undefined) {
414
+ return skippedConfig(
415
+ filePath,
416
+ 'existing Codex JoripSpace configuration could not be isolated safely; it was left unchanged',
417
+ 'unsupported_toml_representation'
418
+ );
419
+ }
420
+
421
+ const server = buildCodexServer(existingServer || {});
422
+ const block = stringifyToml({ mcp_servers: { [JORIPSPACE_SERVER_ID]: server } }).trimEnd();
423
+ const nextSource = appendTomlBlock(removed.source, block, detectEol(source));
424
+ const candidate = parseTomlConfigSource(nextSource);
425
+ if (!candidate.ok) {
426
+ throw codedError(
427
+ 'MCP_CONFIG_GENERATION_FAILED',
428
+ 'generated Codex MCP configuration did not pass TOML validation'
429
+ );
430
+ }
431
+ if (
432
+ !isDeepStrictEqual(candidate.value.mcp_servers?.[JORIPSPACE_SERVER_ID], server) ||
433
+ !isDeepStrictEqual(withoutTomlServer(config), withoutTomlServer(candidate.value))
434
+ ) {
435
+ throw codedError(
436
+ 'MCP_CONFIG_GENERATION_FAILED',
437
+ 'generated Codex MCP configuration did not preserve unrelated settings'
438
+ );
439
+ }
440
+ if (nextSource === source) {
441
+ return {
442
+ status: 'configured',
443
+ registration: 'unchanged',
444
+ changed: false,
445
+ path: filePath,
446
+ };
447
+ }
448
+
449
+ writeTextAtomically(filePath, nextSource, { expectedSource: existed ? source : null });
450
+ return {
451
+ status: 'configured',
452
+ registration: existed ? 'updated' : 'created',
453
+ changed: true,
454
+ path: filePath,
455
+ };
456
+ }
457
+
458
+ function buildCodexServer(value) {
459
+ const safe = isPlainObject(value) ? value : {};
460
+ const server = {
461
+ url: JORIPSPACE_MCP_URL,
462
+ auth: 'oauth',
463
+ enabled: true,
464
+ required: false,
465
+ };
466
+ for (const key of ['startup_timeout_ms', 'startup_timeout_sec', 'tool_timeout_sec']) {
467
+ if (isFiniteNonNegativeNumber(safe[key])) server[key] = safe[key];
468
+ }
469
+ for (const key of ['enabled_tools', 'disabled_tools']) {
470
+ if (isStringArray(safe[key])) server[key] = [...safe[key]];
471
+ }
472
+ if (
473
+ typeof safe.default_tools_approval_mode === 'string' &&
474
+ ['auto', 'prompt', 'writes', 'approve'].includes(safe.default_tools_approval_mode)
475
+ ) {
476
+ server.default_tools_approval_mode = safe.default_tools_approval_mode;
477
+ }
478
+ if (isPlainObject(safe.tools)) {
479
+ const tools = {};
480
+ for (const [toolName, toolConfig] of Object.entries(safe.tools)) {
481
+ if (
482
+ isPlainObject(toolConfig) &&
483
+ typeof toolConfig.approval_mode === 'string' &&
484
+ ['auto', 'prompt', 'writes', 'approve'].includes(toolConfig.approval_mode)
485
+ ) {
486
+ tools[toolName] = { approval_mode: toolConfig.approval_mode };
487
+ }
488
+ }
489
+ if (Object.keys(tools).length) server.tools = tools;
490
+ }
491
+ return server;
492
+ }
493
+
494
+ function sanitizeJoripspaceServer(value) {
495
+ const blockedExactKeys = new Set([
496
+ '__proto__',
497
+ 'args',
498
+ 'auth',
499
+ 'authprovidertype',
500
+ 'binary',
501
+ 'callback',
502
+ 'clientid',
503
+ 'command',
504
+ 'constructor',
505
+ 'cwd',
506
+ 'env',
507
+ 'environment',
508
+ 'executable',
509
+ 'helper',
510
+ 'oauth',
511
+ 'process',
512
+ 'prototype',
513
+ 'script',
514
+ 'workingdirectory',
515
+ ]);
516
+ const scrub = (input) => {
517
+ if (Array.isArray(input)) return input.map(scrub);
518
+ if (!isPlainObject(input)) return input;
519
+ const output = {};
520
+ for (const [key, nested] of Object.entries(input)) {
521
+ const normalized = normalizeConfigKey(key);
522
+ if (
523
+ blockedExactKeys.has(normalized) ||
524
+ normalized.startsWith('auth') ||
525
+ normalized.includes('oauth') ||
526
+ normalized.includes('header') ||
527
+ normalized.includes('callback') ||
528
+ normalized.includes('helper') ||
529
+ /(token|secret|password|authorization|cookie|apikey|credential|bearer)/.test(normalized)
530
+ ) {
531
+ continue;
532
+ }
533
+ output[key] = scrub(nested);
534
+ }
535
+ return output;
536
+ };
537
+ return scrub(value);
538
+ }
539
+
540
+ function parseJsonConfigSource(source, { allowJsonc }) {
541
+ const errors = [];
542
+ const root = parseTree(source, errors, {
543
+ allowTrailingComma: allowJsonc,
544
+ disallowComments: !allowJsonc,
545
+ });
546
+ if (errors.length || !root) {
547
+ const code = errors[0] ? printParseErrorCode(errors[0].error) : 'InvalidSymbol';
548
+ return {
549
+ ok: false,
550
+ value: null,
551
+ error: `existing MCP configuration is not valid ${allowJsonc ? 'JSONC' : 'JSON'} (${code}); it was left unchanged`,
552
+ errorCode: allowJsonc ? 'invalid_jsonc' : 'invalid_json',
553
+ };
554
+ }
555
+ const duplicate = findDuplicateJsonProperty(root);
556
+ if (duplicate) {
557
+ return {
558
+ ok: false,
559
+ value: null,
560
+ error: `existing MCP configuration contains duplicate key ${duplicate}; it was left unchanged`,
561
+ errorCode: 'duplicate_json_key',
562
+ };
563
+ }
564
+ return { ok: true, value: toPlainJsonValue(getNodeValue(root)) };
565
+ }
566
+
567
+ function findDuplicateJsonProperty(node, currentPath = []) {
568
+ if (node.type === 'object') {
569
+ const seen = new Set();
570
+ for (const property of node.children || []) {
571
+ const key = property.children?.[0]?.value;
572
+ const valueNode = property.children?.[1];
573
+ if (typeof key !== 'string') continue;
574
+ const nextPath = [...currentPath, key];
575
+ if (seen.has(key)) return JSON.stringify(nextPath.join('.'));
576
+ seen.add(key);
577
+ const nested = valueNode ? findDuplicateJsonProperty(valueNode, nextPath) : null;
578
+ if (nested) return nested;
579
+ }
580
+ } else if (node.type === 'array') {
581
+ for (let index = 0; index < (node.children || []).length; index += 1) {
582
+ const nested = findDuplicateJsonProperty(node.children[index], [...currentPath, String(index)]);
583
+ if (nested) return nested;
584
+ }
585
+ }
586
+ return null;
587
+ }
588
+
589
+ function parseTomlConfigSource(source) {
590
+ try {
591
+ const value = parseToml(String(source || ''));
592
+ if (!isPlainObject(value)) throw new Error('root is not a table');
593
+ return { ok: true, value };
594
+ } catch {
595
+ return {
596
+ ok: false,
597
+ value: null,
598
+ error: 'existing Codex configuration is not valid TOML; it was left unchanged',
599
+ errorCode: 'invalid_toml',
600
+ };
601
+ }
602
+ }
603
+
604
+ function removeTomlTableTree(source, targetPath) {
605
+ const lines = String(source || '').match(/[^\n]*\n|[^\n]+$/g) || [];
606
+ const kept = [];
607
+ let multilineState = null;
608
+ let skipping = false;
609
+ let found = false;
610
+
611
+ for (const line of lines) {
612
+ if (!multilineState && /^\s*\[/.test(line)) {
613
+ const headerPath = parseTomlHeaderPath(line);
614
+ if (headerPath) {
615
+ skipping = pathStartsWith(headerPath, targetPath);
616
+ if (skipping) found = true;
617
+ } else if (/^\s*\[\[?/.test(line)) {
618
+ skipping = false;
619
+ }
620
+ }
621
+ if (!skipping) kept.push(line);
622
+ multilineState = advanceTomlMultilineState(line, multilineState);
623
+ }
624
+ return { source: kept.join(''), found };
625
+ }
626
+
627
+ function parseTomlHeaderPath(line) {
628
+ const header = String(line || '').replace(/\r?\n$/, '');
629
+ try {
630
+ const parsed = parseToml(`${header}\n__joripspace_header_probe__ = true\n`);
631
+ return findTomlProbePath(parsed);
632
+ } catch {
633
+ return null;
634
+ }
635
+ }
636
+
637
+ function findTomlProbePath(value, currentPath = []) {
638
+ if (isPlainObject(value)) {
639
+ if (value.__joripspace_header_probe__ === true) return currentPath;
640
+ for (const [key, nested] of Object.entries(value)) {
641
+ const found = findTomlProbePath(nested, [...currentPath, key]);
642
+ if (found) return found;
643
+ }
644
+ } else if (Array.isArray(value)) {
645
+ for (const nested of value) {
646
+ const found = findTomlProbePath(nested, currentPath);
647
+ if (found) return found;
648
+ }
649
+ }
650
+ return null;
651
+ }
652
+
653
+ function advanceTomlMultilineState(line, initialState) {
654
+ let state = initialState;
655
+ let index = 0;
656
+ while (index < line.length) {
657
+ if (state === 'basic') {
658
+ const end = line.indexOf('"""', index);
659
+ if (end < 0) return state;
660
+ if (isEscapedAt(line, end)) {
661
+ index = end + 1;
662
+ continue;
663
+ }
664
+ state = null;
665
+ index = end + 3;
666
+ continue;
667
+ }
668
+ if (state === 'literal') {
669
+ const end = line.indexOf("'''", index);
670
+ if (end < 0) return state;
671
+ state = null;
672
+ index = end + 3;
673
+ continue;
674
+ }
675
+
676
+ const character = line[index];
677
+ if (character === '#') break;
678
+ if (line.startsWith('"""', index)) {
679
+ state = 'basic';
680
+ index += 3;
681
+ continue;
682
+ }
683
+ if (line.startsWith("'''", index)) {
684
+ state = 'literal';
685
+ index += 3;
686
+ continue;
687
+ }
688
+ if (character === '"') {
689
+ index += 1;
690
+ while (index < line.length) {
691
+ if (line[index] === '"' && !isEscapedAt(line, index)) {
692
+ index += 1;
693
+ break;
694
+ }
695
+ index += 1;
696
+ }
697
+ continue;
698
+ }
699
+ if (character === "'") {
700
+ const end = line.indexOf("'", index + 1);
701
+ index = end < 0 ? line.length : end + 1;
702
+ continue;
703
+ }
704
+ index += 1;
705
+ }
706
+ return state;
707
+ }
708
+
709
+ function isEscapedAt(source, index) {
710
+ let slashCount = 0;
711
+ for (let cursor = index - 1; cursor >= 0 && source[cursor] === '\\'; cursor -= 1) {
712
+ slashCount += 1;
713
+ }
714
+ return slashCount % 2 === 1;
715
+ }
716
+
717
+ function pathStartsWith(value, prefix) {
718
+ return prefix.every((segment, index) => value[index] === segment);
719
+ }
720
+
721
+ function appendTomlBlock(source, block, eol = '\n') {
722
+ const normalizedBlock = String(block || '')
723
+ .trimEnd()
724
+ .replace(/\r?\n/g, eol);
725
+ let prefix = String(source || '');
726
+ if (!prefix) return `${normalizedBlock}${eol}`;
727
+ if (!prefix.endsWith('\n')) prefix += eol;
728
+ if (!prefix.endsWith(`${eol}${eol}`)) prefix += eol;
729
+ return `${prefix}${normalizedBlock}${eol}`;
730
+ }
731
+
732
+ function replaceTomlTable(source, tableName, replacement) {
733
+ return replaceTomlTableTree(source, tableName, replacement);
734
+ }
735
+
736
+ function replaceTomlTableTree(source, tableName, replacement) {
737
+ const removed = removeTomlTableTree(String(source || ''), String(tableName).split('.'));
738
+ return appendTomlBlock(removed.source, replacement, detectEol(source));
739
+ }
740
+
741
+ function withoutJsonServer(config, containerKey) {
742
+ const copy = { ...config };
743
+ if (isPlainObject(copy[containerKey])) {
744
+ const container = { ...copy[containerKey] };
745
+ delete container[JORIPSPACE_SERVER_ID];
746
+ if (Object.keys(container).length) copy[containerKey] = container;
747
+ else delete copy[containerKey];
748
+ }
749
+ return copy;
750
+ }
751
+
752
+ function getJsonPath(value, segments) {
753
+ let current = value;
754
+ for (const segment of segments) {
755
+ if (!isPlainObject(current)) return undefined;
756
+ current = current[segment];
757
+ }
758
+ return current;
759
+ }
760
+
761
+ function withoutJsonPath(value, segments) {
762
+ if (!isPlainObject(value)) return value;
763
+ const [segment, ...remaining] = segments;
764
+ const copy = { ...value };
765
+ if (segment === undefined) return copy;
766
+ if (remaining.length === 0) {
767
+ delete copy[segment];
768
+ return copy;
769
+ }
770
+ if (isPlainObject(copy[segment])) {
771
+ const nested = withoutJsonPath(copy[segment], remaining);
772
+ if (Object.keys(nested).length === 0) delete copy[segment];
773
+ else copy[segment] = nested;
774
+ }
775
+ return copy;
776
+ }
777
+
778
+ function withoutTomlServer(config) {
779
+ const copy = { ...config };
780
+ if (isPlainObject(copy.mcp_servers)) {
781
+ const servers = { ...copy.mcp_servers };
782
+ delete servers[JORIPSPACE_SERVER_ID];
783
+ if (Object.keys(servers).length) copy.mcp_servers = servers;
784
+ else delete copy.mcp_servers;
785
+ }
786
+ return copy;
787
+ }
788
+
789
+ function jsonFormattingOptions(source) {
790
+ const eol = detectEol(source);
791
+ const indentation = /\r?\n([ \t]+)["}]/.exec(source)?.[1] || ' ';
792
+ if (indentation.includes('\t')) return { insertSpaces: false, tabSize: 1, eol };
793
+ return { insertSpaces: true, tabSize: Math.max(1, indentation.length), eol };
794
+ }
795
+
796
+ function detectEol(source) {
797
+ return String(source || '').includes('\r\n') ? '\r\n' : '\n';
798
+ }
799
+
800
+ function writeTextAtomically(filePath, source, options = {}) {
801
+ const directory = path.dirname(filePath);
802
+ fs.mkdirSync(directory, { recursive: true });
803
+ const hasExpected = Object.prototype.hasOwnProperty.call(options, 'expectedSource');
804
+ const expectedSource = hasExpected ? options.expectedSource : readTextIfExists(filePath);
805
+ if (readTextIfExists(filePath) !== expectedSource) throw concurrentConfigError();
806
+
807
+ let mode = 0o600;
808
+ try {
809
+ mode = fs.statSync(filePath).mode & 0o777;
810
+ } catch (error) {
811
+ if (error?.code !== 'ENOENT') throw error;
812
+ }
813
+ const temporaryPath = `${filePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
814
+ let descriptor;
815
+ let temporaryExists = false;
816
+ try {
817
+ descriptor = fs.openSync(temporaryPath, 'wx', mode);
818
+ temporaryExists = true;
819
+ fs.writeFileSync(descriptor, source, 'utf8');
820
+ fs.fsyncSync(descriptor);
821
+ fs.closeSync(descriptor);
822
+ descriptor = undefined;
823
+ try {
824
+ fs.chmodSync(temporaryPath, mode);
825
+ } catch (error) {
826
+ if (process.platform !== 'win32') throw error;
827
+ }
828
+
829
+ if (typeof options.beforeCommit === 'function') options.beforeCommit();
830
+ if (readTextIfExists(filePath) !== expectedSource) throw concurrentConfigError();
831
+ fs.renameSync(temporaryPath, filePath);
832
+ temporaryExists = false;
833
+ fsyncDirectory(directory);
834
+ if (fs.readFileSync(filePath, 'utf8') !== source) {
835
+ throw codedError('MCP_CONFIG_WRITE_VERIFY_FAILED', 'MCP configuration write verification failed');
836
+ }
837
+ } finally {
838
+ if (descriptor !== undefined) {
839
+ try {
840
+ fs.closeSync(descriptor);
841
+ } catch {}
842
+ }
843
+ if (temporaryExists) {
844
+ try {
845
+ fs.rmSync(temporaryPath, { force: true });
846
+ } catch {}
847
+ }
848
+ }
849
+ }
850
+
851
+ function fsyncDirectory(directory) {
852
+ if (process.platform === 'win32') return;
853
+ let descriptor;
854
+ try {
855
+ descriptor = fs.openSync(directory, 'r');
856
+ fs.fsyncSync(descriptor);
857
+ } catch (error) {
858
+ if (!['EINVAL', 'ENOTSUP', 'EISDIR'].includes(error?.code)) throw error;
859
+ } finally {
860
+ if (descriptor !== undefined) fs.closeSync(descriptor);
861
+ }
862
+ }
863
+
864
+ function readTextIfExists(filePath) {
865
+ try {
866
+ return fs.readFileSync(filePath, 'utf8');
867
+ } catch (error) {
868
+ if (error?.code === 'ENOENT') return null;
869
+ throw error;
870
+ }
871
+ }
872
+
873
+ function concurrentConfigError() {
874
+ return codedError('MCP_CONFIG_CONFLICT', 'MCP configuration changed concurrently; it was not overwritten');
875
+ }
876
+
877
+ function codedError(code, message) {
878
+ const error = new Error(message);
879
+ error.code = code;
880
+ return error;
881
+ }
882
+
883
+ function skippedConfig(filePath, error, errorCode) {
884
+ return {
885
+ status: 'skipped',
886
+ registration: 'skipped',
887
+ changed: false,
888
+ path: filePath,
889
+ error,
890
+ error_code: errorCode,
891
+ };
892
+ }
893
+
894
+ function defaultCommandExists(command, env = process.env) {
895
+ const pathValue = String(env.PATH || env.Path || env.path || '');
896
+ if (!pathValue) return false;
897
+ const pathEntries = pathValue
898
+ .split(path.delimiter)
899
+ .map((entry) => entry.trim().replace(/^"|"$/g, ''))
900
+ .filter(Boolean);
901
+ const extensions =
902
+ process.platform === 'win32'
903
+ ? commandHasExtension(command)
904
+ ? ['']
905
+ : String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD')
906
+ .split(';')
907
+ .filter(Boolean)
908
+ : [''];
909
+
910
+ for (const directory of pathEntries) {
911
+ for (const extension of extensions) {
912
+ const candidate = path.join(directory, `${command}${extension}`);
913
+ try {
914
+ const stats = fs.statSync(candidate);
915
+ if (!stats.isFile()) continue;
916
+ if (process.platform === 'win32' || (stats.mode & 0o111) !== 0) return true;
917
+ } catch (error) {
918
+ if (!['ENOENT', 'ENOTDIR', 'EACCES'].includes(error?.code)) throw error;
919
+ }
920
+ }
921
+ }
922
+ return false;
923
+ }
924
+
925
+ function commandHasExtension(command) {
926
+ return path.extname(command) !== '';
927
+ }
928
+
929
+ function normalizeConfigKey(key) {
930
+ return String(key)
931
+ .toLowerCase()
932
+ .replace(/[^a-z0-9_]/g, '')
933
+ .replace(/_/g, '');
934
+ }
935
+
936
+ function toPlainJsonValue(value) {
937
+ if (Array.isArray(value)) return value.map(toPlainJsonValue);
938
+ if (!value || typeof value !== 'object') return value;
939
+ const output = {};
940
+ for (const [key, nested] of Object.entries(value)) {
941
+ Object.defineProperty(output, key, {
942
+ value: toPlainJsonValue(nested),
943
+ enumerable: true,
944
+ configurable: true,
945
+ writable: true,
946
+ });
947
+ }
948
+ return output;
949
+ }
950
+
951
+ function isPlainObject(value) {
952
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
953
+ const prototype = Object.getPrototypeOf(value);
954
+ return prototype === Object.prototype || prototype === null;
955
+ }
956
+
957
+ function isFiniteNonNegativeNumber(value) {
958
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
959
+ }
960
+
961
+ function isStringArray(value) {
962
+ return Array.isArray(value) && value.every((entry) => typeof entry === 'string');
963
+ }
964
+
965
+ function cloneSerializable(value) {
966
+ return value == null ? value : JSON.parse(JSON.stringify(value));
967
+ }
968
+
969
+ module.exports = {
970
+ JORIPSPACE_MCP_URL,
971
+ MCP_AGENT_ADAPTERS,
972
+ configureUserMcpServers,
973
+ defaultCommandExists,
974
+ mergeCodexConfig,
975
+ mergeJsonMcpConfig,
976
+ mergeOpenCodeConfig,
977
+ replaceTomlTable,
978
+ replaceTomlTableTree,
979
+ sanitizeJoripspaceServer,
980
+ writeTextAtomically,
981
+ };