@yawlabs/mcp 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +142 -2
- package/README.md +12 -6
- package/dist/{auto-upgrade-WMCX5NYW.js → auto-upgrade-A3WTRVGV.js} +1 -1
- package/dist/chunk-PAUBVL2N.js +4943 -0
- package/dist/index.js +1400 -815
- package/package.json +3 -1
- package/dist/chunk-R4MTSNP4.js +0 -2167
|
@@ -0,0 +1,4943 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/auto-upgrade.ts
|
|
4
|
+
import { spawn as spawn3 } from "child_process";
|
|
5
|
+
import { createHash } from "crypto";
|
|
6
|
+
import {
|
|
7
|
+
closeSync,
|
|
8
|
+
openSync,
|
|
9
|
+
readFileSync as readFileSync3,
|
|
10
|
+
realpathSync as realpathSync2,
|
|
11
|
+
renameSync,
|
|
12
|
+
statSync as statSync2,
|
|
13
|
+
unlinkSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
writeSync
|
|
16
|
+
} from "fs";
|
|
17
|
+
import { tmpdir } from "os";
|
|
18
|
+
import { dirname as dirname2, join as join11, sep as sep2 } from "path";
|
|
19
|
+
|
|
20
|
+
// src/internal-secret-env.ts
|
|
21
|
+
var INTERNAL_SECRET_ENV_KEYS = /* @__PURE__ */ new Set([
|
|
22
|
+
"YAW_MCP_TOKEN",
|
|
23
|
+
"YAW_MCP_VAULT_PASSPHRASE",
|
|
24
|
+
"YAW_MCP_VAULT_PASSPHRASE_NEW"
|
|
25
|
+
]);
|
|
26
|
+
function scrubInternalSecretsFromProcessEnv() {
|
|
27
|
+
for (const key of Object.keys(process.env)) {
|
|
28
|
+
if (INTERNAL_SECRET_ENV_KEYS.has(key.toUpperCase())) delete process.env[key];
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function stripInternalSecretsFromEnv(env) {
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const [key, value] of Object.entries(env)) {
|
|
34
|
+
if (INTERNAL_SECRET_ENV_KEYS.has(key.toUpperCase())) continue;
|
|
35
|
+
out[key] = value;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/logger.ts
|
|
41
|
+
var LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
42
|
+
function minLevel() {
|
|
43
|
+
return LOG_LEVELS[process.env.LOG_LEVEL?.toLowerCase()] ?? LOG_LEVELS.info;
|
|
44
|
+
}
|
|
45
|
+
function guardStderrErrors() {
|
|
46
|
+
try {
|
|
47
|
+
if (process.stderr.listenerCount("error") === 0) {
|
|
48
|
+
process.stderr.on("error", () => {
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
var surface = "server";
|
|
55
|
+
function setLogSurface(next) {
|
|
56
|
+
surface = next;
|
|
57
|
+
}
|
|
58
|
+
function logLevelRequested() {
|
|
59
|
+
const raw = process.env.LOG_LEVEL?.trim().toLowerCase();
|
|
60
|
+
return raw !== void 0 && raw in LOG_LEVELS;
|
|
61
|
+
}
|
|
62
|
+
function renderData(data) {
|
|
63
|
+
if (data === void 0) return "";
|
|
64
|
+
try {
|
|
65
|
+
const parts = Object.entries(data).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`);
|
|
66
|
+
return parts.length > 0 ? ` (${parts.join("; ")})` : "";
|
|
67
|
+
} catch {
|
|
68
|
+
return " (details omitted)";
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function log(level, msg, data) {
|
|
72
|
+
if (LOG_LEVELS[level] < minLevel()) return;
|
|
73
|
+
guardStderrErrors();
|
|
74
|
+
if (surface === "cli" && !logLevelRequested()) {
|
|
75
|
+
if (LOG_LEVELS[level] < LOG_LEVELS.warn) return;
|
|
76
|
+
try {
|
|
77
|
+
process.stderr.write(`yaw-mcp: ${level === "warn" ? "warning" : "error"}: ${msg}${renderData(data)}
|
|
78
|
+
`);
|
|
79
|
+
} catch {
|
|
80
|
+
}
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
84
|
+
let entry;
|
|
85
|
+
try {
|
|
86
|
+
entry = JSON.stringify({ ...data, level, msg, ts });
|
|
87
|
+
} catch {
|
|
88
|
+
entry = JSON.stringify({ level, msg, ts, dataOmitted: true });
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
process.stderr.write(`${entry}
|
|
92
|
+
`);
|
|
93
|
+
} catch {
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
var brokenStreams = /* @__PURE__ */ new WeakSet();
|
|
97
|
+
var guardedStreams = /* @__PURE__ */ new WeakSet();
|
|
98
|
+
function createStreamWriter(stream) {
|
|
99
|
+
if (!guardedStreams.has(stream)) {
|
|
100
|
+
guardedStreams.add(stream);
|
|
101
|
+
try {
|
|
102
|
+
stream.on("error", () => {
|
|
103
|
+
brokenStreams.add(stream);
|
|
104
|
+
});
|
|
105
|
+
} catch {
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return (s) => {
|
|
109
|
+
if (brokenStreams.has(stream)) return;
|
|
110
|
+
try {
|
|
111
|
+
stream.write(s);
|
|
112
|
+
} catch {
|
|
113
|
+
brokenStreams.add(stream);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/upgrade-cmd.ts
|
|
119
|
+
import { spawn as spawn2 } from "child_process";
|
|
120
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
121
|
+
import { join as join10 } from "path";
|
|
122
|
+
|
|
123
|
+
// src/oam-spawn.ts
|
|
124
|
+
import { spawn } from "child_process";
|
|
125
|
+
import { accessSync, constants, existsSync as existsSync2, readdirSync, readFileSync, statSync } from "fs";
|
|
126
|
+
import { homedir as homedir4 } from "os";
|
|
127
|
+
import { dirname, isAbsolute as isAbsolute6, join as join9, sep } from "path";
|
|
128
|
+
import { fileURLToPath } from "url";
|
|
129
|
+
|
|
130
|
+
// src/install-targets.ts
|
|
131
|
+
import { homedir as homedir2 } from "os";
|
|
132
|
+
import { isAbsolute as isAbsolute5, join as join8, resolve as resolve5 } from "path";
|
|
133
|
+
|
|
134
|
+
// src/client-config.ts
|
|
135
|
+
import { existsSync } from "fs";
|
|
136
|
+
import { readFile } from "fs/promises";
|
|
137
|
+
|
|
138
|
+
// src/client-config-json.ts
|
|
139
|
+
import { parseTree as parseTree2 } from "jsonc-parser";
|
|
140
|
+
|
|
141
|
+
// src/jsonc.ts
|
|
142
|
+
import {
|
|
143
|
+
applyEdits,
|
|
144
|
+
createScanner,
|
|
145
|
+
findNodeAtLocation,
|
|
146
|
+
getNodeValue,
|
|
147
|
+
modify,
|
|
148
|
+
parseTree
|
|
149
|
+
} from "jsonc-parser";
|
|
150
|
+
function stripJsoncComments(src) {
|
|
151
|
+
let out = "";
|
|
152
|
+
let i = 0;
|
|
153
|
+
const len = src.length;
|
|
154
|
+
let inString = false;
|
|
155
|
+
let stringChar = "";
|
|
156
|
+
while (i < len) {
|
|
157
|
+
const c = src[i];
|
|
158
|
+
if (inString) {
|
|
159
|
+
out += c;
|
|
160
|
+
if (c === "\\" && i + 1 < len) {
|
|
161
|
+
out += src[i + 1];
|
|
162
|
+
i += 2;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (c === stringChar) inString = false;
|
|
166
|
+
i++;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (c === '"' || c === "'") {
|
|
170
|
+
inString = true;
|
|
171
|
+
stringChar = c;
|
|
172
|
+
out += c;
|
|
173
|
+
i++;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const next = src[i + 1];
|
|
177
|
+
if (c === "/" && next === "/") {
|
|
178
|
+
while (i < len && src[i] !== "\n") i++;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
if (c === "/" && next === "*") {
|
|
182
|
+
i += 2;
|
|
183
|
+
while (i < len && !(src[i] === "*" && src[i + 1] === "/")) {
|
|
184
|
+
if (src[i] === "\n") out += "\n";
|
|
185
|
+
i++;
|
|
186
|
+
}
|
|
187
|
+
i += 2;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
out += c;
|
|
191
|
+
i++;
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
function stripTrailingCommas(src) {
|
|
196
|
+
let out = "";
|
|
197
|
+
let i = 0;
|
|
198
|
+
const len = src.length;
|
|
199
|
+
let inString = false;
|
|
200
|
+
let stringChar = "";
|
|
201
|
+
while (i < len) {
|
|
202
|
+
const c = src[i];
|
|
203
|
+
if (inString) {
|
|
204
|
+
out += c;
|
|
205
|
+
if (c === "\\" && i + 1 < len) {
|
|
206
|
+
out += src[i + 1];
|
|
207
|
+
i += 2;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (c === stringChar) inString = false;
|
|
211
|
+
i++;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (c === '"' || c === "'") {
|
|
215
|
+
inString = true;
|
|
216
|
+
stringChar = c;
|
|
217
|
+
out += c;
|
|
218
|
+
i++;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (c === ",") {
|
|
222
|
+
let j = i + 1;
|
|
223
|
+
while (j < len && (src[j] === " " || src[j] === " " || src[j] === "\r" || src[j] === "\n")) j++;
|
|
224
|
+
if (j < len && (src[j] === "]" || src[j] === "}")) {
|
|
225
|
+
out += " ";
|
|
226
|
+
i++;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
out += c;
|
|
231
|
+
i++;
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
function parseJsonc(src) {
|
|
236
|
+
const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
|
|
237
|
+
const stripped = stripTrailingCommas(stripJsoncComments(debommed));
|
|
238
|
+
return JSON.parse(stripped);
|
|
239
|
+
}
|
|
240
|
+
var FORMATTING_OPTIONS = {
|
|
241
|
+
insertSpaces: true,
|
|
242
|
+
tabSize: 2,
|
|
243
|
+
eol: "\n"
|
|
244
|
+
};
|
|
245
|
+
var TOKEN_CLOSE_BRACE = 2;
|
|
246
|
+
var TOKEN_CLOSE_BRACKET = 4;
|
|
247
|
+
var TOKEN_COMMA = 5;
|
|
248
|
+
var TOKEN_LINE_COMMENT = 12;
|
|
249
|
+
var TOKEN_BLOCK_COMMENT = 13;
|
|
250
|
+
var TOKEN_LINE_BREAK = 14;
|
|
251
|
+
var TOKEN_WHITESPACE = 15;
|
|
252
|
+
var isHorizontalSpace = (c) => c === " " || c === " ";
|
|
253
|
+
var isLineBreak = (c) => c === "\n" || c === "\r";
|
|
254
|
+
function lineStartOf(text, pos) {
|
|
255
|
+
let i = pos;
|
|
256
|
+
while (i > 0 && !isLineBreak(text[i - 1])) i--;
|
|
257
|
+
return i;
|
|
258
|
+
}
|
|
259
|
+
function indentOfLine(text, pos) {
|
|
260
|
+
const start = lineStartOf(text, pos);
|
|
261
|
+
let end = start;
|
|
262
|
+
while (isHorizontalSpace(text[end])) end++;
|
|
263
|
+
return text.slice(start, end);
|
|
264
|
+
}
|
|
265
|
+
function startsLine(text, pos) {
|
|
266
|
+
for (let i = lineStartOf(text, pos); i < pos; i++) {
|
|
267
|
+
if (!isHorizontalSpace(text[i])) return false;
|
|
268
|
+
}
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
function isOneLine(text, node) {
|
|
272
|
+
for (let i = node.offset; i < node.offset + node.length; i++) {
|
|
273
|
+
if (isLineBreak(text[i])) return false;
|
|
274
|
+
}
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
function detectEol(text) {
|
|
278
|
+
const match = /\r\n|\n|\r/.exec(text);
|
|
279
|
+
return match ? match[0] : "\n";
|
|
280
|
+
}
|
|
281
|
+
function detectIndentStep(text, container) {
|
|
282
|
+
const base = indentOfLine(text, container.offset);
|
|
283
|
+
for (const child of container.children ?? []) {
|
|
284
|
+
if (!startsLine(text, child.offset)) continue;
|
|
285
|
+
const indent = indentOfLine(text, child.offset);
|
|
286
|
+
const step = indent.slice(base.length);
|
|
287
|
+
if (indent.startsWith(base) && /^(?: +|\t+)$/.test(step)) return step;
|
|
288
|
+
}
|
|
289
|
+
let spaces = 0;
|
|
290
|
+
for (const match of text.matchAll(/^([ \t]+)["\]}]/gm)) {
|
|
291
|
+
const indent = match[1];
|
|
292
|
+
if (indent.startsWith(" ")) return " ";
|
|
293
|
+
if (!indent.includes(" ") && (spaces === 0 || indent.length < spaces)) spaces = indent.length;
|
|
294
|
+
}
|
|
295
|
+
return spaces > 0 ? " ".repeat(spaces) : " ";
|
|
296
|
+
}
|
|
297
|
+
function render(value, step, eol, indent, compact) {
|
|
298
|
+
const json = compact ? JSON.stringify(value) : JSON.stringify(value, null, step);
|
|
299
|
+
if (json === void 0) throw new Error(`cannot write a ${typeof value} value as JSON`);
|
|
300
|
+
return compact ? json : json.split("\n").join(eol + indent);
|
|
301
|
+
}
|
|
302
|
+
function scanRestOfLine(text, from) {
|
|
303
|
+
const scanner = createScanner(text, false);
|
|
304
|
+
scanner.setPosition(from);
|
|
305
|
+
let comma;
|
|
306
|
+
for (; ; ) {
|
|
307
|
+
const kind = scanner.scan();
|
|
308
|
+
if (kind === TOKEN_WHITESPACE || kind === TOKEN_LINE_COMMENT || kind === TOKEN_BLOCK_COMMENT) continue;
|
|
309
|
+
if (kind === TOKEN_COMMA && comma === void 0) {
|
|
310
|
+
comma = scanner.getTokenOffset();
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
return { comma, stop: scanner.getTokenOffset(), stopLength: scanner.getTokenLength(), stopKind: kind };
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function commaAfter(text, from) {
|
|
317
|
+
const scanner = createScanner(text, true);
|
|
318
|
+
scanner.setPosition(from);
|
|
319
|
+
const kind = scanner.scan();
|
|
320
|
+
return kind === TOKEN_COMMA ? scanner.getTokenOffset() : void 0;
|
|
321
|
+
}
|
|
322
|
+
function insertMember(text, container, key, value) {
|
|
323
|
+
const eol = detectEol(text);
|
|
324
|
+
const step = detectIndentStep(text, container);
|
|
325
|
+
const keyJson = key === null ? null : JSON.stringify(key);
|
|
326
|
+
const pretty = keyJson === null ? "" : `${keyJson}: `;
|
|
327
|
+
const compact = (sep3) => keyJson === null ? "" : `${keyJson}:${sep3}`;
|
|
328
|
+
const closeKind = key === null ? TOKEN_CLOSE_BRACKET : TOKEN_CLOSE_BRACE;
|
|
329
|
+
const members = container.children ?? [];
|
|
330
|
+
const close = container.offset + container.length - 1;
|
|
331
|
+
if (members.length === 0) {
|
|
332
|
+
const rest2 = scanRestOfLine(text, container.offset + 1);
|
|
333
|
+
if (rest2.stopKind === TOKEN_LINE_BREAK) {
|
|
334
|
+
const indent2 = indentOfLine(text, container.offset) + step;
|
|
335
|
+
return [
|
|
336
|
+
{
|
|
337
|
+
offset: rest2.stop,
|
|
338
|
+
length: 0,
|
|
339
|
+
content: `${eol}${indent2}${pretty}${render(value, step, eol, indent2, false)}`
|
|
340
|
+
}
|
|
341
|
+
];
|
|
342
|
+
}
|
|
343
|
+
let root = container;
|
|
344
|
+
while (root.parent !== void 0) root = root.parent;
|
|
345
|
+
if (isOneLine(text, root)) {
|
|
346
|
+
const colonOffset = container.parent?.colonOffset;
|
|
347
|
+
const gap = colonOffset !== void 0 && text[colonOffset + 1] === " " ? " " : "";
|
|
348
|
+
return [{ offset: close, length: 0, content: `${compact(gap)}${render(value, step, eol, "", true)}` }];
|
|
349
|
+
}
|
|
350
|
+
const outer = indentOfLine(text, container.offset);
|
|
351
|
+
const indent = outer + step;
|
|
352
|
+
const inside = text.slice(container.offset + 1, close);
|
|
353
|
+
const blank = /^[ \t]*$/.test(inside);
|
|
354
|
+
return [
|
|
355
|
+
{
|
|
356
|
+
offset: blank ? container.offset + 1 : close,
|
|
357
|
+
length: blank ? inside.length : 0,
|
|
358
|
+
content: `${eol}${indent}${pretty}${render(value, step, eol, indent, false)}${eol}${outer}`
|
|
359
|
+
}
|
|
360
|
+
];
|
|
361
|
+
}
|
|
362
|
+
const last = members[members.length - 1];
|
|
363
|
+
const lastEnd = last.offset + last.length;
|
|
364
|
+
const trailingComma = commaAfter(text, lastEnd);
|
|
365
|
+
const rest = scanRestOfLine(text, trailingComma === void 0 ? lastEnd : trailingComma + 1);
|
|
366
|
+
const edits = [];
|
|
367
|
+
if (trailingComma === void 0) edits.push({ offset: lastEnd, length: 0, content: "," });
|
|
368
|
+
const ownComma = trailingComma === void 0 ? "" : ",";
|
|
369
|
+
if (rest.stopKind === TOKEN_LINE_BREAK) {
|
|
370
|
+
const anchor = [...members].reverse().find((m) => startsLine(text, m.offset));
|
|
371
|
+
const indent = anchor ? indentOfLine(text, anchor.offset) : indentOfLine(text, container.offset) + step;
|
|
372
|
+
edits.push({
|
|
373
|
+
offset: rest.stop,
|
|
374
|
+
length: 0,
|
|
375
|
+
content: `${eol}${indent}${pretty}${render(value, step, eol, indent, false)}${ownComma}`
|
|
376
|
+
});
|
|
377
|
+
return edits;
|
|
378
|
+
}
|
|
379
|
+
if (rest.stopKind === closeKind) {
|
|
380
|
+
const colon = last.colonOffset !== void 0 && text[last.colonOffset + 1] === " " ? " " : "";
|
|
381
|
+
const gap = isHorizontalSpace(text[rest.stop - 1]) ? " " : "";
|
|
382
|
+
edits.push({
|
|
383
|
+
offset: rest.stop,
|
|
384
|
+
length: 0,
|
|
385
|
+
content: `${compact(colon)}${render(value, step, eol, "", true)}${ownComma}${gap}`
|
|
386
|
+
});
|
|
387
|
+
return edits;
|
|
388
|
+
}
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
function removeMember(text, container, member) {
|
|
392
|
+
const members = container.children ?? [];
|
|
393
|
+
const index = members.indexOf(member);
|
|
394
|
+
const isLast = index === members.length - 1;
|
|
395
|
+
const end = member.offset + member.length;
|
|
396
|
+
const ownComma = commaAfter(text, end);
|
|
397
|
+
const rest = scanRestOfLine(text, end);
|
|
398
|
+
const edits = [];
|
|
399
|
+
const ownLines = startsLine(text, member.offset) && rest.stopKind === TOKEN_LINE_BREAK && (rest.comma !== void 0 || ownComma === void 0);
|
|
400
|
+
if (ownLines) {
|
|
401
|
+
const start = lineStartOf(text, member.offset);
|
|
402
|
+
edits.push({ offset: start, length: rest.stop + rest.stopLength - start, content: "" });
|
|
403
|
+
} else {
|
|
404
|
+
let from = member.offset;
|
|
405
|
+
let to = ownComma === void 0 ? end : ownComma + 1;
|
|
406
|
+
let after = to;
|
|
407
|
+
while (isHorizontalSpace(text[after])) after++;
|
|
408
|
+
to = after;
|
|
409
|
+
if (after >= text.length || isLineBreak(text[after])) {
|
|
410
|
+
while (from > 0 && isHorizontalSpace(text[from - 1])) from--;
|
|
411
|
+
}
|
|
412
|
+
if (members.length === 1) {
|
|
413
|
+
const open = container.offset + 1;
|
|
414
|
+
const close = container.offset + container.length - 1;
|
|
415
|
+
if (/^\s*$/.test(text.slice(open, from) + text.slice(to, close))) {
|
|
416
|
+
from = open;
|
|
417
|
+
to = close;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
edits.push({ offset: from, length: to - from, content: "" });
|
|
421
|
+
}
|
|
422
|
+
if (isLast && index > 0 && ownComma === void 0) {
|
|
423
|
+
const previous = members[index - 1];
|
|
424
|
+
const separator = commaAfter(text, previous.offset + previous.length);
|
|
425
|
+
if (separator !== void 0) edits.push({ offset: separator, length: 1, content: "" });
|
|
426
|
+
}
|
|
427
|
+
return edits;
|
|
428
|
+
}
|
|
429
|
+
function replaceValue(text, container, node, value) {
|
|
430
|
+
const content = render(
|
|
431
|
+
value,
|
|
432
|
+
detectIndentStep(text, container),
|
|
433
|
+
detectEol(text),
|
|
434
|
+
indentOfLine(text, node.offset),
|
|
435
|
+
isOneLine(text, container)
|
|
436
|
+
);
|
|
437
|
+
return { offset: node.offset, length: node.length, content };
|
|
438
|
+
}
|
|
439
|
+
function spliceEdits(text, path2, value) {
|
|
440
|
+
const errors = [];
|
|
441
|
+
const root = parseTree(text, errors, { allowTrailingComma: true });
|
|
442
|
+
if (root === void 0 || errors.length > 0) return null;
|
|
443
|
+
const remaining = path2.slice();
|
|
444
|
+
let toWrite = value;
|
|
445
|
+
let parent;
|
|
446
|
+
let key;
|
|
447
|
+
while (remaining.length > 0) {
|
|
448
|
+
key = remaining.pop();
|
|
449
|
+
parent = findNodeAtLocation(root, remaining);
|
|
450
|
+
if (parent !== void 0 || toWrite === void 0) break;
|
|
451
|
+
toWrite = typeof key === "string" ? { [key]: toWrite } : [toWrite];
|
|
452
|
+
}
|
|
453
|
+
if (parent === void 0 || key === void 0) return null;
|
|
454
|
+
if (parent.type === "object" && typeof key === "string") {
|
|
455
|
+
const existing = findNodeAtLocation(parent, [key]);
|
|
456
|
+
if (existing?.parent !== void 0) {
|
|
457
|
+
if (toWrite === void 0) return removeMember(text, parent, existing.parent);
|
|
458
|
+
return [replaceValue(text, parent, existing, toWrite)];
|
|
459
|
+
}
|
|
460
|
+
if (toWrite === void 0) return [];
|
|
461
|
+
return insertMember(text, parent, key, toWrite);
|
|
462
|
+
}
|
|
463
|
+
if (parent.type === "array" && typeof key === "number" && toWrite !== void 0 && key >= 0) {
|
|
464
|
+
const element = parent.children?.[key];
|
|
465
|
+
if (element !== void 0) return [replaceValue(text, parent, element, toWrite)];
|
|
466
|
+
}
|
|
467
|
+
return null;
|
|
468
|
+
}
|
|
469
|
+
function computeEdits(text, path2, value) {
|
|
470
|
+
return spliceEdits(text, path2, value) ?? modify(text, path2, value, { formattingOptions: FORMATTING_OPTIONS });
|
|
471
|
+
}
|
|
472
|
+
function editJsoncEntry(src, containerPath, entryName, value) {
|
|
473
|
+
if (entryName === "") {
|
|
474
|
+
throw new Error("editJsoncEntry: entryName must be a non-empty key");
|
|
475
|
+
}
|
|
476
|
+
const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
|
|
477
|
+
return applyEdits(debommed, computeEdits(debommed, [...containerPath, entryName], value));
|
|
478
|
+
}
|
|
479
|
+
function removeJsoncEntry(src, containerPath, entryName) {
|
|
480
|
+
if (entryName === "") {
|
|
481
|
+
throw new Error("removeJsoncEntry: entryName must be a non-empty key");
|
|
482
|
+
}
|
|
483
|
+
const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
|
|
484
|
+
const edits = computeEdits(debommed, [...containerPath, entryName], void 0);
|
|
485
|
+
if (edits.length === 0) return src;
|
|
486
|
+
return applyEdits(debommed, edits);
|
|
487
|
+
}
|
|
488
|
+
function editJsoncPath(src, path2, value) {
|
|
489
|
+
if (path2.length === 0) {
|
|
490
|
+
throw new Error("editJsoncPath: path must not be empty");
|
|
491
|
+
}
|
|
492
|
+
if (path2.some((seg) => seg === "")) {
|
|
493
|
+
throw new Error("editJsoncPath: path segments must be non-empty");
|
|
494
|
+
}
|
|
495
|
+
const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
|
|
496
|
+
const edits = computeEdits(debommed, path2, value);
|
|
497
|
+
if (edits.length === 0) return src;
|
|
498
|
+
return applyEdits(debommed, edits);
|
|
499
|
+
}
|
|
500
|
+
function elementValue(child) {
|
|
501
|
+
return getNodeValue(child);
|
|
502
|
+
}
|
|
503
|
+
function arrayNodeAt(text, path2) {
|
|
504
|
+
const errors = [];
|
|
505
|
+
const root = parseTree(text, errors, { allowTrailingComma: true });
|
|
506
|
+
if (root === void 0 || errors.length > 0) return null;
|
|
507
|
+
const node = findNodeAtLocation(root, path2);
|
|
508
|
+
return node !== void 0 && node.type === "array" ? node : null;
|
|
509
|
+
}
|
|
510
|
+
function addJsoncArrayElement(src, path2, value) {
|
|
511
|
+
if (path2.length === 0) throw new Error("addJsoncArrayElement: path must not be empty");
|
|
512
|
+
const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
|
|
513
|
+
const array = arrayNodeAt(debommed, path2);
|
|
514
|
+
if (array === null) {
|
|
515
|
+
const errors = [];
|
|
516
|
+
const root = parseTree(debommed, errors, { allowTrailingComma: true });
|
|
517
|
+
const existing = root === void 0 ? void 0 : findNodeAtLocation(root, path2);
|
|
518
|
+
if (existing !== void 0) {
|
|
519
|
+
throw new Error(`addJsoncArrayElement: ${path2.join(".")} is a ${existing.type}, not an array`);
|
|
520
|
+
}
|
|
521
|
+
return editJsoncPath(debommed, path2, [value]);
|
|
522
|
+
}
|
|
523
|
+
const wanted = JSON.stringify(value);
|
|
524
|
+
for (const child of array.children ?? []) {
|
|
525
|
+
if (JSON.stringify(elementValue(child)) === wanted) return src;
|
|
526
|
+
}
|
|
527
|
+
const edits = insertMember(debommed, array, null, value);
|
|
528
|
+
if (edits === null) {
|
|
529
|
+
const next = [...(array.children ?? []).map(elementValue), value];
|
|
530
|
+
return editJsoncPath(debommed, path2, next);
|
|
531
|
+
}
|
|
532
|
+
return applyEdits(debommed, edits);
|
|
533
|
+
}
|
|
534
|
+
function removeJsoncArrayElements(src, path2, matches) {
|
|
535
|
+
if (path2.length === 0) throw new Error("removeJsoncArrayElements: path must not be empty");
|
|
536
|
+
const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
|
|
537
|
+
const array = arrayNodeAt(debommed, path2);
|
|
538
|
+
if (array === null) return src;
|
|
539
|
+
const doomed = (array.children ?? []).filter((child) => matches(elementValue(child)));
|
|
540
|
+
if (doomed.length === 0) return src;
|
|
541
|
+
let text = debommed;
|
|
542
|
+
for (let i = 0; i < doomed.length; i++) {
|
|
543
|
+
const current = arrayNodeAt(text, path2);
|
|
544
|
+
if (current === null) break;
|
|
545
|
+
const member = (current.children ?? []).find((child) => matches(elementValue(child)));
|
|
546
|
+
if (member === void 0) break;
|
|
547
|
+
text = applyEdits(text, removeMember(text, current, member));
|
|
548
|
+
}
|
|
549
|
+
const emptied = arrayNodeAt(text, path2);
|
|
550
|
+
if (emptied !== null && (emptied.children ?? []).length === 0) {
|
|
551
|
+
const open = emptied.offset + 1;
|
|
552
|
+
const close = emptied.offset + emptied.length - 1;
|
|
553
|
+
if (close > open && /^\s*$/.test(text.slice(open, close))) {
|
|
554
|
+
text = text.slice(0, open) + text.slice(close);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return text;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// src/client-config-json.ts
|
|
561
|
+
var BOM = String.fromCharCode(65279);
|
|
562
|
+
function stripBom(raw) {
|
|
563
|
+
return raw.charCodeAt(0) === 65279 ? { text: raw.slice(1), had: true } : { text: raw, had: false };
|
|
564
|
+
}
|
|
565
|
+
function isRecord(value) {
|
|
566
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
567
|
+
}
|
|
568
|
+
function containerAt(root, segments) {
|
|
569
|
+
let cursor = root;
|
|
570
|
+
for (const key of segments) {
|
|
571
|
+
if (!isRecord(cursor)) return null;
|
|
572
|
+
cursor = cursor[key];
|
|
573
|
+
}
|
|
574
|
+
return isRecord(cursor) ? cursor : null;
|
|
575
|
+
}
|
|
576
|
+
function blockedSegment(root, segments) {
|
|
577
|
+
let node = root;
|
|
578
|
+
for (let i = 0; i < segments.length; i++) {
|
|
579
|
+
const value = node[segments[i]];
|
|
580
|
+
if (value === void 0) return null;
|
|
581
|
+
if (isRecord(value)) {
|
|
582
|
+
node = value;
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
return {
|
|
586
|
+
path: segments.slice(0, i + 1),
|
|
587
|
+
shape: describeValueShape(value),
|
|
588
|
+
reparable: value === null || !Array.isArray(value) || value.length === 0
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
function strictPosition(err, raw, bomShift) {
|
|
594
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
595
|
+
const match = /at position (\d+)/.exec(message);
|
|
596
|
+
if (match === null) return null;
|
|
597
|
+
return positionAt(raw, Number(match[1]) + bomShift);
|
|
598
|
+
}
|
|
599
|
+
function jsoncPosition(raw, bomShift) {
|
|
600
|
+
const errors = [];
|
|
601
|
+
parseTree2(raw.slice(bomShift), errors, { allowTrailingComma: true });
|
|
602
|
+
const first = errors[0];
|
|
603
|
+
return first === void 0 ? null : positionAt(raw, first.offset + bomShift);
|
|
604
|
+
}
|
|
605
|
+
function entriesOf(container, transform) {
|
|
606
|
+
return Object.entries(container).map(([key, value]) => {
|
|
607
|
+
const normalized = normalizeEntry(value, transform);
|
|
608
|
+
return { key, value, launch: launchOf(normalized) };
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
function buildFreshConfig(containerPath, key, entry) {
|
|
612
|
+
if (containerPath.length === 0) throw new Error("buildFreshConfig: containerPath cannot be empty");
|
|
613
|
+
const root = {};
|
|
614
|
+
let parent = root;
|
|
615
|
+
for (let i = 0; i < containerPath.length - 1; i++) {
|
|
616
|
+
const child = {};
|
|
617
|
+
parent[containerPath[i]] = child;
|
|
618
|
+
parent = child;
|
|
619
|
+
}
|
|
620
|
+
parent[containerPath[containerPath.length - 1]] = { [key]: entry };
|
|
621
|
+
return root;
|
|
622
|
+
}
|
|
623
|
+
function describeJsonLocation(absolute, addr) {
|
|
624
|
+
const segments = addr.containerPath;
|
|
625
|
+
if (segments.length <= 1) return absolute;
|
|
626
|
+
const tail = segments.slice(2).map((key) => `.${key}`).join("");
|
|
627
|
+
return `${absolute} under ${segments[0]}[${JSON.stringify(segments[1])}]${tail}`;
|
|
628
|
+
}
|
|
629
|
+
function messageOf(err) {
|
|
630
|
+
return err instanceof Error ? err.message : String(err);
|
|
631
|
+
}
|
|
632
|
+
function readStrictJson(raw) {
|
|
633
|
+
const { text, had } = stripBom(raw);
|
|
634
|
+
try {
|
|
635
|
+
return { ok: true, parsed: JSON.parse(text) };
|
|
636
|
+
} catch (err) {
|
|
637
|
+
return {
|
|
638
|
+
ok: false,
|
|
639
|
+
violation: { syntax: "JSON", detail: messageOf(err), position: strictPosition(err, raw, had ? 1 : 0) }
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
function classifyJson(raw, addr, transform, strict) {
|
|
644
|
+
if (raw.trim().length === 0) return { kind: "absent" };
|
|
645
|
+
const { had } = stripBom(raw);
|
|
646
|
+
const shift = had ? 1 : 0;
|
|
647
|
+
let parsed;
|
|
648
|
+
let unloadable = null;
|
|
649
|
+
if (strict) {
|
|
650
|
+
const client = readStrictJson(raw);
|
|
651
|
+
if (client.ok) {
|
|
652
|
+
parsed = client.parsed;
|
|
653
|
+
} else {
|
|
654
|
+
let lenient;
|
|
655
|
+
try {
|
|
656
|
+
lenient = parseJsonc(raw);
|
|
657
|
+
} catch (err) {
|
|
658
|
+
return {
|
|
659
|
+
kind: "malformed",
|
|
660
|
+
syntax: "JSON",
|
|
661
|
+
reason: "syntax",
|
|
662
|
+
detail: messageOf(err),
|
|
663
|
+
position: jsoncPosition(raw, shift)
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
parsed = lenient;
|
|
667
|
+
unloadable = client.violation;
|
|
668
|
+
}
|
|
669
|
+
} else {
|
|
670
|
+
try {
|
|
671
|
+
parsed = parseJsonc(raw);
|
|
672
|
+
} catch (err) {
|
|
673
|
+
return {
|
|
674
|
+
kind: "malformed",
|
|
675
|
+
syntax: "JSON",
|
|
676
|
+
reason: "syntax",
|
|
677
|
+
detail: messageOf(err),
|
|
678
|
+
position: jsoncPosition(raw, shift)
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (!isRecord(parsed)) {
|
|
683
|
+
return { kind: "malformed", syntax: "JSON", reason: "root", detail: describeValueShape(parsed), position: null };
|
|
684
|
+
}
|
|
685
|
+
const blocked = blockedSegment(parsed, addr.containerPath);
|
|
686
|
+
if (blocked !== null) return { kind: "blocked", ...blocked, unloadable };
|
|
687
|
+
const container = containerAt(parsed, addr.containerPath);
|
|
688
|
+
if (container === null) return { kind: "ok", containerPresent: false, entries: [], unloadable };
|
|
689
|
+
return { kind: "ok", containerPresent: true, entries: entriesOf(container, transform), unloadable };
|
|
690
|
+
}
|
|
691
|
+
function upsertJson(raw, addr, key, entry) {
|
|
692
|
+
if (raw === null || raw.trim().length === 0) {
|
|
693
|
+
return `${JSON.stringify(buildFreshConfig(addr.containerPath, key, entry), null, 2)}
|
|
694
|
+
`;
|
|
695
|
+
}
|
|
696
|
+
return editJsoncEntry(raw, [...addr.containerPath], key, entry);
|
|
697
|
+
}
|
|
698
|
+
function removeJson(raw, addr, key) {
|
|
699
|
+
let parsed;
|
|
700
|
+
try {
|
|
701
|
+
parsed = parseJsonc(raw);
|
|
702
|
+
} catch {
|
|
703
|
+
return raw;
|
|
704
|
+
}
|
|
705
|
+
if (!isRecord(parsed)) return raw;
|
|
706
|
+
const container = containerAt(parsed, addr.containerPath);
|
|
707
|
+
if (container === null || !Object.hasOwn(container, key)) return raw;
|
|
708
|
+
return removeJsoncEntry(raw, [...addr.containerPath], key);
|
|
709
|
+
}
|
|
710
|
+
function repairJson(raw, _addr, blockedPath) {
|
|
711
|
+
if (blockedPath.length === 0) throw new Error("repairContainer: an empty key path cannot be repaired");
|
|
712
|
+
return editJsoncEntry(raw, blockedPath.slice(0, -1), blockedPath[blockedPath.length - 1], {});
|
|
713
|
+
}
|
|
714
|
+
function previewJson(addr, key, entry, _creating) {
|
|
715
|
+
return JSON.stringify(buildFreshConfig(addr.containerPath, key, entry), null, 2);
|
|
716
|
+
}
|
|
717
|
+
function canonJson(raw, addr, opts) {
|
|
718
|
+
const parsed = parseJsonc(raw);
|
|
719
|
+
if (!isRecord(parsed)) throw new Error("client-config-json: canon needs a JSON object");
|
|
720
|
+
const clone = JSON.parse(JSON.stringify(parsed));
|
|
721
|
+
const segments = addr.containerPath;
|
|
722
|
+
const leaf = segments[segments.length - 1];
|
|
723
|
+
if (opts?.dropContainer === true && leaf !== void 0) {
|
|
724
|
+
let holder = clone;
|
|
725
|
+
let cut = 0;
|
|
726
|
+
for (let i = 0; i < segments.length; i++) {
|
|
727
|
+
cut = i;
|
|
728
|
+
const value = holder[segments[i]];
|
|
729
|
+
if (!isRecord(value) || i === segments.length - 1) break;
|
|
730
|
+
holder = value;
|
|
731
|
+
}
|
|
732
|
+
delete holder[segments[cut]];
|
|
733
|
+
for (let depth = cut; depth > 0; depth--) {
|
|
734
|
+
const above = containerAt(clone, segments.slice(0, depth - 1));
|
|
735
|
+
const key = segments[depth - 1];
|
|
736
|
+
const value = above === null ? void 0 : above[key];
|
|
737
|
+
if (above === null || !isRecord(value) || Object.keys(value).length > 0) break;
|
|
738
|
+
delete above[key];
|
|
739
|
+
}
|
|
740
|
+
} else if (leaf !== void 0) {
|
|
741
|
+
const parent = containerAt(clone, segments.slice(0, -1));
|
|
742
|
+
const container = parent === null ? void 0 : parent[leaf];
|
|
743
|
+
if (isRecord(container)) {
|
|
744
|
+
for (const key of opts?.drop ?? []) delete container[key];
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return canonicalJson(clone);
|
|
748
|
+
}
|
|
749
|
+
var JSONC_ADAPTER = {
|
|
750
|
+
syntax: "JSON",
|
|
751
|
+
classify: (raw, addr, transform) => classifyJson(raw, addr, transform, false),
|
|
752
|
+
upsert: upsertJson,
|
|
753
|
+
remove: removeJson,
|
|
754
|
+
repairContainer: repairJson,
|
|
755
|
+
renderPreview: previewJson,
|
|
756
|
+
describeLocation: describeJsonLocation,
|
|
757
|
+
canon: canonJson
|
|
758
|
+
};
|
|
759
|
+
var JSON_ADAPTER = {
|
|
760
|
+
syntax: "JSON",
|
|
761
|
+
classify: (raw, addr, transform) => classifyJson(raw, addr, transform, true),
|
|
762
|
+
upsert: upsertJson,
|
|
763
|
+
remove: removeJson,
|
|
764
|
+
repairContainer: repairJson,
|
|
765
|
+
renderPreview: previewJson,
|
|
766
|
+
describeLocation: describeJsonLocation,
|
|
767
|
+
canon: canonJson
|
|
768
|
+
};
|
|
769
|
+
|
|
770
|
+
// src/install-target-model.ts
|
|
771
|
+
import { homedir } from "os";
|
|
772
|
+
import { join } from "path";
|
|
773
|
+
var CURRENT_OS = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux";
|
|
774
|
+
var ENTRY_NAME = "mcp";
|
|
775
|
+
var LEGACY_ENTRY_NAMES = ["mcp.hosting", "mcph", "yaw-mcp"];
|
|
776
|
+
function defineTarget(t) {
|
|
777
|
+
return t;
|
|
778
|
+
}
|
|
779
|
+
function resolveAppDataDir(opts) {
|
|
780
|
+
if (opts.appData !== void 0 && opts.appData.length > 0) return opts.appData;
|
|
781
|
+
if (opts.home !== void 0) return join(opts.home, "AppData", "Roaming");
|
|
782
|
+
const env = opts.env ?? process.env;
|
|
783
|
+
const fromEnv = env.APPDATA;
|
|
784
|
+
return fromEnv && fromEnv.length > 0 ? fromEnv : join(homedir(), "AppData", "Roaming");
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// src/client-config.ts
|
|
788
|
+
function syntaxNameFor(format) {
|
|
789
|
+
return format === "toml" ? "TOML" : "JSON";
|
|
790
|
+
}
|
|
791
|
+
function effectiveConfigFormat(shape, scope) {
|
|
792
|
+
return scope?.strictJson === true && shape.format === "jsonc" ? "json" : shape.format;
|
|
793
|
+
}
|
|
794
|
+
function selectSites(sites, exists = existsSync) {
|
|
795
|
+
return sites.filter((site) => site.detectDir === null || exists(site.detectDir));
|
|
796
|
+
}
|
|
797
|
+
function addressOf(site) {
|
|
798
|
+
return { format: site.format, containerPath: site.resolved.containerPath };
|
|
799
|
+
}
|
|
800
|
+
function positionAt(raw, offset) {
|
|
801
|
+
const clamped = Math.max(0, Math.min(offset, raw.length));
|
|
802
|
+
let line = 1;
|
|
803
|
+
let lineStart = 0;
|
|
804
|
+
for (let i = 0; i < clamped; i++) {
|
|
805
|
+
if (raw[i] === "\n") {
|
|
806
|
+
line++;
|
|
807
|
+
lineStart = i + 1;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
return { offset: clamped, line, column: clamped - lineStart + 1 };
|
|
811
|
+
}
|
|
812
|
+
function unloadableConfigProblem(v) {
|
|
813
|
+
return `has comments or trailing commas, which its client reads as invalid ${v.syntax} (${v.detail}), so no server in it is loading`;
|
|
814
|
+
}
|
|
815
|
+
function unloadableConfigFix(then) {
|
|
816
|
+
return `remove the comments and trailing commas, or move the file aside, then ${then}`;
|
|
817
|
+
}
|
|
818
|
+
function isRecord2(value) {
|
|
819
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
820
|
+
}
|
|
821
|
+
function normalizeEntry(stored, transform) {
|
|
822
|
+
return transform?.normalize === void 0 ? stored : transform.normalize(stored);
|
|
823
|
+
}
|
|
824
|
+
function launchOf(value) {
|
|
825
|
+
if (!isRecord2(value)) return null;
|
|
826
|
+
const record = value;
|
|
827
|
+
if (typeof record.command !== "string") return null;
|
|
828
|
+
const args = Array.isArray(record.args) ? record.args.filter((a) => typeof a === "string") : [];
|
|
829
|
+
const env = stringMap(record.env);
|
|
830
|
+
return env === void 0 ? { command: record.command, args } : { command: record.command, args, env };
|
|
831
|
+
}
|
|
832
|
+
function stringMap(value) {
|
|
833
|
+
if (!isRecord2(value)) return void 0;
|
|
834
|
+
const kept = {};
|
|
835
|
+
for (const [key, v] of Object.entries(value)) {
|
|
836
|
+
if (typeof v === "string") kept[key] = v;
|
|
837
|
+
}
|
|
838
|
+
return Object.keys(kept).length > 0 ? kept : void 0;
|
|
839
|
+
}
|
|
840
|
+
function carryableEnvOf(stored) {
|
|
841
|
+
if (!isRecord2(stored)) return void 0;
|
|
842
|
+
return stringMap(stored.env);
|
|
843
|
+
}
|
|
844
|
+
function carriedFieldsOf(stored, transform) {
|
|
845
|
+
if (transform?.carry === void 0) return {};
|
|
846
|
+
if (!isRecord2(stored)) return {};
|
|
847
|
+
const carried = { ...transform.carry(stored) };
|
|
848
|
+
delete carried.env;
|
|
849
|
+
return carried;
|
|
850
|
+
}
|
|
851
|
+
function importViewOf(stored, transform) {
|
|
852
|
+
if (transform?.forImport !== void 0) return transform.forImport(stored);
|
|
853
|
+
const normalized = normalizeEntry(stored, transform);
|
|
854
|
+
return { entry: isRecord2(normalized) ? normalized : stored };
|
|
855
|
+
}
|
|
856
|
+
function composeEntry(opts) {
|
|
857
|
+
const extra = opts.transform?.extraFields?.({ os: opts.os, purpose: opts.purpose }) ?? {};
|
|
858
|
+
const out = { ...opts.carried, ...extra, ...opts.base };
|
|
859
|
+
if (out.env === void 0 && opts.env !== void 0 && Object.keys(opts.env).length > 0) out.env = opts.env;
|
|
860
|
+
return out;
|
|
861
|
+
}
|
|
862
|
+
function reloadDoneClause(reload, label) {
|
|
863
|
+
switch (reload) {
|
|
864
|
+
case "live":
|
|
865
|
+
return `${label} starts the server when the file is saved -- no restart needed.`;
|
|
866
|
+
case "reload-window":
|
|
867
|
+
return "Reload the IDE window to pick up the new MCP server.";
|
|
868
|
+
case "next-session":
|
|
869
|
+
return `${label} picks the entry up in its next session.`;
|
|
870
|
+
default:
|
|
871
|
+
return "Restart it to pick up the new MCP server.";
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
function reloadRemovalClause(reload, label) {
|
|
875
|
+
return reload === "next-session" ? `${label} drops the server in its next session.` : "Restart it to drop the server.";
|
|
876
|
+
}
|
|
877
|
+
var MissingConfigAdapterError = class extends Error {
|
|
878
|
+
format;
|
|
879
|
+
constructor(format) {
|
|
880
|
+
const syntax = syntaxNameFor(format);
|
|
881
|
+
super(
|
|
882
|
+
`no config adapter for "${format}" -- this build of yaw-mcp cannot read or write ${syntax} client configs. Register one with registerConfigAdapter("${format}", ...) before using a ${format} target.`
|
|
883
|
+
);
|
|
884
|
+
this.name = "MissingConfigAdapterError";
|
|
885
|
+
this.format = format;
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
var REGISTERED = /* @__PURE__ */ new Map();
|
|
889
|
+
function builtInAdapter(format) {
|
|
890
|
+
if (format === "json") return JSON_ADAPTER;
|
|
891
|
+
if (format === "jsonc") return JSONC_ADAPTER;
|
|
892
|
+
return void 0;
|
|
893
|
+
}
|
|
894
|
+
function registerConfigAdapter(format, adapter) {
|
|
895
|
+
if (builtInAdapter(format) !== void 0 || REGISTERED.has(format)) {
|
|
896
|
+
throw new Error(`a config adapter for "${format}" is already registered`);
|
|
897
|
+
}
|
|
898
|
+
REGISTERED.set(format, adapter);
|
|
899
|
+
}
|
|
900
|
+
function adapterFor(format) {
|
|
901
|
+
const adapter = builtInAdapter(format) ?? REGISTERED.get(format);
|
|
902
|
+
if (adapter === void 0) throw new MissingConfigAdapterError(format);
|
|
903
|
+
return adapter;
|
|
904
|
+
}
|
|
905
|
+
function canonicalJson(value) {
|
|
906
|
+
if (typeof value === "bigint") return value.toString();
|
|
907
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
908
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
909
|
+
const record = value;
|
|
910
|
+
const keys = Object.keys(record).filter((key) => record[key] !== void 0).sort();
|
|
911
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
|
|
912
|
+
}
|
|
913
|
+
function describeValueShape(value) {
|
|
914
|
+
if (value === null) return "null";
|
|
915
|
+
if (Array.isArray(value)) return value.length === 0 ? "an empty array" : `an array of ${value.length}`;
|
|
916
|
+
return `a ${typeof value}`;
|
|
917
|
+
}
|
|
918
|
+
function terminateWithNewline(text) {
|
|
919
|
+
return text.endsWith("\n") ? text : `${text}
|
|
920
|
+
`;
|
|
921
|
+
}
|
|
922
|
+
function findLegacyKey(keys) {
|
|
923
|
+
return LEGACY_ENTRY_NAMES.find((name) => keys.includes(name)) ?? null;
|
|
924
|
+
}
|
|
925
|
+
function classifyClientConfig(raw, site, opts = {}) {
|
|
926
|
+
const adapter = adapterFor(site.format);
|
|
927
|
+
const candidates = opts.containerPaths !== void 0 && opts.containerPaths.length > 0 ? opts.containerPaths : [site.resolved.containerPath];
|
|
928
|
+
const addressAt = (index) => ({ format: site.format, containerPath: candidates[index] });
|
|
929
|
+
if (raw === null) return makeView({ kind: "absent" }, null, addressAt(0), 0, adapter, opts);
|
|
930
|
+
let chosen = 0;
|
|
931
|
+
let read = adapter.classify(raw, addressAt(0), opts.transform);
|
|
932
|
+
if (candidates.length > 1) {
|
|
933
|
+
let bestWired = isWired(read);
|
|
934
|
+
let bestPresent = read.kind === "ok" && read.containerPresent;
|
|
935
|
+
for (let i = 1; !bestWired && i < candidates.length; i++) {
|
|
936
|
+
const other = adapter.classify(raw, addressAt(i), opts.transform);
|
|
937
|
+
const wired = isWired(other);
|
|
938
|
+
const present = other.kind === "ok" && other.containerPresent;
|
|
939
|
+
if (wired || present && !bestPresent) {
|
|
940
|
+
chosen = i;
|
|
941
|
+
read = other;
|
|
942
|
+
bestWired = wired;
|
|
943
|
+
bestPresent = present;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
return makeView(read, raw, addressAt(chosen), chosen, adapter, opts);
|
|
948
|
+
}
|
|
949
|
+
function isWired(read) {
|
|
950
|
+
if (read.kind !== "ok") return false;
|
|
951
|
+
const keys = read.entries.map((e) => e.key);
|
|
952
|
+
return keys.includes(ENTRY_NAME) || findLegacyKey(keys) !== null;
|
|
953
|
+
}
|
|
954
|
+
function makeView(read, raw, address, addressIndex, adapter, opts) {
|
|
955
|
+
const entries = read.kind === "ok" ? read.entries : [];
|
|
956
|
+
const at = (key) => entries.find((e) => e.key === (key ?? ENTRY_NAME));
|
|
957
|
+
return {
|
|
958
|
+
read,
|
|
959
|
+
raw,
|
|
960
|
+
address,
|
|
961
|
+
addressIndex,
|
|
962
|
+
adapter,
|
|
963
|
+
entries: () => entries,
|
|
964
|
+
entry: (key) => at(key),
|
|
965
|
+
normalized: (key) => {
|
|
966
|
+
const found = at(key);
|
|
967
|
+
return found === void 0 ? void 0 : normalizeEntry(found.value, opts.transform);
|
|
968
|
+
},
|
|
969
|
+
legacyKey: () => findLegacyKey(entries.map((e) => e.key)),
|
|
970
|
+
otherServerKeys: () => {
|
|
971
|
+
const skip = /* @__PURE__ */ new Set([ENTRY_NAME, ...LEGACY_ENTRY_NAMES]);
|
|
972
|
+
return entries.filter((e) => !skip.has(e.key) && typeof e.value === "object" && e.value !== null && !Array.isArray(e.value)).map((e) => e.key);
|
|
973
|
+
},
|
|
974
|
+
count: () => entries.length,
|
|
975
|
+
carryableEnv: (key) => carryableEnvOf(at(key)?.value),
|
|
976
|
+
carried: (key) => carriedFieldsOf(at(key)?.value, opts.transform),
|
|
977
|
+
unloadable: () => read.kind === "ok" || read.kind === "blocked" ? read.unloadable : null
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
function containerKeysAt(raw, site, prefix) {
|
|
981
|
+
if (raw === null || prefix.length === 0) return [];
|
|
982
|
+
const read = classifyClientConfig(raw, siteAt(site, prefix)).read;
|
|
983
|
+
return read.kind === "ok" ? read.entries.map((entry) => entry.key) : [];
|
|
984
|
+
}
|
|
985
|
+
function siteAt(site, containerPath) {
|
|
986
|
+
return { ...site, resolved: { ...site.resolved, containerPath: [...containerPath] } };
|
|
987
|
+
}
|
|
988
|
+
async function readClientConfigFile(site, opts = {}) {
|
|
989
|
+
const load = opts.readFile ?? ((path2) => readFile(path2, "utf8"));
|
|
990
|
+
let raw;
|
|
991
|
+
try {
|
|
992
|
+
raw = await load(site.resolved.absolute);
|
|
993
|
+
} catch (err) {
|
|
994
|
+
const code = err?.code;
|
|
995
|
+
if (code === "ENOENT") return classifyClientConfig(null, site, opts);
|
|
996
|
+
const read = {
|
|
997
|
+
kind: "unreadable",
|
|
998
|
+
code: typeof code === "string" ? code : null,
|
|
999
|
+
message: err instanceof Error ? err.message : String(err)
|
|
1000
|
+
};
|
|
1001
|
+
return makeView(read, null, addressOf(site), 0, adapterFor(site.format), opts);
|
|
1002
|
+
}
|
|
1003
|
+
return classifyClientConfig(raw, site, opts);
|
|
1004
|
+
}
|
|
1005
|
+
var ClientConfigWriteError = class extends Error {
|
|
1006
|
+
constructor(message) {
|
|
1007
|
+
super(message);
|
|
1008
|
+
this.name = "ClientConfigWriteError";
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
function applyClientConfigEdits(view, edits, site) {
|
|
1012
|
+
if (edits.length === 0) throw new ClientConfigWriteError("applyClientConfigEdits: no edits to apply");
|
|
1013
|
+
const where = site === void 0 ? "the config file" : site.resolved.absolute;
|
|
1014
|
+
const { adapter, address, read } = view;
|
|
1015
|
+
const writes = edits.some((edit) => edit.op !== "remove");
|
|
1016
|
+
if (read.kind === "absent") {
|
|
1017
|
+
const only = edits[0];
|
|
1018
|
+
if (edits.length !== 1 || only.op !== "upsert") {
|
|
1019
|
+
throw new ClientConfigWriteError(
|
|
1020
|
+
`${where} does not exist, so there is nothing in it to ${only.op === "remove" ? "remove" : "repair"}`
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
let fresh;
|
|
1024
|
+
try {
|
|
1025
|
+
fresh = adapter.upsert(null, address, only.key, only.entry);
|
|
1026
|
+
} catch (err) {
|
|
1027
|
+
throw new ClientConfigWriteError(
|
|
1028
|
+
`${where} could not be created (${err instanceof Error ? err.message : String(err)})`
|
|
1029
|
+
);
|
|
1030
|
+
}
|
|
1031
|
+
verifyEdits(adapter, address, null, fresh, edits, where, view);
|
|
1032
|
+
return fresh;
|
|
1033
|
+
}
|
|
1034
|
+
if (read.kind === "blocked") {
|
|
1035
|
+
const repair = edits.find((edit) => edit.op === "repair" && sameSegments(edit.path, read.path));
|
|
1036
|
+
if (repair === void 0 || !read.reparable || edits[0] !== repair) {
|
|
1037
|
+
throw new ClientConfigWriteError(refusalFor(read, where, edits));
|
|
1038
|
+
}
|
|
1039
|
+
} else if (read.kind !== "ok") {
|
|
1040
|
+
throw new ClientConfigWriteError(refusalFor(read, where, edits));
|
|
1041
|
+
}
|
|
1042
|
+
const unloadable = view.unloadable();
|
|
1043
|
+
if (unloadable !== null && writes) {
|
|
1044
|
+
throw new ClientConfigWriteError(
|
|
1045
|
+
`${where} ${unloadableConfigProblem(unloadable)} -- refusing to write into it; ${unloadableConfigFix("re-run")}`
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
const before = view.raw;
|
|
1049
|
+
if (before === null) throw new ClientConfigWriteError(`${where} was classified without its bytes`);
|
|
1050
|
+
let text = before;
|
|
1051
|
+
try {
|
|
1052
|
+
for (const edit of edits) {
|
|
1053
|
+
if (edit.op === "upsert") text = adapter.upsert(text, address, edit.key, edit.entry);
|
|
1054
|
+
else if (edit.op === "remove") text = adapter.remove(text, address, edit.key);
|
|
1055
|
+
else text = adapter.repairContainer(text, address, edit.path);
|
|
1056
|
+
}
|
|
1057
|
+
} catch (err) {
|
|
1058
|
+
if (err instanceof ClientConfigWriteError) throw err;
|
|
1059
|
+
throw new ClientConfigWriteError(
|
|
1060
|
+
`${where} could not be edited (${err instanceof Error ? err.message : String(err)})`
|
|
1061
|
+
);
|
|
1062
|
+
}
|
|
1063
|
+
verifyEdits(adapter, address, before, text, edits, where, view);
|
|
1064
|
+
return text;
|
|
1065
|
+
}
|
|
1066
|
+
function refusalFor(read, where, edits) {
|
|
1067
|
+
if (read.kind === "unreadable") return `${where} could not be read (${read.message})`;
|
|
1068
|
+
if (read.kind === "malformed") {
|
|
1069
|
+
const at = read.position === null ? "" : ` at line ${read.position.line} column ${read.position.column}`;
|
|
1070
|
+
return read.reason === "root" ? `${where} is not a ${read.syntax} object (it is ${read.detail})` : `${where} is not valid ${read.syntax}${at} (${read.detail})`;
|
|
1071
|
+
}
|
|
1072
|
+
if (read.kind === "unspliceable") {
|
|
1073
|
+
return `the "${read.key}" entry in ${where} is ${read.reason}, so yaw-mcp will not edit it`;
|
|
1074
|
+
}
|
|
1075
|
+
if (read.kind === "blocked") {
|
|
1076
|
+
const key = read.path.join(".");
|
|
1077
|
+
const repaired = edits.some((edit) => edit.op === "repair" && sameSegments(edit.path, read.path));
|
|
1078
|
+
if (repaired && read.reparable) {
|
|
1079
|
+
return `"${key}" in ${where} is ${read.shape}: its repair has to be the FIRST edit, before anything is spliced in`;
|
|
1080
|
+
}
|
|
1081
|
+
return read.reparable ? `"${key}" in ${where} is ${read.shape}, not an object -- it has to be repaired before an entry can be written` : `"${key}" in ${where} is ${read.shape}, not an object -- refusing to overwrite it`;
|
|
1082
|
+
}
|
|
1083
|
+
return `${where} cannot be edited`;
|
|
1084
|
+
}
|
|
1085
|
+
function sameSegments(a, b) {
|
|
1086
|
+
return a.length === b.length && a.every((segment, i) => segment === b[i]);
|
|
1087
|
+
}
|
|
1088
|
+
function verifyEdits(adapter, address, before, after, edits, where, view) {
|
|
1089
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1090
|
+
for (const edit of edits) {
|
|
1091
|
+
if (edit.op !== "repair") touched.add(edit.key);
|
|
1092
|
+
}
|
|
1093
|
+
let reread = adapter.classify(after, address, void 0);
|
|
1094
|
+
if (reread.kind === "absent" && edits.every((edit) => edit.op === "remove")) {
|
|
1095
|
+
reread = { kind: "ok", containerPresent: false, entries: [], unloadable: null };
|
|
1096
|
+
}
|
|
1097
|
+
if (reread.kind !== "ok") {
|
|
1098
|
+
throw new ClientConfigWriteError(
|
|
1099
|
+
`writing to ${where} would have produced a file yaw-mcp cannot read back (${reread.kind}) -- nothing was written`
|
|
1100
|
+
);
|
|
1101
|
+
}
|
|
1102
|
+
if (reread.unloadable !== null && view.unloadable() === null) {
|
|
1103
|
+
throw new ClientConfigWriteError(
|
|
1104
|
+
`writing to ${where} would have produced a file its client cannot load (${reread.unloadable.detail}) -- nothing was written`
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
const keptBefore = view.entries().filter((e) => !touched.has(e.key));
|
|
1108
|
+
const keptAfter = reread.entries.filter((e) => !touched.has(e.key));
|
|
1109
|
+
if (keptAfter.map((e) => e.key).join(" ") !== keptBefore.map((e) => e.key).join(" ")) {
|
|
1110
|
+
throw new ClientConfigWriteError(
|
|
1111
|
+
`writing to ${where} would have changed which other servers it holds, or their order -- nothing was written`
|
|
1112
|
+
);
|
|
1113
|
+
}
|
|
1114
|
+
for (let i = 0; i < keptBefore.length; i++) {
|
|
1115
|
+
if (canonicalJson(keptBefore[i].value) !== canonicalJson(keptAfter[i].value)) {
|
|
1116
|
+
throw new ClientConfigWriteError(
|
|
1117
|
+
`writing to ${where} would have changed the "${keptBefore[i].key}" entry beside it -- nothing was written`
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
for (const edit of edits) {
|
|
1122
|
+
if (edit.op === "upsert") {
|
|
1123
|
+
const written = reread.entries.find((e) => e.key === edit.key);
|
|
1124
|
+
if (written === void 0 || canonicalJson(written.value) !== canonicalJson(edit.entry)) {
|
|
1125
|
+
throw new ClientConfigWriteError(
|
|
1126
|
+
`the "${edit.key}" entry did not read back from ${where} as it was written -- nothing was written`
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
} else if (edit.op === "remove" && reread.entries.some((e) => e.key === edit.key)) {
|
|
1130
|
+
throw new ClientConfigWriteError(
|
|
1131
|
+
`the "${edit.key}" entry is still in ${where} after removing it -- nothing was written`
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
if (before !== null) {
|
|
1136
|
+
const containerChanged = edits.some((edit) => edit.op === "repair") || view.read.kind === "ok" && !view.read.containerPresent;
|
|
1137
|
+
const opts = containerChanged ? { dropContainer: true } : { drop: [...touched] };
|
|
1138
|
+
if (adapter.canon(before, address, opts) !== adapter.canon(after, address, opts)) {
|
|
1139
|
+
throw new ClientConfigWriteError(
|
|
1140
|
+
`writing to ${where} would have changed other settings in the file -- nothing was written`
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
function readClientEnv(env = process.env) {
|
|
1146
|
+
const value = (name) => {
|
|
1147
|
+
const raw = env[name];
|
|
1148
|
+
return raw !== void 0 && raw.length > 0 ? raw : void 0;
|
|
1149
|
+
};
|
|
1150
|
+
const out = {};
|
|
1151
|
+
const appData = value("APPDATA");
|
|
1152
|
+
if (appData !== void 0) out.appData = appData;
|
|
1153
|
+
const claudeConfigDir = value("CLAUDE_CONFIG_DIR");
|
|
1154
|
+
if (claudeConfigDir !== void 0) out.claudeConfigDir = claudeConfigDir;
|
|
1155
|
+
const clineDataDir = value("CLINE_DATA_DIR");
|
|
1156
|
+
if (clineDataDir !== void 0) out.clineDataDir = clineDataDir;
|
|
1157
|
+
const clineDir = value("CLINE_DIR");
|
|
1158
|
+
if (clineDir !== void 0) out.clineDir = clineDir;
|
|
1159
|
+
const clineMcpSettingsPath = value("CLINE_MCP_SETTINGS_PATH");
|
|
1160
|
+
if (clineMcpSettingsPath !== void 0) out.clineMcpSettingsPath = clineMcpSettingsPath;
|
|
1161
|
+
const codexHome = value("CODEX_HOME");
|
|
1162
|
+
if (codexHome !== void 0) out.codexHome = codexHome;
|
|
1163
|
+
const continueGlobalDir2 = value("CONTINUE_GLOBAL_DIR");
|
|
1164
|
+
if (continueGlobalDir2 !== void 0) out.continueGlobalDir = continueGlobalDir2;
|
|
1165
|
+
const typedCliBundle2 = value("TYPED_CLI_BUNDLE");
|
|
1166
|
+
if (typedCliBundle2 !== void 0) out.typedCliBundle = typedCliBundle2;
|
|
1167
|
+
const xdgConfigHome = value("XDG_CONFIG_HOME");
|
|
1168
|
+
if (xdgConfigHome !== void 0) out.xdgConfigHome = xdgConfigHome;
|
|
1169
|
+
const yawMode = value("YAW_MODE");
|
|
1170
|
+
if (yawMode !== void 0) out.yawMode = yawMode;
|
|
1171
|
+
return out;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// src/target-cline.ts
|
|
1175
|
+
import { join as join2 } from "path";
|
|
1176
|
+
var CLINE_EXTENSION_ID = "saoudrizwan.claude-dev";
|
|
1177
|
+
var SETTINGS_FILE = "cline_mcp_settings.json";
|
|
1178
|
+
var CLINE_HOSTS = [
|
|
1179
|
+
{ id: "vscode", label: "VS Code", dir: "Code" },
|
|
1180
|
+
{ id: "vscode-insiders", label: "VS Code Insiders", dir: "Code - Insiders" },
|
|
1181
|
+
{ id: "vscodium", label: "VSCodium", dir: "VSCodium" },
|
|
1182
|
+
{ id: "cursor", label: "Cursor", dir: "Cursor" },
|
|
1183
|
+
{ id: "windsurf", label: "Windsurf", dir: "Windsurf" }
|
|
1184
|
+
];
|
|
1185
|
+
function displayPath(base, segments) {
|
|
1186
|
+
const sep3 = base.os === "windows" ? "\\" : "/";
|
|
1187
|
+
const head = segments[0] === "~" && base.os === "windows" ? "%USERPROFILE%" : segments[0];
|
|
1188
|
+
return [head, ...segments.slice(1)].join(sep3);
|
|
1189
|
+
}
|
|
1190
|
+
function editorRoot(base, dirName) {
|
|
1191
|
+
if (base.os === "windows") return { dir: join2(base.appData, dirName), display: ["%APPDATA%", dirName] };
|
|
1192
|
+
if (base.os === "macos") {
|
|
1193
|
+
return {
|
|
1194
|
+
dir: join2(base.home, "Library", "Application Support", dirName),
|
|
1195
|
+
display: ["~", "Library", "Application Support", dirName]
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
return { dir: join2(base.home, ".config", dirName), display: ["~", ".config", dirName] };
|
|
1199
|
+
}
|
|
1200
|
+
function sharedSettingsFile(base) {
|
|
1201
|
+
const trimmed = (v) => {
|
|
1202
|
+
const t = v?.trim();
|
|
1203
|
+
return t && t.length > 0 ? t : void 0;
|
|
1204
|
+
};
|
|
1205
|
+
const exact = trimmed(base.env.clineMcpSettingsPath);
|
|
1206
|
+
if (exact) return { absolute: exact, display: exact };
|
|
1207
|
+
const dataDir = trimmed(base.env.clineDataDir);
|
|
1208
|
+
if (dataDir) {
|
|
1209
|
+
const absolute = join2(dataDir, "settings", SETTINGS_FILE);
|
|
1210
|
+
return { absolute, display: absolute };
|
|
1211
|
+
}
|
|
1212
|
+
const clineDir = trimmed(base.env.clineDir);
|
|
1213
|
+
if (clineDir) {
|
|
1214
|
+
const absolute = join2(clineDir, "data", "settings", SETTINGS_FILE);
|
|
1215
|
+
return { absolute, display: absolute };
|
|
1216
|
+
}
|
|
1217
|
+
return {
|
|
1218
|
+
absolute: join2(base.home, ".cline", "data", "settings", SETTINGS_FILE),
|
|
1219
|
+
display: displayPath(base, ["~", ".cline", "data", "settings", SETTINGS_FILE])
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
function clineSites(base) {
|
|
1223
|
+
const shared = sharedSettingsFile(base);
|
|
1224
|
+
const sites = [
|
|
1225
|
+
{
|
|
1226
|
+
id: "shared",
|
|
1227
|
+
label: "shared settings",
|
|
1228
|
+
resolved: { absolute: shared.absolute, display: shared.display, containerPath: ["mcpServers"] },
|
|
1229
|
+
// Unconditional: this is the file the CLI and the newer extension
|
|
1230
|
+
// runtime read, and it is where install creates one if none exists.
|
|
1231
|
+
detectDir: null
|
|
1232
|
+
}
|
|
1233
|
+
];
|
|
1234
|
+
for (const host of CLINE_HOSTS) {
|
|
1235
|
+
const root = editorRoot(base, host.dir);
|
|
1236
|
+
const storage = join2(root.dir, "User", "globalStorage", CLINE_EXTENSION_ID);
|
|
1237
|
+
sites.push({
|
|
1238
|
+
id: host.id,
|
|
1239
|
+
label: host.label,
|
|
1240
|
+
resolved: {
|
|
1241
|
+
absolute: join2(storage, "settings", SETTINGS_FILE),
|
|
1242
|
+
display: displayPath(base, [
|
|
1243
|
+
...root.display,
|
|
1244
|
+
"User",
|
|
1245
|
+
"globalStorage",
|
|
1246
|
+
CLINE_EXTENSION_ID,
|
|
1247
|
+
"settings",
|
|
1248
|
+
SETTINGS_FILE
|
|
1249
|
+
]),
|
|
1250
|
+
containerPath: ["mcpServers"]
|
|
1251
|
+
},
|
|
1252
|
+
// Kept only when the extension has actually run in that editor, which
|
|
1253
|
+
// is what creates its globalStorage directory.
|
|
1254
|
+
detectDir: storage
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
return sites;
|
|
1258
|
+
}
|
|
1259
|
+
function carryClineFields(stored) {
|
|
1260
|
+
const out = {};
|
|
1261
|
+
if (typeof stored.disabled === "boolean") out.disabled = stored.disabled;
|
|
1262
|
+
if (Array.isArray(stored.autoApprove) && stored.autoApprove.every((v) => typeof v === "string")) {
|
|
1263
|
+
out.autoApprove = [...stored.autoApprove];
|
|
1264
|
+
}
|
|
1265
|
+
if (typeof stored.timeout === "number" && Number.isFinite(stored.timeout) && stored.timeout >= 0) {
|
|
1266
|
+
out.timeout = stored.timeout;
|
|
1267
|
+
}
|
|
1268
|
+
if (stored.type === "stdio") out.type = "stdio";
|
|
1269
|
+
return out;
|
|
1270
|
+
}
|
|
1271
|
+
function normalizeClineEntry(stored) {
|
|
1272
|
+
if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return stored;
|
|
1273
|
+
const obj = stored;
|
|
1274
|
+
const transport = obj.transport;
|
|
1275
|
+
if (typeof transport !== "object" || transport === null || Array.isArray(transport)) return stored;
|
|
1276
|
+
const { transport: _dropped, ...rest } = obj;
|
|
1277
|
+
return { ...transport, ...rest };
|
|
1278
|
+
}
|
|
1279
|
+
var CLINE_TARGET = defineTarget({
|
|
1280
|
+
clientId: "cline",
|
|
1281
|
+
label: "Cline",
|
|
1282
|
+
// STRICT: Cline parses this file with JSON.parse, so a comment in it stops
|
|
1283
|
+
// every server in it from loading. The strict adapter refuses a write into
|
|
1284
|
+
// such a file rather than adding a server nothing will read.
|
|
1285
|
+
config: { format: "json", root: "mcpServers" },
|
|
1286
|
+
availableOn: ["macos", "linux", "windows"],
|
|
1287
|
+
// The extension watches the file and reconnects without a restart.
|
|
1288
|
+
reload: "live",
|
|
1289
|
+
entry: {
|
|
1290
|
+
carry: carryClineFields,
|
|
1291
|
+
normalize: normalizeClineEntry
|
|
1292
|
+
},
|
|
1293
|
+
hooks: {
|
|
1294
|
+
// Cline's entries can carry `${env:NAME}`, but there is no inputs block
|
|
1295
|
+
// and no workspace folder to resolve against, so import reports such a
|
|
1296
|
+
// value as unresolved instead of substituting one.
|
|
1297
|
+
importVariables: "cline-env"
|
|
1298
|
+
},
|
|
1299
|
+
notes: "Cline keeps one cline_mcp_settings.json per runtime: ~/.cline/data/settings/ for the Cline CLI and the VS Code extension's newer runtime, and <editor>/User/globalStorage/saoudrizwan.claude-dev/settings/ for the extension's legacy runtime -- so install writes the first always and each editor copy it finds. The file is strict JSON: no comments, no trailing commas. The Cline extension watches it and reconnects without a restart.",
|
|
1300
|
+
resolvePath: (base) => clineSites(base)[0].resolved,
|
|
1301
|
+
sites: clineSites,
|
|
1302
|
+
scopes: [
|
|
1303
|
+
{
|
|
1304
|
+
scope: "user",
|
|
1305
|
+
label: "User (global)",
|
|
1306
|
+
description: "Every Cline copy on this machine: the shared ~/.cline file and each editor Cline has run in.",
|
|
1307
|
+
requiresProjectDir: false
|
|
1308
|
+
}
|
|
1309
|
+
]
|
|
1310
|
+
});
|
|
1311
|
+
|
|
1312
|
+
// src/target-codex-cli.ts
|
|
1313
|
+
import { isAbsolute, join as join3, resolve } from "path";
|
|
1314
|
+
|
|
1315
|
+
// src/client-config-toml.ts
|
|
1316
|
+
import { parse as parseTomlText, TomlDate, TomlError } from "smol-toml";
|
|
1317
|
+
var TOML_SYNTAX = "TOML";
|
|
1318
|
+
var PARSE_OPTIONS = { integersAsBigInt: "asNeeded" };
|
|
1319
|
+
var TomlConfigError = class extends Error {
|
|
1320
|
+
line;
|
|
1321
|
+
column;
|
|
1322
|
+
reason;
|
|
1323
|
+
detail;
|
|
1324
|
+
constructor(reason, line, column) {
|
|
1325
|
+
const detail = `line ${line}, column ${column}: ${reason}`;
|
|
1326
|
+
super(`not valid TOML (${detail})`);
|
|
1327
|
+
this.name = "TomlConfigError";
|
|
1328
|
+
this.reason = reason;
|
|
1329
|
+
this.line = line;
|
|
1330
|
+
this.column = column;
|
|
1331
|
+
this.detail = detail;
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
var TomlSpliceRefusal = class extends Error {
|
|
1335
|
+
shape;
|
|
1336
|
+
remedy;
|
|
1337
|
+
constructor(subject, shape, remedy) {
|
|
1338
|
+
super(`${subject} is ${shape} -- ${remedy}`);
|
|
1339
|
+
this.name = "TomlSpliceRefusal";
|
|
1340
|
+
this.shape = shape;
|
|
1341
|
+
this.remedy = remedy;
|
|
1342
|
+
}
|
|
1343
|
+
};
|
|
1344
|
+
var TomlVerifyError = class extends Error {
|
|
1345
|
+
constructor(reason) {
|
|
1346
|
+
super(reason);
|
|
1347
|
+
this.name = "TomlVerifyError";
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
var TomlRenderError = class extends Error {
|
|
1351
|
+
constructor(message) {
|
|
1352
|
+
super(message);
|
|
1353
|
+
this.name = "TomlRenderError";
|
|
1354
|
+
}
|
|
1355
|
+
};
|
|
1356
|
+
function bomOffset(text) {
|
|
1357
|
+
return text.charCodeAt(0) === 65279 ? 1 : 0;
|
|
1358
|
+
}
|
|
1359
|
+
function stripBom2(raw) {
|
|
1360
|
+
return raw.slice(bomOffset(raw));
|
|
1361
|
+
}
|
|
1362
|
+
function parseTomlConfig(raw) {
|
|
1363
|
+
try {
|
|
1364
|
+
return parseTomlText(stripBom2(raw), PARSE_OPTIONS);
|
|
1365
|
+
} catch (e) {
|
|
1366
|
+
if (e instanceof TomlError) {
|
|
1367
|
+
const reason = e.message.split("\n")[0].replace(/^Invalid TOML document:\s*/, "");
|
|
1368
|
+
return raiseParse(reason, e.line, e.column);
|
|
1369
|
+
}
|
|
1370
|
+
throw e;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
function raiseParse(reason, line, column) {
|
|
1374
|
+
throw new TomlConfigError(reason, typeof line === "number" ? line : 0, typeof column === "number" ? column : 0);
|
|
1375
|
+
}
|
|
1376
|
+
function isTomlTable(value) {
|
|
1377
|
+
return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype;
|
|
1378
|
+
}
|
|
1379
|
+
function describeTomlShape(value) {
|
|
1380
|
+
if (value === null) return "null";
|
|
1381
|
+
if (Array.isArray(value)) return value.length === 0 ? "an empty array" : `an array of ${value.length}`;
|
|
1382
|
+
if (value instanceof TomlDate) return "a date";
|
|
1383
|
+
if (typeof value === "bigint") return "a number";
|
|
1384
|
+
if (isTomlTable(value)) return "a table";
|
|
1385
|
+
return `a ${typeof value}`;
|
|
1386
|
+
}
|
|
1387
|
+
var isHorizontalSpace2 = (c) => c === " " || c === " ";
|
|
1388
|
+
var isBareKeyChar = (c) => c !== void 0 && /^[A-Za-z0-9_-]$/.test(c);
|
|
1389
|
+
function detectTomlEol(text) {
|
|
1390
|
+
const match = /\r\n|\n|\r/.exec(text);
|
|
1391
|
+
return match ? match[0] : "\n";
|
|
1392
|
+
}
|
|
1393
|
+
function lineEnd(text, from) {
|
|
1394
|
+
let i = from;
|
|
1395
|
+
while (i < text.length && text[i] !== "\n" && text[i] !== "\r") i++;
|
|
1396
|
+
if (text[i] === "\r" && text[i + 1] === "\n") return i + 2;
|
|
1397
|
+
return i < text.length ? i + 1 : i;
|
|
1398
|
+
}
|
|
1399
|
+
function isBlankLine(text, start, end) {
|
|
1400
|
+
for (let i = start; i < end; i++) {
|
|
1401
|
+
const c = text[i];
|
|
1402
|
+
if (c !== " " && c !== " " && c !== "\n" && c !== "\r") return false;
|
|
1403
|
+
}
|
|
1404
|
+
return true;
|
|
1405
|
+
}
|
|
1406
|
+
function isBlankOrCommentLine(text, start, end) {
|
|
1407
|
+
let i = start;
|
|
1408
|
+
while (i < end && isHorizontalSpace2(text[i])) i++;
|
|
1409
|
+
if (i >= end) return true;
|
|
1410
|
+
const c = text[i];
|
|
1411
|
+
return c === "#" || c === "\n" || c === "\r";
|
|
1412
|
+
}
|
|
1413
|
+
function decodeBasicBody(body) {
|
|
1414
|
+
if (!body.includes("\\")) return body;
|
|
1415
|
+
let out = "";
|
|
1416
|
+
for (let i = 0; i < body.length; i++) {
|
|
1417
|
+
const c = body[i];
|
|
1418
|
+
if (c !== "\\") {
|
|
1419
|
+
out += c;
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
const next = body[i + 1];
|
|
1423
|
+
switch (next) {
|
|
1424
|
+
case "b":
|
|
1425
|
+
out += String.fromCharCode(8);
|
|
1426
|
+
i++;
|
|
1427
|
+
break;
|
|
1428
|
+
case "t":
|
|
1429
|
+
out += String.fromCharCode(9);
|
|
1430
|
+
i++;
|
|
1431
|
+
break;
|
|
1432
|
+
case "n":
|
|
1433
|
+
out += String.fromCharCode(10);
|
|
1434
|
+
i++;
|
|
1435
|
+
break;
|
|
1436
|
+
case "f":
|
|
1437
|
+
out += String.fromCharCode(12);
|
|
1438
|
+
i++;
|
|
1439
|
+
break;
|
|
1440
|
+
case "r":
|
|
1441
|
+
out += String.fromCharCode(13);
|
|
1442
|
+
i++;
|
|
1443
|
+
break;
|
|
1444
|
+
case "e":
|
|
1445
|
+
out += String.fromCharCode(27);
|
|
1446
|
+
i++;
|
|
1447
|
+
break;
|
|
1448
|
+
case '"':
|
|
1449
|
+
out += '"';
|
|
1450
|
+
i++;
|
|
1451
|
+
break;
|
|
1452
|
+
case "\\":
|
|
1453
|
+
out += "\\";
|
|
1454
|
+
i++;
|
|
1455
|
+
break;
|
|
1456
|
+
case "x":
|
|
1457
|
+
case "u":
|
|
1458
|
+
case "U": {
|
|
1459
|
+
const width = next === "x" ? 2 : next === "u" ? 4 : 8;
|
|
1460
|
+
const hex = body.slice(i + 2, i + 2 + width);
|
|
1461
|
+
if (hex.length === width && /^[0-9A-Fa-f]+$/.test(hex)) {
|
|
1462
|
+
out += String.fromCodePoint(Number.parseInt(hex, 16));
|
|
1463
|
+
i += 1 + width;
|
|
1464
|
+
} else {
|
|
1465
|
+
out += c;
|
|
1466
|
+
}
|
|
1467
|
+
break;
|
|
1468
|
+
}
|
|
1469
|
+
default:
|
|
1470
|
+
out += c;
|
|
1471
|
+
break;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
return out;
|
|
1475
|
+
}
|
|
1476
|
+
function readKeyPath(text, i) {
|
|
1477
|
+
const path2 = [];
|
|
1478
|
+
let pos = i;
|
|
1479
|
+
for (; ; ) {
|
|
1480
|
+
while (isHorizontalSpace2(text[pos])) pos++;
|
|
1481
|
+
const c = text[pos];
|
|
1482
|
+
if (c === '"') {
|
|
1483
|
+
const body = readQuoted(text, pos, '"');
|
|
1484
|
+
if (body === null) break;
|
|
1485
|
+
path2.push(decodeBasicBody(body.body));
|
|
1486
|
+
pos = body.end;
|
|
1487
|
+
} else if (c === "'") {
|
|
1488
|
+
const body = readQuoted(text, pos, "'");
|
|
1489
|
+
if (body === null) break;
|
|
1490
|
+
path2.push(body.body);
|
|
1491
|
+
pos = body.end;
|
|
1492
|
+
} else if (isBareKeyChar(c)) {
|
|
1493
|
+
let j = pos;
|
|
1494
|
+
while (isBareKeyChar(text[j])) j++;
|
|
1495
|
+
path2.push(text.slice(pos, j));
|
|
1496
|
+
pos = j;
|
|
1497
|
+
} else {
|
|
1498
|
+
break;
|
|
1499
|
+
}
|
|
1500
|
+
let after = pos;
|
|
1501
|
+
while (isHorizontalSpace2(text[after])) after++;
|
|
1502
|
+
if (text[after] === ".") {
|
|
1503
|
+
pos = after + 1;
|
|
1504
|
+
continue;
|
|
1505
|
+
}
|
|
1506
|
+
pos = after;
|
|
1507
|
+
break;
|
|
1508
|
+
}
|
|
1509
|
+
return { path: path2, end: pos };
|
|
1510
|
+
}
|
|
1511
|
+
function readQuoted(text, pos, quote) {
|
|
1512
|
+
let i = pos + 1;
|
|
1513
|
+
let body = "";
|
|
1514
|
+
while (i < text.length) {
|
|
1515
|
+
const c = text[i];
|
|
1516
|
+
if (c === "\n" || c === "\r") return null;
|
|
1517
|
+
if (quote === '"' && c === "\\") {
|
|
1518
|
+
body += c + (text[i + 1] ?? "");
|
|
1519
|
+
i += 2;
|
|
1520
|
+
continue;
|
|
1521
|
+
}
|
|
1522
|
+
if (c === quote) return { body, end: i + 1 };
|
|
1523
|
+
body += c;
|
|
1524
|
+
i++;
|
|
1525
|
+
}
|
|
1526
|
+
return null;
|
|
1527
|
+
}
|
|
1528
|
+
function readHeader(text, pos) {
|
|
1529
|
+
const arrayTable = text[pos + 1] === "[";
|
|
1530
|
+
const read = readKeyPath(text, pos + (arrayTable ? 2 : 1));
|
|
1531
|
+
if (read.path.length === 0) return null;
|
|
1532
|
+
let i = read.end;
|
|
1533
|
+
while (isHorizontalSpace2(text[i])) i++;
|
|
1534
|
+
if (text[i] !== "]") return null;
|
|
1535
|
+
i++;
|
|
1536
|
+
if (arrayTable) {
|
|
1537
|
+
if (text[i] !== "]") return null;
|
|
1538
|
+
i++;
|
|
1539
|
+
}
|
|
1540
|
+
return { keyPath: read.path, arrayTable, end: i };
|
|
1541
|
+
}
|
|
1542
|
+
function scanTomlSections(text) {
|
|
1543
|
+
const sections = [];
|
|
1544
|
+
const assignments = [];
|
|
1545
|
+
const continuedLines = /* @__PURE__ */ new Map();
|
|
1546
|
+
let section = [];
|
|
1547
|
+
let state = "normal";
|
|
1548
|
+
let depth = 0;
|
|
1549
|
+
let pos = bomOffset(text);
|
|
1550
|
+
let lineStart = pos;
|
|
1551
|
+
while (pos < text.length || lineStart < text.length) {
|
|
1552
|
+
const end = lineEnd(text, pos);
|
|
1553
|
+
if (state === "mlBasic" || state === "mlLiteral") continuedLines.set(lineStart, state);
|
|
1554
|
+
else if (depth > 0) continuedLines.set(lineStart, "bracket");
|
|
1555
|
+
if (state === "normal" && depth === 0) {
|
|
1556
|
+
let i = pos;
|
|
1557
|
+
while (isHorizontalSpace2(text[i])) i++;
|
|
1558
|
+
const c = text[i];
|
|
1559
|
+
if (c === "[") {
|
|
1560
|
+
const header = readHeader(text, i);
|
|
1561
|
+
if (header !== null) {
|
|
1562
|
+
sections.push({
|
|
1563
|
+
keyPath: header.keyPath,
|
|
1564
|
+
arrayTable: header.arrayTable,
|
|
1565
|
+
start: lineStart,
|
|
1566
|
+
headerEnd: end,
|
|
1567
|
+
contentEnd: end,
|
|
1568
|
+
end
|
|
1569
|
+
});
|
|
1570
|
+
section = header.keyPath;
|
|
1571
|
+
pos = header.end;
|
|
1572
|
+
}
|
|
1573
|
+
} else if (c !== void 0 && c !== "#" && c !== "\n" && c !== "\r") {
|
|
1574
|
+
const read = readKeyPath(text, i);
|
|
1575
|
+
if (read.path.length > 0) {
|
|
1576
|
+
let eq = read.end;
|
|
1577
|
+
while (isHorizontalSpace2(text[eq])) eq++;
|
|
1578
|
+
if (text[eq] === "=") {
|
|
1579
|
+
let v = eq + 1;
|
|
1580
|
+
while (isHorizontalSpace2(text[v])) v++;
|
|
1581
|
+
assignments.push({
|
|
1582
|
+
section,
|
|
1583
|
+
keyPath: read.path,
|
|
1584
|
+
inlineTable: text[v] === "{",
|
|
1585
|
+
start: lineStart
|
|
1586
|
+
});
|
|
1587
|
+
pos = eq + 1;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
({ state, depth } = scanSpan(text, pos, end, state, depth));
|
|
1593
|
+
lineStart = end;
|
|
1594
|
+
pos = end;
|
|
1595
|
+
if (lineStart >= text.length) break;
|
|
1596
|
+
}
|
|
1597
|
+
for (let s = 0; s < sections.length; s++) {
|
|
1598
|
+
const self = sections[s];
|
|
1599
|
+
self.end = s + 1 < sections.length ? sections[s + 1].start : text.length;
|
|
1600
|
+
let contentEnd = self.end;
|
|
1601
|
+
while (contentEnd > self.headerEnd) {
|
|
1602
|
+
const prevStart = lineStartBefore(text, contentEnd);
|
|
1603
|
+
if (continuedLines.has(prevStart)) break;
|
|
1604
|
+
if (!isBlankOrCommentLine(text, prevStart, contentEnd)) break;
|
|
1605
|
+
contentEnd = prevStart;
|
|
1606
|
+
}
|
|
1607
|
+
self.contentEnd = Math.max(contentEnd, self.headerEnd);
|
|
1608
|
+
}
|
|
1609
|
+
return { sections, assignments, continuedLines, eol: detectTomlEol(text) };
|
|
1610
|
+
}
|
|
1611
|
+
function lineStartBefore(text, end) {
|
|
1612
|
+
let i = end;
|
|
1613
|
+
if (i > 0 && text[i - 1] === "\n") i--;
|
|
1614
|
+
if (i > 0 && text[i - 1] === "\r") i--;
|
|
1615
|
+
while (i > 0 && text[i - 1] !== "\n" && text[i - 1] !== "\r") i--;
|
|
1616
|
+
return i;
|
|
1617
|
+
}
|
|
1618
|
+
function scanSpan(text, from, to, state, depth) {
|
|
1619
|
+
let i = from;
|
|
1620
|
+
while (i < to) {
|
|
1621
|
+
const c = text[i];
|
|
1622
|
+
switch (state) {
|
|
1623
|
+
case "normal":
|
|
1624
|
+
if (c === "#") {
|
|
1625
|
+
i = to;
|
|
1626
|
+
continue;
|
|
1627
|
+
}
|
|
1628
|
+
if (c === '"') {
|
|
1629
|
+
if (text[i + 1] === '"' && text[i + 2] === '"') {
|
|
1630
|
+
state = "mlBasic";
|
|
1631
|
+
i += 3;
|
|
1632
|
+
continue;
|
|
1633
|
+
}
|
|
1634
|
+
state = "basic";
|
|
1635
|
+
i++;
|
|
1636
|
+
continue;
|
|
1637
|
+
}
|
|
1638
|
+
if (c === "'") {
|
|
1639
|
+
if (text[i + 1] === "'" && text[i + 2] === "'") {
|
|
1640
|
+
state = "mlLiteral";
|
|
1641
|
+
i += 3;
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
state = "literal";
|
|
1645
|
+
i++;
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
if (c === "[" || c === "{") depth++;
|
|
1649
|
+
else if (c === "]" || c === "}") depth = Math.max(0, depth - 1);
|
|
1650
|
+
i++;
|
|
1651
|
+
continue;
|
|
1652
|
+
case "basic":
|
|
1653
|
+
if (c === "\\") {
|
|
1654
|
+
i += 2;
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
if (c === '"') state = "normal";
|
|
1658
|
+
i++;
|
|
1659
|
+
continue;
|
|
1660
|
+
case "literal":
|
|
1661
|
+
if (c === "'") state = "normal";
|
|
1662
|
+
i++;
|
|
1663
|
+
continue;
|
|
1664
|
+
case "mlBasic":
|
|
1665
|
+
if (c === "\\") {
|
|
1666
|
+
i += 2;
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
if (c === '"' && text[i + 1] === '"' && text[i + 2] === '"') {
|
|
1670
|
+
i += 3;
|
|
1671
|
+
while (i < to && text[i] === '"') i++;
|
|
1672
|
+
state = "normal";
|
|
1673
|
+
continue;
|
|
1674
|
+
}
|
|
1675
|
+
i++;
|
|
1676
|
+
continue;
|
|
1677
|
+
case "mlLiteral":
|
|
1678
|
+
if (c === "'" && text[i + 1] === "'" && text[i + 2] === "'") {
|
|
1679
|
+
i += 3;
|
|
1680
|
+
while (i < to && text[i] === "'") i++;
|
|
1681
|
+
state = "normal";
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
i++;
|
|
1685
|
+
continue;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
if (state === "basic" || state === "literal") state = "normal";
|
|
1689
|
+
return { state, depth };
|
|
1690
|
+
}
|
|
1691
|
+
var pathStartsWith = (path2, prefix) => prefix.length <= path2.length && prefix.every((seg, i) => path2[i] === seg);
|
|
1692
|
+
var pathEquals = (a, b) => a.length === b.length && a.every((seg, i) => seg === b[i]);
|
|
1693
|
+
function tomlKey(key) {
|
|
1694
|
+
return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
|
|
1695
|
+
}
|
|
1696
|
+
function tomlString(value) {
|
|
1697
|
+
for (let i = 0; i < value.length; i++) {
|
|
1698
|
+
const code = value.charCodeAt(i);
|
|
1699
|
+
if (code >= 55296 && code <= 56319) {
|
|
1700
|
+
const next = value.charCodeAt(i + 1);
|
|
1701
|
+
if (Number.isNaN(next) || next < 56320 || next > 57343) {
|
|
1702
|
+
throw new TomlRenderError(
|
|
1703
|
+
`cannot write a lone surrogate (U+${code.toString(16).toUpperCase()}) into TOML: a TOML string holds Unicode scalar values only -- fix the value, then re-run`
|
|
1704
|
+
);
|
|
1705
|
+
}
|
|
1706
|
+
i++;
|
|
1707
|
+
continue;
|
|
1708
|
+
}
|
|
1709
|
+
if (code >= 56320 && code <= 57343) {
|
|
1710
|
+
throw new TomlRenderError(
|
|
1711
|
+
`cannot write a lone surrogate (U+${code.toString(16).toUpperCase()}) into TOML: a TOML string holds Unicode scalar values only -- fix the value, then re-run`
|
|
1712
|
+
);
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
return JSON.stringify(value).split(String.fromCharCode(127)).join("\\u007F");
|
|
1716
|
+
}
|
|
1717
|
+
var FLOAT_FIELDS = /* @__PURE__ */ new Set(["startup_timeout_sec", "tool_timeout_sec"]);
|
|
1718
|
+
function tomlNumber(value, key) {
|
|
1719
|
+
if (typeof value === "bigint") return value.toString();
|
|
1720
|
+
if (!Number.isFinite(value)) {
|
|
1721
|
+
throw new TomlRenderError(`cannot write ${String(value)} as the "${key}" value: it is not a finite number`);
|
|
1722
|
+
}
|
|
1723
|
+
if (FLOAT_FIELDS.has(key) && Number.isInteger(value)) return `${value}.0`;
|
|
1724
|
+
return String(value);
|
|
1725
|
+
}
|
|
1726
|
+
function tomlValue(value, key) {
|
|
1727
|
+
if (typeof value === "string") return tomlString(value);
|
|
1728
|
+
if (typeof value === "number" || typeof value === "bigint") return tomlNumber(value, key);
|
|
1729
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
1730
|
+
if (Array.isArray(value)) return `[${value.map((item) => tomlArrayItem(item, key)).join(", ")}]`;
|
|
1731
|
+
throw new TomlRenderError(
|
|
1732
|
+
`cannot write the "${key}" field as TOML: ${describeTomlShape(value)} has no spelling this writer produces -- edit it by hand`
|
|
1733
|
+
);
|
|
1734
|
+
}
|
|
1735
|
+
function tomlArrayItem(item, key) {
|
|
1736
|
+
if (isTomlTable(item)) {
|
|
1737
|
+
const pairs = Object.entries(item).filter(([, v]) => v !== void 0);
|
|
1738
|
+
for (const [k, v] of pairs) {
|
|
1739
|
+
if (isTomlTable(v) || Array.isArray(v)) {
|
|
1740
|
+
throw new TomlRenderError(
|
|
1741
|
+
`cannot write the "${key}" field as TOML: its inline table has a nested "${k}" -- edit it by hand`
|
|
1742
|
+
);
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
return `{ ${pairs.map(([k, v]) => `${tomlKey(k)} = ${tomlValue(v, k)}`).join(", ")} }`;
|
|
1746
|
+
}
|
|
1747
|
+
return tomlValue(item, key);
|
|
1748
|
+
}
|
|
1749
|
+
var FIELD_ORDER = [
|
|
1750
|
+
"command",
|
|
1751
|
+
"args",
|
|
1752
|
+
"env",
|
|
1753
|
+
"env_vars",
|
|
1754
|
+
"cwd",
|
|
1755
|
+
"url",
|
|
1756
|
+
"bearer_token_env_var",
|
|
1757
|
+
"http_headers",
|
|
1758
|
+
"env_http_headers",
|
|
1759
|
+
"http_headers_helper",
|
|
1760
|
+
"auth",
|
|
1761
|
+
"enabled",
|
|
1762
|
+
"environment_id",
|
|
1763
|
+
"required",
|
|
1764
|
+
"supports_parallel_tool_calls",
|
|
1765
|
+
"omit_tools_from",
|
|
1766
|
+
"startup_timeout_sec",
|
|
1767
|
+
"tool_timeout_sec",
|
|
1768
|
+
"default_tools_approval_mode",
|
|
1769
|
+
"enabled_tools",
|
|
1770
|
+
"disabled_tools",
|
|
1771
|
+
"scopes",
|
|
1772
|
+
"oauth",
|
|
1773
|
+
"oauth_resource",
|
|
1774
|
+
"tools"
|
|
1775
|
+
];
|
|
1776
|
+
var SUBTABLE_FIELDS = /* @__PURE__ */ new Set(["env", "http_headers", "env_http_headers"]);
|
|
1777
|
+
var byUtf8Bytes = (a, b) => Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
|
|
1778
|
+
function orderedFields(entry) {
|
|
1779
|
+
const present = Object.keys(entry).filter((k) => entry[k] !== void 0);
|
|
1780
|
+
const known = FIELD_ORDER.filter((k) => present.includes(k));
|
|
1781
|
+
const unknown = present.filter((k) => !FIELD_ORDER.includes(k)).sort(byUtf8Bytes);
|
|
1782
|
+
return [...known, ...unknown];
|
|
1783
|
+
}
|
|
1784
|
+
function renderTomlEntry(containerPath, name, entry, eol = "\n") {
|
|
1785
|
+
const header = [...containerPath, name].map(tomlKey).join(".");
|
|
1786
|
+
const fields = orderedFields(entry);
|
|
1787
|
+
const lines = [`[${header}]`];
|
|
1788
|
+
const subTables = [];
|
|
1789
|
+
for (const key of fields) {
|
|
1790
|
+
const value = entry[key];
|
|
1791
|
+
if (SUBTABLE_FIELDS.has(key)) {
|
|
1792
|
+
if (!isTomlTable(value)) {
|
|
1793
|
+
throw new TomlRenderError(
|
|
1794
|
+
`cannot write the "${key}" field as TOML: it is ${describeTomlShape(value)}, not a table of "NAME" = "value" pairs`
|
|
1795
|
+
);
|
|
1796
|
+
}
|
|
1797
|
+
const pairs = Object.entries(value).filter(([, v]) => v !== void 0);
|
|
1798
|
+
if (pairs.length === 0) continue;
|
|
1799
|
+
pairs.sort(([a], [b]) => byUtf8Bytes(a, b));
|
|
1800
|
+
subTables.push(
|
|
1801
|
+
[`[${header}.${tomlKey(key)}]`, ...pairs.map(([k, v]) => `${tomlKey(k)} = ${tomlValue(v, k)}`)].join(eol)
|
|
1802
|
+
);
|
|
1803
|
+
continue;
|
|
1804
|
+
}
|
|
1805
|
+
if (isTomlTable(value)) {
|
|
1806
|
+
throw new TomlRenderError(
|
|
1807
|
+
`cannot write the "${key}" field of the "${name}" entry: only ${[...SUBTABLE_FIELDS].map((k) => `"${k}"`).join(", ")} are written as sub-tables, so rewriting this entry would drop your "${key}" table -- move it to another server or delete it, then re-run`
|
|
1808
|
+
);
|
|
1809
|
+
}
|
|
1810
|
+
lines.push(`${tomlKey(key)} = ${tomlValue(value, key)}`);
|
|
1811
|
+
}
|
|
1812
|
+
return [lines.join(eol), ...subTables].join(`${eol}${eol}`) + eol;
|
|
1813
|
+
}
|
|
1814
|
+
function entryAsWritten(entry) {
|
|
1815
|
+
const out = {};
|
|
1816
|
+
for (const key of Object.keys(entry)) {
|
|
1817
|
+
const value = entry[key];
|
|
1818
|
+
if (value === void 0) continue;
|
|
1819
|
+
if (SUBTABLE_FIELDS.has(key) && isTomlTable(value)) {
|
|
1820
|
+
const pairs = Object.entries(value).filter(([, v]) => v !== void 0);
|
|
1821
|
+
if (pairs.length === 0) continue;
|
|
1822
|
+
out[key] = Object.fromEntries(pairs);
|
|
1823
|
+
continue;
|
|
1824
|
+
}
|
|
1825
|
+
out[key] = value;
|
|
1826
|
+
}
|
|
1827
|
+
return out;
|
|
1828
|
+
}
|
|
1829
|
+
function readTomlConfig(raw, containerPath, entryNames = []) {
|
|
1830
|
+
if (raw.trim() === "") return { kind: "absent" };
|
|
1831
|
+
let parsed;
|
|
1832
|
+
try {
|
|
1833
|
+
parsed = parseTomlConfig(raw);
|
|
1834
|
+
} catch (e) {
|
|
1835
|
+
if (e instanceof TomlConfigError) {
|
|
1836
|
+
return {
|
|
1837
|
+
kind: "malformed",
|
|
1838
|
+
syntax: TOML_SYNTAX,
|
|
1839
|
+
reason: e.reason,
|
|
1840
|
+
line: e.line,
|
|
1841
|
+
column: e.column,
|
|
1842
|
+
detail: e.detail
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
throw e;
|
|
1846
|
+
}
|
|
1847
|
+
if (!isTomlTable(parsed)) {
|
|
1848
|
+
return { kind: "blocked", path: [], shape: describeTomlShape(parsed), reparable: false };
|
|
1849
|
+
}
|
|
1850
|
+
let cursor = parsed;
|
|
1851
|
+
for (let i = 0; i < containerPath.length; i++) {
|
|
1852
|
+
const key = containerPath[i];
|
|
1853
|
+
if (!(key in cursor)) return { kind: "ok", containerPresent: false, entries: [] };
|
|
1854
|
+
const next = cursor[key];
|
|
1855
|
+
if (!isTomlTable(next)) {
|
|
1856
|
+
return {
|
|
1857
|
+
kind: "blocked",
|
|
1858
|
+
path: containerPath.slice(0, i + 1),
|
|
1859
|
+
shape: describeTomlShape(next),
|
|
1860
|
+
reparable: false
|
|
1861
|
+
};
|
|
1862
|
+
}
|
|
1863
|
+
cursor = next;
|
|
1864
|
+
}
|
|
1865
|
+
const scan = scanTomlSections(raw);
|
|
1866
|
+
for (const name of entryNames) {
|
|
1867
|
+
const problem = entryShapeProblem(scan, parsed, containerPath, name);
|
|
1868
|
+
if (problem !== null) {
|
|
1869
|
+
return {
|
|
1870
|
+
kind: "unspliceable",
|
|
1871
|
+
key: name,
|
|
1872
|
+
shape: problem.shape,
|
|
1873
|
+
remedy: problem.remedy,
|
|
1874
|
+
removable: problem.removable
|
|
1875
|
+
};
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
const entries = Object.keys(cursor).map((key) => ({ key, value: cursor[key] }));
|
|
1879
|
+
return { kind: "ok", containerPresent: true, entries };
|
|
1880
|
+
}
|
|
1881
|
+
function tomlEntryFields(read, name) {
|
|
1882
|
+
if (read.kind !== "ok") return void 0;
|
|
1883
|
+
const found = read.entries.find((e) => e.key === name);
|
|
1884
|
+
if (found === void 0 || !isTomlTable(found.value)) return void 0;
|
|
1885
|
+
return found.value;
|
|
1886
|
+
}
|
|
1887
|
+
function tomlEntryNames(read) {
|
|
1888
|
+
return read.kind === "ok" ? read.entries.map((e) => e.key) : [];
|
|
1889
|
+
}
|
|
1890
|
+
function entryShapeProblem(scan, parsed, containerPath, name) {
|
|
1891
|
+
const entryPath = [...containerPath, name];
|
|
1892
|
+
const headerLabel = `[${entryPath.map(tomlKey).join(".")}]`;
|
|
1893
|
+
const containerLabel = containerPath.map(tomlKey).join(".");
|
|
1894
|
+
const own = scan.sections.filter((s) => pathEquals(s.keyPath, entryPath));
|
|
1895
|
+
if (own.some((s) => s.arrayTable)) {
|
|
1896
|
+
return {
|
|
1897
|
+
shape: `an array of tables ([[${entryPath.map(tomlKey).join(".")}]])`,
|
|
1898
|
+
remedy: `Codex reads a server as a single table, so make it one ${headerLabel} table (or remove it), then re-run`,
|
|
1899
|
+
removable: true
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
if (own.length > 0) return null;
|
|
1903
|
+
if (!entryExistsInParsed(parsed, entryPath)) return null;
|
|
1904
|
+
const rootDotted = scan.assignments.some(
|
|
1905
|
+
(a) => a.section.length === 0 && a.keyPath.length > 1 && pathStartsWith(a.keyPath, entryPath)
|
|
1906
|
+
);
|
|
1907
|
+
if (rootDotted) {
|
|
1908
|
+
return {
|
|
1909
|
+
shape: `written as dotted keys at the top level (${entryPath.join(".")}.command = ...)`,
|
|
1910
|
+
remedy: `only a ${headerLabel} table can be rewritten in place -- replace those lines with the table below by hand (or delete them and re-run)`,
|
|
1911
|
+
removable: false
|
|
1912
|
+
};
|
|
1913
|
+
}
|
|
1914
|
+
const inContainer = scan.assignments.filter((a) => pathEquals(a.section, containerPath) && a.keyPath[0] === name);
|
|
1915
|
+
if (inContainer.some((a) => a.keyPath.length > 1)) {
|
|
1916
|
+
return {
|
|
1917
|
+
shape: `written as dotted keys under [${containerLabel}] (${name}.command = ...)`,
|
|
1918
|
+
remedy: `only a ${headerLabel} table can be rewritten in place -- replace those lines with the table below by hand (or delete them and re-run)`,
|
|
1919
|
+
removable: false
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
if (inContainer.some((a) => a.inlineTable)) {
|
|
1923
|
+
return {
|
|
1924
|
+
shape: `an inline table under [${containerLabel}] (${name} = { ... })`,
|
|
1925
|
+
remedy: `only a ${headerLabel} table can be rewritten in place -- replace that line with the table below by hand (or delete it and re-run)`,
|
|
1926
|
+
removable: false
|
|
1927
|
+
};
|
|
1928
|
+
}
|
|
1929
|
+
if (rootContainerIsInline(scan, containerPath)) {
|
|
1930
|
+
return {
|
|
1931
|
+
shape: `inside the inline table ${containerLabel} = { ... }`,
|
|
1932
|
+
remedy: `TOML cannot extend an inline table with a later table, so convert it to ${headerLabel}-style tables by hand, then re-run`,
|
|
1933
|
+
removable: false
|
|
1934
|
+
};
|
|
1935
|
+
}
|
|
1936
|
+
return {
|
|
1937
|
+
shape: `not written as a ${headerLabel} table`,
|
|
1938
|
+
remedy: `only a ${headerLabel} table can be rewritten in place -- replace it with the table below by hand (or delete it and re-run)`,
|
|
1939
|
+
removable: false
|
|
1940
|
+
};
|
|
1941
|
+
}
|
|
1942
|
+
function entryExistsInParsed(parsed, entryPath) {
|
|
1943
|
+
let cursor = parsed;
|
|
1944
|
+
for (const key of entryPath) {
|
|
1945
|
+
if (!isTomlTable(cursor) || !(key in cursor)) return false;
|
|
1946
|
+
cursor = cursor[key];
|
|
1947
|
+
}
|
|
1948
|
+
return true;
|
|
1949
|
+
}
|
|
1950
|
+
function rootContainerIsInline(scan, containerPath) {
|
|
1951
|
+
return scan.assignments.some(
|
|
1952
|
+
(a) => a.section.length === 0 && pathStartsWith(containerPath, a.keyPath) && a.inlineTable
|
|
1953
|
+
);
|
|
1954
|
+
}
|
|
1955
|
+
function applyEdits2(text, edits) {
|
|
1956
|
+
const sorted = [...edits].sort((a, b) => a.start - b.start);
|
|
1957
|
+
let out = "";
|
|
1958
|
+
let cursor = 0;
|
|
1959
|
+
for (const edit of sorted) {
|
|
1960
|
+
if (edit.start < cursor) {
|
|
1961
|
+
throw new TomlVerifyError(
|
|
1962
|
+
`internal error: overlapping TOML edits at offset ${edit.start} -- nothing was written`
|
|
1963
|
+
);
|
|
1964
|
+
}
|
|
1965
|
+
out += text.slice(cursor, edit.start) + edit.text;
|
|
1966
|
+
cursor = edit.end;
|
|
1967
|
+
}
|
|
1968
|
+
return out + text.slice(cursor);
|
|
1969
|
+
}
|
|
1970
|
+
function deleteSectionEdits(text, sections) {
|
|
1971
|
+
const spans = sections.map((s) => ({ start: s.start, end: s.contentEnd })).sort((a, b) => a.start - b.start);
|
|
1972
|
+
const regions = [];
|
|
1973
|
+
for (const span of spans) {
|
|
1974
|
+
const last = regions[regions.length - 1];
|
|
1975
|
+
if (last !== void 0 && (span.start <= last.end || isBlankLine(text, last.end, span.start))) {
|
|
1976
|
+
last.end = Math.max(last.end, span.end);
|
|
1977
|
+
continue;
|
|
1978
|
+
}
|
|
1979
|
+
regions.push({ ...span });
|
|
1980
|
+
}
|
|
1981
|
+
return regions.map(({ start, end }) => {
|
|
1982
|
+
const bom = bomOffset(text);
|
|
1983
|
+
const beforeStart = lineStartBefore(text, start);
|
|
1984
|
+
const beforeIsBlank = start > bom && isBlankLine(text, beforeStart, start);
|
|
1985
|
+
const afterEnd = lineEnd(text, end);
|
|
1986
|
+
const afterIsBlank = end < text.length && isBlankLine(text, end, afterEnd);
|
|
1987
|
+
if (beforeIsBlank && (afterIsBlank || end >= text.length)) return { start: beforeStart, end, text: "" };
|
|
1988
|
+
if (start === bom && afterIsBlank) return { start, end: afterEnd, text: "" };
|
|
1989
|
+
return { start, end, text: "" };
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1992
|
+
function upsertTomlEntry(raw, containerPath, name, entry, options = {}) {
|
|
1993
|
+
const legacyNames = options.replaceLegacy ?? [];
|
|
1994
|
+
if (raw === null || raw.trim() === "") {
|
|
1995
|
+
const fresh = renderTomlEntry(containerPath, name, entry, raw === null ? "\n" : detectTomlEol(raw));
|
|
1996
|
+
verifyTomlSplice("", fresh, containerPath, { upsert: { name, entry } });
|
|
1997
|
+
return fresh;
|
|
1998
|
+
}
|
|
1999
|
+
const parsed = parseTomlConfig(raw);
|
|
2000
|
+
if (!isTomlTable(parsed)) {
|
|
2001
|
+
throw new TomlSpliceRefusal("the document root", "not a TOML table", "fix the file by hand, then re-run");
|
|
2002
|
+
}
|
|
2003
|
+
const container = containerValue(parsed, containerPath);
|
|
2004
|
+
if (container !== void 0 && !isTomlTable(container)) {
|
|
2005
|
+
throw new TomlSpliceRefusal(
|
|
2006
|
+
`"${containerPath.join(".")}"`,
|
|
2007
|
+
`${describeTomlShape(container)}, not a TOML table`,
|
|
2008
|
+
"make it a table (or remove the key), then re-run"
|
|
2009
|
+
);
|
|
2010
|
+
}
|
|
2011
|
+
const scan = scanTomlSections(raw);
|
|
2012
|
+
refuseUnspliceable(scan, parsed, containerPath, [name, ...legacyNames]);
|
|
2013
|
+
const eol = scan.eol;
|
|
2014
|
+
const block = renderTomlEntry(containerPath, name, entry, eol);
|
|
2015
|
+
const entryPath = [...containerPath, name];
|
|
2016
|
+
const edits = [];
|
|
2017
|
+
const ownSections = scan.sections.filter((s) => pathStartsWith(s.keyPath, entryPath));
|
|
2018
|
+
const legacySections = legacyNames.flatMap(
|
|
2019
|
+
(legacy) => scan.sections.filter((s) => pathStartsWith(s.keyPath, [...containerPath, legacy]))
|
|
2020
|
+
);
|
|
2021
|
+
const anchor = ownSections[0] ?? legacySections[0];
|
|
2022
|
+
if (anchor !== void 0) {
|
|
2023
|
+
edits.push({ start: anchor.start, end: anchor.contentEnd, text: block });
|
|
2024
|
+
edits.push(
|
|
2025
|
+
...deleteSectionEdits(
|
|
2026
|
+
raw,
|
|
2027
|
+
[...ownSections, ...legacySections].filter((s) => s !== anchor)
|
|
2028
|
+
)
|
|
2029
|
+
);
|
|
2030
|
+
} else {
|
|
2031
|
+
if (rootContainerIsInline(scan, containerPath)) {
|
|
2032
|
+
throw new TomlSpliceRefusal(
|
|
2033
|
+
`"${containerPath.join(".")}"`,
|
|
2034
|
+
"an inline table, which cannot gain an entry without rewriting it",
|
|
2035
|
+
`convert it to [${[...containerPath, name].map(tomlKey).join(".")}]-style tables by hand, then re-run`
|
|
2036
|
+
);
|
|
2037
|
+
}
|
|
2038
|
+
edits.push(insertEdit(raw, scan, containerPath, block, eol));
|
|
2039
|
+
}
|
|
2040
|
+
const next = applyEdits2(raw, edits);
|
|
2041
|
+
verifyTomlSplice(raw, next, containerPath, { upsert: { name, entry }, removed: legacyNames });
|
|
2042
|
+
return next;
|
|
2043
|
+
}
|
|
2044
|
+
function removeTomlEntry(raw, containerPath, name) {
|
|
2045
|
+
if (raw.trim() === "") return raw;
|
|
2046
|
+
const parsed = parseTomlConfig(raw);
|
|
2047
|
+
if (!isTomlTable(parsed)) return raw;
|
|
2048
|
+
const scan = scanTomlSections(raw);
|
|
2049
|
+
const entryPath = [...containerPath, name];
|
|
2050
|
+
const sections = scan.sections.filter((s) => pathStartsWith(s.keyPath, entryPath));
|
|
2051
|
+
if (sections.length === 0) {
|
|
2052
|
+
refuseUnspliceable(scan, parsed, containerPath, [name]);
|
|
2053
|
+
return raw;
|
|
2054
|
+
}
|
|
2055
|
+
const next = applyEdits2(raw, deleteSectionEdits(raw, sections));
|
|
2056
|
+
verifyTomlSplice(raw, next, containerPath, { removed: [name] });
|
|
2057
|
+
return next;
|
|
2058
|
+
}
|
|
2059
|
+
function containerValue(parsed, containerPath) {
|
|
2060
|
+
let cursor = parsed;
|
|
2061
|
+
for (const key of containerPath) {
|
|
2062
|
+
if (!isTomlTable(cursor)) return void 0;
|
|
2063
|
+
if (!(key in cursor)) return void 0;
|
|
2064
|
+
cursor = cursor[key];
|
|
2065
|
+
}
|
|
2066
|
+
return cursor;
|
|
2067
|
+
}
|
|
2068
|
+
function refuseUnspliceable(scan, parsed, containerPath, names) {
|
|
2069
|
+
for (const name of names) {
|
|
2070
|
+
const problem = entryShapeProblem(scan, parsed, containerPath, name);
|
|
2071
|
+
if (problem !== null) {
|
|
2072
|
+
throw new TomlSpliceRefusal(`the "${name}" entry`, problem.shape, problem.remedy);
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
function insertEdit(text, scan, containerPath, block, eol) {
|
|
2077
|
+
const inContainer = scan.sections.filter((s) => pathStartsWith(s.keyPath, containerPath));
|
|
2078
|
+
const at = inContainer.length > 0 ? inContainer[inContainer.length - 1].contentEnd : text.length;
|
|
2079
|
+
let prefix = "";
|
|
2080
|
+
if (at >= text.length && text.length > 0 && !/\r|\n/.test(text[text.length - 1])) {
|
|
2081
|
+
prefix += eol;
|
|
2082
|
+
}
|
|
2083
|
+
const beforeStart = lineStartBefore(text, at);
|
|
2084
|
+
if (at > 0 && !isBlankLine(text, beforeStart, at)) prefix += eol;
|
|
2085
|
+
let suffix = "";
|
|
2086
|
+
if (at < text.length && !isBlankLine(text, at, lineEnd(text, at))) suffix = eol;
|
|
2087
|
+
return { start: at, end: at, text: prefix + block + suffix };
|
|
2088
|
+
}
|
|
2089
|
+
function canonValue(value) {
|
|
2090
|
+
if (typeof value === "bigint") return { $bigint: value.toString() };
|
|
2091
|
+
if (value instanceof TomlDate) return { $date: value.toISOString() };
|
|
2092
|
+
if (Array.isArray(value)) return value.map(canonValue);
|
|
2093
|
+
if (isTomlTable(value)) {
|
|
2094
|
+
const out = {};
|
|
2095
|
+
for (const key of Object.keys(value).sort()) {
|
|
2096
|
+
if (value[key] === void 0) continue;
|
|
2097
|
+
out[key] = canonValue(value[key]);
|
|
2098
|
+
}
|
|
2099
|
+
return out;
|
|
2100
|
+
}
|
|
2101
|
+
return value;
|
|
2102
|
+
}
|
|
2103
|
+
function canonTomlConfig(raw, containerPath, drop = []) {
|
|
2104
|
+
const parsed = parseTomlConfig(raw);
|
|
2105
|
+
const value = canonValue(parsed);
|
|
2106
|
+
if (!isTomlTable(value)) return JSON.stringify(value);
|
|
2107
|
+
let cursor = value;
|
|
2108
|
+
for (let i = 0; i < containerPath.length; i++) {
|
|
2109
|
+
const key = containerPath[i];
|
|
2110
|
+
const next = cursor[key];
|
|
2111
|
+
if (!isTomlTable(next)) return JSON.stringify(value);
|
|
2112
|
+
if (i === containerPath.length - 1) {
|
|
2113
|
+
for (const name of drop) delete next[name];
|
|
2114
|
+
if (Object.keys(next).length === 0) delete cursor[key];
|
|
2115
|
+
break;
|
|
2116
|
+
}
|
|
2117
|
+
cursor = next;
|
|
2118
|
+
}
|
|
2119
|
+
return JSON.stringify(value);
|
|
2120
|
+
}
|
|
2121
|
+
function containerOrder(raw, containerPath) {
|
|
2122
|
+
const parsed = parseTomlConfig(raw);
|
|
2123
|
+
const container = isTomlTable(parsed) ? containerValue(parsed, containerPath) : void 0;
|
|
2124
|
+
return isTomlTable(container) ? Object.keys(container) : [];
|
|
2125
|
+
}
|
|
2126
|
+
function verifyTomlSplice(before, after, containerPath, expectation = {}) {
|
|
2127
|
+
const touched = [
|
|
2128
|
+
...expectation.upsert === void 0 ? [] : [expectation.upsert.name],
|
|
2129
|
+
...expectation.removed ?? []
|
|
2130
|
+
];
|
|
2131
|
+
let afterRead;
|
|
2132
|
+
try {
|
|
2133
|
+
afterRead = readTomlConfig(after, containerPath);
|
|
2134
|
+
} catch (e) {
|
|
2135
|
+
throw new TomlVerifyError(`the edited text does not parse as TOML (${e.message})`);
|
|
2136
|
+
}
|
|
2137
|
+
if (afterRead.kind === "malformed") {
|
|
2138
|
+
throw new TomlVerifyError(`the edited text does not parse as TOML (${afterRead.detail})`);
|
|
2139
|
+
}
|
|
2140
|
+
if (afterRead.kind === "blocked") {
|
|
2141
|
+
throw new TomlVerifyError(`the edit left "${afterRead.path.join(".")}" as ${afterRead.shape}, not a table`);
|
|
2142
|
+
}
|
|
2143
|
+
const beforeRest = canonTomlConfig(before, containerPath, touched);
|
|
2144
|
+
const afterRest = canonTomlConfig(after, containerPath, touched);
|
|
2145
|
+
if (beforeRest !== afterRest) {
|
|
2146
|
+
throw new TomlVerifyError("the edit changed settings outside the entry it was asked to change");
|
|
2147
|
+
}
|
|
2148
|
+
const beforeOrder = containerOrder(before, containerPath).filter((k) => !touched.includes(k));
|
|
2149
|
+
const afterOrder = containerOrder(after, containerPath).filter((k) => !touched.includes(k));
|
|
2150
|
+
if (beforeOrder.join("\0") !== afterOrder.join("\0")) {
|
|
2151
|
+
throw new TomlVerifyError("the edit reordered the other entries");
|
|
2152
|
+
}
|
|
2153
|
+
for (const name of expectation.removed ?? []) {
|
|
2154
|
+
if (tomlEntryNames(afterRead).includes(name)) {
|
|
2155
|
+
throw new TomlVerifyError(`the edit did not remove the "${name}" entry`);
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
if (expectation.upsert !== void 0) {
|
|
2159
|
+
const stored = tomlEntryFields(afterRead, expectation.upsert.name);
|
|
2160
|
+
if (stored === void 0) {
|
|
2161
|
+
throw new TomlVerifyError(`the edit did not leave a "${expectation.upsert.name}" table behind`);
|
|
2162
|
+
}
|
|
2163
|
+
if (JSON.stringify(canonValue(stored)) !== JSON.stringify(canonValue(entryAsWritten(expectation.upsert.entry)))) {
|
|
2164
|
+
throw new TomlVerifyError(`the "${expectation.upsert.name}" entry did not read back as the value written`);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
// src/target-codex-cli.ts
|
|
2170
|
+
var CONTAINER_KEY = "mcp_servers";
|
|
2171
|
+
function tomlPosition(raw, line, column) {
|
|
2172
|
+
if (line < 1 || column < 1) return null;
|
|
2173
|
+
const bom = raw.charCodeAt(0) === 65279 ? 1 : 0;
|
|
2174
|
+
let offset = bom;
|
|
2175
|
+
for (let seen = 1; seen < line; seen++) {
|
|
2176
|
+
const next = raw.indexOf("\n", offset);
|
|
2177
|
+
if (next === -1) return null;
|
|
2178
|
+
offset = next + 1;
|
|
2179
|
+
}
|
|
2180
|
+
return { offset: Math.min(offset + column - 1, raw.length), line, column };
|
|
2181
|
+
}
|
|
2182
|
+
var SPLICEABLE_NAMES = [ENTRY_NAME];
|
|
2183
|
+
function entryViewsOf(read, transform) {
|
|
2184
|
+
if (read.kind !== "ok") return [];
|
|
2185
|
+
return read.entries.map(({ key, value }) => ({ key, value, launch: launchOf(normalizeEntry(value, transform)) }));
|
|
2186
|
+
}
|
|
2187
|
+
function classifyToml(raw, addr, transform) {
|
|
2188
|
+
const read = readTomlConfig(raw, addr.containerPath, SPLICEABLE_NAMES);
|
|
2189
|
+
switch (read.kind) {
|
|
2190
|
+
case "absent":
|
|
2191
|
+
return { kind: "absent" };
|
|
2192
|
+
case "malformed":
|
|
2193
|
+
return {
|
|
2194
|
+
kind: "malformed",
|
|
2195
|
+
syntax: TOML_SYNTAX,
|
|
2196
|
+
reason: "syntax",
|
|
2197
|
+
detail: read.reason,
|
|
2198
|
+
position: tomlPosition(raw, read.line, read.column)
|
|
2199
|
+
};
|
|
2200
|
+
case "blocked":
|
|
2201
|
+
if (read.path.length === 0) {
|
|
2202
|
+
return { kind: "malformed", syntax: TOML_SYNTAX, reason: "root", detail: read.shape, position: null };
|
|
2203
|
+
}
|
|
2204
|
+
return { kind: "blocked", path: read.path, shape: read.shape, reparable: false, unloadable: null };
|
|
2205
|
+
case "unspliceable":
|
|
2206
|
+
return { kind: "unspliceable", key: read.key, reason: read.shape };
|
|
2207
|
+
default:
|
|
2208
|
+
return {
|
|
2209
|
+
kind: "ok",
|
|
2210
|
+
containerPresent: read.containerPresent,
|
|
2211
|
+
entries: entryViewsOf(read, transform),
|
|
2212
|
+
unloadable: null
|
|
2213
|
+
};
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
function upsertToml(raw, addr, key, entry) {
|
|
2217
|
+
return upsertTomlEntry(raw, addr.containerPath, key, entry);
|
|
2218
|
+
}
|
|
2219
|
+
function removeToml(raw, addr, key) {
|
|
2220
|
+
return removeTomlEntry(raw, addr.containerPath, key);
|
|
2221
|
+
}
|
|
2222
|
+
function repairTomlContainer(_raw, _addr, blockedPath) {
|
|
2223
|
+
throw new Error(
|
|
2224
|
+
`"${blockedPath.join(".")}" is not a TOML table, and a TOML container cannot be repaired in place -- make it a table (or remove the key) by hand, then re-run`
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
function previewToml(addr, key, entry, _creating) {
|
|
2228
|
+
return renderTomlEntry(addr.containerPath, key, entry);
|
|
2229
|
+
}
|
|
2230
|
+
function describeTomlLocation(absolute, _addr) {
|
|
2231
|
+
return absolute;
|
|
2232
|
+
}
|
|
2233
|
+
function canonToml(raw, addr, opts = {}) {
|
|
2234
|
+
const drop = opts.dropContainer === true ? tomlEntryNames(readTomlConfig(raw, addr.containerPath)) : opts.drop ?? [];
|
|
2235
|
+
return canonTomlConfig(raw, addr.containerPath, drop);
|
|
2236
|
+
}
|
|
2237
|
+
var TOML_ADAPTER = {
|
|
2238
|
+
syntax: TOML_SYNTAX,
|
|
2239
|
+
classify: classifyToml,
|
|
2240
|
+
upsert: upsertToml,
|
|
2241
|
+
remove: removeToml,
|
|
2242
|
+
repairContainer: repairTomlContainer,
|
|
2243
|
+
renderPreview: previewToml,
|
|
2244
|
+
describeLocation: describeTomlLocation,
|
|
2245
|
+
canon: canonToml
|
|
2246
|
+
};
|
|
2247
|
+
registerConfigAdapter("toml", TOML_ADAPTER);
|
|
2248
|
+
function resolveCodexPath(base) {
|
|
2249
|
+
const containerPath = [CONTAINER_KEY];
|
|
2250
|
+
if (base.scope === "project") {
|
|
2251
|
+
const sep3 = base.os === "windows" ? "\\" : "/";
|
|
2252
|
+
return {
|
|
2253
|
+
absolute: join3(base.projectDir, ".codex", "config.toml"),
|
|
2254
|
+
display: ["<project folder>", ".codex", "config.toml"].join(sep3),
|
|
2255
|
+
containerPath
|
|
2256
|
+
};
|
|
2257
|
+
}
|
|
2258
|
+
const codexHome = base.env.codexHome;
|
|
2259
|
+
if (codexHome !== void 0 && codexHome.length > 0) {
|
|
2260
|
+
const absolute = join3(isAbsolute(codexHome) ? codexHome : resolve(codexHome), "config.toml");
|
|
2261
|
+
return { absolute, display: absolute, containerPath };
|
|
2262
|
+
}
|
|
2263
|
+
return {
|
|
2264
|
+
absolute: join3(base.home, ".codex", "config.toml"),
|
|
2265
|
+
display: base.os === "windows" ? "%USERPROFILE%\\.codex\\config.toml" : "~/.codex/config.toml",
|
|
2266
|
+
containerPath
|
|
2267
|
+
};
|
|
2268
|
+
}
|
|
2269
|
+
function isEnvVarItem(item) {
|
|
2270
|
+
if (typeof item === "string") return true;
|
|
2271
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) return false;
|
|
2272
|
+
const record = item;
|
|
2273
|
+
if (typeof record.name !== "string") return false;
|
|
2274
|
+
const source = record.source;
|
|
2275
|
+
const sourceOk = source === void 0 || source === "local" || source === "remote";
|
|
2276
|
+
return sourceOk && Object.keys(record).every((key) => key === "name" || key === "source");
|
|
2277
|
+
}
|
|
2278
|
+
function carryCodexFields(stored) {
|
|
2279
|
+
const out = {};
|
|
2280
|
+
if (Array.isArray(stored.env_vars) && stored.env_vars.length > 0 && stored.env_vars.every(isEnvVarItem)) {
|
|
2281
|
+
out.env_vars = [...stored.env_vars];
|
|
2282
|
+
}
|
|
2283
|
+
if (typeof stored.enabled === "boolean") out.enabled = stored.enabled;
|
|
2284
|
+
return out;
|
|
2285
|
+
}
|
|
2286
|
+
function normalizeCodexEntry(stored) {
|
|
2287
|
+
if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return stored;
|
|
2288
|
+
const record = stored;
|
|
2289
|
+
const ms = record.startup_timeout_ms;
|
|
2290
|
+
if (record.startup_timeout_sec !== void 0 || typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) {
|
|
2291
|
+
return stored;
|
|
2292
|
+
}
|
|
2293
|
+
const { startup_timeout_ms: _dropped, ...rest } = record;
|
|
2294
|
+
return { ...rest, startup_timeout_sec: ms / 1e3 };
|
|
2295
|
+
}
|
|
2296
|
+
var IMPORT_DISCARDS = [
|
|
2297
|
+
"env_vars",
|
|
2298
|
+
"cwd",
|
|
2299
|
+
"startup_timeout_sec",
|
|
2300
|
+
"startup_timeout_ms",
|
|
2301
|
+
"tool_timeout_sec",
|
|
2302
|
+
"enabled_tools",
|
|
2303
|
+
"disabled_tools",
|
|
2304
|
+
"default_tools_approval_mode",
|
|
2305
|
+
"bearer_token_env_var",
|
|
2306
|
+
"env_http_headers",
|
|
2307
|
+
"http_headers_helper",
|
|
2308
|
+
"experimental_environment",
|
|
2309
|
+
"environment_id",
|
|
2310
|
+
"required",
|
|
2311
|
+
"supports_parallel_tool_calls",
|
|
2312
|
+
"auth",
|
|
2313
|
+
"oauth",
|
|
2314
|
+
"tools"
|
|
2315
|
+
];
|
|
2316
|
+
function codexImportView(stored) {
|
|
2317
|
+
const entry = {};
|
|
2318
|
+
for (const [key, value] of Object.entries(stored)) {
|
|
2319
|
+
if (IMPORT_DISCARDS.includes(key) || key === "enabled" || key === "http_headers") continue;
|
|
2320
|
+
entry[key] = value;
|
|
2321
|
+
}
|
|
2322
|
+
if (typeof stored.http_headers === "object" && stored.http_headers !== null && !Array.isArray(stored.http_headers)) {
|
|
2323
|
+
entry.headers = stored.http_headers;
|
|
2324
|
+
}
|
|
2325
|
+
const view = { entry };
|
|
2326
|
+
if (stored.enabled === false) view.disabled = true;
|
|
2327
|
+
const discarded = IMPORT_DISCARDS.filter((key) => stored[key] !== void 0);
|
|
2328
|
+
if (discarded.length > 0) view.discardedKeys = discarded;
|
|
2329
|
+
return view;
|
|
2330
|
+
}
|
|
2331
|
+
var CODEX_CLI_TARGET = defineTarget({
|
|
2332
|
+
clientId: "codex-cli",
|
|
2333
|
+
label: "Codex CLI",
|
|
2334
|
+
config: { format: "toml", root: CONTAINER_KEY },
|
|
2335
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2336
|
+
entry: {
|
|
2337
|
+
normalize: normalizeCodexEntry,
|
|
2338
|
+
carry: carryCodexFields,
|
|
2339
|
+
// Written on OUR entry and on a `try` trial alike, and compared like
|
|
2340
|
+
// command and args -- a user who changes it sees it in the drift diff.
|
|
2341
|
+
//
|
|
2342
|
+
// 60, against Codex's documented default of 10 (D1). The install command
|
|
2343
|
+
// in the README is itself `npx -y @yawlabs/mcp@latest`, so Codex's first
|
|
2344
|
+
// launch finds a warm npm cache; 10 seconds is the wrong order of
|
|
2345
|
+
// magnitude for that launch and 60 is not. A genuinely COLD fetch (a fresh
|
|
2346
|
+
// machine, or the first spawn after a new release) can still exceed it --
|
|
2347
|
+
// the remedy there is to re-run the spawn, not a timeout we could pick.
|
|
2348
|
+
extraFields: () => ({ startup_timeout_sec: 60 }),
|
|
2349
|
+
// Bare `npx` on Windows: Codex resolves the `.cmd` shim itself (S2), which
|
|
2350
|
+
// is also what `codex mcp add` writes, so a `cmd /c` entry of ours would
|
|
2351
|
+
// read as drift the moment the user ran that command. It needs Codex
|
|
2352
|
+
// 0.59.0 or newer (S3), which the notes state. A `try` upstream still
|
|
2353
|
+
// takes the shared wrap: that entry names a THIRD-PARTY launcher whose
|
|
2354
|
+
// args have to survive cmd's parse, which is what escapeCmdArg's caret
|
|
2355
|
+
// depths are for, and `buildLaunchEntry`'s upstream branch wraps on
|
|
2356
|
+
// Windows regardless of this field.
|
|
2357
|
+
windowsLaunch: { broker: "bare", upstream: "cmd-wrap" },
|
|
2358
|
+
forImport: codexImportView
|
|
2359
|
+
},
|
|
2360
|
+
notes: "Codex CLI reads MCP servers from config.toml ([mcp_servers.<name>] tables) under CODEX_HOME, which defaults to ~/.codex. A project's .codex/config.toml is read only once Codex trusts the project. Codex starts a server with a cleared environment and forwards an allowlist, so put yaw-mcp settings in the entry's [mcp_servers.mcp.env] table or name them in env_vars. On Windows the entry is bare npx, not cmd /c npx, and needs Codex 0.59.0 or newer, which resolves npx's .cmd shim itself. Restart Codex after editing; `codex mcp list` shows the entry.",
|
|
2361
|
+
resolvePath: resolveCodexPath,
|
|
2362
|
+
scopes: [
|
|
2363
|
+
// User FIRST, like every other multi-scope row: the probe walks this array
|
|
2364
|
+
// in order and it decides `--list` and doctor row order.
|
|
2365
|
+
{
|
|
2366
|
+
scope: "user",
|
|
2367
|
+
label: "User (global)",
|
|
2368
|
+
description: "Private to this machine; applies to every project.",
|
|
2369
|
+
requiresProjectDir: false
|
|
2370
|
+
},
|
|
2371
|
+
{
|
|
2372
|
+
scope: "project",
|
|
2373
|
+
label: "Project",
|
|
2374
|
+
description: "Commit to share with your team; Codex reads it once the project is trusted.",
|
|
2375
|
+
requiresProjectDir: true
|
|
2376
|
+
}
|
|
2377
|
+
]
|
|
2378
|
+
});
|
|
2379
|
+
|
|
2380
|
+
// src/target-continue.ts
|
|
2381
|
+
import { isAbsolute as isAbsolute2, join as join4, resolve as resolve2 } from "path";
|
|
2382
|
+
var CONTINUE_FILE = "yaw-mcp.json";
|
|
2383
|
+
function continueGlobalDir(base) {
|
|
2384
|
+
const raw = base.env.continueGlobalDir;
|
|
2385
|
+
if (raw && raw.length > 0) {
|
|
2386
|
+
const dir = isAbsolute2(raw) ? raw : resolve2(raw);
|
|
2387
|
+
return { dir, display: dir };
|
|
2388
|
+
}
|
|
2389
|
+
return {
|
|
2390
|
+
dir: join4(base.home, ".continue"),
|
|
2391
|
+
display: base.os === "windows" ? "%USERPROFILE%\\.continue" : "~/.continue"
|
|
2392
|
+
};
|
|
2393
|
+
}
|
|
2394
|
+
function resolveContinuePath(base) {
|
|
2395
|
+
const sep3 = base.os === "windows" ? "\\" : "/";
|
|
2396
|
+
if (base.scope === "project") {
|
|
2397
|
+
return {
|
|
2398
|
+
absolute: join4(base.projectDir, ".continue", "mcpServers", CONTINUE_FILE),
|
|
2399
|
+
display: ["<project folder>", ".continue", "mcpServers", CONTINUE_FILE].join(sep3),
|
|
2400
|
+
containerPath: ["mcpServers"]
|
|
2401
|
+
};
|
|
2402
|
+
}
|
|
2403
|
+
const global = continueGlobalDir(base);
|
|
2404
|
+
const absolute = join4(global.dir, "mcpServers", CONTINUE_FILE);
|
|
2405
|
+
const display = global.display === global.dir ? absolute : [global.display, "mcpServers", CONTINUE_FILE].join(sep3);
|
|
2406
|
+
return { absolute, display, containerPath: ["mcpServers"] };
|
|
2407
|
+
}
|
|
2408
|
+
var CONTINUE_TARGET = defineTarget({
|
|
2409
|
+
clientId: "continue",
|
|
2410
|
+
label: "Continue",
|
|
2411
|
+
// DEDICATED: this file is created by install and holds nothing else, unlike
|
|
2412
|
+
// every other row's shared user config.
|
|
2413
|
+
config: { format: "jsonc", root: "mcpServers", ownership: "dedicated" },
|
|
2414
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2415
|
+
// Continue's VS Code extension does not watch the mcpServers folder, so the
|
|
2416
|
+
// user has to reload the IDE window -- not restart the whole editor.
|
|
2417
|
+
reload: "reload-window",
|
|
2418
|
+
entry: {
|
|
2419
|
+
// Continue adds the cmd.exe wrapper itself, so the broker entry is a BARE
|
|
2420
|
+
// npx on Windows; pre-wrapping it breaks under a WSL remote, where
|
|
2421
|
+
// Continue deliberately does not wrap. A `try` upstream still takes the
|
|
2422
|
+
// shared wrap: that entry names a third-party launcher whose args have to
|
|
2423
|
+
// survive cmd's parse, which is what escapeCmdArg's depths are for.
|
|
2424
|
+
windowsLaunch: { broker: "bare", upstream: "cmd-wrap" }
|
|
2425
|
+
},
|
|
2426
|
+
notes: "Continue's IDE extensions load the JSON files in that mcpServers folder, whichever agent is selected -- its `cn` CLI does not read the folder. Reload the IDE window after installing or uninstalling (VS Code: Developer: Reload Window); Continue's VS Code extension does not watch that folder. On Windows the entry is bare npx, not cmd /c npx: Continue adds the cmd.exe wrapper itself.",
|
|
2427
|
+
resolvePath: resolveContinuePath,
|
|
2428
|
+
scopes: [
|
|
2429
|
+
{
|
|
2430
|
+
scope: "user",
|
|
2431
|
+
label: "User (global)",
|
|
2432
|
+
description: "Private to this machine; loaded whichever Continue agent is selected.",
|
|
2433
|
+
requiresProjectDir: false
|
|
2434
|
+
},
|
|
2435
|
+
{
|
|
2436
|
+
scope: "project",
|
|
2437
|
+
label: "Project",
|
|
2438
|
+
description: "Commit to share with your team; loaded while this folder is open in the IDE.",
|
|
2439
|
+
requiresProjectDir: true
|
|
2440
|
+
}
|
|
2441
|
+
]
|
|
2442
|
+
});
|
|
2443
|
+
|
|
2444
|
+
// src/target-typed.ts
|
|
2445
|
+
import { isAbsolute as isAbsolute3, join as join5, resolve as resolve3 } from "path";
|
|
2446
|
+
var CONTAINER_KEY2 = "mcpServers";
|
|
2447
|
+
var WINDOWS_SEP = String.fromCharCode(92);
|
|
2448
|
+
var DEFAULT_BUNDLE_SEGMENTS = [".config", "typed", "typed-cli", "cli.mjs"];
|
|
2449
|
+
function typedCliBundle(base) {
|
|
2450
|
+
const override = base.env.typedCliBundle;
|
|
2451
|
+
if (override !== void 0) return isAbsolute3(override) ? override : resolve3(override);
|
|
2452
|
+
return join5(base.home, ...DEFAULT_BUNDLE_SEGMENTS);
|
|
2453
|
+
}
|
|
2454
|
+
function staleTypedCliWarning(bundle, base) {
|
|
2455
|
+
return base.env.typedCliBundle !== void 0 ? `the typed CLI bundle at ${bundle} (TYPED_CLI_BUNDLE) predates ~/.config/typed/mcp.json, so that typed will not load this entry until the bundle is rebuilt or replaced -- \`typed update\` updates only the default ~/.config/typed/typed-cli/cli.mjs.` : `the typed CLI at ${bundle} predates ~/.config/typed/mcp.json, so it will not load this entry until it updates -- run \`typed update\`.`;
|
|
2456
|
+
}
|
|
2457
|
+
function resolveTypedPath(base) {
|
|
2458
|
+
return underHome(base, [".config", "typed", "mcp.json"]);
|
|
2459
|
+
}
|
|
2460
|
+
function underHome(base, segments) {
|
|
2461
|
+
return {
|
|
2462
|
+
absolute: join5(base.home, ...segments),
|
|
2463
|
+
display: base.os === "windows" ? ["%USERPROFILE%", ...segments].join(WINDOWS_SEP) : ["~", ...segments].join("/"),
|
|
2464
|
+
containerPath: [CONTAINER_KEY2]
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
function typedAlsoReads(base) {
|
|
2468
|
+
const cfg = base.env.claudeConfigDir;
|
|
2469
|
+
const inConfigDir = (name) => cfg !== void 0 && cfg.length > 0 ? {
|
|
2470
|
+
absolute: join5(cfg, name),
|
|
2471
|
+
display: [cfg, name].join(base.os === "windows" ? WINDOWS_SEP : "/"),
|
|
2472
|
+
containerPath: [CONTAINER_KEY2]
|
|
2473
|
+
} : underHome(base, [".claude", name]);
|
|
2474
|
+
return [
|
|
2475
|
+
underHome(base, [".mcp.json"]),
|
|
2476
|
+
inConfigDir(".mcp.json"),
|
|
2477
|
+
underHome(base, [".claude.json"]),
|
|
2478
|
+
inConfigDir(".claude.json")
|
|
2479
|
+
];
|
|
2480
|
+
}
|
|
2481
|
+
var TYPED_TARGET = defineTarget({
|
|
2482
|
+
clientId: "typed",
|
|
2483
|
+
label: "typed",
|
|
2484
|
+
// STRICT: typed parses this file with JSON.parse.
|
|
2485
|
+
config: { format: "json", root: CONTAINER_KEY2 },
|
|
2486
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2487
|
+
// typed reads its MCP config once per session and does not watch the file.
|
|
2488
|
+
reload: "next-session",
|
|
2489
|
+
uninstallNote: "typed's CLI preloads Yaw MCP on its own when no config it reads references it and it finds a yaw-mcp on PATH or a ~/.yaw-mcp directory -- set TYPED_CLI_NO_YAW_MCP=1 to keep it out.",
|
|
2490
|
+
entry: {
|
|
2491
|
+
windowsLaunch: { broker: "bare", upstream: "cmd-wrap" }
|
|
2492
|
+
},
|
|
2493
|
+
// The grant is Claude Code's scheme, and typed reads it from the same file.
|
|
2494
|
+
hooks: { permissionsPatch: "claude-code", alsoReads: typedAlsoReads },
|
|
2495
|
+
// See AND A PROBE FOR IT in the header.
|
|
2496
|
+
programProbe: {
|
|
2497
|
+
programFile: typedCliBundle,
|
|
2498
|
+
markers: ['"mcp.json"', "'mcp.json'"],
|
|
2499
|
+
warning: staleTypedCliWarning
|
|
2500
|
+
},
|
|
2501
|
+
notes: "typed reads ~/.config/typed/mcp.json when a session starts, ahead of the user-scope files it shares with Claude Code, so this entry wins over an \"mcp\" entry Yaw Terminal manages in ~/.claude.json; a project's .mcp.json still wins over it. On a Yaw Terminal machine that means an npx entry here replaces Yaw Terminal's local launch for typed, and npx resolves @latest on every typed start, which can outlast typed's MCP connect timeout -- `npm i -g @yawlabs/mcp` with oam installed, then re-run install, writes a fast absolute-path entry instead, or raise MCP_TIMEOUT. The file is strict JSON: no comments, no trailing commas. The mcp__mcp__* grant goes in Claude Code's user settings.json, which typed reads too; under a set CLAUDE_CONFIG_DIR that is <CLAUDE_CONFIG_DIR>/settings.json, so the grant is scoped to that config dir while this file is not. There is no project scope here: <project>/.mcp.json is Claude Code's project file, which typed also reads -- use `yaw-mcp install mcp` for it. Needs a typed CLI newer than 1.5.0; older typed reads only Claude Code's files, so use `yaw-mcp install claude-code` there. typed picks the change up in its next session.",
|
|
2502
|
+
resolvePath: resolveTypedPath,
|
|
2503
|
+
scopes: [
|
|
2504
|
+
{
|
|
2505
|
+
scope: "user",
|
|
2506
|
+
label: "User (global)",
|
|
2507
|
+
description: "typed's own MCP file; applies to every project.",
|
|
2508
|
+
requiresProjectDir: false
|
|
2509
|
+
}
|
|
2510
|
+
]
|
|
2511
|
+
});
|
|
2512
|
+
|
|
2513
|
+
// src/target-zed.ts
|
|
2514
|
+
import { isAbsolute as isAbsolute4, join as join6 } from "path";
|
|
2515
|
+
function zedConfigDir(base) {
|
|
2516
|
+
if (base.os === "windows") {
|
|
2517
|
+
return { dir: join6(base.appData, "Zed"), display: "%APPDATA%\\Zed" };
|
|
2518
|
+
}
|
|
2519
|
+
const xdg = base.env.xdgConfigHome;
|
|
2520
|
+
if (base.os === "linux" && xdg && isAbsolute4(xdg)) {
|
|
2521
|
+
return { dir: join6(xdg, "zed"), display: `$XDG_CONFIG_HOME/zed` };
|
|
2522
|
+
}
|
|
2523
|
+
return { dir: join6(base.home, ".config", "zed"), display: "~/.config/zed" };
|
|
2524
|
+
}
|
|
2525
|
+
function resolveZedPath(base) {
|
|
2526
|
+
if (base.scope === "project") {
|
|
2527
|
+
const sep4 = base.os === "windows" ? "\\" : "/";
|
|
2528
|
+
return {
|
|
2529
|
+
absolute: join6(base.projectDir, ".zed", "settings.json"),
|
|
2530
|
+
display: ["<project folder>", ".zed", "settings.json"].join(sep4),
|
|
2531
|
+
containerPath: ["context_servers"]
|
|
2532
|
+
};
|
|
2533
|
+
}
|
|
2534
|
+
const cfg = zedConfigDir(base);
|
|
2535
|
+
if (!cfg) throw new Error(`Zed's settings.json location on ${base.os} is unknown`);
|
|
2536
|
+
const sep3 = base.os === "windows" ? "\\" : "/";
|
|
2537
|
+
return {
|
|
2538
|
+
absolute: join6(cfg.dir, "settings.json"),
|
|
2539
|
+
display: [cfg.display, "settings.json"].join(base.os === "windows" ? sep3 : "/"),
|
|
2540
|
+
containerPath: ["context_servers"]
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
2543
|
+
function carryZedFields(stored) {
|
|
2544
|
+
const out = {};
|
|
2545
|
+
if (typeof stored.enabled === "boolean") out.enabled = stored.enabled;
|
|
2546
|
+
if (typeof stored.remote === "boolean") out.remote = stored.remote;
|
|
2547
|
+
if (typeof stored.timeout === "number" && Number.isFinite(stored.timeout) && stored.timeout >= 0) {
|
|
2548
|
+
out.timeout = stored.timeout;
|
|
2549
|
+
}
|
|
2550
|
+
return out;
|
|
2551
|
+
}
|
|
2552
|
+
var ZED_TARGET = defineTarget({
|
|
2553
|
+
clientId: "zed",
|
|
2554
|
+
label: "Zed",
|
|
2555
|
+
config: { format: "jsonc", root: "context_servers" },
|
|
2556
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2557
|
+
// Zed's `watch_config_file` restarts, starts or stops servers when
|
|
2558
|
+
// settings.json is saved, so the Done line must not tell the user to
|
|
2559
|
+
// restart the editor.
|
|
2560
|
+
reload: "live",
|
|
2561
|
+
entry: {
|
|
2562
|
+
carry: carryZedFields
|
|
2563
|
+
},
|
|
2564
|
+
notes: "Zed reads context_servers from settings.json, which allows // comments and trailing commas, and starts, restarts or stops servers when the file is saved -- no restart needed. On Linux the path follows $XDG_CONFIG_HOME when it is set; the Flatpak build reads $FLATPAK_XDG_CONFIG_HOME/zed/settings.json instead, which install does not follow. Zed ignores a project's .zed/settings.json until you trust the project. Needs Zed v0.214.5 (2025-11-26) or newer: earlier versions reject this entry shape.",
|
|
2565
|
+
resolvePath: resolveZedPath,
|
|
2566
|
+
scopes: [
|
|
2567
|
+
// User FIRST, like every other multi-scope row: the probe walks this array
|
|
2568
|
+
// in order and it decides `--list` and doctor row order.
|
|
2569
|
+
{
|
|
2570
|
+
scope: "user",
|
|
2571
|
+
label: "User (global)",
|
|
2572
|
+
description: "Private to this machine; applies to every Zed project.",
|
|
2573
|
+
requiresProjectDir: false
|
|
2574
|
+
},
|
|
2575
|
+
{
|
|
2576
|
+
scope: "project",
|
|
2577
|
+
label: "Project",
|
|
2578
|
+
description: "Commit to share with your team; Zed applies it once the project is trusted.",
|
|
2579
|
+
requiresProjectDir: true
|
|
2580
|
+
}
|
|
2581
|
+
]
|
|
2582
|
+
});
|
|
2583
|
+
|
|
2584
|
+
// src/claude-code-settings.ts
|
|
2585
|
+
import { readFile as readFile2, stat } from "fs/promises";
|
|
2586
|
+
import { basename, join as join7, resolve as resolve4 } from "path";
|
|
2587
|
+
var CLAUDE_CODE_ALLOW_PATTERN = "mcp__mcp__*";
|
|
2588
|
+
function resolveClaudeCodeSettingsPath(scope, opts) {
|
|
2589
|
+
const { home, projectDir, claudeConfigDir } = opts;
|
|
2590
|
+
const cfgDir = claudeConfigDir && claudeConfigDir.length > 0 ? claudeConfigDir : null;
|
|
2591
|
+
if (scope === "user") return cfgDir ? join7(cfgDir, "settings.json") : join7(home, ".claude", "settings.json");
|
|
2592
|
+
if (scope === "project" && projectDir) return join7(projectDir, ".claude", "settings.json");
|
|
2593
|
+
if (scope === "local" && projectDir) return join7(projectDir, ".claude", "settings.local.json");
|
|
2594
|
+
return null;
|
|
2595
|
+
}
|
|
2596
|
+
function yawModeOverlay(opts) {
|
|
2597
|
+
if (opts.yawMode !== "augment" && opts.yawMode !== "fresh") return null;
|
|
2598
|
+
const dir = opts.claudeConfigDir;
|
|
2599
|
+
if (dir === void 0 || dir.length === 0) return null;
|
|
2600
|
+
return basename(resolve4(dir)).startsWith(YAW_MODE_OVERLAY_PREFIX) ? opts.yawMode : null;
|
|
2601
|
+
}
|
|
2602
|
+
var YAW_MODE_OVERLAY_PREFIX = "yaw-mode-";
|
|
2603
|
+
function mergePermissionsAllow(existing, patterns) {
|
|
2604
|
+
const out = { ...existing };
|
|
2605
|
+
const prev = out.permissions;
|
|
2606
|
+
const perms = typeof prev === "object" && prev !== null && !Array.isArray(prev) ? { ...prev } : {};
|
|
2607
|
+
const prevAllow = perms.allow;
|
|
2608
|
+
const allow = Array.isArray(prevAllow) ? [...prevAllow] : [];
|
|
2609
|
+
for (const p of patterns) {
|
|
2610
|
+
if (!allow.includes(p)) allow.push(p);
|
|
2611
|
+
}
|
|
2612
|
+
perms.allow = allow;
|
|
2613
|
+
out.permissions = perms;
|
|
2614
|
+
return out;
|
|
2615
|
+
}
|
|
2616
|
+
function removePermissionsAllow(existing, patterns) {
|
|
2617
|
+
const prev = existing.permissions;
|
|
2618
|
+
if (typeof prev !== "object" || prev === null || Array.isArray(prev)) return existing;
|
|
2619
|
+
const prevAllow = prev.allow;
|
|
2620
|
+
if (!Array.isArray(prevAllow)) return existing;
|
|
2621
|
+
const allow = prevAllow.filter((p) => !(typeof p === "string" && patterns.includes(p)));
|
|
2622
|
+
if (allow.length === prevAllow.length) return existing;
|
|
2623
|
+
return { ...existing, permissions: { ...prev, allow } };
|
|
2624
|
+
}
|
|
2625
|
+
function patchPermissionsAllowText(raw, patterns, op) {
|
|
2626
|
+
let text = raw;
|
|
2627
|
+
for (const pattern of patterns) {
|
|
2628
|
+
text = op === "add" ? addJsoncArrayElement(text, ["permissions", "allow"], pattern) : removeJsoncArrayElements(text, ["permissions", "allow"], (v) => v === pattern);
|
|
2629
|
+
}
|
|
2630
|
+
return text;
|
|
2631
|
+
}
|
|
2632
|
+
async function settingsFingerprint(path2) {
|
|
2633
|
+
try {
|
|
2634
|
+
const st = await stat(path2);
|
|
2635
|
+
return { mtimeMs: st.mtimeMs, size: st.size };
|
|
2636
|
+
} catch {
|
|
2637
|
+
return null;
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
async function prepareClaudeCodeSettingsPatch(opts) {
|
|
2641
|
+
const path2 = resolveClaudeCodeSettingsPath(opts.scope, {
|
|
2642
|
+
home: opts.home,
|
|
2643
|
+
projectDir: opts.projectDir,
|
|
2644
|
+
claudeConfigDir: opts.claudeConfigDir
|
|
2645
|
+
});
|
|
2646
|
+
if (!path2) return null;
|
|
2647
|
+
let existing = {};
|
|
2648
|
+
let rawSettings = null;
|
|
2649
|
+
const fingerprint = await settingsFingerprint(path2);
|
|
2650
|
+
if (fingerprint !== null) {
|
|
2651
|
+
try {
|
|
2652
|
+
const raw = await readFile2(path2, "utf8");
|
|
2653
|
+
if (raw.trim().length > 0) {
|
|
2654
|
+
const parsed = parseJsonc(raw);
|
|
2655
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
2656
|
+
existing = parsed;
|
|
2657
|
+
rawSettings = raw;
|
|
2658
|
+
} else {
|
|
2659
|
+
return {
|
|
2660
|
+
path: path2,
|
|
2661
|
+
nextJson: "",
|
|
2662
|
+
changed: false,
|
|
2663
|
+
added: [],
|
|
2664
|
+
removed: [],
|
|
2665
|
+
malformed: true,
|
|
2666
|
+
malformedReason: "not a JSON object",
|
|
2667
|
+
fingerprint
|
|
2668
|
+
};
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
2671
|
+
} catch (e) {
|
|
2672
|
+
return {
|
|
2673
|
+
path: path2,
|
|
2674
|
+
nextJson: "",
|
|
2675
|
+
changed: false,
|
|
2676
|
+
added: [],
|
|
2677
|
+
removed: [],
|
|
2678
|
+
malformed: true,
|
|
2679
|
+
malformedReason: e.message,
|
|
2680
|
+
fingerprint
|
|
2681
|
+
};
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
const op = opts.op ?? "add";
|
|
2685
|
+
const merged = op === "remove" ? removePermissionsAllow(existing, [CLAUDE_CODE_ALLOW_PATTERN]) : mergePermissionsAllow(existing, [CLAUDE_CODE_ALLOW_PATTERN]);
|
|
2686
|
+
const before = JSON.stringify(existing);
|
|
2687
|
+
const after = JSON.stringify(merged);
|
|
2688
|
+
if (before === after) return { path: path2, nextJson: "", changed: false, added: [], removed: [], fingerprint };
|
|
2689
|
+
const prevAllow = existing.permissions?.allow;
|
|
2690
|
+
const prevAllowList = Array.isArray(prevAllow) ? prevAllow : [];
|
|
2691
|
+
const added = op === "add" ? [CLAUDE_CODE_ALLOW_PATTERN].filter((p) => !prevAllowList.includes(p)) : [];
|
|
2692
|
+
const removed = op === "remove" ? [CLAUDE_CODE_ALLOW_PATTERN].filter((p) => prevAllowList.includes(p)) : [];
|
|
2693
|
+
if (rawSettings !== null) {
|
|
2694
|
+
const perms = existing.permissions;
|
|
2695
|
+
if (perms !== void 0 && (typeof perms !== "object" || perms === null || Array.isArray(perms))) {
|
|
2696
|
+
return {
|
|
2697
|
+
path: path2,
|
|
2698
|
+
nextJson: "",
|
|
2699
|
+
changed: false,
|
|
2700
|
+
added: [],
|
|
2701
|
+
removed: [],
|
|
2702
|
+
malformed: true,
|
|
2703
|
+
malformedReason: `"permissions" is ${describeValueShape(perms)}, not a JSON object`,
|
|
2704
|
+
fingerprint
|
|
2705
|
+
};
|
|
2706
|
+
}
|
|
2707
|
+
try {
|
|
2708
|
+
const next = patchPermissionsAllowText(rawSettings, [CLAUDE_CODE_ALLOW_PATTERN], op);
|
|
2709
|
+
return { path: path2, nextJson: next.endsWith("\n") ? next : `${next}
|
|
2710
|
+
`, changed: true, added, removed, fingerprint };
|
|
2711
|
+
} catch (e) {
|
|
2712
|
+
return {
|
|
2713
|
+
path: path2,
|
|
2714
|
+
nextJson: "",
|
|
2715
|
+
changed: false,
|
|
2716
|
+
added: [],
|
|
2717
|
+
removed: [],
|
|
2718
|
+
malformed: true,
|
|
2719
|
+
malformedReason: `could not splice permissions.allow (${e.message})`,
|
|
2720
|
+
fingerprint
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
return { path: path2, nextJson: `${JSON.stringify(merged, null, 2)}
|
|
2725
|
+
`, changed: true, added, removed, fingerprint };
|
|
2726
|
+
}
|
|
2727
|
+
|
|
2728
|
+
// src/install-targets.ts
|
|
2729
|
+
var TARGET_ROWS = [
|
|
2730
|
+
defineTarget({
|
|
2731
|
+
clientId: "claude-code",
|
|
2732
|
+
label: "Claude Code",
|
|
2733
|
+
config: { format: "jsonc", root: "mcpServers" },
|
|
2734
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2735
|
+
hooks: { permissionsPatch: "claude-code" },
|
|
2736
|
+
scopes: [
|
|
2737
|
+
{
|
|
2738
|
+
scope: "user",
|
|
2739
|
+
label: "User (global)",
|
|
2740
|
+
description: "Private to this machine; applies to every project.",
|
|
2741
|
+
requiresProjectDir: false
|
|
2742
|
+
},
|
|
2743
|
+
{
|
|
2744
|
+
scope: "project",
|
|
2745
|
+
label: "Project",
|
|
2746
|
+
description: "Commit to share with your team.",
|
|
2747
|
+
requiresProjectDir: true,
|
|
2748
|
+
// `.mcp.json` is read with strict JSON, unlike `~/.claude.json`: a
|
|
2749
|
+
// comment or a trailing comma in it means Claude Code loads NO server
|
|
2750
|
+
// from that file. Declaring it here is what makes the write facade
|
|
2751
|
+
// refuse to splice an entry into one -- printing "Done" over a file
|
|
2752
|
+
// nothing reads, and leaving the user to wonder why their broker never
|
|
2753
|
+
// appears, is the failure this flag exists to stop. It is a REFUSAL,
|
|
2754
|
+
// not a repair: the comments are the user's, and yaw-mcp does not get
|
|
2755
|
+
// to delete them to make its own write land.
|
|
2756
|
+
strictJson: true
|
|
2757
|
+
},
|
|
2758
|
+
{
|
|
2759
|
+
scope: "local",
|
|
2760
|
+
label: "Local",
|
|
2761
|
+
description: "Per-project override; typically gitignored.",
|
|
2762
|
+
requiresProjectDir: true
|
|
2763
|
+
}
|
|
2764
|
+
]
|
|
2765
|
+
}),
|
|
2766
|
+
defineTarget({
|
|
2767
|
+
clientId: "claude-desktop",
|
|
2768
|
+
label: "Claude Desktop",
|
|
2769
|
+
config: { format: "jsonc", root: "mcpServers" },
|
|
2770
|
+
availableOn: ["macos", "windows"],
|
|
2771
|
+
// Not "no Linux build" -- there is one, a beta. What is missing is a
|
|
2772
|
+
// documented Linux path for claude_desktop_config.json; the header note
|
|
2773
|
+
// lists the sources checked.
|
|
2774
|
+
notConfigurableOn: {
|
|
2775
|
+
linux: "Claude Desktop for Linux is in beta, and Anthropic has not documented where it reads claude_desktop_config.json"
|
|
2776
|
+
},
|
|
2777
|
+
// ASCII `--`, not an em-dash: install prints this verbatim (`Note: ...`),
|
|
2778
|
+
// and Claude Desktop is a Windows client -- on a console whose codepage is
|
|
2779
|
+
// not UTF-8 the em-dash rendered as mojibake in the line the user reads.
|
|
2780
|
+
notes: "Claude Desktop reads one file per OS -- no project scope. Restart the app after editing.",
|
|
2781
|
+
scopes: [
|
|
2782
|
+
{
|
|
2783
|
+
scope: "user",
|
|
2784
|
+
label: "User",
|
|
2785
|
+
description: "The only config file Claude Desktop reads.",
|
|
2786
|
+
requiresProjectDir: false
|
|
2787
|
+
}
|
|
2788
|
+
]
|
|
2789
|
+
}),
|
|
2790
|
+
defineTarget({
|
|
2791
|
+
clientId: "cursor",
|
|
2792
|
+
label: "Cursor",
|
|
2793
|
+
config: { format: "jsonc", root: "mcpServers" },
|
|
2794
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2795
|
+
scopes: [
|
|
2796
|
+
{
|
|
2797
|
+
scope: "user",
|
|
2798
|
+
label: "User (global)",
|
|
2799
|
+
description: "Private to this machine; applies to every Cursor project.",
|
|
2800
|
+
requiresProjectDir: false
|
|
2801
|
+
},
|
|
2802
|
+
{
|
|
2803
|
+
scope: "project",
|
|
2804
|
+
label: "Project",
|
|
2805
|
+
description: "Commit to share with your team.",
|
|
2806
|
+
requiresProjectDir: true
|
|
2807
|
+
}
|
|
2808
|
+
]
|
|
2809
|
+
}),
|
|
2810
|
+
defineTarget({
|
|
2811
|
+
clientId: "vscode",
|
|
2812
|
+
label: "VS Code",
|
|
2813
|
+
config: { format: "jsonc", root: "servers" },
|
|
2814
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2815
|
+
hooks: { importVariables: "vscode-inputs" },
|
|
2816
|
+
notes: "VS Code uses `servers` (not `mcpServers`) as the top-level key in mcp.json -- the user-profile file and .vscode/mcp.json share that shape. The user file covers the DEFAULT profile only; a custom profile keeps its own copy under Code/User/profiles/<id>/mcp.json. Needs VS Code 1.102 or newer, before which user-level MCP lived under the `mcp` key in settings.json.",
|
|
2817
|
+
scopes: [
|
|
2818
|
+
// User FIRST: enumerateProbeSlots walks this array in order, so it
|
|
2819
|
+
// decides --list and doctor row order, and every other multi-scope
|
|
2820
|
+
// client lists user before project.
|
|
2821
|
+
{
|
|
2822
|
+
scope: "user",
|
|
2823
|
+
label: "User (global)",
|
|
2824
|
+
description: "Private to this machine; applies to every VS Code workspace.",
|
|
2825
|
+
requiresProjectDir: false
|
|
2826
|
+
},
|
|
2827
|
+
{
|
|
2828
|
+
scope: "project",
|
|
2829
|
+
label: "Workspace",
|
|
2830
|
+
description: "Per-project config; commit to share.",
|
|
2831
|
+
requiresProjectDir: true
|
|
2832
|
+
}
|
|
2833
|
+
]
|
|
2834
|
+
}),
|
|
2835
|
+
// APPENDED, never inserted: autoDetectClient returns the first usable probe
|
|
2836
|
+
// slot in array order and documents Claude-Code-first as an invariant, so an
|
|
2837
|
+
// insert would silently change which client `try` picks for existing users.
|
|
2838
|
+
defineTarget({
|
|
2839
|
+
clientId: "windsurf",
|
|
2840
|
+
label: "Windsurf",
|
|
2841
|
+
config: { format: "jsonc", root: "mcpServers" },
|
|
2842
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2843
|
+
notes: "Windsurf reads ~/.codeium/windsurf/mcp_config.json and does not create it on first launch. If the server does not appear, open Cascade -> MCP servers -> Manage plugins -> View raw config and check it is the file above.",
|
|
2844
|
+
scopes: [
|
|
2845
|
+
{
|
|
2846
|
+
scope: "user",
|
|
2847
|
+
label: "User (global)",
|
|
2848
|
+
description: "The only config file Windsurf reads; it has no workspace scope.",
|
|
2849
|
+
requiresProjectDir: false
|
|
2850
|
+
}
|
|
2851
|
+
]
|
|
2852
|
+
}),
|
|
2853
|
+
defineTarget({
|
|
2854
|
+
clientId: "gemini-cli",
|
|
2855
|
+
label: "Gemini CLI",
|
|
2856
|
+
config: { format: "jsonc", root: "mcpServers" },
|
|
2857
|
+
availableOn: ["macos", "linux", "windows"],
|
|
2858
|
+
notes: "Gemini CLI merges ~/.gemini/settings.json with <project>/.gemini/settings.json, project winning. `mcpServers` is a top-level key, distinct from the sibling `mcp` object that holds discovery knobs.",
|
|
2859
|
+
scopes: [
|
|
2860
|
+
{
|
|
2861
|
+
scope: "user",
|
|
2862
|
+
label: "User (global)",
|
|
2863
|
+
description: "Private to this machine; applies to every project.",
|
|
2864
|
+
requiresProjectDir: false
|
|
2865
|
+
},
|
|
2866
|
+
{
|
|
2867
|
+
scope: "project",
|
|
2868
|
+
label: "Project",
|
|
2869
|
+
description: "Commit to share with your team; wins over the user file.",
|
|
2870
|
+
requiresProjectDir: true
|
|
2871
|
+
}
|
|
2872
|
+
]
|
|
2873
|
+
}),
|
|
2874
|
+
// APPENDED, never inserted, for the reason spelled out above the windsurf
|
|
2875
|
+
// row: `try`'s auto-detect returns the FIRST usable probe slot in this
|
|
2876
|
+
// array's order, so inserting a row ahead of an existing one silently
|
|
2877
|
+
// changes which client an existing user's `try` picks. New targets go on the
|
|
2878
|
+
// end, in the order they land.
|
|
2879
|
+
ZED_TARGET,
|
|
2880
|
+
CLINE_TARGET,
|
|
2881
|
+
CONTINUE_TARGET,
|
|
2882
|
+
// Importing this row is also what registers the "toml" config adapter (see
|
|
2883
|
+
// its module header), so the format is readable exactly when a row uses it.
|
|
2884
|
+
CODEX_CLI_TARGET,
|
|
2885
|
+
// The second row to declare `hooks.permissionsPatch: "claude-code"`: typed
|
|
2886
|
+
// reads permissions.allow from Claude Code's user settings.json, so its
|
|
2887
|
+
// install unions the same grant into the same file (see its module header).
|
|
2888
|
+
TYPED_TARGET
|
|
2889
|
+
];
|
|
2890
|
+
var INSTALL_TARGETS = TARGET_ROWS;
|
|
2891
|
+
function resolveInstallPath(opts) {
|
|
2892
|
+
const { target, base } = resolveTargetBase(opts);
|
|
2893
|
+
if (target.resolvePath) return target.resolvePath(base);
|
|
2894
|
+
return pathFor(target.clientId, base.scope, base.os, {
|
|
2895
|
+
home: base.home,
|
|
2896
|
+
appData: base.appData,
|
|
2897
|
+
projectDir: base.projectDir,
|
|
2898
|
+
claudeConfigDir: base.env.claudeConfigDir
|
|
2899
|
+
});
|
|
2900
|
+
}
|
|
2901
|
+
function resolveInstallSites(opts) {
|
|
2902
|
+
const { target, scopeSpec, base } = resolveTargetBase(opts);
|
|
2903
|
+
const format = effectiveConfigFormat(target.config, scopeSpec);
|
|
2904
|
+
if (target.sites) return target.sites(base).map((site) => ({ ...site, format }));
|
|
2905
|
+
return [
|
|
2906
|
+
{
|
|
2907
|
+
// "default" rather than the client id: the id names the SITE within a
|
|
2908
|
+
// target, and every single-site row has exactly one.
|
|
2909
|
+
id: "default",
|
|
2910
|
+
label: target.label,
|
|
2911
|
+
resolved: resolveInstallPath(opts),
|
|
2912
|
+
format,
|
|
2913
|
+
detectDir: null
|
|
2914
|
+
}
|
|
2915
|
+
];
|
|
2916
|
+
}
|
|
2917
|
+
function resolveProgramProbe(opts) {
|
|
2918
|
+
const { target, base } = resolveTargetBase(opts);
|
|
2919
|
+
const probe = target.programProbe;
|
|
2920
|
+
if (probe === void 0) return null;
|
|
2921
|
+
const file = probe.programFile(base);
|
|
2922
|
+
return { file, markers: probe.markers, warning: probe.warning(file, base) };
|
|
2923
|
+
}
|
|
2924
|
+
function resolveAlsoReadSites(opts) {
|
|
2925
|
+
const { target, scopeSpec, base } = resolveTargetBase(opts);
|
|
2926
|
+
const format = effectiveConfigFormat(target.config, scopeSpec);
|
|
2927
|
+
return (target.hooks?.alsoReads?.(base) ?? []).map((resolved, i) => ({
|
|
2928
|
+
id: `also-reads-${i}`,
|
|
2929
|
+
label: target.label,
|
|
2930
|
+
resolved,
|
|
2931
|
+
format,
|
|
2932
|
+
detectDir: null
|
|
2933
|
+
}));
|
|
2934
|
+
}
|
|
2935
|
+
function resolveTargetBase(opts) {
|
|
2936
|
+
const home = opts.home ?? homedir2();
|
|
2937
|
+
const appData = opts.appData && opts.appData.length > 0 ? opts.appData : join8(home, "AppData", "Roaming");
|
|
2938
|
+
const { clientId, scope, os, projectDir, claudeConfigDir } = opts;
|
|
2939
|
+
const target = INSTALL_TARGETS.find((t) => t.clientId === clientId);
|
|
2940
|
+
if (!target) throw new Error(`Unknown client: ${clientId}`);
|
|
2941
|
+
const scopeSpec = target.scopes.find((s) => s.scope === scope);
|
|
2942
|
+
if (!scopeSpec) throw new Error(`Client ${clientId} does not support scope ${scope}`);
|
|
2943
|
+
if (!target.availableOn.includes(os)) {
|
|
2944
|
+
const why = target.notConfigurableOn?.[os];
|
|
2945
|
+
throw new Error(
|
|
2946
|
+
why ? `${target.label} cannot be configured on ${os}: ${why}` : `${target.label} is not available on ${os}`
|
|
2947
|
+
);
|
|
2948
|
+
}
|
|
2949
|
+
if (scopeSpec.requiresProjectDir && !projectDir) {
|
|
2950
|
+
throw new Error(`Scope ${scope} for ${clientId} requires a project directory`);
|
|
2951
|
+
}
|
|
2952
|
+
const absoluteProjectDir = projectDir && !isAbsolute5(projectDir) ? resolve5(projectDir) : projectDir;
|
|
2953
|
+
const cfgDir = claudeConfigDir && claudeConfigDir.length > 0 ? claudeConfigDir : void 0;
|
|
2954
|
+
const env = { ...opts.clientEnv, ...cfgDir ? { claudeConfigDir: cfgDir } : {} };
|
|
2955
|
+
const base = {
|
|
2956
|
+
home,
|
|
2957
|
+
appData,
|
|
2958
|
+
projectDir: absoluteProjectDir ?? "",
|
|
2959
|
+
os,
|
|
2960
|
+
scope,
|
|
2961
|
+
env
|
|
2962
|
+
};
|
|
2963
|
+
return { target, scopeSpec, base };
|
|
2964
|
+
}
|
|
2965
|
+
function claudeCodeProjectKey(projectDir) {
|
|
2966
|
+
if (WINDOWS_DRIVE_PATH.test(projectDir)) {
|
|
2967
|
+
return withoutTrailingSlash(projectDir[0].toUpperCase() + projectDir.slice(1).replace(/\\/g, "/"), 3);
|
|
2968
|
+
}
|
|
2969
|
+
if (projectDir.startsWith("\\\\")) {
|
|
2970
|
+
const key = projectDir.replace(/\\/g, "/");
|
|
2971
|
+
const root = /^\/\/[^/]+\/[^/]+\//.exec(key);
|
|
2972
|
+
return root ? withoutTrailingSlash(key, root[0].length) : key;
|
|
2973
|
+
}
|
|
2974
|
+
return withoutTrailingSlash(projectDir, 1);
|
|
2975
|
+
}
|
|
2976
|
+
function withoutTrailingSlash(key, rootLength) {
|
|
2977
|
+
let end = key.length;
|
|
2978
|
+
while (end > rootLength && key[end - 1] === "/") end--;
|
|
2979
|
+
return key.slice(0, end);
|
|
2980
|
+
}
|
|
2981
|
+
var WINDOWS_DRIVE_PATH = /^[A-Za-z]:[\\/]/;
|
|
2982
|
+
var PROJECTS_KEY = "projects";
|
|
2983
|
+
function sameClaudeCodeProjectKey(a, b) {
|
|
2984
|
+
if (a === b) return true;
|
|
2985
|
+
if (!WINDOWS_DRIVE_PATH.test(a) || !WINDOWS_DRIVE_PATH.test(b)) return false;
|
|
2986
|
+
return a[0].toLowerCase() === b[0].toLowerCase() && a.slice(1) === b.slice(1);
|
|
2987
|
+
}
|
|
2988
|
+
function claudeCodeContainerPaths(root, containerPath) {
|
|
2989
|
+
return claudeCodeContainerPathVariants(containerPath, (prefix) => {
|
|
2990
|
+
if (prefix.length !== 1 || prefix[0] !== PROJECTS_KEY) return [];
|
|
2991
|
+
if (typeof root !== "object" || root === null || Array.isArray(root)) return [];
|
|
2992
|
+
const projects = root[PROJECTS_KEY];
|
|
2993
|
+
if (typeof projects !== "object" || projects === null || Array.isArray(projects)) return [];
|
|
2994
|
+
return Object.keys(projects);
|
|
2995
|
+
});
|
|
2996
|
+
}
|
|
2997
|
+
function claudeCodeContainerPathVariants(containerPath, keysAt) {
|
|
2998
|
+
const canonical = [...containerPath];
|
|
2999
|
+
if (containerPath.length < 2 || containerPath[0] !== PROJECTS_KEY) return [canonical];
|
|
3000
|
+
const key = containerPath[1];
|
|
3001
|
+
if (!WINDOWS_DRIVE_PATH.test(key)) return [canonical];
|
|
3002
|
+
const out = [canonical];
|
|
3003
|
+
for (const candidate of keysAt([PROJECTS_KEY])) {
|
|
3004
|
+
if (candidate !== key && sameClaudeCodeProjectKey(candidate, key)) {
|
|
3005
|
+
out.push([PROJECTS_KEY, candidate, ...containerPath.slice(2)]);
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
return out;
|
|
3009
|
+
}
|
|
3010
|
+
function pathFor(client, scope, os, base) {
|
|
3011
|
+
const { home, appData, projectDir, claudeConfigDir } = base;
|
|
3012
|
+
const sep3 = os === "windows" ? "\\" : "/";
|
|
3013
|
+
const joinPath = (...parts) => parts.join(sep3);
|
|
3014
|
+
if (client === "claude-code") {
|
|
3015
|
+
if (scope === "user") {
|
|
3016
|
+
if (claudeConfigDir) {
|
|
3017
|
+
const absolute = join8(claudeConfigDir, ".claude.json");
|
|
3018
|
+
return { absolute, display: absolute, containerPath: ["mcpServers"] };
|
|
3019
|
+
}
|
|
3020
|
+
const display = os === "windows" ? "%USERPROFILE%\\.claude.json" : "~/.claude.json";
|
|
3021
|
+
return { absolute: join8(home, ".claude.json"), display, containerPath: ["mcpServers"] };
|
|
3022
|
+
}
|
|
3023
|
+
if (scope === "project") {
|
|
3024
|
+
return {
|
|
3025
|
+
absolute: join8(projectDir, ".mcp.json"),
|
|
3026
|
+
display: joinPath("<project folder>", ".mcp.json"),
|
|
3027
|
+
containerPath: ["mcpServers"]
|
|
3028
|
+
};
|
|
3029
|
+
}
|
|
3030
|
+
const projectKey = claudeCodeProjectKey(projectDir);
|
|
3031
|
+
if (claudeConfigDir) {
|
|
3032
|
+
const absolute = join8(claudeConfigDir, ".claude.json");
|
|
3033
|
+
return { absolute, display: absolute, containerPath: ["projects", projectKey, "mcpServers"] };
|
|
3034
|
+
}
|
|
3035
|
+
return {
|
|
3036
|
+
absolute: join8(home, ".claude.json"),
|
|
3037
|
+
display: os === "windows" ? "%USERPROFILE%\\.claude.json" : "~/.claude.json",
|
|
3038
|
+
containerPath: ["projects", projectKey, "mcpServers"]
|
|
3039
|
+
};
|
|
3040
|
+
}
|
|
3041
|
+
if (client === "claude-desktop") {
|
|
3042
|
+
if (os === "macos") {
|
|
3043
|
+
return {
|
|
3044
|
+
absolute: join8(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"),
|
|
3045
|
+
display: "~/Library/Application Support/Claude/claude_desktop_config.json",
|
|
3046
|
+
containerPath: ["mcpServers"]
|
|
3047
|
+
};
|
|
3048
|
+
}
|
|
3049
|
+
if (os === "windows") {
|
|
3050
|
+
return {
|
|
3051
|
+
absolute: join8(appData, "Claude", "claude_desktop_config.json"),
|
|
3052
|
+
display: "%APPDATA%\\Claude\\claude_desktop_config.json",
|
|
3053
|
+
containerPath: ["mcpServers"]
|
|
3054
|
+
};
|
|
3055
|
+
}
|
|
3056
|
+
throw new Error("Claude Desktop's claude_desktop_config.json location on Linux is undocumented");
|
|
3057
|
+
}
|
|
3058
|
+
if (client === "cursor") {
|
|
3059
|
+
if (scope === "user") {
|
|
3060
|
+
const display = os === "windows" ? "%USERPROFILE%\\.cursor\\mcp.json" : "~/.cursor/mcp.json";
|
|
3061
|
+
return { absolute: join8(home, ".cursor", "mcp.json"), display, containerPath: ["mcpServers"] };
|
|
3062
|
+
}
|
|
3063
|
+
return {
|
|
3064
|
+
absolute: join8(projectDir, ".cursor", "mcp.json"),
|
|
3065
|
+
display: joinPath("<project folder>", ".cursor", "mcp.json"),
|
|
3066
|
+
containerPath: ["mcpServers"]
|
|
3067
|
+
};
|
|
3068
|
+
}
|
|
3069
|
+
if (client === "vscode") {
|
|
3070
|
+
if (scope === "user") {
|
|
3071
|
+
if (os === "windows") {
|
|
3072
|
+
return {
|
|
3073
|
+
absolute: join8(appData, "Code", "User", "mcp.json"),
|
|
3074
|
+
display: "%APPDATA%\\Code\\User\\mcp.json",
|
|
3075
|
+
containerPath: ["servers"]
|
|
3076
|
+
};
|
|
3077
|
+
}
|
|
3078
|
+
if (os === "macos") {
|
|
3079
|
+
return {
|
|
3080
|
+
absolute: join8(home, "Library", "Application Support", "Code", "User", "mcp.json"),
|
|
3081
|
+
display: "~/Library/Application Support/Code/User/mcp.json",
|
|
3082
|
+
containerPath: ["servers"]
|
|
3083
|
+
};
|
|
3084
|
+
}
|
|
3085
|
+
return {
|
|
3086
|
+
absolute: join8(home, ".config", "Code", "User", "mcp.json"),
|
|
3087
|
+
display: "~/.config/Code/User/mcp.json",
|
|
3088
|
+
containerPath: ["servers"]
|
|
3089
|
+
};
|
|
3090
|
+
}
|
|
3091
|
+
return {
|
|
3092
|
+
absolute: join8(projectDir, ".vscode", "mcp.json"),
|
|
3093
|
+
display: joinPath("<project folder>", ".vscode", "mcp.json"),
|
|
3094
|
+
containerPath: ["servers"]
|
|
3095
|
+
};
|
|
3096
|
+
}
|
|
3097
|
+
if (client === "windsurf") {
|
|
3098
|
+
const display = os === "windows" ? "%USERPROFILE%\\.codeium\\windsurf\\mcp_config.json" : "~/.codeium/windsurf/mcp_config.json";
|
|
3099
|
+
return {
|
|
3100
|
+
absolute: join8(home, ".codeium", "windsurf", "mcp_config.json"),
|
|
3101
|
+
display,
|
|
3102
|
+
containerPath: ["mcpServers"]
|
|
3103
|
+
};
|
|
3104
|
+
}
|
|
3105
|
+
if (client === "gemini-cli") {
|
|
3106
|
+
if (scope === "user") {
|
|
3107
|
+
const display = os === "windows" ? "%USERPROFILE%\\.gemini\\settings.json" : "~/.gemini/settings.json";
|
|
3108
|
+
return { absolute: join8(home, ".gemini", "settings.json"), display, containerPath: ["mcpServers"] };
|
|
3109
|
+
}
|
|
3110
|
+
return {
|
|
3111
|
+
absolute: join8(projectDir, ".gemini", "settings.json"),
|
|
3112
|
+
display: joinPath("<project folder>", ".gemini", "settings.json"),
|
|
3113
|
+
containerPath: ["mcpServers"]
|
|
3114
|
+
};
|
|
3115
|
+
}
|
|
3116
|
+
throw new Error(`Unhandled client: ${client}`);
|
|
3117
|
+
}
|
|
3118
|
+
var CMD_METACHARS = /[&|<>^()]/g;
|
|
3119
|
+
var HAS_CMD_METACHAR = /[&|<>^()]/;
|
|
3120
|
+
var KNOWN_CMD_SHIM_LAUNCHERS = /* @__PURE__ */ new Set(["npx", "npm", "pnpm", "yarn", "bunx"]);
|
|
3121
|
+
var KNOWN_DIRECT_BINARIES = /* @__PURE__ */ new Set([
|
|
3122
|
+
"node",
|
|
3123
|
+
"deno",
|
|
3124
|
+
"bun",
|
|
3125
|
+
"python",
|
|
3126
|
+
"python3",
|
|
3127
|
+
"py",
|
|
3128
|
+
"uv",
|
|
3129
|
+
"uvx",
|
|
3130
|
+
"pipx",
|
|
3131
|
+
"ruby",
|
|
3132
|
+
"php",
|
|
3133
|
+
"docker",
|
|
3134
|
+
"dotnet",
|
|
3135
|
+
"java",
|
|
3136
|
+
"go"
|
|
3137
|
+
]);
|
|
3138
|
+
function isCmdShimLauncher(command) {
|
|
3139
|
+
const base = command.replace(/^.*[\\/]/, "").toLowerCase();
|
|
3140
|
+
if (/\.(?:cmd|bat)$/.test(base)) return true;
|
|
3141
|
+
if (/\.(?:exe|com)$/.test(base)) return false;
|
|
3142
|
+
const stem = base.replace(/\.[^.]*$/, "");
|
|
3143
|
+
if (KNOWN_CMD_SHIM_LAUNCHERS.has(stem)) return true;
|
|
3144
|
+
if (KNOWN_DIRECT_BINARIES.has(stem)) return false;
|
|
3145
|
+
return true;
|
|
3146
|
+
}
|
|
3147
|
+
function escapeCmdArg(arg, opts) {
|
|
3148
|
+
if (arg.includes('"')) {
|
|
3149
|
+
if (HAS_CMD_METACHAR.test(arg)) {
|
|
3150
|
+
throw new Error(
|
|
3151
|
+
`Cannot safely encode an argument that contains BOTH a double-quote and a cmd.exe metacharacter (& | < > ^ ( )) for the Windows cmd /c launcher: ${arg} -- passing it through cmd.exe risks a command injection at client-spawn time. Rework the server's args to drop one of the two.`
|
|
3152
|
+
);
|
|
3153
|
+
}
|
|
3154
|
+
return arg;
|
|
3155
|
+
}
|
|
3156
|
+
if (/[ \t]/.test(arg)) return arg;
|
|
3157
|
+
const caret = opts.shim ? "^^^" : "^";
|
|
3158
|
+
return arg.replace(CMD_METACHARS, (m) => caret + m);
|
|
3159
|
+
}
|
|
3160
|
+
function buildLaunchEntry(opts) {
|
|
3161
|
+
if (opts.upstream) {
|
|
3162
|
+
const { command, args, env } = opts.upstream;
|
|
3163
|
+
if (opts.os === "windows") {
|
|
3164
|
+
if (/[ \t]/.test(command)) {
|
|
3165
|
+
throw new Error(
|
|
3166
|
+
`Cannot safely encode a launcher command that contains whitespace for the Windows cmd /c launcher: ${command} -- cmd.exe strips the outer quotes when the line carries another quoted token, so the client's spawn fails with "'...' is not recognized". Point the server at a whitespace-free launcher (a bare npx/uvx resolved on PATH, or a short path).`
|
|
3167
|
+
);
|
|
3168
|
+
}
|
|
3169
|
+
const shim = isCmdShimLauncher(command);
|
|
3170
|
+
const wrapped = {
|
|
3171
|
+
command: "cmd",
|
|
3172
|
+
args: ["/c", escapeCmdArg(command, { shim: false }), ...args.map((a) => escapeCmdArg(a, { shim }))]
|
|
3173
|
+
};
|
|
3174
|
+
if (env && Object.keys(env).length > 0) wrapped.env = { ...env };
|
|
3175
|
+
return wrapped;
|
|
3176
|
+
}
|
|
3177
|
+
const entry = { command, args: [...args] };
|
|
3178
|
+
if (env && Object.keys(env).length > 0) entry.env = { ...env };
|
|
3179
|
+
return entry;
|
|
3180
|
+
}
|
|
3181
|
+
const pkg = opts.pkg ?? "@yawlabs/mcp@latest";
|
|
3182
|
+
if (opts.oamBinPath && isAbsolute5(opts.oamBinPath) && opts.oamEntry && !opts.pkg) {
|
|
3183
|
+
return { command: opts.oamBinPath, args: ["run", "--no-check", opts.oamEntry] };
|
|
3184
|
+
}
|
|
3185
|
+
return opts.os === "windows" && opts.windowsWrap !== false ? { command: "cmd", args: ["/c", "npx", "-y", pkg] } : { command: "npx", args: ["-y", pkg] };
|
|
3186
|
+
}
|
|
3187
|
+
function isProjectLocalEntry(entryPath, cwd) {
|
|
3188
|
+
const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
3189
|
+
const entry = norm(entryPath);
|
|
3190
|
+
const here = norm(cwd);
|
|
3191
|
+
const idx = entry.indexOf("/node_modules/");
|
|
3192
|
+
if (idx <= 0) return false;
|
|
3193
|
+
const root = entry.slice(0, idx);
|
|
3194
|
+
return here === root || here.startsWith(`${root}/`);
|
|
3195
|
+
}
|
|
3196
|
+
function findLegacyEntry(container) {
|
|
3197
|
+
return LEGACY_ENTRY_NAMES.find((n) => n in container) ?? null;
|
|
3198
|
+
}
|
|
3199
|
+
function findBlockedContainerSegment(root, containerPath) {
|
|
3200
|
+
let node = root;
|
|
3201
|
+
for (let i = 0; i < containerPath.length; i++) {
|
|
3202
|
+
const value = node[containerPath[i]];
|
|
3203
|
+
if (value === void 0) return null;
|
|
3204
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
3205
|
+
node = value;
|
|
3206
|
+
continue;
|
|
3207
|
+
}
|
|
3208
|
+
return {
|
|
3209
|
+
path: containerPath.slice(0, i + 1),
|
|
3210
|
+
value,
|
|
3211
|
+
reparable: value === null || !Array.isArray(value) || value.length === 0
|
|
3212
|
+
};
|
|
3213
|
+
}
|
|
3214
|
+
return null;
|
|
3215
|
+
}
|
|
3216
|
+
function describeJsonShape(value) {
|
|
3217
|
+
if (value === null) return "null";
|
|
3218
|
+
if (Array.isArray(value)) return value.length === 0 ? "an empty array" : `an array of ${value.length}`;
|
|
3219
|
+
return `a ${typeof value}`;
|
|
3220
|
+
}
|
|
3221
|
+
function unparseableConfigFix(then) {
|
|
3222
|
+
return `fix the JSON by hand, or move the file aside, then ${then}`;
|
|
3223
|
+
}
|
|
3224
|
+
function blockedContainerFix(then) {
|
|
3225
|
+
return `make it an object (or remove the key), then ${then}`;
|
|
3226
|
+
}
|
|
3227
|
+
|
|
3228
|
+
// src/paths.ts
|
|
3229
|
+
import { realpath, stat as stat2 } from "fs/promises";
|
|
3230
|
+
import { homedir as homedir3 } from "os";
|
|
3231
|
+
import path from "path";
|
|
3232
|
+
function cacheDir() {
|
|
3233
|
+
if (process.platform === "win32") {
|
|
3234
|
+
const localAppData = process.env.LOCALAPPDATA;
|
|
3235
|
+
const base = localAppData && localAppData.length > 0 ? localAppData : path.join(homedir3(), "AppData", "Local");
|
|
3236
|
+
return path.join(base, "yaw-mcp", "Cache");
|
|
3237
|
+
}
|
|
3238
|
+
if (process.platform === "darwin") {
|
|
3239
|
+
return path.join(homedir3(), "Library", "Caches", "yaw-mcp");
|
|
3240
|
+
}
|
|
3241
|
+
const xdg = process.env.XDG_CACHE_HOME;
|
|
3242
|
+
return path.join(xdg && xdg.length > 0 ? xdg : path.join(homedir3(), ".cache"), "yaw-mcp");
|
|
3243
|
+
}
|
|
3244
|
+
var CONFIG_DIRNAME = ".yaw-mcp";
|
|
3245
|
+
var SIDECARS_DIRNAME = "sidecars";
|
|
3246
|
+
function sidecarsRoot(home = homedir3()) {
|
|
3247
|
+
return path.join(userConfigDir(home), SIDECARS_DIRNAME);
|
|
3248
|
+
}
|
|
3249
|
+
function sidecarsNodeModules(home = homedir3()) {
|
|
3250
|
+
return path.join(sidecarsRoot(home), "node_modules");
|
|
3251
|
+
}
|
|
3252
|
+
function userConfigDir(home = homedir3()) {
|
|
3253
|
+
return path.join(home, CONFIG_DIRNAME);
|
|
3254
|
+
}
|
|
3255
|
+
function normalizeForCompare(p) {
|
|
3256
|
+
return process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p;
|
|
3257
|
+
}
|
|
3258
|
+
function tildePath(abs, home, sep3) {
|
|
3259
|
+
if (!home || !path.isAbsolute(abs)) return abs;
|
|
3260
|
+
const absResolved = path.resolve(abs);
|
|
3261
|
+
const homeResolved = path.resolve(home);
|
|
3262
|
+
const head = absResolved.slice(0, homeResolved.length);
|
|
3263
|
+
if (normalizeForCompare(head) !== normalizeForCompare(homeResolved)) return abs;
|
|
3264
|
+
const rest = absResolved.slice(homeResolved.length);
|
|
3265
|
+
if (rest === "") return "~";
|
|
3266
|
+
let tail;
|
|
3267
|
+
if (homeResolved.endsWith(path.sep)) tail = rest;
|
|
3268
|
+
else if (rest.startsWith(path.sep)) tail = rest.slice(path.sep.length);
|
|
3269
|
+
else return abs;
|
|
3270
|
+
return `~${sep3}${tail.split(path.sep).join(sep3)}`;
|
|
3271
|
+
}
|
|
3272
|
+
async function realpathOrSelf(p) {
|
|
3273
|
+
try {
|
|
3274
|
+
return await realpath(p);
|
|
3275
|
+
} catch {
|
|
3276
|
+
return p;
|
|
3277
|
+
}
|
|
3278
|
+
}
|
|
3279
|
+
function isUnderHome(dir, homeResolved) {
|
|
3280
|
+
const dirKey = normalizeForCompare(dir);
|
|
3281
|
+
const homeKey = normalizeForCompare(homeResolved);
|
|
3282
|
+
if (dirKey === homeKey) return false;
|
|
3283
|
+
const rel = path.relative(homeKey, dirKey);
|
|
3284
|
+
if (rel === "" || path.isAbsolute(rel)) return false;
|
|
3285
|
+
return rel !== ".." && !rel.startsWith(`..${path.sep}`);
|
|
3286
|
+
}
|
|
3287
|
+
var ALLOW_UNOWNED_ENV = "YAW_MCP_ALLOW_UNOWNED_PROJECT_DIRS";
|
|
3288
|
+
var warnedUntrustedDirs = /* @__PURE__ */ new Set();
|
|
3289
|
+
function ownedByCurrentUser(st, env) {
|
|
3290
|
+
const geteuid = process.geteuid;
|
|
3291
|
+
if (typeof geteuid !== "function") return env[ALLOW_UNOWNED_ENV] === "1";
|
|
3292
|
+
return typeof st.uid === "number" && st.uid === geteuid.call(process);
|
|
3293
|
+
}
|
|
3294
|
+
async function findProjectConfigDir(start, home = homedir3(), env = process.env) {
|
|
3295
|
+
const homeFallback = home && home.length > 0 ? home : homedir3();
|
|
3296
|
+
const homeResolved = path.resolve(await realpathOrSelf(path.resolve(homeFallback)));
|
|
3297
|
+
let dir = path.resolve(await realpathOrSelf(path.resolve(start)));
|
|
3298
|
+
const userConfigKey = normalizeForCompare(await realpathOrSelf(path.join(homeResolved, CONFIG_DIRNAME)));
|
|
3299
|
+
const boundedByHome = isUnderHome(dir, homeResolved) || normalizeForCompare(dir) === normalizeForCompare(homeResolved);
|
|
3300
|
+
let prev = "";
|
|
3301
|
+
while (dir !== prev) {
|
|
3302
|
+
if (boundedByHome && !isUnderHome(dir, homeResolved)) return null;
|
|
3303
|
+
const candidate = path.join(dir, CONFIG_DIRNAME);
|
|
3304
|
+
try {
|
|
3305
|
+
const st = await stat2(candidate);
|
|
3306
|
+
if (!st.isDirectory()) {
|
|
3307
|
+
log("debug", "Skipping a .yaw-mcp that exists but is not a directory", { candidate });
|
|
3308
|
+
} else if (normalizeForCompare(await realpathOrSelf(candidate)) === userConfigKey) {
|
|
3309
|
+
log("debug", "Skipping a .yaw-mcp/ that resolves to the user-global config dir", { candidate });
|
|
3310
|
+
} else if (boundedByHome || ownedByCurrentUser(st, env)) {
|
|
3311
|
+
return candidate;
|
|
3312
|
+
} else {
|
|
3313
|
+
if (!warnedUntrustedDirs.has(candidate)) {
|
|
3314
|
+
warnedUntrustedDirs.add(candidate);
|
|
3315
|
+
log("warn", "Skipping an untrusted .yaw-mcp/ dir outside $HOME", {
|
|
3316
|
+
candidate,
|
|
3317
|
+
hint: `owned by another user, or ownership is unverifiable on this platform (set ${ALLOW_UNOWNED_ENV}=1 to trust it)`
|
|
3318
|
+
});
|
|
3319
|
+
}
|
|
3320
|
+
}
|
|
3321
|
+
} catch {
|
|
3322
|
+
}
|
|
3323
|
+
prev = dir;
|
|
3324
|
+
dir = path.dirname(dir);
|
|
3325
|
+
}
|
|
3326
|
+
return null;
|
|
3327
|
+
}
|
|
3328
|
+
var GUIDE_FILENAME = "YAW-MCP.md";
|
|
3329
|
+
function guidePath(configDir) {
|
|
3330
|
+
return path.join(configDir, GUIDE_FILENAME);
|
|
3331
|
+
}
|
|
3332
|
+
|
|
3333
|
+
// src/oam-spawn.ts
|
|
3334
|
+
function packageName(spec) {
|
|
3335
|
+
const start = spec.startsWith("@") ? 1 : 0;
|
|
3336
|
+
const at = spec.indexOf("@", start);
|
|
3337
|
+
return at === -1 ? spec : spec.slice(0, at);
|
|
3338
|
+
}
|
|
3339
|
+
function specSuffix(spec) {
|
|
3340
|
+
const start = spec.startsWith("@") ? 1 : 0;
|
|
3341
|
+
const at = spec.indexOf("@", start);
|
|
3342
|
+
return at === -1 ? null : spec.slice(at + 1);
|
|
3343
|
+
}
|
|
3344
|
+
var EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
3345
|
+
function specConstraint(spec) {
|
|
3346
|
+
const suffix = specSuffix(spec);
|
|
3347
|
+
if (suffix === null || suffix === "") return { kind: "any" };
|
|
3348
|
+
if (EXACT_VERSION.test(suffix)) return { kind: "exact", version: suffix };
|
|
3349
|
+
const versionish = /^[v=<>^~*\d]/.test(suffix) || suffix.includes("||");
|
|
3350
|
+
return versionish ? { kind: "range", raw: suffix } : { kind: "any" };
|
|
3351
|
+
}
|
|
3352
|
+
function isRegistrySpec(spec) {
|
|
3353
|
+
if (spec.includes(":") || /^[./~\\]/.test(spec)) return false;
|
|
3354
|
+
const m = /^(?:@([^/]+)\/)?([^./_][^/]*)$/.exec(packageName(spec));
|
|
3355
|
+
if (!m) return false;
|
|
3356
|
+
const [, scope, name] = m;
|
|
3357
|
+
return (scope === void 0 || encodeURIComponent(scope) === scope) && encodeURIComponent(name) === name;
|
|
3358
|
+
}
|
|
3359
|
+
function npxSpecIndex(args) {
|
|
3360
|
+
return args.findIndex((a) => a !== "-y" && a !== "--yes");
|
|
3361
|
+
}
|
|
3362
|
+
function npxSpec(args) {
|
|
3363
|
+
const idx = npxSpecIndex(args);
|
|
3364
|
+
if (idx === -1) return null;
|
|
3365
|
+
const spec = args[idx];
|
|
3366
|
+
return spec.startsWith("-") ? null : spec;
|
|
3367
|
+
}
|
|
3368
|
+
var MIN_OAM_VERSION = "0.15.2";
|
|
3369
|
+
var OAM_INSTALL_SH = "curl -fsSL https://oamjs.org/install.sh | sh";
|
|
3370
|
+
var OAM_INSTALL_PS1 = "irm https://oamjs.org/install.ps1 | iex";
|
|
3371
|
+
function oamInstallCommand(os) {
|
|
3372
|
+
return os === "windows" ? OAM_INSTALL_PS1 : OAM_INSTALL_SH;
|
|
3373
|
+
}
|
|
3374
|
+
function oamPublishesBinaryFor(platform, arch) {
|
|
3375
|
+
if (platform === "win32" || platform === "darwin") return arch === "x64" || arch === "arm64";
|
|
3376
|
+
if (platform === "linux") return arch === "x64";
|
|
3377
|
+
return false;
|
|
3378
|
+
}
|
|
3379
|
+
function oamPublishesBinaryForThisMachine() {
|
|
3380
|
+
return oamPublishesBinaryFor(process.platform, process.arch);
|
|
3381
|
+
}
|
|
3382
|
+
function oamNoBinaryReason() {
|
|
3383
|
+
return `no published oam binary for ${process.platform}-${process.arch} yet -- build from source at https://oamjs.org`;
|
|
3384
|
+
}
|
|
3385
|
+
function oamInstallAdvice(os) {
|
|
3386
|
+
if (os === CURRENT_OS && !oamPublishesBinaryForThisMachine()) return oamNoBinaryReason();
|
|
3387
|
+
return oamInstallCommand(os);
|
|
3388
|
+
}
|
|
3389
|
+
function oamHeapOomHint(stderr) {
|
|
3390
|
+
if (!stderr.includes("OAM-RT-OOM")) return null;
|
|
3391
|
+
return `The oam-hosted child hit its V8 heap cap (oam defaults to 4 GiB). Raise it with OAM_MAX_HEAP_MB=<mb> in this server's env, or set "runtime": "node" for this server in bundles.json.`;
|
|
3392
|
+
}
|
|
3393
|
+
var warnedOamUnavailable = false;
|
|
3394
|
+
function oamFailureLabel(failure) {
|
|
3395
|
+
if (failure === "timeout") return "`oam --version` did not answer in time";
|
|
3396
|
+
if (failure === "exit") return "`oam --version` exited non-zero";
|
|
3397
|
+
return "the binary could not be executed";
|
|
3398
|
+
}
|
|
3399
|
+
var oamProbeCache;
|
|
3400
|
+
function parseOamVersion(out) {
|
|
3401
|
+
const m = /\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?/.exec(out);
|
|
3402
|
+
return m ? m[0] : null;
|
|
3403
|
+
}
|
|
3404
|
+
function parseSemver(s) {
|
|
3405
|
+
const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?/.exec(s);
|
|
3406
|
+
if (!m) return null;
|
|
3407
|
+
const pre = m[4] === void 0 ? [] : m[4].split(".").map((id) => /^\d+$/.test(id) ? Number(id) : id);
|
|
3408
|
+
return { release: [Number(m[1]), Number(m[2]), Number(m[3])], pre };
|
|
3409
|
+
}
|
|
3410
|
+
function comparePre(a, b) {
|
|
3411
|
+
if (a.length === 0 || b.length === 0) {
|
|
3412
|
+
if (a.length === b.length) return 0;
|
|
3413
|
+
return a.length === 0 ? 1 : -1;
|
|
3414
|
+
}
|
|
3415
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) {
|
|
3416
|
+
const x = a[i];
|
|
3417
|
+
const y = b[i];
|
|
3418
|
+
if (x === y) continue;
|
|
3419
|
+
if (typeof x === "number" && typeof y === "number") return x < y ? -1 : 1;
|
|
3420
|
+
if (typeof x === "number") return -1;
|
|
3421
|
+
if (typeof y === "number") return 1;
|
|
3422
|
+
return x < y ? -1 : 1;
|
|
3423
|
+
}
|
|
3424
|
+
if (a.length === b.length) return 0;
|
|
3425
|
+
return a.length < b.length ? -1 : 1;
|
|
3426
|
+
}
|
|
3427
|
+
function compareSemver(a, b) {
|
|
3428
|
+
for (let i = 0; i < 3; i++) {
|
|
3429
|
+
if (a.release[i] !== b.release[i]) return a.release[i] < b.release[i] ? -1 : 1;
|
|
3430
|
+
}
|
|
3431
|
+
return comparePre(a.pre, b.pre);
|
|
3432
|
+
}
|
|
3433
|
+
function compareVersions(a, b) {
|
|
3434
|
+
const pa = parseSemver(a);
|
|
3435
|
+
const pb = parseSemver(b);
|
|
3436
|
+
if (!pa || !pb) return 0;
|
|
3437
|
+
return compareSemver(pa, pb);
|
|
3438
|
+
}
|
|
3439
|
+
function satisfiesExactPin(declared, want) {
|
|
3440
|
+
if (declared === null) return false;
|
|
3441
|
+
const d = parseSemver(declared);
|
|
3442
|
+
const w = parseSemver(want);
|
|
3443
|
+
if (d && w) return compareSemver(d, w) === 0;
|
|
3444
|
+
return declared === want;
|
|
3445
|
+
}
|
|
3446
|
+
function winNormalize(p, platform = process.platform) {
|
|
3447
|
+
return platform === "win32" ? p.replace(/\//g, "\\") : p;
|
|
3448
|
+
}
|
|
3449
|
+
function isExecutableFile(candidate, platform) {
|
|
3450
|
+
try {
|
|
3451
|
+
if (!statSync(candidate).isFile()) return false;
|
|
3452
|
+
if (platform !== "win32") accessSync(candidate, constants.X_OK);
|
|
3453
|
+
return true;
|
|
3454
|
+
} catch {
|
|
3455
|
+
return false;
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
function resolveBinAbsolute(bin, env = process.env, platform = process.platform) {
|
|
3459
|
+
if (isAbsolute6(bin)) return isExecutableFile(bin, platform) ? winNormalize(bin, platform) : null;
|
|
3460
|
+
if (bin.includes("/") || platform === "win32" && bin.includes("\\")) return null;
|
|
3461
|
+
const pathVar = env.PATH ?? env.Path ?? env.path ?? "";
|
|
3462
|
+
if (!pathVar) return null;
|
|
3463
|
+
const dirs = pathVar.split(platform === "win32" ? ";" : ":").filter(Boolean);
|
|
3464
|
+
const pathext = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
|
3465
|
+
const carriesExt = pathext.some((e) => bin.toLowerCase().endsWith(e.toLowerCase()));
|
|
3466
|
+
const exts = platform === "win32" ? carriesExt ? ["", ...pathext] : pathext : [""];
|
|
3467
|
+
for (const dir of dirs) {
|
|
3468
|
+
const clean = dir.replace(/^"|"$/g, "");
|
|
3469
|
+
for (const ext of exts) {
|
|
3470
|
+
const candidate = join9(clean, bin + ext);
|
|
3471
|
+
if (!isAbsolute6(candidate)) continue;
|
|
3472
|
+
if (isExecutableFile(candidate, platform)) return winNormalize(candidate, platform);
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
return null;
|
|
3476
|
+
}
|
|
3477
|
+
function classifyProbeFailure(err) {
|
|
3478
|
+
const code = err?.code;
|
|
3479
|
+
if (code === "ETIMEDOUT") return "timeout";
|
|
3480
|
+
if (code === "EOAMEXIT") return "exit";
|
|
3481
|
+
return "spawn";
|
|
3482
|
+
}
|
|
3483
|
+
var OAM_PROBE_TIMEOUT_MS = 3e3;
|
|
3484
|
+
var OAM_PROBE_KILL_SIGNAL = "SIGKILL";
|
|
3485
|
+
var OAM_PROBE_MAX_OUTPUT = 8 * 1024;
|
|
3486
|
+
var VERSION_CARRY = 32;
|
|
3487
|
+
function createProbeCollector(max = OAM_PROBE_MAX_OUTPUT) {
|
|
3488
|
+
let head = "";
|
|
3489
|
+
let carry = "";
|
|
3490
|
+
let found = null;
|
|
3491
|
+
let pending = null;
|
|
3492
|
+
return {
|
|
3493
|
+
push(chunk) {
|
|
3494
|
+
if (found !== null) return;
|
|
3495
|
+
const scan = carry + chunk;
|
|
3496
|
+
const hit = parseOamVersion(scan);
|
|
3497
|
+
if (hit !== null) {
|
|
3498
|
+
if (scan.endsWith(hit)) pending = hit;
|
|
3499
|
+
else found = hit;
|
|
3500
|
+
}
|
|
3501
|
+
carry = scan.slice(-VERSION_CARRY);
|
|
3502
|
+
if (head.length >= max) return;
|
|
3503
|
+
head += chunk.slice(0, max - head.length);
|
|
3504
|
+
},
|
|
3505
|
+
/** The version if one appeared anywhere, else the capped head (which
|
|
3506
|
+
* parses to null either way, so the caller's contract is unchanged).
|
|
3507
|
+
* Called after the stream closes, so a still-pending match is final: no
|
|
3508
|
+
* further chunk can extend it. */
|
|
3509
|
+
result() {
|
|
3510
|
+
return found ?? pending ?? head;
|
|
3511
|
+
},
|
|
3512
|
+
/** Test hook: bytes actually retained. */
|
|
3513
|
+
retainedLength() {
|
|
3514
|
+
return head.length;
|
|
3515
|
+
}
|
|
3516
|
+
};
|
|
3517
|
+
}
|
|
3518
|
+
function spawnVersionProbe(bin) {
|
|
3519
|
+
return new Promise((resolve6, reject) => {
|
|
3520
|
+
let settled = false;
|
|
3521
|
+
let timer;
|
|
3522
|
+
const settle = (fn) => {
|
|
3523
|
+
if (settled) return;
|
|
3524
|
+
settled = true;
|
|
3525
|
+
if (timer) clearTimeout(timer);
|
|
3526
|
+
fn();
|
|
3527
|
+
};
|
|
3528
|
+
let child;
|
|
3529
|
+
try {
|
|
3530
|
+
child = spawn(bin, ["--version"], {
|
|
3531
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
3532
|
+
windowsHide: process.platform === "win32",
|
|
3533
|
+
// oam is a binary yaw-mcp did not write; README promises the vault
|
|
3534
|
+
// passphrase is stripped from every child yaw-mcp starts, and this
|
|
3535
|
+
// probe was one of two spawns that still inherited process.env whole.
|
|
3536
|
+
env: stripInternalSecretsFromEnv(process.env)
|
|
3537
|
+
});
|
|
3538
|
+
} catch (err) {
|
|
3539
|
+
reject(err);
|
|
3540
|
+
return;
|
|
3541
|
+
}
|
|
3542
|
+
const collector = createProbeCollector();
|
|
3543
|
+
child.stdout?.setEncoding("utf8");
|
|
3544
|
+
child.stdout?.on("error", () => {
|
|
3545
|
+
});
|
|
3546
|
+
child.stdout?.on("data", (chunk) => collector.push(chunk));
|
|
3547
|
+
child.on("error", (err) => settle(() => reject(err)));
|
|
3548
|
+
child.on(
|
|
3549
|
+
"close",
|
|
3550
|
+
(code, signal) => settle(() => {
|
|
3551
|
+
if (code === 0) {
|
|
3552
|
+
resolve6(collector.result());
|
|
3553
|
+
return;
|
|
3554
|
+
}
|
|
3555
|
+
const err = new Error(`oam exited ${code ?? signal}`);
|
|
3556
|
+
err.code = "EOAMEXIT";
|
|
3557
|
+
reject(err);
|
|
3558
|
+
})
|
|
3559
|
+
);
|
|
3560
|
+
timer = setTimeout(() => {
|
|
3561
|
+
settle(() => {
|
|
3562
|
+
try {
|
|
3563
|
+
child.kill(OAM_PROBE_KILL_SIGNAL);
|
|
3564
|
+
} catch {
|
|
3565
|
+
}
|
|
3566
|
+
try {
|
|
3567
|
+
child.stdout?.destroy();
|
|
3568
|
+
child.unref();
|
|
3569
|
+
} catch {
|
|
3570
|
+
}
|
|
3571
|
+
const err = new Error(`oam --version exceeded ${OAM_PROBE_TIMEOUT_MS}ms`);
|
|
3572
|
+
err.code = "ETIMEDOUT";
|
|
3573
|
+
reject(err);
|
|
3574
|
+
});
|
|
3575
|
+
}, OAM_PROBE_TIMEOUT_MS);
|
|
3576
|
+
timer.unref?.();
|
|
3577
|
+
});
|
|
3578
|
+
}
|
|
3579
|
+
var oamProbeInFlight;
|
|
3580
|
+
var oamProbeGeneration = 0;
|
|
3581
|
+
async function probeOam(run = spawnVersionProbe) {
|
|
3582
|
+
if (oamProbeCache !== void 0) return oamProbeCache;
|
|
3583
|
+
if (oamProbeInFlight !== void 0) return oamProbeInFlight;
|
|
3584
|
+
const generation = oamProbeGeneration;
|
|
3585
|
+
oamProbeInFlight = probeOamUncached(run, generation).finally(() => {
|
|
3586
|
+
if (generation === oamProbeGeneration) oamProbeInFlight = void 0;
|
|
3587
|
+
});
|
|
3588
|
+
return oamProbeInFlight;
|
|
3589
|
+
}
|
|
3590
|
+
async function probeOamUncached(run, generation) {
|
|
3591
|
+
const explicit = Boolean(process.env.OAM_BIN);
|
|
3592
|
+
const bin = winNormalize(process.env.OAM_BIN || (process.platform === "win32" ? "oam.exe" : "oam"));
|
|
3593
|
+
const publish = (probe) => {
|
|
3594
|
+
if (generation === oamProbeGeneration) oamProbeCache = probe;
|
|
3595
|
+
return probe;
|
|
3596
|
+
};
|
|
3597
|
+
try {
|
|
3598
|
+
const version = parseOamVersion(await run(bin));
|
|
3599
|
+
if (version !== null && compareVersions(version, MIN_OAM_VERSION) < 0) {
|
|
3600
|
+
log("warn", "oam is installed but below the minimum supported version; falling back to node", {
|
|
3601
|
+
// The full token, prerelease suffix included: a build reporting
|
|
3602
|
+
// "0.8.3-rc.1" against a 0.8.3 floor lands here deliberately (semver
|
|
3603
|
+
// ranks a prerelease below its release), and naming it as "0.8.3" would
|
|
3604
|
+
// make this line look like a comparator bug.
|
|
3605
|
+
oamVersion: version,
|
|
3606
|
+
minVersion: MIN_OAM_VERSION,
|
|
3607
|
+
// The floor tracks the latest release, so below-min always means out
|
|
3608
|
+
// of date, and oam updates itself in place.
|
|
3609
|
+
updateWith: "oam self-update",
|
|
3610
|
+
// ...but updating alone changes nothing here. oamProbeCache is written
|
|
3611
|
+
// once per process and only ever cleared by a test hook, so every
|
|
3612
|
+
// opted-in server keeps landing on node until the broker restarts --
|
|
3613
|
+
// and an MCP broker under a desktop client lives for days. Without this
|
|
3614
|
+
// the user runs the update, sees no further log line, and reads a
|
|
3615
|
+
// working fix as a fix that did not work. The timeout and generic
|
|
3616
|
+
// failure warns say "for this process" for the same reason.
|
|
3617
|
+
thenRestart: "restart yaw-mcp; this probe is cached for the process lifetime"
|
|
3618
|
+
});
|
|
3619
|
+
return publish({ bin: null, binPath: null, version, belowMin: true, failure: null, failureDetail: null });
|
|
3620
|
+
}
|
|
3621
|
+
if (version === null) {
|
|
3622
|
+
log("debug", "oam --version printed no parsable version; the minimum-version gate did not run for this binary", {
|
|
3623
|
+
bin,
|
|
3624
|
+
minVersion: MIN_OAM_VERSION
|
|
3625
|
+
});
|
|
3626
|
+
}
|
|
3627
|
+
return publish({
|
|
3628
|
+
bin,
|
|
3629
|
+
// Resolved once, alongside the probe that proved the name spawns, so the
|
|
3630
|
+
// install path never has to re-derive it (or spawn `where`/`which`).
|
|
3631
|
+
binPath: resolveBinAbsolute(bin),
|
|
3632
|
+
version,
|
|
3633
|
+
belowMin: false,
|
|
3634
|
+
failure: null,
|
|
3635
|
+
failureDetail: null
|
|
3636
|
+
});
|
|
3637
|
+
} catch (err) {
|
|
3638
|
+
const code = err?.code;
|
|
3639
|
+
const absent = code === "ENOENT" && !explicit;
|
|
3640
|
+
if (code === "ETIMEDOUT") {
|
|
3641
|
+
log("warn", "oam did not respond to --version in time; falling back to node for this process", {
|
|
3642
|
+
timeoutMs: OAM_PROBE_TIMEOUT_MS,
|
|
3643
|
+
bin
|
|
3644
|
+
});
|
|
3645
|
+
} else if (code !== "ENOENT") {
|
|
3646
|
+
log("warn", "oam --version failed; falling back to node for this process", {
|
|
3647
|
+
bin,
|
|
3648
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3649
|
+
});
|
|
3650
|
+
} else if (explicit) {
|
|
3651
|
+
log("warn", "OAM_BIN points at a path that does not exist; falling back to node for this process", {
|
|
3652
|
+
bin,
|
|
3653
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3654
|
+
});
|
|
3655
|
+
}
|
|
3656
|
+
return publish({
|
|
3657
|
+
bin: null,
|
|
3658
|
+
binPath: null,
|
|
3659
|
+
version: null,
|
|
3660
|
+
belowMin: false,
|
|
3661
|
+
failure: absent ? null : classifyProbeFailure(err),
|
|
3662
|
+
failureDetail: absent ? null : err instanceof Error ? err.message : String(err)
|
|
3663
|
+
});
|
|
3664
|
+
}
|
|
3665
|
+
}
|
|
3666
|
+
var WIN_EXE_EXT = /\.(?:exe|cmd|bat)$/i;
|
|
3667
|
+
function nodeLaunchKind(command) {
|
|
3668
|
+
const base = (command.split(/[\\/]/).pop() ?? command).replace(WIN_EXE_EXT, "").toLowerCase();
|
|
3669
|
+
if (base === "node") return "node";
|
|
3670
|
+
if (base === "npx") return "npx";
|
|
3671
|
+
return null;
|
|
3672
|
+
}
|
|
3673
|
+
var TS_ENTRY_RE = /\.[mc]?ts$/i;
|
|
3674
|
+
function rewriteForOam(command, args, deps) {
|
|
3675
|
+
const bin = deps.oamBin;
|
|
3676
|
+
if (!bin) return { command, args };
|
|
3677
|
+
const toOam = (entry, rest) => {
|
|
3678
|
+
const flags = TS_ENTRY_RE.test(entry) ? ["--no-check"] : [];
|
|
3679
|
+
return {
|
|
3680
|
+
command: bin,
|
|
3681
|
+
args: rest.length > 0 ? ["run", ...flags, entry, "--", ...rest] : ["run", ...flags, entry]
|
|
3682
|
+
};
|
|
3683
|
+
};
|
|
3684
|
+
const kind = nodeLaunchKind(command);
|
|
3685
|
+
if (kind === "node") {
|
|
3686
|
+
const [entry, ...rest] = args;
|
|
3687
|
+
if (!entry) return { command, args };
|
|
3688
|
+
if (entry.startsWith("-")) return { command, args };
|
|
3689
|
+
return toOam(entry, rest);
|
|
3690
|
+
}
|
|
3691
|
+
if (kind === "npx") {
|
|
3692
|
+
const specIdx = npxSpecIndex(args);
|
|
3693
|
+
const spec = specIdx === -1 ? void 0 : args[specIdx];
|
|
3694
|
+
if (!spec) return { command, args };
|
|
3695
|
+
if (spec.startsWith("-")) {
|
|
3696
|
+
log("debug", "npx launch carries flags yaw-mcp does not parse; staying on npx instead of oam", {
|
|
3697
|
+
flag: spec,
|
|
3698
|
+
argc: args.length
|
|
3699
|
+
});
|
|
3700
|
+
return { command, args };
|
|
3701
|
+
}
|
|
3702
|
+
if (!isRegistrySpec(spec)) {
|
|
3703
|
+
log("debug", "npx spec is a git/path target, not a registry package; staying on npx instead of oam", { spec });
|
|
3704
|
+
return { command, args };
|
|
3705
|
+
}
|
|
3706
|
+
const pkg = packageName(spec);
|
|
3707
|
+
const constraint = specConstraint(spec);
|
|
3708
|
+
if (constraint.kind === "range") {
|
|
3709
|
+
log("debug", "npx spec constrains the version with a range yaw-mcp cannot evaluate; staying on npx", {
|
|
3710
|
+
package: pkg,
|
|
3711
|
+
range: constraint.raw
|
|
3712
|
+
});
|
|
3713
|
+
return { command, args };
|
|
3714
|
+
}
|
|
3715
|
+
const wantVersion = constraint.kind === "exact" ? constraint.version : null;
|
|
3716
|
+
const entry = deps.resolveEntry(pkg, wantVersion);
|
|
3717
|
+
if (!entry) {
|
|
3718
|
+
if (wantVersion !== null) {
|
|
3719
|
+
log("debug", "no on-disk copy declares the pinned version; staying on npx so the pin is honoured", {
|
|
3720
|
+
package: pkg,
|
|
3721
|
+
version: wantVersion
|
|
3722
|
+
});
|
|
3723
|
+
} else {
|
|
3724
|
+
log("debug", "npx package has no on-disk entry; staying on npx instead of oam", { package: pkg });
|
|
3725
|
+
}
|
|
3726
|
+
return { command, args };
|
|
3727
|
+
}
|
|
3728
|
+
return toOam(entry, args.slice(specIdx + 1));
|
|
3729
|
+
}
|
|
3730
|
+
return { command, args };
|
|
3731
|
+
}
|
|
3732
|
+
var NPX_CACHE_MARKER = `${sep}_npx${sep}`;
|
|
3733
|
+
function npxHashNodeModules(npxRoot) {
|
|
3734
|
+
try {
|
|
3735
|
+
return readdirSync(npxRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join9(npxRoot, e.name, "node_modules"));
|
|
3736
|
+
} catch {
|
|
3737
|
+
return [];
|
|
3738
|
+
}
|
|
3739
|
+
}
|
|
3740
|
+
function npxCacheNodeModules(fromUrl = import.meta.url) {
|
|
3741
|
+
let here;
|
|
3742
|
+
try {
|
|
3743
|
+
here = fileURLToPath(fromUrl);
|
|
3744
|
+
} catch {
|
|
3745
|
+
return [];
|
|
3746
|
+
}
|
|
3747
|
+
const idx = here.indexOf(NPX_CACHE_MARKER);
|
|
3748
|
+
if (idx === -1) return [];
|
|
3749
|
+
const npxRoot = here.slice(0, idx + NPX_CACHE_MARKER.length - sep.length);
|
|
3750
|
+
return npxHashNodeModules(npxRoot);
|
|
3751
|
+
}
|
|
3752
|
+
function npmrcValue(raw) {
|
|
3753
|
+
const v = raw.trim();
|
|
3754
|
+
const quoted = v.length > 1 && (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'"));
|
|
3755
|
+
if (quoted) {
|
|
3756
|
+
if (v.startsWith('"')) {
|
|
3757
|
+
try {
|
|
3758
|
+
return JSON.parse(v);
|
|
3759
|
+
} catch {
|
|
3760
|
+
return v.slice(1, -1);
|
|
3761
|
+
}
|
|
3762
|
+
}
|
|
3763
|
+
return v.slice(1, -1);
|
|
3764
|
+
}
|
|
3765
|
+
let out = "";
|
|
3766
|
+
let esc = false;
|
|
3767
|
+
for (const c of v) {
|
|
3768
|
+
if (esc) {
|
|
3769
|
+
out += ";#\\".includes(c) ? c : `\\${c}`;
|
|
3770
|
+
esc = false;
|
|
3771
|
+
continue;
|
|
3772
|
+
}
|
|
3773
|
+
if (c === ";" || c === "#") break;
|
|
3774
|
+
if (c === "\\") {
|
|
3775
|
+
esc = true;
|
|
3776
|
+
continue;
|
|
3777
|
+
}
|
|
3778
|
+
out += c;
|
|
3779
|
+
}
|
|
3780
|
+
if (esc) out += "\\";
|
|
3781
|
+
return out.trim();
|
|
3782
|
+
}
|
|
3783
|
+
function npmrcCache(file) {
|
|
3784
|
+
let text;
|
|
3785
|
+
try {
|
|
3786
|
+
text = readFileSync(file, "utf8");
|
|
3787
|
+
} catch {
|
|
3788
|
+
return null;
|
|
3789
|
+
}
|
|
3790
|
+
let last = null;
|
|
3791
|
+
for (const line of text.split(/\r?\n/)) {
|
|
3792
|
+
const m = /^\s*cache\s*=(.*)$/.exec(line);
|
|
3793
|
+
if (!m) continue;
|
|
3794
|
+
const value = expandNpmrcEnv(npmrcValue(m[1]));
|
|
3795
|
+
if (!value) continue;
|
|
3796
|
+
last = value.startsWith("~/") ? join9(homedir4(), value.slice(2)) : value;
|
|
3797
|
+
}
|
|
3798
|
+
return last;
|
|
3799
|
+
}
|
|
3800
|
+
function expandNpmrcEnv(value, env = process.env) {
|
|
3801
|
+
return value.replace(/(\\*)\$\{([^${}]+)\}/g, (orig, esc, name) => {
|
|
3802
|
+
if (esc.length % 2 === 1) return orig.slice((esc.length + 1) / 2);
|
|
3803
|
+
const val = env[name];
|
|
3804
|
+
return esc.slice(esc.length / 2) + (val === void 0 ? `\${${name}}` : val);
|
|
3805
|
+
});
|
|
3806
|
+
}
|
|
3807
|
+
var npmCacheDirCache = /* @__PURE__ */ new Map();
|
|
3808
|
+
function npmCacheDir(fromUrl = import.meta.url) {
|
|
3809
|
+
const cached = npmCacheDirCache.get(fromUrl);
|
|
3810
|
+
if (cached !== void 0) return cached;
|
|
3811
|
+
const resolved = resolveNpmCacheDir(fromUrl);
|
|
3812
|
+
npmCacheDirCache.set(fromUrl, resolved);
|
|
3813
|
+
return resolved;
|
|
3814
|
+
}
|
|
3815
|
+
function resolveNpmCacheDir(fromUrl) {
|
|
3816
|
+
const envKey = Object.keys(process.env).find((k) => /^npm_config_cache$/i.test(k));
|
|
3817
|
+
const fromEnv = envKey === void 0 ? void 0 : process.env[envKey];
|
|
3818
|
+
if (fromEnv) return fromEnv;
|
|
3819
|
+
const candidates = [join9(homedir4(), ".npmrc")];
|
|
3820
|
+
for (const nodeModules of ownNodeModules(fromUrl)) {
|
|
3821
|
+
candidates.push(
|
|
3822
|
+
join9(dirname(nodeModules), "etc", "npmrc"),
|
|
3823
|
+
// <prefix>/node_modules (Windows)
|
|
3824
|
+
join9(dirname(dirname(nodeModules)), "etc", "npmrc"),
|
|
3825
|
+
// <prefix>/lib/node_modules (POSIX)
|
|
3826
|
+
join9(nodeModules, "npm", "npmrc")
|
|
3827
|
+
// builtin, beside npm itself
|
|
3828
|
+
);
|
|
3829
|
+
}
|
|
3830
|
+
const nodeDir = dirname(process.execPath);
|
|
3831
|
+
candidates.push(
|
|
3832
|
+
join9(nodeDir, "node_modules", "npm", "npmrc"),
|
|
3833
|
+
// Windows layout
|
|
3834
|
+
join9(nodeDir, "..", "lib", "node_modules", "npm", "npmrc")
|
|
3835
|
+
// POSIX layout
|
|
3836
|
+
);
|
|
3837
|
+
for (const file of candidates) {
|
|
3838
|
+
const cache = npmrcCache(file);
|
|
3839
|
+
if (cache) return cache;
|
|
3840
|
+
}
|
|
3841
|
+
const fallback = process.platform === "win32" ? process.env.LOCALAPPDATA && join9(process.env.LOCALAPPDATA, "npm-cache") : join9(homedir4(), ".npm");
|
|
3842
|
+
return fallback && existsSync2(fallback) ? fallback : null;
|
|
3843
|
+
}
|
|
3844
|
+
function npmCacheNpxNodeModules(cacheDir2) {
|
|
3845
|
+
if (!cacheDir2) return [];
|
|
3846
|
+
return npxHashNodeModules(join9(cacheDir2, "_npx"));
|
|
3847
|
+
}
|
|
3848
|
+
function ownNodeModules(fromUrl = import.meta.url) {
|
|
3849
|
+
let here;
|
|
3850
|
+
try {
|
|
3851
|
+
here = fileURLToPath(fromUrl);
|
|
3852
|
+
} catch {
|
|
3853
|
+
return [];
|
|
3854
|
+
}
|
|
3855
|
+
const seg = `${sep}node_modules${sep}`;
|
|
3856
|
+
const idx = here.lastIndexOf(seg);
|
|
3857
|
+
if (idx === -1) return [];
|
|
3858
|
+
return [here.slice(0, idx + seg.length - sep.length)];
|
|
3859
|
+
}
|
|
3860
|
+
function packageEntry(pkgDir, pkg) {
|
|
3861
|
+
const pjPath = join9(pkgDir, "package.json");
|
|
3862
|
+
if (!existsSync2(pjPath)) return null;
|
|
3863
|
+
let parsed;
|
|
3864
|
+
try {
|
|
3865
|
+
parsed = JSON.parse(readFileSync(pjPath, "utf8"));
|
|
3866
|
+
} catch {
|
|
3867
|
+
return null;
|
|
3868
|
+
}
|
|
3869
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
3870
|
+
const j = parsed;
|
|
3871
|
+
let rel;
|
|
3872
|
+
if (typeof j.bin === "string") {
|
|
3873
|
+
rel = j.bin;
|
|
3874
|
+
} else if (j.bin && typeof j.bin === "object") {
|
|
3875
|
+
const bins = j.bin;
|
|
3876
|
+
const own = (key) => typeof key === "string" && Object.hasOwn(bins, key) ? bins[key] : void 0;
|
|
3877
|
+
const unscoped = pkg.slice(pkg.lastIndexOf("/") + 1);
|
|
3878
|
+
rel = own(unscoped) ?? own(j.name) ?? Object.values(bins)[0];
|
|
3879
|
+
}
|
|
3880
|
+
if (!rel && typeof j.main === "string") rel = j.main;
|
|
3881
|
+
if (typeof rel !== "string" || rel.length === 0) return null;
|
|
3882
|
+
const entry = isAbsolute6(rel) ? rel : join9(pkgDir, rel);
|
|
3883
|
+
if (!existsSync2(entry)) return null;
|
|
3884
|
+
return {
|
|
3885
|
+
entry,
|
|
3886
|
+
version: typeof j.version === "string" ? j.version : null
|
|
3887
|
+
};
|
|
3888
|
+
}
|
|
3889
|
+
function resolveNpmEntry(pkg, fromUrl = import.meta.url, npmCache = npmCacheDir(fromUrl), managedRoot = sidecarsNodeModules(), wantVersion = null) {
|
|
3890
|
+
const parts = pkg.split("/");
|
|
3891
|
+
const own = ownNodeModules(fromUrl);
|
|
3892
|
+
const ownCache = own.filter((nodeModules) => nodeModules.includes(NPX_CACHE_MARKER));
|
|
3893
|
+
const ownDurable = own.filter((nodeModules) => !nodeModules.includes(NPX_CACHE_MARKER));
|
|
3894
|
+
const durable = [
|
|
3895
|
+
...managedRoot ? [{ nodeModules: managedRoot, source: "managed" }] : [],
|
|
3896
|
+
// Only the copies that are genuinely durable take part in the take-outright
|
|
3897
|
+
// loop. A sidecar sitting in the broker's OWN _npx hash dir is a cache copy
|
|
3898
|
+
// like any other, so it belongs in the highest-version scan below -- taking
|
|
3899
|
+
// it outright let an old build in our own hash dir beat a NEWER copy in a
|
|
3900
|
+
// sibling cache dir, which is the opposite of the rule that scan exists to
|
|
3901
|
+
// enforce. (Only the ranking was wrong: the replaced branch already keyed
|
|
3902
|
+
// `source` off NPX_CACHE_MARKER, so an own `_npx` copy was tagged
|
|
3903
|
+
// "npx-cache" and did get the `npx -y <pkg>@latest` refresh advice.)
|
|
3904
|
+
...ownDurable.map((nodeModules) => ({ nodeModules, source: "durable" }))
|
|
3905
|
+
];
|
|
3906
|
+
for (const { nodeModules, source } of durable) {
|
|
3907
|
+
const hit = packageEntry(join9(nodeModules, ...parts), pkg);
|
|
3908
|
+
if (!hit) continue;
|
|
3909
|
+
if (wantVersion !== null && !satisfiesExactPin(hit.version, wantVersion)) continue;
|
|
3910
|
+
notePinnedSidecar(pkg, hit.version, source, nodeModules);
|
|
3911
|
+
return hit.entry;
|
|
3912
|
+
}
|
|
3913
|
+
const roots = /* @__PURE__ */ new Set([...ownCache, ...npxCacheNodeModules(fromUrl), ...npmCacheNpxNodeModules(npmCache)]);
|
|
3914
|
+
let best = null;
|
|
3915
|
+
let bestRoot = null;
|
|
3916
|
+
let bestParsed = null;
|
|
3917
|
+
for (const nodeModules of roots) {
|
|
3918
|
+
const hit = packageEntry(join9(nodeModules, ...parts), pkg);
|
|
3919
|
+
if (!hit) continue;
|
|
3920
|
+
if (wantVersion !== null && !satisfiesExactPin(hit.version, wantVersion)) continue;
|
|
3921
|
+
const parsed = hit.version === null ? null : parseSemver(hit.version);
|
|
3922
|
+
const wins = best === null || parsed !== null && (bestParsed === null || compareSemver(parsed, bestParsed) > 0);
|
|
3923
|
+
if (wins) {
|
|
3924
|
+
best = hit;
|
|
3925
|
+
bestRoot = nodeModules;
|
|
3926
|
+
bestParsed = parsed;
|
|
3927
|
+
}
|
|
3928
|
+
}
|
|
3929
|
+
if (best !== null && bestRoot !== null) notePinnedSidecar(pkg, best.version, "npx-cache", bestRoot);
|
|
3930
|
+
return best?.entry ?? null;
|
|
3931
|
+
}
|
|
3932
|
+
var REFRESH_COMMAND = {
|
|
3933
|
+
managed: () => "yaw-mcp sidecars install",
|
|
3934
|
+
durable: (pkg) => `npm install ${pkg}@latest`,
|
|
3935
|
+
// No trailing flag. `npx -y <pkg>@latest` re-resolves the tag and refreshes
|
|
3936
|
+
// the cache tree BEFORE it execs the binary, which is all the refresh
|
|
3937
|
+
// needs -- and stdio MCP servers ignore flags like `--help` and simply
|
|
3938
|
+
// start, so tacking one on turns "runs briefly" into "hangs the terminal
|
|
3939
|
+
// on a server waiting for stdin" (measured on
|
|
3940
|
+
// @modelcontextprotocol/server-memory). `npm cache add` is no substitute:
|
|
3941
|
+
// it only fills _cacache, never the _npx install tree this resolver reads.
|
|
3942
|
+
// No inline `#` comment either: that is comment syntax only in sh and
|
|
3943
|
+
// PowerShell -- cmd.exe hands `#` and everything after it to npx as literal
|
|
3944
|
+
// argv for the spawned server, which arg-parsing servers fail on. The
|
|
3945
|
+
// Ctrl-C guidance rides in REFRESH_NOTE instead, so the command itself is
|
|
3946
|
+
// copy-paste safe in all three shells.
|
|
3947
|
+
"npx-cache": (pkg) => `npx -y ${pkg}@latest`
|
|
3948
|
+
};
|
|
3949
|
+
var REFRESH_NOTE = {
|
|
3950
|
+
"npx-cache": "then Ctrl-C -- the cache is refreshed before the server starts"
|
|
3951
|
+
};
|
|
3952
|
+
var pinnedReported = /* @__PURE__ */ new Set();
|
|
3953
|
+
function notePinnedSidecar(pkg, version, source, from) {
|
|
3954
|
+
if (pinnedReported.has(pkg)) return;
|
|
3955
|
+
pinnedReported.add(pkg);
|
|
3956
|
+
log(
|
|
3957
|
+
source === "managed" ? "debug" : "info",
|
|
3958
|
+
"hosting sidecar on oam from an on-disk copy; it will not self-update the way npx does",
|
|
3959
|
+
{
|
|
3960
|
+
package: pkg,
|
|
3961
|
+
version: version ?? "unknown",
|
|
3962
|
+
source,
|
|
3963
|
+
// The node_modules the entry was actually resolved out of. refreshWith
|
|
3964
|
+
// cannot name it -- a durable tree may be global or project-local, and
|
|
3965
|
+
// the command differs -- so this is what makes the advice actionable
|
|
3966
|
+
// rather than something to run in whatever cwd the user happens to be.
|
|
3967
|
+
from,
|
|
3968
|
+
refreshWith: REFRESH_COMMAND[source](pkg),
|
|
3969
|
+
// Only npx-cache has one today; JSON.stringify drops the field entirely
|
|
3970
|
+
// for the sources that do not, rather than printing "undefined".
|
|
3971
|
+
refreshNote: REFRESH_NOTE[source]
|
|
3972
|
+
}
|
|
3973
|
+
);
|
|
3974
|
+
}
|
|
3975
|
+
function resolveStableNpmEntry(pkg, fromUrl = import.meta.url) {
|
|
3976
|
+
for (const nodeModules of ownNodeModules(fromUrl)) {
|
|
3977
|
+
if (nodeModules.includes(NPX_CACHE_MARKER)) continue;
|
|
3978
|
+
const hit = packageEntry(join9(nodeModules, ...pkg.split("/")), pkg);
|
|
3979
|
+
if (hit) return hit.entry;
|
|
3980
|
+
}
|
|
3981
|
+
return null;
|
|
3982
|
+
}
|
|
3983
|
+
async function resolveOamSpawn(command, args, optedIn = true) {
|
|
3984
|
+
const probe = await probeOam();
|
|
3985
|
+
if (optedIn && probe.bin === null && !probe.belowMin && !warnedOamUnavailable && nodeLaunchKind(command) !== null) {
|
|
3986
|
+
warnedOamUnavailable = true;
|
|
3987
|
+
if (probe.failure !== null) {
|
|
3988
|
+
log("warn", "a server opted in to oam but oam is installed and unusable; running it on node instead", {
|
|
3989
|
+
reason: oamFailureLabel(probe.failure),
|
|
3990
|
+
// The raw error behind the label. It is the part a support ticket needs
|
|
3991
|
+
// and the part the plain-English line deliberately does not carry.
|
|
3992
|
+
detail: probe.failureDetail,
|
|
3993
|
+
// No install commands: the install is already there. Pointing OAM_BIN
|
|
3994
|
+
// at a working copy is the actionable move, and the probe is cached for
|
|
3995
|
+
// the process lifetime, so repairing it needs a restart to take effect.
|
|
3996
|
+
overrideWith: "OAM_BIN",
|
|
3997
|
+
thenRestart: "restart yaw-mcp; this probe is cached for the process lifetime"
|
|
3998
|
+
});
|
|
3999
|
+
} else {
|
|
4000
|
+
log("warn", "a server opted in to oam but oam is not installed; running it on node instead", {
|
|
4001
|
+
// Both, not oamInstallCommand(CURRENT_OS): this is a structured log
|
|
4002
|
+
// line read off a server's stderr, which is routinely a different
|
|
4003
|
+
// machine from the one reading it. The rendered REPORTS (doctor,
|
|
4004
|
+
// install) are the surfaces that know which platform they are about.
|
|
4005
|
+
install: OAM_INSTALL_SH,
|
|
4006
|
+
installWindows: OAM_INSTALL_PS1,
|
|
4007
|
+
overrideWith: "OAM_BIN"
|
|
4008
|
+
});
|
|
4009
|
+
}
|
|
4010
|
+
}
|
|
4011
|
+
return rewriteForOam(command, args, {
|
|
4012
|
+
oamBin: probe.bin,
|
|
4013
|
+
// The three injectables (fromUrl, npmCache, managedRoot) keep their
|
|
4014
|
+
// production defaults -- explicit `undefined` rather than a reorder,
|
|
4015
|
+
// because they are positional and every test call site passes them.
|
|
4016
|
+
resolveEntry: (pkg, wantVersion) => resolveNpmEntry(pkg, void 0, void 0, void 0, wantVersion)
|
|
4017
|
+
});
|
|
4018
|
+
}
|
|
4019
|
+
function isOamCommand(command) {
|
|
4020
|
+
const base = command.split(/[\\/]/).pop() ?? command;
|
|
4021
|
+
return /^oam(\.exe)?$/i.test(base);
|
|
4022
|
+
}
|
|
4023
|
+
function isOamLaunch(command, args = []) {
|
|
4024
|
+
if (isOamCommand(command)) return true;
|
|
4025
|
+
const base = command.split(/[\\/]/).pop() ?? command;
|
|
4026
|
+
if (/^cmd(\.exe)?$/i.test(base)) {
|
|
4027
|
+
const first = args.find((a) => !/^\/[a-z]$/i.test(a));
|
|
4028
|
+
return first !== void 0 && isOamCommand(first);
|
|
4029
|
+
}
|
|
4030
|
+
if (/^(sh|bash|zsh|dash)$/i.test(base)) {
|
|
4031
|
+
const dashC = args.indexOf("-c");
|
|
4032
|
+
const payload = dashC >= 0 ? args[dashC + 1] : args[0];
|
|
4033
|
+
if (payload === void 0) return false;
|
|
4034
|
+
const firstToken = payload.trim().split(/\s+/)[0]?.replace(/^["']|["']$/g, "");
|
|
4035
|
+
return firstToken !== void 0 && firstToken.length > 0 && isOamCommand(firstToken);
|
|
4036
|
+
}
|
|
4037
|
+
return false;
|
|
4038
|
+
}
|
|
4039
|
+
|
|
4040
|
+
// src/upgrade-cmd.ts
|
|
4041
|
+
var POSIX_GLOBAL_LIB_PREFIX = /^(?:[A-Za-z]:)?(?:\/usr(?:\/local)?|\/opt\/[^/]+)\/lib\/node_modules\/@yawlabs\/mcp\//;
|
|
4042
|
+
var MANAGED_NODE_LIB_PREFIX = /\/(?:\.nvm\/versions\/node\/[^/]+|\.volta\/tools\/image\/node\/[^/]+|\.asdf\/installs\/nodejs\/[^/]+|(?:\.local\/share\/)?\.?fnm\/node-versions\/[^/]+\/installation|\.nodenv\/versions\/[^/]+|\.nvs\/[^/]+\/[^/]+\/[^/]+|n\/versions\/node\/[^/]+|\.local)\/lib\/node_modules\/@yawlabs\/mcp\//;
|
|
4043
|
+
var UPGRADE_USAGE = `Usage: yaw-mcp upgrade [--run] [--json]
|
|
4044
|
+
|
|
4045
|
+
Show (or execute) the command to upgrade @yawlabs/mcp to the latest version.
|
|
4046
|
+
|
|
4047
|
+
--run Run the upgrade in place (global npm, pnpm, bun, and local npm
|
|
4048
|
+
installs). No-op for npx installs -- they always fetch the latest.
|
|
4049
|
+
--json Emit a machine-readable snapshot ({ current, latest, stale,
|
|
4050
|
+
method, command, cwd }) instead of prose. "cwd" is the directory
|
|
4051
|
+
"command" must run IN -- the package-tree root for a
|
|
4052
|
+
local-node-modules install, null for every other method (the
|
|
4053
|
+
command can run anywhere). Running a local install's command from
|
|
4054
|
+
the wrong directory creates a stray package.json + node_modules
|
|
4055
|
+
there instead of upgrading the tree.
|
|
4056
|
+
NOTE: --json is a report-only snapshot; it never spawns an upgrade
|
|
4057
|
+
even when combined with --run, and exits 1 whenever "stale" is
|
|
4058
|
+
true. Use --run without --json to actually perform the upgrade.`;
|
|
4059
|
+
function parseUpgradeArgs(argv) {
|
|
4060
|
+
const opts = {};
|
|
4061
|
+
for (const a of argv) {
|
|
4062
|
+
if (a === "--run") opts.run = true;
|
|
4063
|
+
else if (a === "--json") opts.json = true;
|
|
4064
|
+
else if (a === "--help" || a === "-h") return { ok: false, error: UPGRADE_USAGE, help: true };
|
|
4065
|
+
else return { ok: false, error: `yaw-mcp upgrade: unknown argument "${a}"
|
|
4066
|
+
|
|
4067
|
+
${UPGRADE_USAGE}` };
|
|
4068
|
+
}
|
|
4069
|
+
return { ok: true, options: opts };
|
|
4070
|
+
}
|
|
4071
|
+
function detectInstallMethod(argvPath, realpath2 = realpathSync, resolveWhen = ["unknown"]) {
|
|
4072
|
+
if (!argvPath) return "unknown";
|
|
4073
|
+
const literal = classifyEntrypoint(argvPath);
|
|
4074
|
+
if (!resolveWhen.includes(literal)) return literal;
|
|
4075
|
+
let resolved;
|
|
4076
|
+
try {
|
|
4077
|
+
resolved = realpath2(argvPath);
|
|
4078
|
+
} catch {
|
|
4079
|
+
return literal;
|
|
4080
|
+
}
|
|
4081
|
+
return resolved === argvPath ? literal : classifyEntrypoint(resolved);
|
|
4082
|
+
}
|
|
4083
|
+
function classifyEntrypoint(argvPath) {
|
|
4084
|
+
const normalized = argvPath.replace(/\\/g, "/");
|
|
4085
|
+
if (/\/_npx\/[0-9a-f]+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "npx";
|
|
4086
|
+
if (/\/app\.asar\.unpacked\//.test(normalized)) return "bundled-app";
|
|
4087
|
+
if (/\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
|
|
4088
|
+
if (POSIX_GLOBAL_LIB_PREFIX.test(normalized)) return "global-npm";
|
|
4089
|
+
if (MANAGED_NODE_LIB_PREFIX.test(normalized)) return "global-npm";
|
|
4090
|
+
if (/\/AppData\/Roaming\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
|
|
4091
|
+
if (/\/bin\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
|
|
4092
|
+
if (/\/pnpm\/global\/\d+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "pnpm-global";
|
|
4093
|
+
if (/\/\.bun\/install\/global\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "bun-global";
|
|
4094
|
+
if (/\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "local-node-modules";
|
|
4095
|
+
if (/\/(yaw-mcp|mcph|mcp)\/(dist|src)\//.test(normalized)) return "dev-checkout";
|
|
4096
|
+
return "unknown";
|
|
4097
|
+
}
|
|
4098
|
+
function localInstallRoot(argvPath) {
|
|
4099
|
+
if (!argvPath) return null;
|
|
4100
|
+
const idx = argvPath.replace(/\\/g, "/").indexOf("/node_modules/");
|
|
4101
|
+
return idx > 0 ? argvPath.slice(0, idx) : null;
|
|
4102
|
+
}
|
|
4103
|
+
function runningPackageDir(argvPath, realpath2 = realpathSync) {
|
|
4104
|
+
if (!argvPath) return null;
|
|
4105
|
+
const literal = packageDirOf(argvPath);
|
|
4106
|
+
if (literal !== null) return literal;
|
|
4107
|
+
try {
|
|
4108
|
+
return packageDirOf(realpath2(argvPath));
|
|
4109
|
+
} catch {
|
|
4110
|
+
return null;
|
|
4111
|
+
}
|
|
4112
|
+
}
|
|
4113
|
+
function packageDirOf(p) {
|
|
4114
|
+
const marker = "/node_modules/@yawlabs/mcp/";
|
|
4115
|
+
const idx = p.replace(/\\/g, "/").lastIndexOf(marker);
|
|
4116
|
+
return idx === -1 ? null : p.slice(0, idx + marker.length - 1);
|
|
4117
|
+
}
|
|
4118
|
+
function defaultInstalledVersion(pkgDir) {
|
|
4119
|
+
if (process.env.VITEST) return null;
|
|
4120
|
+
try {
|
|
4121
|
+
const parsed = JSON.parse(readFileSync2(join10(pkgDir, "package.json"), "utf8"));
|
|
4122
|
+
return typeof parsed.version === "string" ? parsed.version : null;
|
|
4123
|
+
} catch {
|
|
4124
|
+
return null;
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
function killProcessTree(child, platform = process.platform, spawnImpl = spawn2) {
|
|
4128
|
+
if (platform === "win32" && child.pid !== void 0) {
|
|
4129
|
+
try {
|
|
4130
|
+
spawnImpl("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }).on("error", () => {
|
|
4131
|
+
});
|
|
4132
|
+
} catch {
|
|
4133
|
+
}
|
|
4134
|
+
}
|
|
4135
|
+
child.kill();
|
|
4136
|
+
}
|
|
4137
|
+
async function npmGlobalPrefix(spawnImpl) {
|
|
4138
|
+
if (process.env.VITEST && !spawnImpl) return null;
|
|
4139
|
+
const spawnFn = spawnImpl ?? spawn2;
|
|
4140
|
+
return new Promise((resolve6) => {
|
|
4141
|
+
const child = spawnFn("npm", ["prefix", "-g"], {
|
|
4142
|
+
shell: process.platform === "win32",
|
|
4143
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
4144
|
+
// Even a read-only `npm prefix -g` is an npm invocation: yaw-mcp's own
|
|
4145
|
+
// secrets do not ride into it. See internal-secret-env.ts.
|
|
4146
|
+
env: stripInternalSecretsFromEnv(process.env)
|
|
4147
|
+
});
|
|
4148
|
+
let out = "";
|
|
4149
|
+
const timer = setTimeout(() => {
|
|
4150
|
+
killProcessTree(child);
|
|
4151
|
+
resolve6(null);
|
|
4152
|
+
}, 3e3);
|
|
4153
|
+
child.stdout?.on("data", (d) => {
|
|
4154
|
+
out += String(d);
|
|
4155
|
+
});
|
|
4156
|
+
child.on("close", (code) => {
|
|
4157
|
+
clearTimeout(timer);
|
|
4158
|
+
resolve6(code === 0 && out.trim() ? out.trim() : null);
|
|
4159
|
+
});
|
|
4160
|
+
child.on("error", () => {
|
|
4161
|
+
clearTimeout(timer);
|
|
4162
|
+
resolve6(null);
|
|
4163
|
+
});
|
|
4164
|
+
});
|
|
4165
|
+
}
|
|
4166
|
+
function comparablePath(p) {
|
|
4167
|
+
let real = p;
|
|
4168
|
+
try {
|
|
4169
|
+
real = realpathSync(p);
|
|
4170
|
+
} catch {
|
|
4171
|
+
}
|
|
4172
|
+
const normalized = real.replace(/\\/g, "/");
|
|
4173
|
+
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
|
|
4174
|
+
}
|
|
4175
|
+
async function refineInstallMethod(method, argvPath, npmPrefix = npmGlobalPrefix) {
|
|
4176
|
+
if (method !== "local-node-modules" && method !== "unknown") return method;
|
|
4177
|
+
if (!argvPath) return method;
|
|
4178
|
+
const prefix = await npmPrefix();
|
|
4179
|
+
if (!prefix) return method;
|
|
4180
|
+
const entry = comparablePath(argvPath);
|
|
4181
|
+
const pfx = comparablePath(prefix);
|
|
4182
|
+
if (entry.startsWith(`${pfx}/node_modules/`) || entry.startsWith(`${pfx}/lib/node_modules/`)) {
|
|
4183
|
+
return "global-npm";
|
|
4184
|
+
}
|
|
4185
|
+
return method;
|
|
4186
|
+
}
|
|
4187
|
+
var UPGRADE_PACKAGE_SPEC = "@yawlabs/mcp@latest";
|
|
4188
|
+
var UPGRADE_COMMANDS = {
|
|
4189
|
+
"global-npm": { cmd: "npm", args: ["install", "-g", UPGRADE_PACKAGE_SPEC] },
|
|
4190
|
+
"pnpm-global": { cmd: "pnpm", args: ["add", "-g", UPGRADE_PACKAGE_SPEC] },
|
|
4191
|
+
"bun-global": { cmd: "bun", args: ["add", "-g", UPGRADE_PACKAGE_SPEC] },
|
|
4192
|
+
"local-node-modules": { cmd: "npm", args: ["install", UPGRADE_PACKAGE_SPEC] },
|
|
4193
|
+
npx: null,
|
|
4194
|
+
"bundled-app": null,
|
|
4195
|
+
"dev-checkout": null,
|
|
4196
|
+
binary: null,
|
|
4197
|
+
unknown: null
|
|
4198
|
+
};
|
|
4199
|
+
var GLOBAL_UPGRADE_METHODS = ["global-npm", "pnpm-global", "bun-global"];
|
|
4200
|
+
function upgradeSpawnSpec(method, prefixArg = null) {
|
|
4201
|
+
const base = UPGRADE_COMMANDS[method];
|
|
4202
|
+
if (base === null) return null;
|
|
4203
|
+
const args = [...base.args];
|
|
4204
|
+
if (method === "global-npm" && prefixArg !== null) args.splice(args.length - 1, 0, "--prefix", prefixArg);
|
|
4205
|
+
return { cmd: base.cmd, args };
|
|
4206
|
+
}
|
|
4207
|
+
function upgradeCommandLine(method) {
|
|
4208
|
+
const spec = upgradeSpawnSpec(method);
|
|
4209
|
+
return spec === null ? null : [spec.cmd, ...spec.args].join(" ");
|
|
4210
|
+
}
|
|
4211
|
+
var BINARY_RETIRED_HINT = `the standalone-binary track was retired in 0.70.3. Install from npm instead -- \`${upgradeCommandLine("global-npm")}\` -- then delete this executable.`;
|
|
4212
|
+
function globalUpgradeCommandLineForTool(tool) {
|
|
4213
|
+
const method = GLOBAL_UPGRADE_METHODS.find((m) => UPGRADE_COMMANDS[m]?.cmd === tool);
|
|
4214
|
+
return method === void 0 ? null : upgradeCommandLine(method);
|
|
4215
|
+
}
|
|
4216
|
+
function buildUpgradePlan(input) {
|
|
4217
|
+
const { current, latest, method } = input;
|
|
4218
|
+
const stripV = (s) => s.startsWith("v") ? s.slice(1) : s;
|
|
4219
|
+
const stale = latest !== null && current !== "dev" && compareVersions(stripV(current), stripV(latest)) < 0;
|
|
4220
|
+
let command;
|
|
4221
|
+
switch (method) {
|
|
4222
|
+
case "npx":
|
|
4223
|
+
command = null;
|
|
4224
|
+
break;
|
|
4225
|
+
case "bundled-app":
|
|
4226
|
+
command = null;
|
|
4227
|
+
break;
|
|
4228
|
+
case "binary":
|
|
4229
|
+
command = null;
|
|
4230
|
+
break;
|
|
4231
|
+
case "dev-checkout":
|
|
4232
|
+
command = "git pull && npm run build";
|
|
4233
|
+
break;
|
|
4234
|
+
case "unknown":
|
|
4235
|
+
command = upgradeCommandLine("global-npm");
|
|
4236
|
+
break;
|
|
4237
|
+
default:
|
|
4238
|
+
command = upgradeCommandLine(method);
|
|
4239
|
+
break;
|
|
4240
|
+
}
|
|
4241
|
+
return { current, latest, stale, method, command };
|
|
4242
|
+
}
|
|
4243
|
+
var REGISTRY_FETCH_TIMEOUT_MS = 3e3;
|
|
4244
|
+
async function fetchLatestVersion(opts = {}) {
|
|
4245
|
+
if (opts.override) {
|
|
4246
|
+
try {
|
|
4247
|
+
return await opts.override();
|
|
4248
|
+
} catch {
|
|
4249
|
+
return null;
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
const ac = new AbortController();
|
|
4253
|
+
const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? REGISTRY_FETCH_TIMEOUT_MS);
|
|
4254
|
+
try {
|
|
4255
|
+
const res = await fetch("https://registry.npmjs.org/@yawlabs/mcp/latest", {
|
|
4256
|
+
signal: ac.signal,
|
|
4257
|
+
headers: { accept: "application/json" }
|
|
4258
|
+
});
|
|
4259
|
+
if (!res.ok) return null;
|
|
4260
|
+
const body = await res.json();
|
|
4261
|
+
return typeof body.version === "string" ? body.version : null;
|
|
4262
|
+
} catch {
|
|
4263
|
+
return null;
|
|
4264
|
+
} finally {
|
|
4265
|
+
clearTimeout(timer);
|
|
4266
|
+
}
|
|
4267
|
+
}
|
|
4268
|
+
async function probeOamQuietly() {
|
|
4269
|
+
const prev = process.env.LOG_LEVEL;
|
|
4270
|
+
process.env.LOG_LEVEL = "error";
|
|
4271
|
+
try {
|
|
4272
|
+
return await probeOam();
|
|
4273
|
+
} finally {
|
|
4274
|
+
if (prev === void 0) delete process.env.LOG_LEVEL;
|
|
4275
|
+
else process.env.LOG_LEVEL = prev;
|
|
4276
|
+
}
|
|
4277
|
+
}
|
|
4278
|
+
async function oamFloorLines(probe) {
|
|
4279
|
+
if (!probe && process.env.VITEST) return [];
|
|
4280
|
+
try {
|
|
4281
|
+
const oam = probe ? await probe() : await probeOamQuietly();
|
|
4282
|
+
if (!oam.belowMin) return [];
|
|
4283
|
+
return [
|
|
4284
|
+
"",
|
|
4285
|
+
`oam: v${oam.version ?? "unknown"} is installed but below the v${MIN_OAM_VERSION} floor yaw-mcp`,
|
|
4286
|
+
" requires, so MCP sidecars run on node instead of oam. Update it:",
|
|
4287
|
+
"",
|
|
4288
|
+
" oam self-update"
|
|
4289
|
+
];
|
|
4290
|
+
} catch {
|
|
4291
|
+
return [];
|
|
4292
|
+
}
|
|
4293
|
+
}
|
|
4294
|
+
async function defaultRunningPrefix(argvPath) {
|
|
4295
|
+
if (process.env.VITEST) return null;
|
|
4296
|
+
const { detectRunningInstallPrefix: detectRunningInstallPrefix2 } = await import("./auto-upgrade-A3WTRVGV.js");
|
|
4297
|
+
return detectRunningInstallPrefix2(argvPath);
|
|
4298
|
+
}
|
|
4299
|
+
async function defaultSpawn(cmd, args, cwd) {
|
|
4300
|
+
return new Promise((resolve6) => {
|
|
4301
|
+
const child = spawn2(cmd, args, {
|
|
4302
|
+
stdio: "inherit",
|
|
4303
|
+
shell: process.platform === "win32",
|
|
4304
|
+
cwd,
|
|
4305
|
+
// yaw-mcp's own secrets stay out of the install: npm runs every
|
|
4306
|
+
// dependency's pre/postinstall with this env, and a passphrase parked
|
|
4307
|
+
// in yaw-mcp's env block (where README says to put it) must not reach
|
|
4308
|
+
// them. See internal-secret-env.ts.
|
|
4309
|
+
env: stripInternalSecretsFromEnv(process.env)
|
|
4310
|
+
});
|
|
4311
|
+
child.on("close", (code) => resolve6(typeof code === "number" ? code : 1));
|
|
4312
|
+
child.on("error", () => resolve6(1));
|
|
4313
|
+
});
|
|
4314
|
+
}
|
|
4315
|
+
async function detectSea() {
|
|
4316
|
+
if (process.env.ELECTRON_RUN_AS_NODE) return false;
|
|
4317
|
+
const exe = process.execPath.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? "";
|
|
4318
|
+
if (exe === "node" || exe === "node.exe") return false;
|
|
4319
|
+
try {
|
|
4320
|
+
const sea = await import("sea");
|
|
4321
|
+
return typeof sea.isSea === "function" && sea.isSea() === true;
|
|
4322
|
+
} catch {
|
|
4323
|
+
return false;
|
|
4324
|
+
}
|
|
4325
|
+
}
|
|
4326
|
+
async function runUpgrade(opts = {}) {
|
|
4327
|
+
const write = opts.out ?? createStreamWriter(process.stdout);
|
|
4328
|
+
const writeErr = opts.err ?? createStreamWriter(process.stderr);
|
|
4329
|
+
const lines = [];
|
|
4330
|
+
const print = (s = "") => {
|
|
4331
|
+
lines.push(s);
|
|
4332
|
+
write(`${s}
|
|
4333
|
+
`);
|
|
4334
|
+
};
|
|
4335
|
+
const printErr = (s) => {
|
|
4336
|
+
lines.push(s);
|
|
4337
|
+
writeErr(`${s}
|
|
4338
|
+
`);
|
|
4339
|
+
};
|
|
4340
|
+
const fetcher = opts.fetchLatest ?? fetchLatestVersion;
|
|
4341
|
+
const current = opts.currentVersion ?? readCurrentVersion();
|
|
4342
|
+
const argvPath = opts.argvPath ?? process.argv[1];
|
|
4343
|
+
const sea = opts.isSea ? opts.isSea() : await detectSea();
|
|
4344
|
+
const method = sea ? "binary" : await refineInstallMethod(detectInstallMethod(argvPath), argvPath, opts.npmPrefix);
|
|
4345
|
+
let latest;
|
|
4346
|
+
try {
|
|
4347
|
+
latest = await fetcher();
|
|
4348
|
+
} catch {
|
|
4349
|
+
latest = null;
|
|
4350
|
+
}
|
|
4351
|
+
const plan = buildUpgradePlan({ current, latest, method });
|
|
4352
|
+
let globalPrefixArg = null;
|
|
4353
|
+
let suggestedCommand = plan.command;
|
|
4354
|
+
if (method === "global-npm") {
|
|
4355
|
+
const rawPrefix = await (opts.runningPrefix ?? defaultRunningPrefix)(argvPath);
|
|
4356
|
+
if (rawPrefix !== null) {
|
|
4357
|
+
const { quoteArgForDisplay: quoteArgForDisplay2, quoteShellArgIfNeeded: quoteShellArgIfNeeded2 } = await import("./auto-upgrade-A3WTRVGV.js");
|
|
4358
|
+
const spawnForm = quoteShellArgIfNeeded2(rawPrefix, opts.platform);
|
|
4359
|
+
const displayForm = quoteArgForDisplay2(rawPrefix, opts.platform);
|
|
4360
|
+
if (spawnForm !== null && displayForm !== null) {
|
|
4361
|
+
globalPrefixArg = spawnForm;
|
|
4362
|
+
const spec2 = upgradeSpawnSpec("global-npm", displayForm);
|
|
4363
|
+
suggestedCommand = spec2 === null ? null : [spec2.cmd, ...spec2.args].join(" ");
|
|
4364
|
+
}
|
|
4365
|
+
}
|
|
4366
|
+
}
|
|
4367
|
+
const installRoot = method === "local-node-modules" ? localInstallRoot(argvPath) : null;
|
|
4368
|
+
if (opts.json) {
|
|
4369
|
+
print(JSON.stringify({ ...plan, command: suggestedCommand, cwd: installRoot }, null, 2));
|
|
4370
|
+
return { exitCode: plan.stale ? 1 : 0, lines };
|
|
4371
|
+
}
|
|
4372
|
+
if (latest === null) {
|
|
4373
|
+
print("yaw-mcp upgrade: couldn't reach the npm registry (offline? firewall?).");
|
|
4374
|
+
if (suggestedCommand) {
|
|
4375
|
+
print("When you're back online, run:");
|
|
4376
|
+
print("");
|
|
4377
|
+
if (installRoot) {
|
|
4378
|
+
print(`in ${installRoot}:`);
|
|
4379
|
+
}
|
|
4380
|
+
print(` ${suggestedCommand}`);
|
|
4381
|
+
} else if (method === "bundled-app") {
|
|
4382
|
+
print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app -- nothing to run.");
|
|
4383
|
+
} else if (method === "binary") {
|
|
4384
|
+
print(`yaw-mcp is a standalone binary; ${BINARY_RETIRED_HINT}`);
|
|
4385
|
+
} else {
|
|
4386
|
+
print("Your install uses `npx -y` -- just restart the MCP client when you're back online.");
|
|
4387
|
+
}
|
|
4388
|
+
for (const line of await oamFloorLines(opts.oamProbe)) print(line);
|
|
4389
|
+
return { exitCode: 0, lines };
|
|
4390
|
+
}
|
|
4391
|
+
print(`Current: ${current}`);
|
|
4392
|
+
print(`Latest: ${latest}`);
|
|
4393
|
+
print(`Install: ${method}`);
|
|
4394
|
+
for (const line of await oamFloorLines(opts.oamProbe)) print(line);
|
|
4395
|
+
if (!plan.stale) {
|
|
4396
|
+
print("");
|
|
4397
|
+
print("OK: You're on the latest version -- nothing to do.");
|
|
4398
|
+
return { exitCode: 0, lines };
|
|
4399
|
+
}
|
|
4400
|
+
print("");
|
|
4401
|
+
if (method === "npx") {
|
|
4402
|
+
print("Your install uses `npx -y` -- restart the MCP client and it will fetch the new version.");
|
|
4403
|
+
return { exitCode: 0, lines };
|
|
4404
|
+
}
|
|
4405
|
+
if (method === "bundled-app") {
|
|
4406
|
+
print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app --");
|
|
4407
|
+
print("there is nothing to run here. Update Yaw Terminal to get the new version.");
|
|
4408
|
+
return { exitCode: 0, lines };
|
|
4409
|
+
}
|
|
4410
|
+
if (method === "binary") {
|
|
4411
|
+
const emit = opts.run ? printErr : print;
|
|
4412
|
+
emit("yaw-mcp is running as a standalone binary -- manual upgrade required.");
|
|
4413
|
+
emit(`There's no package manager to upgrade it, and \`--run\` can't automate this: ${BINARY_RETIRED_HINT}`);
|
|
4414
|
+
return { exitCode: opts.run ? 2 : 1, lines };
|
|
4415
|
+
}
|
|
4416
|
+
const spec = upgradeSpawnSpec(method, globalPrefixArg);
|
|
4417
|
+
const runSpec = spec === null ? null : method === "local-node-modules" ? installRoot !== null ? { ...spec, cwd: installRoot } : null : spec;
|
|
4418
|
+
const commandLine = method === "global-npm" ? suggestedCommand : runSpec ? [runSpec.cmd, ...runSpec.args].join(" ") : plan.command;
|
|
4419
|
+
if (!opts.run) {
|
|
4420
|
+
if (runSpec) {
|
|
4421
|
+
print("Run `yaw-mcp upgrade --run` to upgrade in place, or run it yourself:");
|
|
4422
|
+
} else {
|
|
4423
|
+
print("Manual upgrade required (--run can't safely automate this install method). Run it yourself:");
|
|
4424
|
+
}
|
|
4425
|
+
print("");
|
|
4426
|
+
if (installRoot) {
|
|
4427
|
+
print(`in ${installRoot}:`);
|
|
4428
|
+
}
|
|
4429
|
+
print(` ${commandLine}`);
|
|
4430
|
+
return { exitCode: 1, lines };
|
|
4431
|
+
}
|
|
4432
|
+
if (!runSpec) {
|
|
4433
|
+
printErr(
|
|
4434
|
+
`yaw-mcp upgrade --run: a "${method}" install can't be upgraded automatically (manual upgrade required). Run it yourself:`
|
|
4435
|
+
);
|
|
4436
|
+
printErr("");
|
|
4437
|
+
printErr(` ${commandLine}`);
|
|
4438
|
+
return { exitCode: 2, lines };
|
|
4439
|
+
}
|
|
4440
|
+
const runner = opts.spawnImpl ?? defaultSpawn;
|
|
4441
|
+
if (runSpec.cwd) {
|
|
4442
|
+
print(`Running in ${runSpec.cwd}:`);
|
|
4443
|
+
} else {
|
|
4444
|
+
print("Running:");
|
|
4445
|
+
}
|
|
4446
|
+
print(` ${commandLine}`);
|
|
4447
|
+
print("");
|
|
4448
|
+
const code = await runner(runSpec.cmd, runSpec.args, runSpec.cwd);
|
|
4449
|
+
if (code === 0) {
|
|
4450
|
+
print("");
|
|
4451
|
+
print(`OK: Upgraded @yawlabs/mcp to ${latest}`);
|
|
4452
|
+
const pkgDir = runningPackageDir(argvPath);
|
|
4453
|
+
const running = pkgDir === null ? null : await (opts.installedVersion ?? defaultInstalledVersion)(pkgDir);
|
|
4454
|
+
const bare = (s) => s.startsWith("v") ? s.slice(1) : s;
|
|
4455
|
+
if (running !== null && compareVersions(bare(running), bare(latest)) < 0) {
|
|
4456
|
+
printErr("");
|
|
4457
|
+
printErr(`WARNING: the copy this command ran from still reports ${running}, not ${latest}:`);
|
|
4458
|
+
printErr(` ${pkgDir}`);
|
|
4459
|
+
printErr(
|
|
4460
|
+
"The install landed in a different tree, so your MCP client keeps spawning the old version until that tree is upgraded too (for a copy nested under another package's node_modules, upgrade the package that pins it)."
|
|
4461
|
+
);
|
|
4462
|
+
}
|
|
4463
|
+
return { exitCode: 0, lines };
|
|
4464
|
+
}
|
|
4465
|
+
printErr(`yaw-mcp upgrade: ${runSpec.cmd} exited ${code}. Try running the command yourself:`);
|
|
4466
|
+
printErr("");
|
|
4467
|
+
if (installRoot) {
|
|
4468
|
+
printErr(`in ${installRoot}:`);
|
|
4469
|
+
}
|
|
4470
|
+
printErr(` ${commandLine}`);
|
|
4471
|
+
return { exitCode: 3, lines };
|
|
4472
|
+
}
|
|
4473
|
+
function readCurrentVersion() {
|
|
4474
|
+
return true ? "1.0.2" : "dev";
|
|
4475
|
+
}
|
|
4476
|
+
|
|
4477
|
+
// src/auto-upgrade.ts
|
|
4478
|
+
function quoteShellArgIfNeeded(arg, platform = process.platform) {
|
|
4479
|
+
if (platform !== "win32") return arg;
|
|
4480
|
+
if (/[\r\n\0"%]/.test(arg)) return null;
|
|
4481
|
+
if (!/[\s&|<>^]/.test(arg)) return arg;
|
|
4482
|
+
return `"${arg}"`;
|
|
4483
|
+
}
|
|
4484
|
+
function quoteArgForDisplay(arg, platform = process.platform) {
|
|
4485
|
+
if (platform === "win32") return quoteShellArgIfNeeded(arg, platform);
|
|
4486
|
+
if (/^[A-Za-z0-9_\-./+,:@=]+$/.test(arg)) return arg;
|
|
4487
|
+
return `'${arg.replace(/'/g, "'\\''")}'`;
|
|
4488
|
+
}
|
|
4489
|
+
function detectRunningInstallPrefix(argvPath) {
|
|
4490
|
+
if (!argvPath) return null;
|
|
4491
|
+
let resolved;
|
|
4492
|
+
try {
|
|
4493
|
+
resolved = realpathSync2(argvPath);
|
|
4494
|
+
} catch {
|
|
4495
|
+
return null;
|
|
4496
|
+
}
|
|
4497
|
+
const dir = dirname2(resolved);
|
|
4498
|
+
const idx = dir.lastIndexOf(`${sep2}node_modules${sep2}`);
|
|
4499
|
+
if (idx === -1) return null;
|
|
4500
|
+
const candidate = dir.slice(0, idx);
|
|
4501
|
+
if (candidate.endsWith(`${sep2}lib`)) return candidate.slice(0, -`${sep2}lib`.length);
|
|
4502
|
+
return candidate;
|
|
4503
|
+
}
|
|
4504
|
+
async function compareWithNpmPrefix(detected, probe = npmGlobalPrefix) {
|
|
4505
|
+
const npmPrefix = await probe();
|
|
4506
|
+
if (!npmPrefix?.trim()) return;
|
|
4507
|
+
if (comparablePath(npmPrefix.trim()) === comparablePath(detected)) return;
|
|
4508
|
+
log(
|
|
4509
|
+
"warn",
|
|
4510
|
+
"yaw-mcp self-upgrade: running prefix differs from `npm prefix -g`; installing into the running prefix so the upgrade lands in the tree the client spawned from",
|
|
4511
|
+
{ running: detected, npmPrefix }
|
|
4512
|
+
);
|
|
4513
|
+
}
|
|
4514
|
+
var UPGRADE_LOCK_NAME = ".yaw-mcp-upgrade.lock";
|
|
4515
|
+
var UPGRADE_LOCK_STALE_MS = 10 * 60 * 1e3;
|
|
4516
|
+
var UPGRADE_LOCK_FUTURE_SKEW_MS = 5 * 1e3;
|
|
4517
|
+
function lockHolderAlive(lockPath) {
|
|
4518
|
+
let pid;
|
|
4519
|
+
try {
|
|
4520
|
+
pid = Number.parseInt(readFileSync3(lockPath, "utf8").trim(), 10);
|
|
4521
|
+
} catch {
|
|
4522
|
+
return true;
|
|
4523
|
+
}
|
|
4524
|
+
if (!Number.isInteger(pid) || pid <= 0) return true;
|
|
4525
|
+
if (pid === process.pid) return true;
|
|
4526
|
+
try {
|
|
4527
|
+
process.kill(pid, 0);
|
|
4528
|
+
return true;
|
|
4529
|
+
} catch (err) {
|
|
4530
|
+
return err.code !== "ESRCH";
|
|
4531
|
+
}
|
|
4532
|
+
}
|
|
4533
|
+
function acquireUpgradeLock(dir, lockName = UPGRADE_LOCK_NAME, opts = {}) {
|
|
4534
|
+
const lockPath = join11(dir, lockName);
|
|
4535
|
+
const holderAlive = (path2) => opts.probeHolder ? lockHolderAlive(path2) : true;
|
|
4536
|
+
const mine = String(process.pid);
|
|
4537
|
+
const take = () => {
|
|
4538
|
+
try {
|
|
4539
|
+
const fd = openSync(lockPath, "wx");
|
|
4540
|
+
try {
|
|
4541
|
+
writeSync(fd, `${mine}
|
|
4542
|
+
`);
|
|
4543
|
+
} finally {
|
|
4544
|
+
closeSync(fd);
|
|
4545
|
+
}
|
|
4546
|
+
let released = false;
|
|
4547
|
+
return () => {
|
|
4548
|
+
if (released) return;
|
|
4549
|
+
released = true;
|
|
4550
|
+
try {
|
|
4551
|
+
if (readFileSync3(lockPath, "utf8").trim() !== mine) return;
|
|
4552
|
+
unlinkSync(lockPath);
|
|
4553
|
+
} catch {
|
|
4554
|
+
}
|
|
4555
|
+
};
|
|
4556
|
+
} catch (err) {
|
|
4557
|
+
if (err.code === "EEXIST") return void 0;
|
|
4558
|
+
return () => {
|
|
4559
|
+
};
|
|
4560
|
+
}
|
|
4561
|
+
};
|
|
4562
|
+
const first = take();
|
|
4563
|
+
if (first !== void 0) return first;
|
|
4564
|
+
const isLive = (ageMs2) => ageMs2 > -UPGRADE_LOCK_FUTURE_SKEW_MS && ageMs2 < UPGRADE_LOCK_STALE_MS;
|
|
4565
|
+
let ageMs;
|
|
4566
|
+
try {
|
|
4567
|
+
ageMs = Date.now() - statSync2(lockPath).mtimeMs;
|
|
4568
|
+
} catch {
|
|
4569
|
+
ageMs = UPGRADE_LOCK_STALE_MS;
|
|
4570
|
+
}
|
|
4571
|
+
if (isLive(ageMs) && holderAlive(lockPath)) return null;
|
|
4572
|
+
const stolenPath = `${lockPath}.stale-${process.pid}`;
|
|
4573
|
+
try {
|
|
4574
|
+
renameSync(lockPath, stolenPath);
|
|
4575
|
+
} catch (err) {
|
|
4576
|
+
if (err.code !== "ENOENT") return null;
|
|
4577
|
+
const retry = take();
|
|
4578
|
+
return retry === void 0 ? null : retry;
|
|
4579
|
+
}
|
|
4580
|
+
let stoleLive = false;
|
|
4581
|
+
try {
|
|
4582
|
+
stoleLive = isLive(Date.now() - statSync2(stolenPath).mtimeMs) && holderAlive(stolenPath);
|
|
4583
|
+
} catch {
|
|
4584
|
+
}
|
|
4585
|
+
if (stoleLive) {
|
|
4586
|
+
try {
|
|
4587
|
+
const holder = readFileSync3(stolenPath, "utf8");
|
|
4588
|
+
const fd = openSync(lockPath, "wx");
|
|
4589
|
+
try {
|
|
4590
|
+
writeSync(fd, holder);
|
|
4591
|
+
} finally {
|
|
4592
|
+
closeSync(fd);
|
|
4593
|
+
}
|
|
4594
|
+
} catch {
|
|
4595
|
+
}
|
|
4596
|
+
try {
|
|
4597
|
+
unlinkSync(stolenPath);
|
|
4598
|
+
} catch {
|
|
4599
|
+
}
|
|
4600
|
+
return null;
|
|
4601
|
+
}
|
|
4602
|
+
try {
|
|
4603
|
+
unlinkSync(stolenPath);
|
|
4604
|
+
} catch {
|
|
4605
|
+
}
|
|
4606
|
+
const second = take();
|
|
4607
|
+
return second === void 0 ? null : second;
|
|
4608
|
+
}
|
|
4609
|
+
function defaultAcquireLock(dir, lockName) {
|
|
4610
|
+
if (process.env.VITEST) return () => {
|
|
4611
|
+
};
|
|
4612
|
+
return acquireUpgradeLock(dir, lockName);
|
|
4613
|
+
}
|
|
4614
|
+
var UPGRADE_CHECK_INTERVAL_MS = 60 * 60 * 1e3;
|
|
4615
|
+
var UPGRADE_ATTEMPT_COOLDOWN_MS = 6 * 60 * 60 * 1e3;
|
|
4616
|
+
function readMemo(path2) {
|
|
4617
|
+
let parsed;
|
|
4618
|
+
try {
|
|
4619
|
+
parsed = JSON.parse(readFileSync3(path2, "utf8"));
|
|
4620
|
+
} catch {
|
|
4621
|
+
return null;
|
|
4622
|
+
}
|
|
4623
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
4624
|
+
const memo = parsed;
|
|
4625
|
+
if (typeof memo.at !== "number") return null;
|
|
4626
|
+
const ageMs = Date.now() - memo.at;
|
|
4627
|
+
return ageMs < -UPGRADE_LOCK_FUTURE_SKEW_MS ? null : { ageMs, memo };
|
|
4628
|
+
}
|
|
4629
|
+
function writeMemo(path2, fields) {
|
|
4630
|
+
try {
|
|
4631
|
+
writeFileSync(path2, `${JSON.stringify({ at: Date.now(), ...fields })}
|
|
4632
|
+
`);
|
|
4633
|
+
} catch {
|
|
4634
|
+
}
|
|
4635
|
+
}
|
|
4636
|
+
function checkMemoPath() {
|
|
4637
|
+
return join11(tmpdir(), `.yaw-mcp-upgrade-check-${process.getuid?.() ?? "win"}.json`);
|
|
4638
|
+
}
|
|
4639
|
+
function readCheckMemo(path2) {
|
|
4640
|
+
const read = readMemo(path2);
|
|
4641
|
+
if (read === null || read.ageMs >= UPGRADE_CHECK_INTERVAL_MS) return null;
|
|
4642
|
+
const latest = read.memo.latest;
|
|
4643
|
+
if (latest !== null && typeof latest !== "string") return null;
|
|
4644
|
+
return { latest };
|
|
4645
|
+
}
|
|
4646
|
+
function writeCheckMemo(path2, latest) {
|
|
4647
|
+
writeMemo(path2, { latest });
|
|
4648
|
+
}
|
|
4649
|
+
function attemptMemoPath(dir, lockName) {
|
|
4650
|
+
return join11(dir, `${lockName}.attempt`);
|
|
4651
|
+
}
|
|
4652
|
+
function attemptMemoFallbackPath(dir, lockName, fallbackDir) {
|
|
4653
|
+
const scope = createHash("sha256").update(`${dir}\0${lockName}`).digest("hex").slice(0, 16);
|
|
4654
|
+
return join11(fallbackDir, `.yaw-mcp-upgrade-attempt-${process.getuid?.() ?? "win"}-${scope}.json`);
|
|
4655
|
+
}
|
|
4656
|
+
function defaultCheckedRecently() {
|
|
4657
|
+
if (process.env.VITEST) return null;
|
|
4658
|
+
return readCheckMemo(checkMemoPath());
|
|
4659
|
+
}
|
|
4660
|
+
function defaultRecordCheck(latest) {
|
|
4661
|
+
if (process.env.VITEST) return;
|
|
4662
|
+
writeCheckMemo(checkMemoPath(), latest);
|
|
4663
|
+
}
|
|
4664
|
+
function defaultAttemptedRecently(dir, lockName, version) {
|
|
4665
|
+
if (process.env.VITEST) return false;
|
|
4666
|
+
return attemptedRecentlyAt(dir, lockName, version);
|
|
4667
|
+
}
|
|
4668
|
+
function defaultRecordAttempt(dir, lockName, version) {
|
|
4669
|
+
if (process.env.VITEST) return;
|
|
4670
|
+
recordAttemptAt(dir, lockName, version);
|
|
4671
|
+
}
|
|
4672
|
+
function attemptedRecentlyAt(dir, lockName, version, fallbackDir = tmpdir()) {
|
|
4673
|
+
const recent = (read) => read !== null && read.memo.version === version && read.ageMs < UPGRADE_ATTEMPT_COOLDOWN_MS;
|
|
4674
|
+
if (recent(readMemo(attemptMemoPath(dir, lockName)))) return true;
|
|
4675
|
+
return recent(readMemo(attemptMemoFallbackPath(dir, lockName, fallbackDir)));
|
|
4676
|
+
}
|
|
4677
|
+
function recordAttemptAt(dir, lockName, version, fallbackDir = tmpdir()) {
|
|
4678
|
+
const primary = attemptMemoPath(dir, lockName);
|
|
4679
|
+
try {
|
|
4680
|
+
writeFileSync(primary, `${JSON.stringify({ at: Date.now(), version })}
|
|
4681
|
+
`);
|
|
4682
|
+
return;
|
|
4683
|
+
} catch {
|
|
4684
|
+
}
|
|
4685
|
+
writeMemo(attemptMemoFallbackPath(dir, lockName, fallbackDir), { version });
|
|
4686
|
+
}
|
|
4687
|
+
function defaultSpawn2(cmd, args, onDone = () => {
|
|
4688
|
+
}) {
|
|
4689
|
+
let errorFired = false;
|
|
4690
|
+
let released = false;
|
|
4691
|
+
const finish = () => {
|
|
4692
|
+
if (released) return;
|
|
4693
|
+
released = true;
|
|
4694
|
+
onDone();
|
|
4695
|
+
};
|
|
4696
|
+
const correctiveCmd = globalUpgradeCommandLineForTool(cmd);
|
|
4697
|
+
const child = spawn3(cmd, args, {
|
|
4698
|
+
stdio: "ignore",
|
|
4699
|
+
// yaw-mcp's own secrets stay out of the install. npm runs every
|
|
4700
|
+
// dependency's pre/postinstall with this env, and README tells the user to
|
|
4701
|
+
// put YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's env block precisely because
|
|
4702
|
+
// "yaw-mcp strips its own secrets from every child env" -- a promise the
|
|
4703
|
+
// upstream spawn kept and this one, spawning with the full inherited
|
|
4704
|
+
// process.env, silently did not: a compromised transitive dependency's
|
|
4705
|
+
// install script plus ~/.yaw-mcp/secrets.json was the whole vault.
|
|
4706
|
+
env: stripInternalSecretsFromEnv(process.env),
|
|
4707
|
+
// Not detached, so the install shares yaw-mcp's process group and an MCP
|
|
4708
|
+
// client that tears down the whole tree takes it with it. Two things this
|
|
4709
|
+
// does NOT buy (the file header lists both as known gaps): on POSIX a
|
|
4710
|
+
// plain parent exit does not kill it, and if it IS killed mid-install the
|
|
4711
|
+
// result is not guaranteed intact -- npm reify removes the existing
|
|
4712
|
+
// package dir before moving the new one in, and nothing here repairs a
|
|
4713
|
+
// partial install on the next startup.
|
|
4714
|
+
detached: false,
|
|
4715
|
+
shell: process.platform === "win32"
|
|
4716
|
+
});
|
|
4717
|
+
child.on("close", (code) => {
|
|
4718
|
+
finish();
|
|
4719
|
+
if (errorFired) return;
|
|
4720
|
+
if (code === 0) {
|
|
4721
|
+
log("info", "yaw-mcp self-upgrade complete; the next client restart will run the new version");
|
|
4722
|
+
} else {
|
|
4723
|
+
const hint = cmd === "npm" ? " (often EACCES on a sudo-installed global -- run with the right permissions)" : "";
|
|
4724
|
+
const manual = correctiveCmd === null ? "Set" : `Run \`${correctiveCmd}\` manually, or set`;
|
|
4725
|
+
log(
|
|
4726
|
+
"warn",
|
|
4727
|
+
`yaw-mcp self-upgrade: ${cmd} exited non-zero${hint}. ${manual} YAW_MCP_AUTO_UPGRADE=0 to silence this.`,
|
|
4728
|
+
{ code }
|
|
4729
|
+
);
|
|
4730
|
+
}
|
|
4731
|
+
});
|
|
4732
|
+
child.on("error", (err) => {
|
|
4733
|
+
errorFired = true;
|
|
4734
|
+
finish();
|
|
4735
|
+
log("warn", `yaw-mcp self-upgrade: ${cmd} spawn failed`, { error: err?.message });
|
|
4736
|
+
});
|
|
4737
|
+
}
|
|
4738
|
+
async function maybeAutoUpgrade(deps = {}) {
|
|
4739
|
+
const optOut = process.env.YAW_MCP_AUTO_UPGRADE;
|
|
4740
|
+
if (optOut === "0" || optOut?.toLowerCase() === "false") return;
|
|
4741
|
+
const current = deps.currentVersion ?? (true ? "1.0.2" : "dev");
|
|
4742
|
+
if (current === "dev") return;
|
|
4743
|
+
const argvPath = deps.argvPath ?? process.argv[1];
|
|
4744
|
+
const method = (deps.isSeaImpl ? await deps.isSeaImpl() : await detectSea()) ? "binary" : detectInstallMethod(argvPath, realpathSync2, ["unknown", "local-node-modules"]);
|
|
4745
|
+
const cached = (deps.checkedRecentlyImpl ?? defaultCheckedRecently)();
|
|
4746
|
+
let latest;
|
|
4747
|
+
if (cached !== null) {
|
|
4748
|
+
latest = cached.latest;
|
|
4749
|
+
} else {
|
|
4750
|
+
latest = await (deps.fetchLatestImpl ?? fetchLatestVersion)();
|
|
4751
|
+
(deps.recordCheckImpl ?? defaultRecordCheck)(latest);
|
|
4752
|
+
}
|
|
4753
|
+
if (latest === null) return;
|
|
4754
|
+
const plan = buildUpgradePlan({ current, latest, method });
|
|
4755
|
+
if (!plan.stale) return;
|
|
4756
|
+
const rawPrefix = method === "global-npm" ? detectRunningInstallPrefix(argvPath) : null;
|
|
4757
|
+
const quotedPrefix = rawPrefix === null ? null : quoteShellArgIfNeeded(rawPrefix);
|
|
4758
|
+
const globalSpec = GLOBAL_UPGRADE_METHODS.includes(method) ? upgradeSpawnSpec(method, quotedPrefix) : null;
|
|
4759
|
+
if (globalSpec) {
|
|
4760
|
+
const lockDir = rawPrefix ?? tmpdir();
|
|
4761
|
+
const lockName = rawPrefix === null ? `.yaw-mcp-upgrade-${globalSpec.cmd}-${process.getuid?.() ?? "win"}.lock` : UPGRADE_LOCK_NAME;
|
|
4762
|
+
if ((deps.attemptedRecentlyImpl ?? defaultAttemptedRecently)(lockDir, lockName, latest)) {
|
|
4763
|
+
log("info", "yaw-mcp self-upgrade: this upgrade was already attempted recently; not retrying yet", {
|
|
4764
|
+
current,
|
|
4765
|
+
latest,
|
|
4766
|
+
tool: globalSpec.cmd,
|
|
4767
|
+
lockDir
|
|
4768
|
+
});
|
|
4769
|
+
return;
|
|
4770
|
+
}
|
|
4771
|
+
const releaseLock = (deps.acquireLockImpl ?? defaultAcquireLock)(lockDir, lockName);
|
|
4772
|
+
if (releaseLock === null) {
|
|
4773
|
+
log("info", "yaw-mcp self-upgrade: another process is already upgrading this install; skipping this one", {
|
|
4774
|
+
current,
|
|
4775
|
+
latest,
|
|
4776
|
+
tool: globalSpec.cmd,
|
|
4777
|
+
lockDir
|
|
4778
|
+
});
|
|
4779
|
+
return;
|
|
4780
|
+
}
|
|
4781
|
+
log("info", "yaw-mcp is out of date; upgrading the global install in the background", {
|
|
4782
|
+
current,
|
|
4783
|
+
latest,
|
|
4784
|
+
tool: globalSpec.cmd,
|
|
4785
|
+
// The RAW prefix, not the shell-quoted argv form -- a log field is read
|
|
4786
|
+
// by a human, and stray quotes read as part of the path. Omitted when
|
|
4787
|
+
// quoting failed, because then no `--prefix` was passed at all and npm
|
|
4788
|
+
// resolves its own prefix.
|
|
4789
|
+
prefix: quotedPrefix === null ? void 0 : rawPrefix ?? void 0
|
|
4790
|
+
});
|
|
4791
|
+
if (method === "global-npm" && rawPrefix !== null && quotedPrefix !== null) {
|
|
4792
|
+
compareWithNpmPrefix(rawPrefix, deps.npmPrefixImpl).catch(() => {
|
|
4793
|
+
});
|
|
4794
|
+
}
|
|
4795
|
+
(deps.recordAttemptImpl ?? defaultRecordAttempt)(lockDir, lockName, latest);
|
|
4796
|
+
try {
|
|
4797
|
+
(deps.spawnImpl ?? defaultSpawn2)(globalSpec.cmd, globalSpec.args, releaseLock);
|
|
4798
|
+
} catch (err) {
|
|
4799
|
+
releaseLock();
|
|
4800
|
+
log("warn", `yaw-mcp self-upgrade: could not start ${globalSpec.cmd}`, {
|
|
4801
|
+
error: err instanceof Error ? err.message : String(err)
|
|
4802
|
+
});
|
|
4803
|
+
}
|
|
4804
|
+
return;
|
|
4805
|
+
}
|
|
4806
|
+
if (method === "bundled-app") {
|
|
4807
|
+
log("info", "yaw-mcp (bundled with Yaw Terminal) is behind npm; it updates with the app", { current, latest });
|
|
4808
|
+
return;
|
|
4809
|
+
}
|
|
4810
|
+
if (method === "binary") {
|
|
4811
|
+
log(
|
|
4812
|
+
"info",
|
|
4813
|
+
"yaw-mcp (standalone binary) is behind npm; the binary track was retired -- npm install -g @yawlabs/mcp@latest, then delete the old executable",
|
|
4814
|
+
{ current, latest }
|
|
4815
|
+
);
|
|
4816
|
+
return;
|
|
4817
|
+
}
|
|
4818
|
+
if (method === "npx") {
|
|
4819
|
+
log("info", "yaw-mcp is out of date; restart your MCP client to pick up the latest version", {
|
|
4820
|
+
current,
|
|
4821
|
+
latest,
|
|
4822
|
+
method
|
|
4823
|
+
});
|
|
4824
|
+
} else if (method === "local-node-modules") {
|
|
4825
|
+
log(
|
|
4826
|
+
"info",
|
|
4827
|
+
"yaw-mcp is out of date; run `yaw-mcp upgrade --run` to update this install (a restart re-runs the version pinned in your project's node_modules)",
|
|
4828
|
+
{
|
|
4829
|
+
current,
|
|
4830
|
+
latest,
|
|
4831
|
+
method
|
|
4832
|
+
}
|
|
4833
|
+
);
|
|
4834
|
+
} else {
|
|
4835
|
+
log(
|
|
4836
|
+
"info",
|
|
4837
|
+
"yaw-mcp is out of date; run `yaw-mcp upgrade` for the command that updates this install (`--run` can't automate this install method)",
|
|
4838
|
+
{
|
|
4839
|
+
current,
|
|
4840
|
+
latest,
|
|
4841
|
+
method
|
|
4842
|
+
}
|
|
4843
|
+
);
|
|
4844
|
+
}
|
|
4845
|
+
}
|
|
4846
|
+
|
|
4847
|
+
export {
|
|
4848
|
+
INTERNAL_SECRET_ENV_KEYS,
|
|
4849
|
+
scrubInternalSecretsFromProcessEnv,
|
|
4850
|
+
stripInternalSecretsFromEnv,
|
|
4851
|
+
setLogSurface,
|
|
4852
|
+
log,
|
|
4853
|
+
createStreamWriter,
|
|
4854
|
+
parseJsonc,
|
|
4855
|
+
editJsoncPath,
|
|
4856
|
+
cacheDir,
|
|
4857
|
+
CONFIG_DIRNAME,
|
|
4858
|
+
sidecarsRoot,
|
|
4859
|
+
sidecarsNodeModules,
|
|
4860
|
+
userConfigDir,
|
|
4861
|
+
normalizeForCompare,
|
|
4862
|
+
tildePath,
|
|
4863
|
+
realpathOrSelf,
|
|
4864
|
+
isUnderHome,
|
|
4865
|
+
ALLOW_UNOWNED_ENV,
|
|
4866
|
+
findProjectConfigDir,
|
|
4867
|
+
guidePath,
|
|
4868
|
+
readStrictJson,
|
|
4869
|
+
CURRENT_OS,
|
|
4870
|
+
ENTRY_NAME,
|
|
4871
|
+
LEGACY_ENTRY_NAMES,
|
|
4872
|
+
resolveAppDataDir,
|
|
4873
|
+
effectiveConfigFormat,
|
|
4874
|
+
selectSites,
|
|
4875
|
+
unloadableConfigProblem,
|
|
4876
|
+
unloadableConfigFix,
|
|
4877
|
+
importViewOf,
|
|
4878
|
+
composeEntry,
|
|
4879
|
+
reloadDoneClause,
|
|
4880
|
+
reloadRemovalClause,
|
|
4881
|
+
describeValueShape,
|
|
4882
|
+
terminateWithNewline,
|
|
4883
|
+
classifyClientConfig,
|
|
4884
|
+
containerKeysAt,
|
|
4885
|
+
siteAt,
|
|
4886
|
+
readClientConfigFile,
|
|
4887
|
+
applyClientConfigEdits,
|
|
4888
|
+
readClientEnv,
|
|
4889
|
+
CLAUDE_CODE_ALLOW_PATTERN,
|
|
4890
|
+
resolveClaudeCodeSettingsPath,
|
|
4891
|
+
yawModeOverlay,
|
|
4892
|
+
prepareClaudeCodeSettingsPatch,
|
|
4893
|
+
INSTALL_TARGETS,
|
|
4894
|
+
resolveInstallPath,
|
|
4895
|
+
resolveInstallSites,
|
|
4896
|
+
resolveProgramProbe,
|
|
4897
|
+
resolveAlsoReadSites,
|
|
4898
|
+
claudeCodeContainerPaths,
|
|
4899
|
+
claudeCodeContainerPathVariants,
|
|
4900
|
+
buildLaunchEntry,
|
|
4901
|
+
isProjectLocalEntry,
|
|
4902
|
+
findLegacyEntry,
|
|
4903
|
+
findBlockedContainerSegment,
|
|
4904
|
+
describeJsonShape,
|
|
4905
|
+
unparseableConfigFix,
|
|
4906
|
+
blockedContainerFix,
|
|
4907
|
+
packageName,
|
|
4908
|
+
specConstraint,
|
|
4909
|
+
isRegistrySpec,
|
|
4910
|
+
npxSpecIndex,
|
|
4911
|
+
npxSpec,
|
|
4912
|
+
MIN_OAM_VERSION,
|
|
4913
|
+
oamInstallCommand,
|
|
4914
|
+
oamPublishesBinaryForThisMachine,
|
|
4915
|
+
oamNoBinaryReason,
|
|
4916
|
+
oamInstallAdvice,
|
|
4917
|
+
oamHeapOomHint,
|
|
4918
|
+
oamFailureLabel,
|
|
4919
|
+
compareVersions,
|
|
4920
|
+
probeOam,
|
|
4921
|
+
nodeLaunchKind,
|
|
4922
|
+
resolveStableNpmEntry,
|
|
4923
|
+
resolveOamSpawn,
|
|
4924
|
+
isOamCommand,
|
|
4925
|
+
isOamLaunch,
|
|
4926
|
+
parseUpgradeArgs,
|
|
4927
|
+
detectInstallMethod,
|
|
4928
|
+
refineInstallMethod,
|
|
4929
|
+
BINARY_RETIRED_HINT,
|
|
4930
|
+
buildUpgradePlan,
|
|
4931
|
+
fetchLatestVersion,
|
|
4932
|
+
detectSea,
|
|
4933
|
+
runUpgrade,
|
|
4934
|
+
quoteShellArgIfNeeded,
|
|
4935
|
+
quoteArgForDisplay,
|
|
4936
|
+
detectRunningInstallPrefix,
|
|
4937
|
+
acquireUpgradeLock,
|
|
4938
|
+
readCheckMemo,
|
|
4939
|
+
writeCheckMemo,
|
|
4940
|
+
attemptedRecentlyAt,
|
|
4941
|
+
recordAttemptAt,
|
|
4942
|
+
maybeAutoUpgrade
|
|
4943
|
+
};
|