@caveman-ai/cli 4.0.1 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-skills.generated.js +1 -1
- package/dist/agents.generated.js +28 -27
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +302 -10
- package/dist/codemode.js +1402 -0
- package/dist/index.js +1453 -186
- package/dist/learn-tui.js +49 -47
- package/dist/modules/doctor.js +3 -0
- package/dist/provider-routing.js +11 -5
- package/dist/reserved-verbs.generated.js +0 -1
- package/dist/verified-methods.mirror.js +3 -3
- package/package.json +4 -4
package/dist/codemode.js
ADDED
|
@@ -0,0 +1,1402 @@
|
|
|
1
|
+
import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, symlinkSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { basename, join, resolve } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Harnesses that ship their own native code-mode / programmatic tool execution
|
|
5
|
+
* (Claude Code, Codex CLI, OpenCode, and Hermes Agent's built-in `execute_code`).
|
|
6
|
+
* Caveman's QuickJS Code-Mode stays strictly opt-in (`--codemode` / `execute.mcp = codemode`)
|
|
7
|
+
* so it never conflicts with a host's native codemode unless explicitly requested.
|
|
8
|
+
* Note: Hermes's native `execute_code` runs built-in tools only and blocks MCP servers,
|
|
9
|
+
* so `caveman wrap --codemode hermes` brings programmatic execution to Hermes's MCP tools.
|
|
10
|
+
*/
|
|
11
|
+
export const NATIVE_CODEMODE_AGENTS = new Set(["claude", "codex", "opencode", "hermes"]);
|
|
12
|
+
function isValidServer(cfg) {
|
|
13
|
+
if (typeof cfg.command === "string" && cfg.command.trim())
|
|
14
|
+
return true;
|
|
15
|
+
if (typeof cfg.url === "string") {
|
|
16
|
+
const u = cfg.url.trim();
|
|
17
|
+
return u.startsWith("http://") || u.startsWith("https://");
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
function isSelfServer(name, cfg) {
|
|
22
|
+
const lower = name.trim().toLowerCase();
|
|
23
|
+
if (lower === "caveman" ||
|
|
24
|
+
lower === "caveman-codemode" ||
|
|
25
|
+
lower === "caveman-mcp" ||
|
|
26
|
+
lower === "caveman-tools" ||
|
|
27
|
+
lower === "caveman_native" ||
|
|
28
|
+
lower === "caveman-native") {
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
if (cfg.command) {
|
|
32
|
+
const base = basename(cfg.command.trim()).toLowerCase();
|
|
33
|
+
if (base === "caveman-mcp" || base === "caveman-mcp.exe") {
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
if ((base === "caveman" || base === "caveman.exe") && cfg.args?.[0]?.toLowerCase() === "codemode") {
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Parses standard JSON as well as JSONC / relaxed JSON5 configs (UTF-8 BOM,
|
|
44
|
+
* `//` line comments, `/* *\/` block comments, and trailing commas) used by
|
|
45
|
+
* OpenCode, Kilo, OpenClaw, Gemini CLI, and Qwen Code.
|
|
46
|
+
*/
|
|
47
|
+
export function parseJsonRelaxed(rawText) {
|
|
48
|
+
const text = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
49
|
+
let stripped = "";
|
|
50
|
+
let inString = false;
|
|
51
|
+
let escaped = false;
|
|
52
|
+
let i = 0;
|
|
53
|
+
while (i < text.length) {
|
|
54
|
+
const c = text[i];
|
|
55
|
+
const next = text[i + 1];
|
|
56
|
+
if (inString) {
|
|
57
|
+
stripped += c;
|
|
58
|
+
if (escaped) {
|
|
59
|
+
escaped = false;
|
|
60
|
+
}
|
|
61
|
+
else if (c === "\\") {
|
|
62
|
+
escaped = true;
|
|
63
|
+
}
|
|
64
|
+
else if (c === '"') {
|
|
65
|
+
inString = false;
|
|
66
|
+
}
|
|
67
|
+
i++;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (c === '"') {
|
|
71
|
+
inString = true;
|
|
72
|
+
stripped += c;
|
|
73
|
+
i++;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (c === "/" && next === "/") {
|
|
77
|
+
i += 2;
|
|
78
|
+
while (i < text.length && text[i] !== "\n" && text[i] !== "\r")
|
|
79
|
+
i++;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (c === "/" && next === "*") {
|
|
83
|
+
i += 2;
|
|
84
|
+
while (i < text.length && !(text[i] === "*" && text[i + 1] === "/"))
|
|
85
|
+
i++;
|
|
86
|
+
i += 2;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
stripped += c;
|
|
90
|
+
i++;
|
|
91
|
+
}
|
|
92
|
+
// Remove trailing commas before `}` or `]` outside strings.
|
|
93
|
+
let out = "";
|
|
94
|
+
inString = false;
|
|
95
|
+
escaped = false;
|
|
96
|
+
for (let j = 0; j < stripped.length; j++) {
|
|
97
|
+
const c = stripped[j];
|
|
98
|
+
if (inString) {
|
|
99
|
+
out += c;
|
|
100
|
+
if (escaped)
|
|
101
|
+
escaped = false;
|
|
102
|
+
else if (c === "\\")
|
|
103
|
+
escaped = true;
|
|
104
|
+
else if (c === '"')
|
|
105
|
+
inString = false;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (c === '"') {
|
|
109
|
+
inString = true;
|
|
110
|
+
out += c;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (c === ",") {
|
|
114
|
+
let k = j + 1;
|
|
115
|
+
while (k < stripped.length && /\s/.test(stripped[k]))
|
|
116
|
+
k++;
|
|
117
|
+
if (stripped[k] === "}" || stripped[k] === "]") {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
out += c;
|
|
122
|
+
}
|
|
123
|
+
return JSON.parse(out);
|
|
124
|
+
}
|
|
125
|
+
function stringMap(raw) {
|
|
126
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
127
|
+
return undefined;
|
|
128
|
+
const out = {};
|
|
129
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
130
|
+
if (typeof v === "string")
|
|
131
|
+
out[k] = v;
|
|
132
|
+
}
|
|
133
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
134
|
+
}
|
|
135
|
+
function stringList(raw) {
|
|
136
|
+
if (!Array.isArray(raw))
|
|
137
|
+
return undefined;
|
|
138
|
+
const out = raw.filter((item) => typeof item === "string" && item.trim().length > 0);
|
|
139
|
+
return out.length > 0 ? out : undefined;
|
|
140
|
+
}
|
|
141
|
+
function normalizeServerEntry(raw) {
|
|
142
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
143
|
+
return null;
|
|
144
|
+
const obj = raw;
|
|
145
|
+
if (obj.enabled === false)
|
|
146
|
+
return null;
|
|
147
|
+
const out = {};
|
|
148
|
+
if (typeof obj.command === "string" && obj.command.trim()) {
|
|
149
|
+
out.command = obj.command.trim();
|
|
150
|
+
if (Array.isArray(obj.args)) {
|
|
151
|
+
out.args = obj.args.filter((item) => typeof item === "string");
|
|
152
|
+
}
|
|
153
|
+
const env = stringMap(obj.env);
|
|
154
|
+
if (env)
|
|
155
|
+
out.env = env;
|
|
156
|
+
if (typeof obj.cwd === "string" && obj.cwd.trim())
|
|
157
|
+
out.cwd = obj.cwd.trim();
|
|
158
|
+
}
|
|
159
|
+
const urlVal = typeof obj.url === "string" && obj.url.trim()
|
|
160
|
+
? obj.url.trim()
|
|
161
|
+
: typeof obj.httpUrl === "string" && obj.httpUrl.trim()
|
|
162
|
+
? obj.httpUrl.trim()
|
|
163
|
+
: "";
|
|
164
|
+
if (urlVal) {
|
|
165
|
+
out.url = urlVal;
|
|
166
|
+
const headers = stringMap(obj.headers);
|
|
167
|
+
if (headers)
|
|
168
|
+
out.headers = headers;
|
|
169
|
+
}
|
|
170
|
+
const toolsObj = obj.tools && typeof obj.tools === "object" && !Array.isArray(obj.tools)
|
|
171
|
+
? obj.tools
|
|
172
|
+
: undefined;
|
|
173
|
+
const includeTools = stringList(obj.includeTools) ??
|
|
174
|
+
stringList(obj.include_tools) ??
|
|
175
|
+
stringList(obj.enabled_tools) ??
|
|
176
|
+
stringList(toolsObj?.include);
|
|
177
|
+
if (includeTools)
|
|
178
|
+
out.includeTools = includeTools;
|
|
179
|
+
const excludeTools = stringList(obj.excludeTools) ??
|
|
180
|
+
stringList(obj.exclude_tools) ??
|
|
181
|
+
stringList(obj.disabled_tools) ??
|
|
182
|
+
stringList(toolsObj?.exclude);
|
|
183
|
+
if (excludeTools)
|
|
184
|
+
out.excludeTools = excludeTools;
|
|
185
|
+
return isValidServer(out) ? out : null;
|
|
186
|
+
}
|
|
187
|
+
function parseJsonServers(raw) {
|
|
188
|
+
const out = {};
|
|
189
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
190
|
+
return out;
|
|
191
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
192
|
+
const entry = normalizeServerEntry(value);
|
|
193
|
+
if (entry && !isSelfServer(name, entry)) {
|
|
194
|
+
out[name] = entry;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
function parseOpenCodeMcp(raw) {
|
|
200
|
+
const out = {};
|
|
201
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
202
|
+
return out;
|
|
203
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
204
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
205
|
+
continue;
|
|
206
|
+
const obj = value;
|
|
207
|
+
if (obj.enabled === false)
|
|
208
|
+
continue;
|
|
209
|
+
const entry = {};
|
|
210
|
+
if (typeof obj.url === "string" && obj.url.trim()) {
|
|
211
|
+
entry.url = obj.url.trim();
|
|
212
|
+
const headers = stringMap(obj.headers);
|
|
213
|
+
if (headers)
|
|
214
|
+
entry.headers = headers;
|
|
215
|
+
}
|
|
216
|
+
else if (Array.isArray(obj.command) && obj.command.length > 0 && typeof obj.command[0] === "string") {
|
|
217
|
+
entry.command = obj.command[0].trim();
|
|
218
|
+
if (obj.command.length > 1) {
|
|
219
|
+
entry.args = obj.command.slice(1).filter((item) => typeof item === "string");
|
|
220
|
+
}
|
|
221
|
+
const env = stringMap(obj.environment ?? obj.env);
|
|
222
|
+
if (env)
|
|
223
|
+
entry.env = env;
|
|
224
|
+
}
|
|
225
|
+
if (isValidServer(entry) && !isSelfServer(name, entry)) {
|
|
226
|
+
out[name] = entry;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
function stripTomlComment(line) {
|
|
232
|
+
let inSingle = false;
|
|
233
|
+
let inDouble = false;
|
|
234
|
+
let escaped = false;
|
|
235
|
+
for (let i = 0; i < line.length; i++) {
|
|
236
|
+
const c = line[i];
|
|
237
|
+
if (escaped) {
|
|
238
|
+
escaped = false;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (inDouble && c === "\\") {
|
|
242
|
+
escaped = true;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (c === "'" && !inDouble) {
|
|
246
|
+
inSingle = !inSingle;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
if (c === '"' && !inSingle) {
|
|
250
|
+
inDouble = !inDouble;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (c === "#" && !inSingle && !inDouble) {
|
|
254
|
+
return line.slice(0, i);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return line;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* YAML 1.2 comment stripping: `#` starts a comment ONLY outside quotes AND at
|
|
261
|
+
* column 0 or immediately after whitespace (` ` or `\t`). Preserves URL
|
|
262
|
+
* `#fragments` such as `https://example.com/mcp#v2`.
|
|
263
|
+
*/
|
|
264
|
+
function stripYamlComment(line) {
|
|
265
|
+
let inSingle = false;
|
|
266
|
+
let inDouble = false;
|
|
267
|
+
let escaped = false;
|
|
268
|
+
for (let i = 0; i < line.length; i++) {
|
|
269
|
+
const c = line[i];
|
|
270
|
+
if (escaped) {
|
|
271
|
+
escaped = false;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (inDouble && c === "\\") {
|
|
275
|
+
escaped = true;
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (c === "'" && !inDouble) {
|
|
279
|
+
inSingle = !inSingle;
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (c === '"' && !inSingle) {
|
|
283
|
+
inDouble = !inDouble;
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
if (c === "#" && !inSingle && !inDouble) {
|
|
287
|
+
if (i === 0 || line[i - 1] === " " || line[i - 1] === "\t") {
|
|
288
|
+
return line.slice(0, i);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return line;
|
|
293
|
+
}
|
|
294
|
+
function unquoteKey(raw) {
|
|
295
|
+
const s = raw.trim();
|
|
296
|
+
if (s.length >= 2 && ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'")))) {
|
|
297
|
+
return s.slice(1, -1);
|
|
298
|
+
}
|
|
299
|
+
return s;
|
|
300
|
+
}
|
|
301
|
+
function parseTomlString(raw) {
|
|
302
|
+
const s = raw.trim();
|
|
303
|
+
if (s.length < 2)
|
|
304
|
+
return null;
|
|
305
|
+
if (s.startsWith('"') && s.endsWith('"')) {
|
|
306
|
+
try {
|
|
307
|
+
const parsed = JSON.parse(s);
|
|
308
|
+
return typeof parsed === "string" ? parsed : null;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (s.startsWith("'") && s.endsWith("'")) {
|
|
315
|
+
return s.slice(1, -1);
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
function splitList(raw) {
|
|
320
|
+
const parts = [];
|
|
321
|
+
let start = 0;
|
|
322
|
+
let inSingle = false;
|
|
323
|
+
let inDouble = false;
|
|
324
|
+
let escaped = false;
|
|
325
|
+
for (let i = 0; i < raw.length; i++) {
|
|
326
|
+
const c = raw[i];
|
|
327
|
+
if (escaped) {
|
|
328
|
+
escaped = false;
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (inDouble && c === "\\") {
|
|
332
|
+
escaped = true;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (c === "'" && !inDouble)
|
|
336
|
+
inSingle = !inSingle;
|
|
337
|
+
else if (c === '"' && !inSingle)
|
|
338
|
+
inDouble = !inDouble;
|
|
339
|
+
else if (c === "," && !inSingle && !inDouble) {
|
|
340
|
+
const p = raw.slice(start, i).trim();
|
|
341
|
+
if (p)
|
|
342
|
+
parts.push(p);
|
|
343
|
+
start = i + 1;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const tail = raw.slice(start).trim();
|
|
347
|
+
if (tail)
|
|
348
|
+
parts.push(tail);
|
|
349
|
+
return parts;
|
|
350
|
+
}
|
|
351
|
+
function splitTomlHeader(header) {
|
|
352
|
+
const parts = [];
|
|
353
|
+
let start = 0;
|
|
354
|
+
let inSingle = false;
|
|
355
|
+
let inDouble = false;
|
|
356
|
+
let escaped = false;
|
|
357
|
+
for (let i = 0; i < header.length; i++) {
|
|
358
|
+
const c = header[i];
|
|
359
|
+
if (escaped) {
|
|
360
|
+
escaped = false;
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (inDouble && c === "\\") {
|
|
364
|
+
escaped = true;
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (c === "'" && !inDouble)
|
|
368
|
+
inSingle = !inSingle;
|
|
369
|
+
else if (c === '"' && !inSingle)
|
|
370
|
+
inDouble = !inDouble;
|
|
371
|
+
else if (c === "." && !inSingle && !inDouble) {
|
|
372
|
+
parts.push(unquoteKey(header.slice(start, i)));
|
|
373
|
+
start = i + 1;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
parts.push(unquoteKey(header.slice(start)));
|
|
377
|
+
return parts;
|
|
378
|
+
}
|
|
379
|
+
function parseYamlFlowMap(val) {
|
|
380
|
+
const s = val.trim();
|
|
381
|
+
if (!s.startsWith("{") || !s.endsWith("}"))
|
|
382
|
+
return undefined;
|
|
383
|
+
const inner = s.slice(1, -1).trim();
|
|
384
|
+
if (!inner)
|
|
385
|
+
return undefined;
|
|
386
|
+
const out = {};
|
|
387
|
+
for (const item of splitList(inner)) {
|
|
388
|
+
const colon = item.indexOf(":");
|
|
389
|
+
if (colon <= 0)
|
|
390
|
+
continue;
|
|
391
|
+
const k = unquoteKey(item.slice(0, colon));
|
|
392
|
+
const v = unquoteKey(item.slice(colon + 1));
|
|
393
|
+
if (k)
|
|
394
|
+
out[k] = v;
|
|
395
|
+
}
|
|
396
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
397
|
+
}
|
|
398
|
+
export function parseCodexMcpServersToml(toml) {
|
|
399
|
+
const raw = {};
|
|
400
|
+
const disabled = new Set();
|
|
401
|
+
let current = "";
|
|
402
|
+
let subSection = "";
|
|
403
|
+
let pendingArrayKey = "";
|
|
404
|
+
let pendingArrayBuf = "";
|
|
405
|
+
const applyArray = (cfg, key, rawVal) => {
|
|
406
|
+
const inner = rawVal.slice(1, -1).trim();
|
|
407
|
+
const items = inner
|
|
408
|
+
? splitList(inner).map(parseTomlString).filter((item) => item !== null)
|
|
409
|
+
: [];
|
|
410
|
+
if (key === "args") {
|
|
411
|
+
cfg.args = items;
|
|
412
|
+
}
|
|
413
|
+
else if (key === "env_vars") {
|
|
414
|
+
for (const v of items) {
|
|
415
|
+
if (v)
|
|
416
|
+
cfg.env = { ...(cfg.env ?? {}), [v]: `\${${v}}` };
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
else if (key === "enabled_tools" && items.length > 0) {
|
|
420
|
+
cfg.includeTools = items;
|
|
421
|
+
}
|
|
422
|
+
else if (key === "disabled_tools" && items.length > 0) {
|
|
423
|
+
cfg.excludeTools = items;
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
for (const rawLine of toml.split(/\r?\n/)) {
|
|
427
|
+
const line = stripTomlComment(rawLine).trim();
|
|
428
|
+
if (!line)
|
|
429
|
+
continue;
|
|
430
|
+
if (pendingArrayKey) {
|
|
431
|
+
pendingArrayBuf += " " + line;
|
|
432
|
+
if (line.endsWith("]")) {
|
|
433
|
+
if (current) {
|
|
434
|
+
const cfg = (raw[current] ??= {});
|
|
435
|
+
applyArray(cfg, pendingArrayKey, pendingArrayBuf.trim());
|
|
436
|
+
}
|
|
437
|
+
pendingArrayKey = "";
|
|
438
|
+
pendingArrayBuf = "";
|
|
439
|
+
}
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (line.startsWith("[") && line.endsWith("]")) {
|
|
443
|
+
const header = line.slice(1, -1).trim();
|
|
444
|
+
current = "";
|
|
445
|
+
subSection = "";
|
|
446
|
+
const parts = splitTomlHeader(header);
|
|
447
|
+
if (parts[0] === "mcp_servers") {
|
|
448
|
+
if (parts.length === 2 && parts[1]) {
|
|
449
|
+
current = parts[1];
|
|
450
|
+
}
|
|
451
|
+
else if (parts.length === 3 && parts[1]) {
|
|
452
|
+
if (parts[2] === "env") {
|
|
453
|
+
current = parts[1];
|
|
454
|
+
subSection = "env";
|
|
455
|
+
}
|
|
456
|
+
else if (parts[2] === "headers" || parts[2] === "http_headers") {
|
|
457
|
+
current = parts[1];
|
|
458
|
+
subSection = "headers";
|
|
459
|
+
}
|
|
460
|
+
else if (parts[2] === "env_http_headers") {
|
|
461
|
+
current = parts[1];
|
|
462
|
+
subSection = "env_headers";
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
if (!current)
|
|
469
|
+
continue;
|
|
470
|
+
const eq = line.indexOf("=");
|
|
471
|
+
if (eq <= 0)
|
|
472
|
+
continue;
|
|
473
|
+
const key = unquoteKey(line.slice(0, eq));
|
|
474
|
+
const val = line.slice(eq + 1).trim();
|
|
475
|
+
const cfg = (raw[current] ??= {});
|
|
476
|
+
if (subSection === "env") {
|
|
477
|
+
const s = parseTomlString(val);
|
|
478
|
+
if (s !== null)
|
|
479
|
+
cfg.env = { ...(cfg.env ?? {}), [key]: s };
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
if (subSection === "headers") {
|
|
483
|
+
const s = parseTomlString(val);
|
|
484
|
+
if (s !== null)
|
|
485
|
+
cfg.headers = { ...(cfg.headers ?? {}), [key]: s };
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
if (subSection === "env_headers") {
|
|
489
|
+
const s = parseTomlString(val);
|
|
490
|
+
if (s !== null && s)
|
|
491
|
+
cfg.headers = { ...(cfg.headers ?? {}), [key]: `\${${s}}` };
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
if (key === "enabled" && val === "false") {
|
|
495
|
+
disabled.add(current);
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (key === "command") {
|
|
499
|
+
const s = parseTomlString(val);
|
|
500
|
+
if (s !== null)
|
|
501
|
+
cfg.command = s;
|
|
502
|
+
}
|
|
503
|
+
else if (key === "url") {
|
|
504
|
+
const s = parseTomlString(val);
|
|
505
|
+
if (s !== null)
|
|
506
|
+
cfg.url = s;
|
|
507
|
+
}
|
|
508
|
+
else if (key === "cwd") {
|
|
509
|
+
const s = parseTomlString(val);
|
|
510
|
+
if (s !== null)
|
|
511
|
+
cfg.cwd = s;
|
|
512
|
+
}
|
|
513
|
+
else if (key === "bearer_token_env_var") {
|
|
514
|
+
const s = parseTomlString(val);
|
|
515
|
+
if (s !== null && s) {
|
|
516
|
+
cfg.headers = { ...(cfg.headers ?? {}), Authorization: `Bearer \${${s}}` };
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
else if (key === "args" || key === "env_vars" || key === "enabled_tools" || key === "disabled_tools") {
|
|
520
|
+
if (val.startsWith("[") && val.endsWith("]")) {
|
|
521
|
+
applyArray(cfg, key, val);
|
|
522
|
+
}
|
|
523
|
+
else if (val.startsWith("[")) {
|
|
524
|
+
pendingArrayKey = key;
|
|
525
|
+
pendingArrayBuf = val;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
else if ((key === "env" || key === "headers" || key === "http_headers" || key === "env_http_headers") &&
|
|
529
|
+
val.startsWith("{") &&
|
|
530
|
+
val.endsWith("}")) {
|
|
531
|
+
const inner = val.slice(1, -1).trim();
|
|
532
|
+
if (inner) {
|
|
533
|
+
const map = {};
|
|
534
|
+
for (const item of splitList(inner)) {
|
|
535
|
+
const itemEq = item.indexOf("=");
|
|
536
|
+
if (itemEq <= 0)
|
|
537
|
+
continue;
|
|
538
|
+
const k = unquoteKey(item.slice(0, itemEq));
|
|
539
|
+
const v = parseTomlString(item.slice(itemEq + 1));
|
|
540
|
+
if (v !== null)
|
|
541
|
+
map[k] = key === "env_http_headers" ? `\${${v}}` : v;
|
|
542
|
+
}
|
|
543
|
+
if (key === "env")
|
|
544
|
+
cfg.env = { ...(cfg.env ?? {}), ...map };
|
|
545
|
+
else
|
|
546
|
+
cfg.headers = { ...(cfg.headers ?? {}), ...map };
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const out = {};
|
|
551
|
+
for (const [name, cfg] of Object.entries(raw)) {
|
|
552
|
+
if (disabled.has(name))
|
|
553
|
+
continue;
|
|
554
|
+
const normalized = normalizeServerEntry(cfg);
|
|
555
|
+
if (normalized && !isSelfServer(name, normalized)) {
|
|
556
|
+
out[name] = normalized;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return out;
|
|
560
|
+
}
|
|
561
|
+
export function parseHermesMcpServersYaml(yaml) {
|
|
562
|
+
const raw = {};
|
|
563
|
+
const disabled = new Set();
|
|
564
|
+
let inSection = false;
|
|
565
|
+
let current = "";
|
|
566
|
+
let serverIndent = -1;
|
|
567
|
+
let propIndent = -1;
|
|
568
|
+
let toolsIndent = -1;
|
|
569
|
+
let mode = "";
|
|
570
|
+
let modeIndent = -1;
|
|
571
|
+
for (const rawLine of yaml.split(/\r?\n/)) {
|
|
572
|
+
const trimmed = stripYamlComment(rawLine).trim();
|
|
573
|
+
if (!trimmed)
|
|
574
|
+
continue;
|
|
575
|
+
const indent = rawLine.length - rawLine.trimStart().length;
|
|
576
|
+
if (indent === 0) {
|
|
577
|
+
if (trimmed === "..." || trimmed === "---") {
|
|
578
|
+
inSection = false;
|
|
579
|
+
current = "";
|
|
580
|
+
serverIndent = -1;
|
|
581
|
+
propIndent = -1;
|
|
582
|
+
toolsIndent = -1;
|
|
583
|
+
mode = "";
|
|
584
|
+
modeIndent = -1;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
const colon = trimmed.indexOf(":");
|
|
588
|
+
const topKey = colon > 0 ? unquoteKey(trimmed.slice(0, colon)) : "";
|
|
589
|
+
const topRest = colon > 0 ? trimmed.slice(colon + 1).trim() : "";
|
|
590
|
+
inSection = topKey === "mcp_servers" && topRest === "";
|
|
591
|
+
current = "";
|
|
592
|
+
serverIndent = -1;
|
|
593
|
+
propIndent = -1;
|
|
594
|
+
toolsIndent = -1;
|
|
595
|
+
mode = "";
|
|
596
|
+
modeIndent = -1;
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
if (!inSection)
|
|
600
|
+
continue;
|
|
601
|
+
if ((serverIndent < 0 || indent === serverIndent) && trimmed.endsWith(":") && !trimmed.startsWith("-")) {
|
|
602
|
+
current = unquoteKey(trimmed.slice(0, -1));
|
|
603
|
+
serverIndent = indent;
|
|
604
|
+
propIndent = -1;
|
|
605
|
+
toolsIndent = -1;
|
|
606
|
+
mode = "";
|
|
607
|
+
modeIndent = -1;
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
if (!current || indent <= serverIndent)
|
|
611
|
+
continue;
|
|
612
|
+
const cfg = (raw[current] ??= {});
|
|
613
|
+
// Exit nested block modes when indentation dedents back to or above the key that opened the mode.
|
|
614
|
+
if (toolsIndent >= 0 && indent <= toolsIndent) {
|
|
615
|
+
toolsIndent = -1;
|
|
616
|
+
}
|
|
617
|
+
if (mode && modeIndent >= 0 && indent <= modeIndent) {
|
|
618
|
+
if ((mode === "tools_include" || mode === "tools_exclude") && toolsIndent >= 0 && indent > toolsIndent) {
|
|
619
|
+
mode = "tools";
|
|
620
|
+
modeIndent = toolsIndent;
|
|
621
|
+
}
|
|
622
|
+
else if (!(mode === "args" && trimmed.startsWith("- "))) {
|
|
623
|
+
mode = "";
|
|
624
|
+
modeIndent = -1;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
if (mode === "args" && trimmed.startsWith("- ")) {
|
|
628
|
+
cfg.args = [...(cfg.args ?? []), unquoteKey(trimmed.slice(2).trim())];
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
if (mode === "tools_include" && trimmed.startsWith("- ")) {
|
|
632
|
+
cfg.includeTools = [...(cfg.includeTools ?? []), unquoteKey(trimmed.slice(2).trim())];
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
if (mode === "tools_exclude" && trimmed.startsWith("- ")) {
|
|
636
|
+
cfg.excludeTools = [...(cfg.excludeTools ?? []), unquoteKey(trimmed.slice(2).trim())];
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
const colon = trimmed.indexOf(":");
|
|
640
|
+
if (colon <= 0)
|
|
641
|
+
continue;
|
|
642
|
+
const key = unquoteKey(trimmed.slice(0, colon));
|
|
643
|
+
const val = trimmed.slice(colon + 1).trim();
|
|
644
|
+
if (mode === "env" && indent > modeIndent) {
|
|
645
|
+
cfg.env = { ...(cfg.env ?? {}), [key]: unquoteKey(val) };
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
if (mode === "headers" && indent > modeIndent) {
|
|
649
|
+
cfg.headers = { ...(cfg.headers ?? {}), [key]: unquoteKey(val) };
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
if ((mode === "tools" || mode === "tools_include" || mode === "tools_exclude") && indent > modeIndent) {
|
|
653
|
+
if (key === "include") {
|
|
654
|
+
if (!val) {
|
|
655
|
+
mode = "tools_include";
|
|
656
|
+
modeIndent = indent;
|
|
657
|
+
}
|
|
658
|
+
else if (val.startsWith("[") && val.endsWith("]")) {
|
|
659
|
+
const inner = val.slice(1, -1).trim();
|
|
660
|
+
cfg.includeTools = inner ? splitList(inner).map(unquoteKey) : [];
|
|
661
|
+
}
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
if (key === "exclude") {
|
|
665
|
+
if (!val) {
|
|
666
|
+
mode = "tools_exclude";
|
|
667
|
+
modeIndent = indent;
|
|
668
|
+
}
|
|
669
|
+
else if (val.startsWith("[") && val.endsWith("]")) {
|
|
670
|
+
const inner = val.slice(1, -1).trim();
|
|
671
|
+
cfg.excludeTools = inner ? splitList(inner).map(unquoteKey) : [];
|
|
672
|
+
}
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
if (propIndent < 0)
|
|
677
|
+
propIndent = indent;
|
|
678
|
+
if (indent > propIndent)
|
|
679
|
+
continue;
|
|
680
|
+
mode = "";
|
|
681
|
+
modeIndent = -1;
|
|
682
|
+
if (key === "enabled" && val.toLowerCase() === "false") {
|
|
683
|
+
disabled.add(current);
|
|
684
|
+
}
|
|
685
|
+
else if (key === "command") {
|
|
686
|
+
cfg.command = unquoteKey(val);
|
|
687
|
+
}
|
|
688
|
+
else if (key === "url") {
|
|
689
|
+
cfg.url = unquoteKey(val);
|
|
690
|
+
}
|
|
691
|
+
else if (key === "cwd") {
|
|
692
|
+
cfg.cwd = unquoteKey(val);
|
|
693
|
+
}
|
|
694
|
+
else if (key === "args") {
|
|
695
|
+
if (!val) {
|
|
696
|
+
mode = "args";
|
|
697
|
+
modeIndent = indent;
|
|
698
|
+
}
|
|
699
|
+
else if (val.startsWith("[") && val.endsWith("]")) {
|
|
700
|
+
const inner = val.slice(1, -1).trim();
|
|
701
|
+
cfg.args = inner ? splitList(inner).map(unquoteKey) : [];
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
else if (key === "env") {
|
|
705
|
+
const inline = parseYamlFlowMap(val);
|
|
706
|
+
if (inline)
|
|
707
|
+
cfg.env = { ...(cfg.env ?? {}), ...inline };
|
|
708
|
+
else if (!val) {
|
|
709
|
+
mode = "env";
|
|
710
|
+
modeIndent = indent;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
else if (key === "headers") {
|
|
714
|
+
const inline = parseYamlFlowMap(val);
|
|
715
|
+
if (inline)
|
|
716
|
+
cfg.headers = { ...(cfg.headers ?? {}), ...inline };
|
|
717
|
+
else if (!val) {
|
|
718
|
+
mode = "headers";
|
|
719
|
+
modeIndent = indent;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
else if (key === "tools") {
|
|
723
|
+
if (!val) {
|
|
724
|
+
mode = "tools";
|
|
725
|
+
modeIndent = indent;
|
|
726
|
+
toolsIndent = indent;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
const out = {};
|
|
731
|
+
for (const [name, cfg] of Object.entries(raw)) {
|
|
732
|
+
if (disabled.has(name))
|
|
733
|
+
continue;
|
|
734
|
+
const normalized = normalizeServerEntry(cfg);
|
|
735
|
+
if (normalized && !isSelfServer(name, normalized))
|
|
736
|
+
out[name] = normalized;
|
|
737
|
+
}
|
|
738
|
+
return out;
|
|
739
|
+
}
|
|
740
|
+
function expandHomeOverride(raw, homeDir, env) {
|
|
741
|
+
const trimmed = raw?.trim();
|
|
742
|
+
if (!trimmed)
|
|
743
|
+
return null;
|
|
744
|
+
let expanded = trimmed.replace(/\$(\w+)|\$\{([^{}$]*)\}/g, (whole, bare, braced) => env[bare ?? braced] ?? whole);
|
|
745
|
+
if (process.platform === "win32") {
|
|
746
|
+
expanded = expanded.replace(/%([^%]+)%/g, (whole, name) => env[name] ?? whole);
|
|
747
|
+
}
|
|
748
|
+
if (homeDir) {
|
|
749
|
+
expanded = expanded.replace(/^~(?=$|[\\/])/, homeDir);
|
|
750
|
+
}
|
|
751
|
+
return resolve(expanded);
|
|
752
|
+
}
|
|
753
|
+
function openCodeConfigPaths(workspaceDir, homeDir, env, trustWorkspace = false) {
|
|
754
|
+
const paths = [];
|
|
755
|
+
if (homeDir) {
|
|
756
|
+
const configDir = expandHomeOverride(env.OPENCODE_CONFIG_DIR, homeDir, env)
|
|
757
|
+
?? join(expandHomeOverride(env.XDG_CONFIG_HOME, homeDir, env) ?? join(homeDir, ".config"), "opencode");
|
|
758
|
+
paths.push(join(configDir, "opencode.json"), join(configDir, "opencode.jsonc"));
|
|
759
|
+
}
|
|
760
|
+
const explicit = expandHomeOverride(env.OPENCODE_CONFIG, homeDir, env);
|
|
761
|
+
if (explicit)
|
|
762
|
+
paths.push(explicit);
|
|
763
|
+
if (trustWorkspace && workspaceDir) {
|
|
764
|
+
paths.push(join(workspaceDir, "opencode.json"), join(workspaceDir, "opencode.jsonc"));
|
|
765
|
+
}
|
|
766
|
+
return paths;
|
|
767
|
+
}
|
|
768
|
+
function kiloConfigPaths(workspaceDir, homeDir, env, trustWorkspace = false) {
|
|
769
|
+
const paths = [];
|
|
770
|
+
if (homeDir) {
|
|
771
|
+
const configDir = expandHomeOverride(env.KILO_CONFIG_DIR, homeDir, env)
|
|
772
|
+
?? join(expandHomeOverride(env.XDG_CONFIG_HOME, homeDir, env) ?? join(homeDir, ".config"), "kilo");
|
|
773
|
+
paths.push(join(configDir, "kilo.json"), join(configDir, "kilo.jsonc"));
|
|
774
|
+
}
|
|
775
|
+
const explicit = expandHomeOverride(env.KILO_CONFIG, homeDir, env);
|
|
776
|
+
if (explicit)
|
|
777
|
+
paths.push(explicit);
|
|
778
|
+
if (trustWorkspace && workspaceDir) {
|
|
779
|
+
paths.push(join(workspaceDir, "kilo.json"), join(workspaceDir, "kilo.jsonc"));
|
|
780
|
+
}
|
|
781
|
+
return paths;
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Returns only the external MCP server names configured in OpenCode's own
|
|
785
|
+
* config files. Used by `applyOpenCodeCodemodeOverlay` so we never inject
|
|
786
|
+
* `{ enabled: false }` entries for foreign (Claude/Cursor/Codex) servers,
|
|
787
|
+
* which would fail OpenCode's Zod discriminated-union config schema validation.
|
|
788
|
+
*/
|
|
789
|
+
export function discoverOpenCodeOwnServerNames(workspaceDir, homeDir, env = process.env, trustWorkspace = false) {
|
|
790
|
+
const names = new Set();
|
|
791
|
+
for (const p of openCodeConfigPaths(workspaceDir, homeDir, env, trustWorkspace)) {
|
|
792
|
+
try {
|
|
793
|
+
const doc = parseJsonRelaxed(readFileSync(p, "utf8"));
|
|
794
|
+
for (const name of Object.keys(parseOpenCodeMcp(doc?.mcp))) {
|
|
795
|
+
names.add(name);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
catch { /* absent or unreadable */ }
|
|
799
|
+
}
|
|
800
|
+
return [...names];
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Returns only the external MCP server names configured in Kilo's own config
|
|
804
|
+
* files so `applyKiloCodemodeOverlay` disables only Kilo-owned servers.
|
|
805
|
+
*/
|
|
806
|
+
export function discoverKiloOwnServerNames(workspaceDir, homeDir, env = process.env, trustWorkspace = false) {
|
|
807
|
+
const names = new Set();
|
|
808
|
+
for (const p of kiloConfigPaths(workspaceDir, homeDir, env, trustWorkspace)) {
|
|
809
|
+
try {
|
|
810
|
+
const doc = parseJsonRelaxed(readFileSync(p, "utf8"));
|
|
811
|
+
for (const name of Object.keys(parseOpenCodeMcp(doc?.mcp))) {
|
|
812
|
+
names.add(name);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
catch { /* absent or unreadable */ }
|
|
816
|
+
}
|
|
817
|
+
return [...names];
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Discovers user MCP servers across all major coding agents (Cursor, OpenClaw,
|
|
821
|
+
* Hermes, OpenCode, Kilo, Gemini CLI, Qwen Code, Codex, and Claude Code),
|
|
822
|
+
* supporting both stdio commands and remote Streamable HTTP URLs while
|
|
823
|
+
* excluding disabled and self-referential Caveman servers.
|
|
824
|
+
*
|
|
825
|
+
* Workspace-local executable configs (`.mcp.json`, `.codex/config.toml`,
|
|
826
|
+
* `.gemini/settings.json`, `.qwen/settings.json`, `opencode.json*`, `kilo.json*`)
|
|
827
|
+
* are SKIPPED by default (`trustWorkspace = false`) so untrusted checkouts
|
|
828
|
+
* cannot execute arbitrary commands on `caveman wrap --codemode`. Pass
|
|
829
|
+
* `trustWorkspace = true` (via `--trust-workspace-mcp` or
|
|
830
|
+
* `CAVEMAN_TRUST_WORKSPACE_MCP=1`) to explicitly opt in for trusted repos.
|
|
831
|
+
*/
|
|
832
|
+
export function discoverCodemodeServers(workspaceDir, homeDir, env = process.env, trustWorkspace = false) {
|
|
833
|
+
const merged = {};
|
|
834
|
+
const merge = (src) => {
|
|
835
|
+
for (const [name, cfg] of Object.entries(src)) {
|
|
836
|
+
if (isValidServer(cfg) && !isSelfServer(name, cfg))
|
|
837
|
+
merged[name] = cfg;
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
if (homeDir) {
|
|
841
|
+
try {
|
|
842
|
+
const cursorDoc = parseJsonRelaxed(readFileSync(join(homeDir, ".cursor", "mcp.json"), "utf8"));
|
|
843
|
+
merge(parseJsonServers(cursorDoc?.servers));
|
|
844
|
+
merge(parseJsonServers(cursorDoc?.mcpServers));
|
|
845
|
+
}
|
|
846
|
+
catch { /* absent */ }
|
|
847
|
+
const openclawPath = expandHomeOverride(env.OPENCLAW_CONFIG_PATH, homeDir, env)
|
|
848
|
+
?? join(expandHomeOverride(env.OPENCLAW_STATE_DIR, homeDir, env) ?? join(homeDir, ".openclaw"), "openclaw.json");
|
|
849
|
+
try {
|
|
850
|
+
const openclawDoc = parseJsonRelaxed(readFileSync(openclawPath, "utf8"));
|
|
851
|
+
merge(parseJsonServers(openclawDoc?.mcp?.servers));
|
|
852
|
+
}
|
|
853
|
+
catch { /* absent */ }
|
|
854
|
+
const hermesDir = expandHomeOverride(env.HERMES_HOME, homeDir, env)
|
|
855
|
+
?? (process.platform === "win32"
|
|
856
|
+
? join(env.LOCALAPPDATA?.trim() || join(homeDir, "AppData", "Local"), "hermes")
|
|
857
|
+
: join(homeDir, ".hermes"));
|
|
858
|
+
try {
|
|
859
|
+
const hermesYaml = readFileSync(join(hermesDir, "config.yaml"), "utf8");
|
|
860
|
+
merge(parseHermesMcpServersYaml(hermesYaml));
|
|
861
|
+
}
|
|
862
|
+
catch { /* absent */ }
|
|
863
|
+
for (const p of openCodeConfigPaths(workspaceDir, homeDir, env, trustWorkspace)) {
|
|
864
|
+
try {
|
|
865
|
+
const opencodeDoc = parseJsonRelaxed(readFileSync(p, "utf8"));
|
|
866
|
+
merge(parseOpenCodeMcp(opencodeDoc?.mcp));
|
|
867
|
+
}
|
|
868
|
+
catch { /* absent */ }
|
|
869
|
+
}
|
|
870
|
+
for (const p of kiloConfigPaths(workspaceDir, homeDir, env, trustWorkspace)) {
|
|
871
|
+
try {
|
|
872
|
+
const kiloDoc = parseJsonRelaxed(readFileSync(p, "utf8"));
|
|
873
|
+
merge(parseOpenCodeMcp(kiloDoc?.mcp));
|
|
874
|
+
}
|
|
875
|
+
catch { /* absent */ }
|
|
876
|
+
}
|
|
877
|
+
const geminiHome = expandHomeOverride(env.GEMINI_CLI_HOME, homeDir, env) ?? homeDir;
|
|
878
|
+
try {
|
|
879
|
+
const geminiDoc = parseJsonRelaxed(readFileSync(join(geminiHome, ".gemini", "settings.json"), "utf8"));
|
|
880
|
+
merge(parseJsonServers(geminiDoc?.mcpServers));
|
|
881
|
+
}
|
|
882
|
+
catch { /* absent */ }
|
|
883
|
+
try {
|
|
884
|
+
const qwenDoc = parseJsonRelaxed(readFileSync(join(homeDir, ".qwen", "settings.json"), "utf8"));
|
|
885
|
+
merge(parseJsonServers(qwenDoc?.mcpServers));
|
|
886
|
+
}
|
|
887
|
+
catch { /* absent */ }
|
|
888
|
+
const codexDir = expandHomeOverride(env.CODEX_HOME, homeDir, env) ?? join(homeDir, ".codex");
|
|
889
|
+
try {
|
|
890
|
+
const codexToml = readFileSync(join(codexDir, "config.toml"), "utf8");
|
|
891
|
+
merge(parseCodexMcpServersToml(codexToml));
|
|
892
|
+
}
|
|
893
|
+
catch { /* absent */ }
|
|
894
|
+
const claudePaths = [join(homeDir, ".claude.json")];
|
|
895
|
+
const claudeDir = expandHomeOverride(env.CLAUDE_CONFIG_DIR, homeDir, env);
|
|
896
|
+
if (claudeDir)
|
|
897
|
+
claudePaths.push(join(claudeDir, ".claude.json"));
|
|
898
|
+
for (const claudePath of claudePaths) {
|
|
899
|
+
try {
|
|
900
|
+
const claudeDoc = parseJsonRelaxed(readFileSync(claudePath, "utf8"));
|
|
901
|
+
merge(parseJsonServers(claudeDoc?.mcpServers));
|
|
902
|
+
if (workspaceDir && claudeDoc?.projects && typeof claudeDoc.projects === "object") {
|
|
903
|
+
const cleanWs = resolve(workspaceDir);
|
|
904
|
+
for (const [projPath, proj] of Object.entries(claudeDoc.projects)) {
|
|
905
|
+
if (resolve(projPath) === cleanWs)
|
|
906
|
+
merge(parseJsonServers(proj?.mcpServers));
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
catch { /* absent */ }
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
if (trustWorkspace && workspaceDir) {
|
|
914
|
+
try {
|
|
915
|
+
const projCodex = readFileSync(join(workspaceDir, ".codex", "config.toml"), "utf8");
|
|
916
|
+
merge(parseCodexMcpServersToml(projCodex));
|
|
917
|
+
}
|
|
918
|
+
catch { /* absent */ }
|
|
919
|
+
try {
|
|
920
|
+
const projGemini = parseJsonRelaxed(readFileSync(join(workspaceDir, ".gemini", "settings.json"), "utf8"));
|
|
921
|
+
merge(parseJsonServers(projGemini?.mcpServers));
|
|
922
|
+
}
|
|
923
|
+
catch { /* absent */ }
|
|
924
|
+
try {
|
|
925
|
+
const projQwen = parseJsonRelaxed(readFileSync(join(workspaceDir, ".qwen", "settings.json"), "utf8"));
|
|
926
|
+
merge(parseJsonServers(projQwen?.mcpServers));
|
|
927
|
+
}
|
|
928
|
+
catch { /* absent */ }
|
|
929
|
+
try {
|
|
930
|
+
const projectDoc = parseJsonRelaxed(readFileSync(join(workspaceDir, ".mcp.json"), "utf8"));
|
|
931
|
+
merge(parseJsonServers(projectDoc?.servers));
|
|
932
|
+
merge(parseJsonServers(projectDoc?.mcpServers));
|
|
933
|
+
}
|
|
934
|
+
catch { /* absent */ }
|
|
935
|
+
}
|
|
936
|
+
return merged;
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Writes an ephemeral `codemode-servers.json` file (0600) in `dir` and returns
|
|
940
|
+
* its path. Used inside ephemeral wrap packs so cleanup happens on exit.
|
|
941
|
+
*/
|
|
942
|
+
export function writeEphemeralCodemodeConfig(dir, servers) {
|
|
943
|
+
const path = join(dir, "codemode-servers.json");
|
|
944
|
+
writeFileSync(path, JSON.stringify({ mcpServers: servers }, null, 2) + "\n", { mode: 0o600 });
|
|
945
|
+
return path;
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* Strips `[mcp_servers.*]` tables from an ephemeral Codex `config.toml` when
|
|
949
|
+
* `--codemode` bridges those servers behind `caveman-codemode`, preventing
|
|
950
|
+
* Codex from loading 50+ downstream schemas twice.
|
|
951
|
+
*/
|
|
952
|
+
export function stripExternalCodexMcpTables(toml) {
|
|
953
|
+
const out = [];
|
|
954
|
+
let skipping = false;
|
|
955
|
+
for (const line of toml.split(/\r?\n/)) {
|
|
956
|
+
const trimmed = stripTomlComment(line).trim();
|
|
957
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
958
|
+
const header = trimmed.slice(1, -1).trim();
|
|
959
|
+
const parts = splitTomlHeader(header);
|
|
960
|
+
skipping = parts[0] === "mcp_servers";
|
|
961
|
+
}
|
|
962
|
+
if (!skipping)
|
|
963
|
+
out.push(line);
|
|
964
|
+
}
|
|
965
|
+
return out.join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Builds an ephemeral Gemini CLI system settings file for
|
|
969
|
+
* `GEMINI_CLI_SYSTEM_SETTINGS_PATH`. Preserves any existing system settings
|
|
970
|
+
* (when `baseSystemSettingsPath` is non-empty), registers `caveman-codemode`,
|
|
971
|
+
* and sets `mcp.allowed = ["caveman-codemode"]` so Gemini's additive settings
|
|
972
|
+
* merge does not double-load bridged user/workspace MCP servers.
|
|
973
|
+
*/
|
|
974
|
+
export function writeGeminiCodemodeSettingsOverlay(outDir, baseSystemSettingsPath, cmEntry) {
|
|
975
|
+
let base = {};
|
|
976
|
+
if (baseSystemSettingsPath) {
|
|
977
|
+
try {
|
|
978
|
+
const parsed = parseJsonRelaxed(readFileSync(baseSystemSettingsPath, "utf8"));
|
|
979
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
980
|
+
base = parsed;
|
|
981
|
+
}
|
|
982
|
+
catch { /* no existing system settings */ }
|
|
983
|
+
}
|
|
984
|
+
const existingMcp = base.mcp && typeof base.mcp === "object" && !Array.isArray(base.mcp)
|
|
985
|
+
? { ...base.mcp }
|
|
986
|
+
: {};
|
|
987
|
+
const overlaid = {
|
|
988
|
+
...base,
|
|
989
|
+
mcp: {
|
|
990
|
+
...existingMcp,
|
|
991
|
+
allowed: ["caveman-codemode"],
|
|
992
|
+
},
|
|
993
|
+
mcpServers: {
|
|
994
|
+
"caveman-codemode": {
|
|
995
|
+
command: cmEntry.command,
|
|
996
|
+
args: cmEntry.args,
|
|
997
|
+
},
|
|
998
|
+
},
|
|
999
|
+
};
|
|
1000
|
+
const outPath = join(outDir, "gemini-codemode-settings.json");
|
|
1001
|
+
writeFileSync(outPath, JSON.stringify(overlaid, null, 2) + "\n", { mode: 0o600 });
|
|
1002
|
+
return outPath;
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Injects `mcp["caveman-codemode"]` into an ephemeral `OPENCODE_CONFIG_CONTENT`
|
|
1006
|
+
* JSON payload and disables already-bridged OpenCode-owned MCP servers in the
|
|
1007
|
+
* overlay ONLY (never touching `~/.config/opencode/opencode.json`).
|
|
1008
|
+
*/
|
|
1009
|
+
export function applyOpenCodeCodemodeOverlay(rawConfigJson, bridgedOpenCodeServerNames, cmEntry) {
|
|
1010
|
+
let doc = {};
|
|
1011
|
+
if (rawConfigJson) {
|
|
1012
|
+
try {
|
|
1013
|
+
const parsed = parseJsonRelaxed(rawConfigJson);
|
|
1014
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
1015
|
+
doc = parsed;
|
|
1016
|
+
}
|
|
1017
|
+
catch { /* fallback to empty */ }
|
|
1018
|
+
}
|
|
1019
|
+
const existingMcp = doc.mcp && typeof doc.mcp === "object" && !Array.isArray(doc.mcp)
|
|
1020
|
+
? { ...doc.mcp }
|
|
1021
|
+
: {};
|
|
1022
|
+
for (const name of bridgedOpenCodeServerNames) {
|
|
1023
|
+
existingMcp[name] = { enabled: false };
|
|
1024
|
+
}
|
|
1025
|
+
existingMcp["caveman-codemode"] = {
|
|
1026
|
+
type: "local",
|
|
1027
|
+
command: [cmEntry.command, ...cmEntry.args],
|
|
1028
|
+
enabled: true,
|
|
1029
|
+
};
|
|
1030
|
+
return JSON.stringify({ ...doc, mcp: existingMcp });
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Injects `mcp["caveman-codemode"]` into an ephemeral `KILO_CONFIG_CONTENT`
|
|
1034
|
+
* JSON payload and disables already-bridged Kilo-owned MCP servers without
|
|
1035
|
+
* mutating user settings on disk.
|
|
1036
|
+
*/
|
|
1037
|
+
export function applyKiloCodemodeOverlay(rawConfigJson, cmEntry, bridgedKiloServerNames = []) {
|
|
1038
|
+
let doc = {};
|
|
1039
|
+
if (rawConfigJson) {
|
|
1040
|
+
try {
|
|
1041
|
+
const parsed = parseJsonRelaxed(rawConfigJson);
|
|
1042
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
1043
|
+
doc = parsed;
|
|
1044
|
+
}
|
|
1045
|
+
catch { /* fallback */ }
|
|
1046
|
+
}
|
|
1047
|
+
const existingMcp = doc.mcp && typeof doc.mcp === "object" && !Array.isArray(doc.mcp)
|
|
1048
|
+
? { ...doc.mcp }
|
|
1049
|
+
: {};
|
|
1050
|
+
for (const name of bridgedKiloServerNames) {
|
|
1051
|
+
existingMcp[name] = { enabled: false };
|
|
1052
|
+
}
|
|
1053
|
+
existingMcp["caveman-codemode"] = {
|
|
1054
|
+
type: "local",
|
|
1055
|
+
command: [cmEntry.command, ...cmEntry.args],
|
|
1056
|
+
enabled: true,
|
|
1057
|
+
};
|
|
1058
|
+
return JSON.stringify({ ...doc, mcp: existingMcp });
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Replaces ONLY `mcp.servers` inside an already-ephemeral OpenClaw wrap config
|
|
1062
|
+
* file (`OPENCLAW_CONFIG_PATH`), never touching `~/.openclaw/openclaw.json`.
|
|
1063
|
+
*/
|
|
1064
|
+
export function patchEphemeralOpenClawCodemode(ephemeralConfigPath, cmEntry) {
|
|
1065
|
+
let doc = {};
|
|
1066
|
+
try {
|
|
1067
|
+
const parsed = parseJsonRelaxed(readFileSync(ephemeralConfigPath, "utf8"));
|
|
1068
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
1069
|
+
doc = parsed;
|
|
1070
|
+
}
|
|
1071
|
+
catch { /* fresh */ }
|
|
1072
|
+
const mcp = doc.mcp && typeof doc.mcp === "object" && !Array.isArray(doc.mcp)
|
|
1073
|
+
? { ...doc.mcp }
|
|
1074
|
+
: {};
|
|
1075
|
+
mcp.servers = {
|
|
1076
|
+
"caveman-codemode": {
|
|
1077
|
+
command: cmEntry.command,
|
|
1078
|
+
args: cmEntry.args,
|
|
1079
|
+
},
|
|
1080
|
+
};
|
|
1081
|
+
writeFileSync(ephemeralConfigPath, JSON.stringify({ ...doc, mcp }, null, 2) + "\n", { mode: 0o600 });
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Replaces ONLY `mcpServers` and sets `mcp.allowed = ["caveman-codemode"]`
|
|
1085
|
+
* inside an already-ephemeral Qwen Code system settings overlay
|
|
1086
|
+
* (`QWEN_CODE_SYSTEM_SETTINGS_PATH`), preventing double-loading of bridged
|
|
1087
|
+
* user/workspace MCP servers while preserving auth/model/security policies.
|
|
1088
|
+
*/
|
|
1089
|
+
export function patchEphemeralQwenCodemode(ephemeralSystemSettingsPath, cmEntry) {
|
|
1090
|
+
let doc = {};
|
|
1091
|
+
try {
|
|
1092
|
+
const parsed = parseJsonRelaxed(readFileSync(ephemeralSystemSettingsPath, "utf8"));
|
|
1093
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
1094
|
+
doc = parsed;
|
|
1095
|
+
}
|
|
1096
|
+
catch { /* fresh */ }
|
|
1097
|
+
const existingMcp = doc.mcp && typeof doc.mcp === "object" && !Array.isArray(doc.mcp)
|
|
1098
|
+
? { ...doc.mcp }
|
|
1099
|
+
: {};
|
|
1100
|
+
delete existingMcp.excluded;
|
|
1101
|
+
const next = {
|
|
1102
|
+
...doc,
|
|
1103
|
+
mcp: {
|
|
1104
|
+
...existingMcp,
|
|
1105
|
+
allowed: ["caveman-codemode"],
|
|
1106
|
+
},
|
|
1107
|
+
mcpServers: {
|
|
1108
|
+
"caveman-codemode": {
|
|
1109
|
+
command: cmEntry.command,
|
|
1110
|
+
args: cmEntry.args,
|
|
1111
|
+
},
|
|
1112
|
+
},
|
|
1113
|
+
};
|
|
1114
|
+
writeFileSync(ephemeralSystemSettingsPath, JSON.stringify(next, null, 2) + "\n", { mode: 0o600 });
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Strips any top-level `mcp_servers:` YAML entry (including inline `{}` / `null` /
|
|
1118
|
+
* `~` and quoted `"mcp_servers":`) from an ephemeral Hermes `config.yaml` and
|
|
1119
|
+
* inserts `caveman-codemode` before any trailing `...` YAML document-end marker,
|
|
1120
|
+
* leaving auth/models/plugins untouched and keeping `ruamel.yaml` happy.
|
|
1121
|
+
*/
|
|
1122
|
+
export function rewriteHermesCodemodeYaml(sourceYaml, cmEntry) {
|
|
1123
|
+
const kept = [];
|
|
1124
|
+
let skipping = false;
|
|
1125
|
+
for (const line of sourceYaml.split(/\r?\n/)) {
|
|
1126
|
+
const trimmed = stripYamlComment(line).trim();
|
|
1127
|
+
const indent = line.length - line.trimStart().length;
|
|
1128
|
+
if (trimmed && indent === 0) {
|
|
1129
|
+
if (trimmed === "..." || trimmed === "---") {
|
|
1130
|
+
skipping = false;
|
|
1131
|
+
}
|
|
1132
|
+
else {
|
|
1133
|
+
const colon = trimmed.indexOf(":");
|
|
1134
|
+
const key = colon > 0 ? unquoteKey(trimmed.slice(0, colon)) : "";
|
|
1135
|
+
skipping = key === "mcp_servers";
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
if (!skipping)
|
|
1139
|
+
kept.push(line);
|
|
1140
|
+
}
|
|
1141
|
+
const block = [
|
|
1142
|
+
"mcp_servers:",
|
|
1143
|
+
" caveman-codemode:",
|
|
1144
|
+
` command: ${JSON.stringify(cmEntry.command)}`,
|
|
1145
|
+
` args: [${cmEntry.args.map((a) => JSON.stringify(a)).join(", ")}]`,
|
|
1146
|
+
].join("\n");
|
|
1147
|
+
// If the source document has a top-level `...` document-end marker, insert
|
|
1148
|
+
// `mcp_servers:` before it so `ruamel.yaml` parses a single valid document.
|
|
1149
|
+
const docEndIdx = kept.findIndex((line) => {
|
|
1150
|
+
const t = stripYamlComment(line).trim();
|
|
1151
|
+
return t === "..." && line.length - line.trimStart().length === 0;
|
|
1152
|
+
});
|
|
1153
|
+
if (docEndIdx >= 0) {
|
|
1154
|
+
const before = kept.slice(0, docEndIdx).join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
|
|
1155
|
+
const after = kept.slice(docEndIdx).join("\n").trimEnd();
|
|
1156
|
+
return before ? `${before}\n\n${block}\n${after}\n` : `${block}\n${after}\n`;
|
|
1157
|
+
}
|
|
1158
|
+
const base = kept.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
|
|
1159
|
+
return base ? `${base}\n\n${block}\n` : `${block}\n`;
|
|
1160
|
+
}
|
|
1161
|
+
const HERMES_CODEMODE_BASELINE_FILE = ".caveman-codemode-baseline.yaml";
|
|
1162
|
+
function extractHermesMcpServerBlocks(yaml) {
|
|
1163
|
+
const blocks = new Map();
|
|
1164
|
+
let inSection = false;
|
|
1165
|
+
let serverIndent = -1;
|
|
1166
|
+
let currentName = "";
|
|
1167
|
+
let currentLines = [];
|
|
1168
|
+
const flush = () => {
|
|
1169
|
+
if (currentName && currentLines.length > 0) {
|
|
1170
|
+
// Trim trailing blank lines attached to a server block.
|
|
1171
|
+
while (currentLines.length > 1 && currentLines[currentLines.length - 1].trim() === "") {
|
|
1172
|
+
currentLines.pop();
|
|
1173
|
+
}
|
|
1174
|
+
blocks.set(currentName, currentLines);
|
|
1175
|
+
}
|
|
1176
|
+
currentName = "";
|
|
1177
|
+
currentLines = [];
|
|
1178
|
+
};
|
|
1179
|
+
for (const line of yaml.split(/\r?\n/)) {
|
|
1180
|
+
const trimmed = stripYamlComment(line).trim();
|
|
1181
|
+
const indent = line.length - line.trimStart().length;
|
|
1182
|
+
if (trimmed && indent === 0) {
|
|
1183
|
+
if (trimmed === "..." || trimmed === "---") {
|
|
1184
|
+
if (inSection) {
|
|
1185
|
+
flush();
|
|
1186
|
+
inSection = false;
|
|
1187
|
+
}
|
|
1188
|
+
continue;
|
|
1189
|
+
}
|
|
1190
|
+
const colon = trimmed.indexOf(":");
|
|
1191
|
+
const key = colon > 0 ? unquoteKey(trimmed.slice(0, colon)) : "";
|
|
1192
|
+
if (key === "mcp_servers") {
|
|
1193
|
+
inSection = true;
|
|
1194
|
+
serverIndent = -1;
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
if (inSection) {
|
|
1198
|
+
flush();
|
|
1199
|
+
inSection = false;
|
|
1200
|
+
}
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
if (!inSection)
|
|
1204
|
+
continue;
|
|
1205
|
+
if (!trimmed) {
|
|
1206
|
+
if (currentName)
|
|
1207
|
+
currentLines.push(line);
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
if (serverIndent < 0)
|
|
1211
|
+
serverIndent = indent;
|
|
1212
|
+
if (indent === serverIndent) {
|
|
1213
|
+
flush();
|
|
1214
|
+
const colon = trimmed.indexOf(":");
|
|
1215
|
+
if (colon > 0) {
|
|
1216
|
+
currentName = unquoteKey(trimmed.slice(0, colon));
|
|
1217
|
+
currentLines = [line];
|
|
1218
|
+
}
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
if (currentName && indent > serverIndent) {
|
|
1222
|
+
currentLines.push(line);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
if (inSection)
|
|
1226
|
+
flush();
|
|
1227
|
+
return blocks;
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Merges in-session Hermes `config.yaml` edits (e.g., `hermes mcp add ...` or
|
|
1231
|
+
* model/provider changes) back onto the user's pre-wrap `config.yaml` while
|
|
1232
|
+
* removing the ephemeral `caveman-codemode` overlay entry and preserving all
|
|
1233
|
+
* pre-existing user `mcp_servers` entries that were masked during the wrap.
|
|
1234
|
+
*/
|
|
1235
|
+
export function mergeHermesConfigEdits(editedYaml, originalYaml) {
|
|
1236
|
+
const editedEntries = extractHermesMcpServerBlocks(editedYaml);
|
|
1237
|
+
editedEntries.delete("caveman-codemode");
|
|
1238
|
+
const origEntries = extractHermesMcpServerBlocks(originalYaml);
|
|
1239
|
+
const mergedServerLines = [];
|
|
1240
|
+
for (const [name, lines] of origEntries) {
|
|
1241
|
+
if (!editedEntries.has(name)) {
|
|
1242
|
+
mergedServerLines.push(...lines);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
for (const [, lines] of editedEntries) {
|
|
1246
|
+
mergedServerLines.push(...lines);
|
|
1247
|
+
}
|
|
1248
|
+
const kept = [];
|
|
1249
|
+
let skipping = false;
|
|
1250
|
+
for (const line of editedYaml.split(/\r?\n/)) {
|
|
1251
|
+
const trimmed = stripYamlComment(line).trim();
|
|
1252
|
+
const indent = line.length - line.trimStart().length;
|
|
1253
|
+
if (trimmed && indent === 0) {
|
|
1254
|
+
if (trimmed === "..." || trimmed === "---") {
|
|
1255
|
+
skipping = false;
|
|
1256
|
+
}
|
|
1257
|
+
else {
|
|
1258
|
+
const colon = trimmed.indexOf(":");
|
|
1259
|
+
const key = colon > 0 ? unquoteKey(trimmed.slice(0, colon)) : "";
|
|
1260
|
+
skipping = key === "mcp_servers";
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
if (!skipping)
|
|
1264
|
+
kept.push(line);
|
|
1265
|
+
}
|
|
1266
|
+
if (mergedServerLines.length === 0) {
|
|
1267
|
+
const base = kept.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
|
|
1268
|
+
return base ? `${base}\n` : "";
|
|
1269
|
+
}
|
|
1270
|
+
const block = ["mcp_servers:", ...mergedServerLines].join("\n");
|
|
1271
|
+
const docEndIdx = kept.findIndex((line) => {
|
|
1272
|
+
const t = stripYamlComment(line).trim();
|
|
1273
|
+
return t === "..." && line.length - line.trimStart().length === 0;
|
|
1274
|
+
});
|
|
1275
|
+
if (docEndIdx >= 0) {
|
|
1276
|
+
const before = kept.slice(0, docEndIdx).join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
|
|
1277
|
+
const after = kept.slice(docEndIdx).join("\n").trimEnd();
|
|
1278
|
+
return before ? `${before}\n\n${block}\n${after}\n` : `${block}\n${after}\n`;
|
|
1279
|
+
}
|
|
1280
|
+
const base = kept.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
|
|
1281
|
+
return base ? `${base}\n\n${block}\n` : `${block}\n`;
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Builds an ephemeral `HERMES_HOME` directory linking user plugins/auth/skills/
|
|
1285
|
+
* sessions/state into `outDir` and replacing ONLY `mcp_servers:` in the
|
|
1286
|
+
* ephemeral `config.yaml`. Uses Windows junctions for directories when needed.
|
|
1287
|
+
*/
|
|
1288
|
+
export function buildHermesEphemeralCodemodeHome(sourceHome, outDir, cmEntry) {
|
|
1289
|
+
let sourceYaml = "";
|
|
1290
|
+
try {
|
|
1291
|
+
sourceYaml = readFileSync(join(sourceHome, "config.yaml"), "utf8");
|
|
1292
|
+
}
|
|
1293
|
+
catch { /* no existing config.yaml */ }
|
|
1294
|
+
const overlayYaml = rewriteHermesCodemodeYaml(sourceYaml, cmEntry);
|
|
1295
|
+
writeFileSync(join(outDir, "config.yaml"), overlayYaml, { mode: 0o600 });
|
|
1296
|
+
writeFileSync(join(outDir, HERMES_CODEMODE_BASELINE_FILE), overlayYaml, { mode: 0o600 });
|
|
1297
|
+
if (existsSync(sourceHome)) {
|
|
1298
|
+
try {
|
|
1299
|
+
for (const entry of readdirSync(sourceHome)) {
|
|
1300
|
+
if (entry === "config.yaml" || entry === "codemode-servers.json" || entry === HERMES_CODEMODE_BASELINE_FILE)
|
|
1301
|
+
continue;
|
|
1302
|
+
const src = join(sourceHome, entry);
|
|
1303
|
+
const dst = join(outDir, entry);
|
|
1304
|
+
if (!existsSync(dst)) {
|
|
1305
|
+
try {
|
|
1306
|
+
if (process.platform === "win32") {
|
|
1307
|
+
const isDir = statSync(src).isDirectory();
|
|
1308
|
+
symlinkSync(src, dst, isDir ? "junction" : "file");
|
|
1309
|
+
}
|
|
1310
|
+
else {
|
|
1311
|
+
symlinkSync(src, dst);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
catch { /* ignore unreadable/unsupported entries */ }
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
catch { /* ignore unreadable sourceHome */ }
|
|
1319
|
+
}
|
|
1320
|
+
return outDir;
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Persists any non-symlink files or directories created or atomically replaced
|
|
1324
|
+
* inside an ephemeral `HERMES_HOME` (such as rotated OAuth `auth.json`, newly
|
|
1325
|
+
* created `state.db*`, `.env`, `SOUL.md`, `memories/`, `sessions/`, `cron/`)
|
|
1326
|
+
* back into `sourceHome` before the ephemeral directory is removed.
|
|
1327
|
+
* If the user modified `config.yaml` during the session (for example via
|
|
1328
|
+
* `hermes mcp add`), merges those edits back while removing the ephemeral
|
|
1329
|
+
* `caveman-codemode` overlay and keeping pre-existing `mcp_servers` intact.
|
|
1330
|
+
* Unmodified `config.yaml` leaves `sourceHome/config.yaml` byte-identical.
|
|
1331
|
+
*/
|
|
1332
|
+
export function syncBackHermesEphemeralHome(outDir, sourceHome) {
|
|
1333
|
+
if (!outDir || !sourceHome || !existsSync(outDir))
|
|
1334
|
+
return;
|
|
1335
|
+
try {
|
|
1336
|
+
const entries = readdirSync(outDir);
|
|
1337
|
+
for (const entry of entries) {
|
|
1338
|
+
if (entry === "codemode-servers.json" || entry === HERMES_CODEMODE_BASELINE_FILE)
|
|
1339
|
+
continue;
|
|
1340
|
+
if (entry === "config.yaml") {
|
|
1341
|
+
try {
|
|
1342
|
+
const baselinePath = join(outDir, HERMES_CODEMODE_BASELINE_FILE);
|
|
1343
|
+
if (!existsSync(baselinePath))
|
|
1344
|
+
continue;
|
|
1345
|
+
const baselineYaml = readFileSync(baselinePath, "utf8");
|
|
1346
|
+
const currentYaml = readFileSync(join(outDir, "config.yaml"), "utf8");
|
|
1347
|
+
if (currentYaml === baselineYaml)
|
|
1348
|
+
continue;
|
|
1349
|
+
let origYaml = "";
|
|
1350
|
+
try {
|
|
1351
|
+
origYaml = readFileSync(join(sourceHome, "config.yaml"), "utf8");
|
|
1352
|
+
}
|
|
1353
|
+
catch { /* fresh config.yaml */ }
|
|
1354
|
+
const merged = mergeHermesConfigEdits(currentYaml, origYaml);
|
|
1355
|
+
mkdirSync(sourceHome, { recursive: true });
|
|
1356
|
+
const dst = join(sourceHome, "config.yaml");
|
|
1357
|
+
const tmp = `${dst}.caveman-sync-${process.pid}-${Date.now()}`;
|
|
1358
|
+
writeFileSync(tmp, merged, { mode: 0o600 });
|
|
1359
|
+
renameSync(tmp, dst);
|
|
1360
|
+
}
|
|
1361
|
+
catch { /* best-effort */ }
|
|
1362
|
+
continue;
|
|
1363
|
+
}
|
|
1364
|
+
const src = join(outDir, entry);
|
|
1365
|
+
let lst;
|
|
1366
|
+
try {
|
|
1367
|
+
lst = lstatSync(src);
|
|
1368
|
+
}
|
|
1369
|
+
catch {
|
|
1370
|
+
continue;
|
|
1371
|
+
}
|
|
1372
|
+
// Symlinks point directly at sourceHome — mutations through them already landed.
|
|
1373
|
+
if (lst.isSymbolicLink())
|
|
1374
|
+
continue;
|
|
1375
|
+
try {
|
|
1376
|
+
mkdirSync(sourceHome, { recursive: true });
|
|
1377
|
+
}
|
|
1378
|
+
catch { /* ignore */ }
|
|
1379
|
+
const dst = join(sourceHome, entry);
|
|
1380
|
+
if (lst.isDirectory()) {
|
|
1381
|
+
try {
|
|
1382
|
+
cpSync(src, dst, { recursive: true, force: true });
|
|
1383
|
+
}
|
|
1384
|
+
catch { /* best-effort */ }
|
|
1385
|
+
}
|
|
1386
|
+
else if (lst.isFile()) {
|
|
1387
|
+
try {
|
|
1388
|
+
const tmp = `${dst}.caveman-sync-${process.pid}-${Date.now()}`;
|
|
1389
|
+
copyFileSync(src, tmp);
|
|
1390
|
+
renameSync(tmp, dst);
|
|
1391
|
+
}
|
|
1392
|
+
catch {
|
|
1393
|
+
try {
|
|
1394
|
+
copyFileSync(src, dst);
|
|
1395
|
+
}
|
|
1396
|
+
catch { /* best-effort */ }
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
catch { /* best-effort on exit */ }
|
|
1402
|
+
}
|