claude-code-session-manager 0.130.3 → 0.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/assets/{AgentLibrary-BmrXNwK8.js → AgentLibrary-CYXre0J-.js} +2 -2
  2. package/dist/assets/{AppSettings-Cs4POznd.js → AppSettings-xNSfCj8e.js} +2 -2
  3. package/dist/assets/{Button-UUr5giu8.js → Button-BWljh5IK.js} +1 -1
  4. package/dist/assets/{DocumentEditorPane-C46Hj0lz.js → DocumentEditorPane-FUC2hZlp.js} +1 -1
  5. package/dist/assets/Extensions-CsyUoklz.js +2 -0
  6. package/dist/assets/{History-Bndupj87.js → History-BvNmY9OQ.js} +2 -2
  7. package/dist/assets/{Library-DFn0YPIW.js → Library-DVXk77zA.js} +12 -12
  8. package/dist/assets/{ListDetail-DjMn8a_3.js → ListDetail-DAAx__24.js} +1 -1
  9. package/dist/assets/{Panel-CIvb-XXN.js → Panel-g2D-e-RM.js} +1 -1
  10. package/dist/assets/{ProjectClaudeConfig-BQQRtMdK.js → ProjectClaudeConfig-BDuHJwaO.js} +7 -7
  11. package/dist/assets/{ProvenanceBadge-ej8W2ZIK.js → ProvenanceBadge-wew4_nf3.js} +1 -1
  12. package/dist/assets/Scheduler-CbeUIqD-.js +16 -0
  13. package/dist/assets/{Settings-DqxUna06.js → Settings-B23RsRfm.js} +1 -1
  14. package/dist/assets/{SkillReferenceGraph-BEMTdxdD.js → SkillReferenceGraph-BxQPCfsg.js} +1 -1
  15. package/dist/assets/Skills-4AR2FQrI.js +29 -0
  16. package/dist/assets/{SourceChip-BrPci8FX.js → SourceChip-jrC0vjfw.js} +1 -1
  17. package/dist/assets/{SystemPrompt-B43hNP0X.js → SystemPrompt-hHoBEnYb.js} +1 -1
  18. package/dist/assets/{TiptapBody-B-R2Bpda.js → TiptapBody-FkUqxO9u.js} +1 -1
  19. package/dist/assets/{Toggle-DKb4x1BP.js → Toggle-DQMNWZKT.js} +1 -1
  20. package/dist/assets/{ViewTabs-CcJdFZgv.js → ViewTabs-DGU0ZuxB.js} +1 -1
  21. package/dist/assets/{VoiceButton-BSH0UI3u.js → VoiceButton-BPPvDllh.js} +1 -1
  22. package/dist/assets/{historyTotals-5oUEu_fe.js → historyTotals-D8Oc3wUK.js} +1 -1
  23. package/dist/assets/{index-C9w-dVzo.js → index-9ajPMXBg.js} +1031 -1024
  24. package/dist/assets/{index-CMCcT2yg.css → index-oXqzajWV.css} +1 -1
  25. package/dist/index.html +2 -2
  26. package/dist-web/app.css +1 -1
  27. package/dist-web/app.js +414 -390
  28. package/package.json +1 -1
  29. package/scripts/scheduler-mcp-server.cjs +71 -0
  30. package/src/main/build-info.json +4 -4
  31. package/src/main/index.cjs +9 -0
  32. package/src/main/ipcSchemas.cjs +28 -1
  33. package/src/main/lib/epic/epicMint.cjs +61 -6
  34. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  35. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  36. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  37. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  38. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  39. package/src/main/lib/git/branchSweep.cjs +9 -3
  40. package/src/main/lib/git/gitExec.cjs +8 -1
  41. package/src/main/lib/git/gitWorktree.cjs +564 -62
  42. package/src/main/lib/git/jobWorktree.cjs +3 -0
  43. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  44. package/src/main/lib/mcpToolCatalog.cjs +28 -0
  45. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  46. package/src/main/lib/persona-macro/builtinMacros.cjs +16 -0
  47. package/src/main/lib/persona-macro/macroJobDispatch.cjs +8 -0
  48. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  49. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  50. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  51. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  52. package/src/main/lib/promptSessionSchema.cjs +5 -0
  53. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  54. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  55. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  56. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  57. package/src/main/projectPages.cjs +20 -1
  58. package/src/main/runVerify.cjs +8 -3
  59. package/src/main/scheduler/budget.cjs +146 -7
  60. package/src/main/scheduler/gitTreeGuard.cjs +10 -11
  61. package/src/main/scheduler/reviewLadder.cjs +60 -0
  62. package/src/main/scheduler.cjs +461 -48
  63. package/src/main/seedAgentPersonas.cjs +1 -1
  64. package/src/preload/api.d.ts +159 -1
  65. package/src/preload/apiSurface.json +21 -0
  66. package/src/preload/index.cjs +5 -0
  67. package/src/seed/agents/competitive-analyst.md +69 -0
  68. package/src/seed/agents/competitive-researcher.md +75 -0
  69. package/src/seed/agents/validator.md +2 -2
  70. package/dist/assets/Extensions-B9QdiNOV.js +0 -2
  71. package/dist/assets/Scheduler-DSVBWqRK.js +0 -16
  72. package/dist/assets/Skills-DTXehVS7.js +0 -12
@@ -0,0 +1,831 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * mcpToolsProbe.cjs — checks ONE MCP server by speaking MCP to it:
5
+ * initialize → notifications/initialized → tools/list (following nextCursor,
6
+ * at most MAX_TOOL_PAGES pages), over stdio or Streamable HTTP. It answers
7
+ * "connected, and with which tools" for the Extensions MCP detail ("TOOLS n
8
+ * from the last check"); mcpStatus.cjs (`claude mcp list`) gives status only.
9
+ * On demand only: nothing here runs by itself.
10
+ *
11
+ * checkConfiguredMcpServer backs IPC mcp:check-server. Its request only NAMES a
12
+ * configured server (user ~/.claude.json, project <cwd>/.mcp.json, or an
13
+ * installed plugin's own files); the config is read from disk here, so a caller
14
+ * can never choose the command a check spawns.
15
+ *
16
+ * Top-level lib/ module because no domain folder fits: it is an MCP client,
17
+ * lib/ has no mcp/ folder (its MCP siblings mcpStdioServer.cjs and
18
+ * mcpToolCatalog.cjs sit top-level too), and a one-file subfolder is not allowed.
19
+ *
20
+ * Guarantees:
21
+ * - checkMcpServer resolves, never rejects;
22
+ * - one deadline (timeoutMs) bounds the whole exchange;
23
+ * - at most OUTPUT_CAP_BYTES of server output is read: stdio stdout, or all
24
+ * HTTP response bodies of the check together;
25
+ * - a stdio server runs as its own process group, and the whole group is
26
+ * signalled (SIGTERM, then SIGKILL) on every exit path — done, timeout,
27
+ * error; the server itself has exited by the time the promise resolves;
28
+ * - server.env / server.headers values are redacted from every error, and
29
+ * nothing is logged.
30
+ */
31
+
32
+ const fs = require('node:fs');
33
+ const fsp = require('node:fs/promises');
34
+ const os = require('node:os');
35
+ const path = require('node:path');
36
+ const { spawn } = require('node:child_process');
37
+ const { StringDecoder } = require('node:string_decoder');
38
+ const claudeConfig = require('./claudeConfig.cjs');
39
+ const { readJsonOr } = require('./util/atomicFs.cjs');
40
+ const { cleanChildEnv, pathWithUserBins } = require('./process/cleanEnv.cjs');
41
+ const { killTree, detachedSpawnOpts } = require('./process/killTree.cjs');
42
+ const { resolveSpawn } = require('./process/winSpawn.cjs');
43
+
44
+ const PROTOCOL_VERSION = '2025-06-18';
45
+ const CLIENT_NAME = 'session-manager';
46
+ const DEFAULT_TIMEOUT_MS = 15_000;
47
+ const OUTPUT_CAP_BYTES = 2 * 1024 * 1024;
48
+ const MAX_TOOL_PAGES = 10;
49
+ /** `type` values checked over HTTP. 'sse' (the legacy HTTP+SSE transport) gets the
50
+ * Streamable-HTTP POST the MCP spec has clients try first; there is no fallback. */
51
+ const HTTP_TYPES = new Set(['http', 'streamable-http', 'sse']);
52
+
53
+ const KILL_GRACE_MS = 500; // SIGTERM → SIGKILL
54
+ const REAP_WAIT_MS = 2_000; // after SIGKILL, how long to wait for 'exit'
55
+ const EXIT_DRAIN_MS = 100; // after 'exit', time for the last stdout bytes to arrive
56
+ const SESSION_DELETE_MS = 1_000; // best-effort HTTP session teardown
57
+ const STDERR_KEEP_CHARS = 16 * 1024;
58
+ const JUNK_KEEP_CHARS = 4 * 1024;
59
+ const ERROR_BODY_CHARS = 8 * 1024;
60
+ const DETAIL_MAX_CHARS = 300;
61
+ const MIN_SECRET_CHARS = 4;
62
+
63
+ /** A check outcome other than "connected". */
64
+ class ProbeFailure extends Error {
65
+ /**
66
+ * @param {'failed' | 'needs-auth'} status
67
+ * @param {string} message fixed text, never built from config values or server output
68
+ * @param {unknown} [detail] config-, server- or system-derived text; redacted before it is shown
69
+ */
70
+ constructor(status, message, detail) {
71
+ super(message);
72
+ this.status = status;
73
+ this.detail = detail == null || detail === '' ? null : String(detail);
74
+ }
75
+ }
76
+
77
+ /** @param {unknown} v @returns {v is Record<string, any>} */
78
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
79
+
80
+ /** A config map's primitive values as strings (env and header values must be strings). */
81
+ function stringMap(obj) {
82
+ /** @type {Record<string, string>} */
83
+ const out = {};
84
+ if (!isObject(obj)) return out;
85
+ for (const [key, value] of Object.entries(obj)) {
86
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = String(value);
87
+ }
88
+ return out;
89
+ }
90
+
91
+ /**
92
+ * The redactor for one server's error details: every server.env and
93
+ * server.headers value (plus the token of a "<scheme> <token>" header, and any
94
+ * URL password or query value) becomes ***. Longest first, so a secret that
95
+ * contains another is replaced whole.
96
+ * @returns {(text: string) => string}
97
+ */
98
+ function makeRedactor(server) {
99
+ /** @type {Set<string>} */
100
+ const secrets = new Set();
101
+ const add = (/** @type {string} */ value) => { if (value.length >= MIN_SECRET_CHARS) secrets.add(value); };
102
+ if (isObject(server)) {
103
+ for (const value of Object.values(stringMap(server.env))) add(value);
104
+ for (const value of Object.values(stringMap(server.headers))) {
105
+ add(value);
106
+ for (const part of value.split(/\s+/)) if (part.length >= 8) add(part);
107
+ }
108
+ if (typeof server.url === 'string') {
109
+ try {
110
+ const url = new URL(server.url);
111
+ add(url.password);
112
+ for (const value of url.searchParams.values()) add(value);
113
+ } catch { /* not a URL: openHttp reports that */ }
114
+ }
115
+ }
116
+ const ordered = [...secrets].sort((a, b) => b.length - a.length);
117
+ return (text) => ordered.reduce((out, secret) => out.split(secret).join('***'), text);
118
+ }
119
+
120
+ /** The resolved shape of a failed check. Redact first, then trim: a cut can't expose half a secret. */
121
+ function failureResult(err, redact) {
122
+ const failure = err instanceof ProbeFailure
123
+ ? err
124
+ : new ProbeFailure('failed', 'check failed', err instanceof Error ? err.message : err);
125
+ let detail = failure.detail === null ? '' : redact(failure.detail).replace(/\s+/g, ' ').trim();
126
+ if (detail.length > DETAIL_MAX_CHARS) detail = `${detail.slice(0, DETAIL_MAX_CHARS - 1)}…`;
127
+ return { ok: false, status: failure.status, error: detail ? `${failure.message}: ${detail}` : failure.message };
128
+ }
129
+
130
+ /** 300 → "0.3", 15000 → "15". */
131
+ const formatSeconds = (ms) => String(Number((ms / 1000).toFixed(2)));
132
+
133
+ // ── JSON-RPC ────────────────────────────────────────────────────────────────
134
+
135
+ const sameId = (a, b) => a === b || (typeof a === 'string' && a === String(b));
136
+
137
+ /** Is `msg` the response to request `id`? An id:null error is the server
138
+ * rejecting the request outright (JSON-RPC's parse / invalid-request reply). */
139
+ function isResponseTo(msg, id) {
140
+ return isObject(msg) && typeof msg.method !== 'string'
141
+ && (sameId(msg.id, id) || (msg.id === null && isObject(msg.error)));
142
+ }
143
+
144
+ /** The response to `id` in a parsed reply (a single message or a batch), or null. */
145
+ function findResponse(parsed, id) {
146
+ for (const msg of Array.isArray(parsed) ? parsed : [parsed]) if (isResponseTo(msg, id)) return msg;
147
+ return null;
148
+ }
149
+
150
+ /** A response's result; its error becomes a ProbeFailure. */
151
+ function resultOf(msg, method) {
152
+ if (isObject(msg.error)) {
153
+ const { message, code } = msg.error;
154
+ throw new ProbeFailure('failed', `${method} failed`, typeof message === 'string' && message ? message : `error ${code}`);
155
+ }
156
+ if (!('result' in msg)) throw new ProbeFailure('failed', `invalid ${method} response`);
157
+ return msg.result;
158
+ }
159
+
160
+ /**
161
+ * @typedef {object} Transport
162
+ * @property {(method: string, params: object) => Promise<any>} request the JSON-RPC result; rejects with a ProbeFailure
163
+ * @property {(method: string) => Promise<void>} notify
164
+ * @property {(protocolVersion: string) => void} negotiated
165
+ * @property {(reason: ProbeFailure) => void} abort fail whatever is in flight, now and after
166
+ * @property {() => Promise<void>} close never rejects
167
+ */
168
+
169
+ /** The MCP exchange itself, transport-agnostic. @param {Transport} transport */
170
+ async function runProtocol(transport, clientVersion) {
171
+ const init = await transport.request('initialize', {
172
+ protocolVersion: PROTOCOL_VERSION,
173
+ capabilities: {},
174
+ clientInfo: { name: CLIENT_NAME, version: clientVersion },
175
+ });
176
+ if (!isObject(init)) throw new ProbeFailure('failed', 'invalid initialize result');
177
+ transport.negotiated(typeof init.protocolVersion === 'string' && init.protocolVersion ? init.protocolVersion : PROTOCOL_VERSION);
178
+ await transport.notify('notifications/initialized');
179
+ // MCP: only a server that declares the tools capability serves tools/list.
180
+ if (!isObject(init.capabilities) || !init.capabilities.tools) return [];
181
+ return listTools(transport);
182
+ }
183
+
184
+ /** tools/list, following nextCursor for at most MAX_TOOL_PAGES pages. @param {Transport} transport */
185
+ async function listTools(transport) {
186
+ /** @type {{ name: string, description: string }[]} */
187
+ const tools = [];
188
+ const names = new Set();
189
+ const cursors = new Set();
190
+ let cursor = null;
191
+ for (let page = 0; page < MAX_TOOL_PAGES; page++) {
192
+ const result = await transport.request('tools/list', cursor === null ? {} : { cursor });
193
+ if (!isObject(result) || !Array.isArray(result.tools)) throw new ProbeFailure('failed', 'tools/list returned no tools array');
194
+ for (const tool of result.tools) {
195
+ if (!isObject(tool) || typeof tool.name !== 'string' || !tool.name || names.has(tool.name)) continue;
196
+ names.add(tool.name);
197
+ tools.push({ name: tool.name, description: typeof tool.description === 'string' ? tool.description : '' });
198
+ }
199
+ const next = result.nextCursor;
200
+ if (typeof next !== 'string' || !next || cursors.has(next)) break; // last page, or a server repeating itself
201
+ cursors.add(next);
202
+ cursor = next;
203
+ }
204
+ return tools;
205
+ }
206
+
207
+ // ── stdio ───────────────────────────────────────────────────────────────────
208
+
209
+ function isDirectory(dir) {
210
+ try { return fs.statSync(dir).isDirectory(); } catch { return false; }
211
+ }
212
+
213
+ function spawnFailure(err, command) {
214
+ const code = isObject(err) && typeof err.code === 'string' ? err.code : '';
215
+ if (code === 'ENOENT') return new ProbeFailure('failed', 'command not found', command);
216
+ if (code === 'EACCES') return new ProbeFailure('failed', 'permission denied', command);
217
+ // The code only: spawn's messages can quote argument and env values verbatim.
218
+ return new ProbeFailure('failed', 'could not start server', code);
219
+ }
220
+
221
+ const ERRORISH = /(error|exception)\b|\b(cannot|can't|could not|not found|no such|denied|refused|failed|invalid|missing|unauthori[sz]ed|forbidden)\b/i;
222
+
223
+ /** The most telling stderr line: the last error-looking one, else the last line. */
224
+ function pickStderrLine(tail, trimmed) {
225
+ const lines = tail.split(/\r?\n/)
226
+ .slice(trimmed ? 1 : 0) // a trimmed tail starts mid-line
227
+ .map((l) => l.trim())
228
+ .filter((l) => l && !/^at\s/.test(l) && !/^node\.js v\d/i.test(l));
229
+ for (let i = lines.length - 1; i >= 0; i--) if (ERRORISH.test(lines[i])) return lines[i];
230
+ return lines.length ? lines[lines.length - 1] : '';
231
+ }
232
+
233
+ const hasExited = (child) => child.exitCode !== null || child.signalCode !== null;
234
+
235
+ /** Resolves true once `child` has exited, false after `ms`. */
236
+ function waitForExit(child, ms) {
237
+ if (hasExited(child)) return Promise.resolve(true);
238
+ return new Promise((resolve) => {
239
+ const onExit = () => { clearTimeout(timer); resolve(true); };
240
+ const timer = setTimeout(() => { child.removeListener('exit', onExit); resolve(false); }, ms);
241
+ child.once('exit', onExit);
242
+ });
243
+ }
244
+
245
+ /** Ends the server and everything in its process group: SIGTERM, then SIGKILL
246
+ * after KILL_GRACE_MS. Resolves once the server has exited (bounded). */
247
+ async function stopProcessGroup(child) {
248
+ const pid = child.pid;
249
+ if (!pid) return; // never started
250
+ if (!hasExited(child)) {
251
+ killTree(pid, 'SIGTERM');
252
+ if (!(await waitForExit(child, KILL_GRACE_MS))) {
253
+ killTree(pid, 'SIGKILL');
254
+ await waitForExit(child, REAP_WAIT_MS);
255
+ return;
256
+ }
257
+ }
258
+ // The leader is gone, but what it spawned can outlive it (or ignore SIGTERM).
259
+ // Signal the group only, never the bare pid, which may already be reused.
260
+ if (process.platform !== 'win32') {
261
+ try { process.kill(-pid, 'SIGKILL'); } catch { /* group already empty */ }
262
+ }
263
+ }
264
+
265
+ /** @returns {Transport} */
266
+ function openStdio(server, cwd) {
267
+ const command = server.command;
268
+ if (typeof command !== 'string' || !command) throw new ProbeFailure('failed', 'server has no command');
269
+ const dir = typeof cwd === 'string' && cwd ? cwd : os.homedir();
270
+ if (!isDirectory(dir)) throw new ProbeFailure('failed', 'working directory not found', dir);
271
+ const args = Array.isArray(server.args) ? server.args.map(String) : [];
272
+ // The cleaned app env (secrets stripped) with the server's own env on top:
273
+ // the keys it declares are its configuration, not app secrets to strip.
274
+ const env = { ...cleanChildEnv({ PATH: pathWithUserBins() }), ...stringMap(server.env) };
275
+ const target = resolveSpawn(command, args, { env });
276
+
277
+ let child;
278
+ try {
279
+ child = spawn(target.command, target.args, {
280
+ cwd: dir,
281
+ env,
282
+ shell: false,
283
+ stdio: ['pipe', 'pipe', 'pipe'],
284
+ ...detachedSpawnOpts(), // own process group, so killTree() reaches whatever the server spawns
285
+ ...(target.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
286
+ });
287
+ } catch (err) {
288
+ throw spawnFailure(err, command);
289
+ }
290
+
291
+ /** @type {ProbeFailure | null} set once the server can no longer answer */
292
+ let dead = null;
293
+ /** @type {{ id: number, method: string, resolve: (v: any) => void, reject: (e: unknown) => void } | null} */
294
+ let pending = null;
295
+ let lastMethod = 'initialize';
296
+ let nextId = 1;
297
+ let outBytes = 0;
298
+ let outBuf = '';
299
+ /** @type {string | null} first stdout line that was not JSON-RPC */
300
+ let junk = null;
301
+ let errTail = '';
302
+ let errTrimmed = false;
303
+ /** @type {NodeJS.Timeout | undefined} */
304
+ let drainTimer;
305
+ const outDecoder = new StringDecoder('utf8');
306
+ const errDecoder = new StringDecoder('utf8');
307
+
308
+ const fail = (/** @type {ProbeFailure} */ reason) => {
309
+ if (dead) return;
310
+ dead = reason;
311
+ if (pending) {
312
+ const p = pending;
313
+ pending = null;
314
+ p.reject(reason);
315
+ }
316
+ };
317
+ const write = (msg) => {
318
+ try { child.stdin.write(`${JSON.stringify(msg)}\n`); } catch { /* 'exit' / 'error' report a dead server */ }
319
+ };
320
+ const exitFailure = () => {
321
+ const how = child.signalCode ? `signal ${child.signalCode}` : `code ${child.exitCode}`;
322
+ const stdoutJunk = junk ?? (outBuf.trim() ? outBuf.trim().slice(0, JUNK_KEEP_CHARS) : null);
323
+ const detail = pickStderrLine(errTail, errTrimmed) || (stdoutJunk === null ? null : `stdout was not JSON-RPC: ${stdoutJunk}`);
324
+ return new ProbeFailure('failed', `server exited (${how}) before answering ${lastMethod}`, detail);
325
+ };
326
+
327
+ const onMessage = (msg) => {
328
+ if (typeof msg.method === 'string') {
329
+ // A request from the server must be answered (ping is the one a bare
330
+ // client knows); its notifications need nothing.
331
+ if (msg.id !== undefined && msg.id !== null) {
332
+ write(msg.method === 'ping'
333
+ ? { jsonrpc: '2.0', id: msg.id, result: {} }
334
+ : { jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'Method not found' } });
335
+ }
336
+ return;
337
+ }
338
+ if (!pending || !isResponseTo(msg, pending.id)) return;
339
+ const p = pending;
340
+ pending = null;
341
+ try { p.resolve(resultOf(msg, p.method)); } catch (err) { p.reject(err); }
342
+ };
343
+
344
+ // Lines that are not JSON-RPC are tolerated, as Claude Code's own client does
345
+ // (some servers print a banner); they only explain a later failure.
346
+ const onLine = (line) => {
347
+ let parsed;
348
+ try { parsed = JSON.parse(line); } catch { parsed = undefined; }
349
+ for (const msg of Array.isArray(parsed) ? parsed : [parsed]) {
350
+ if (isObject(msg)) onMessage(msg);
351
+ else if (junk === null) junk = line.slice(0, JUNK_KEEP_CHARS);
352
+ }
353
+ };
354
+
355
+ child.stdout.on('data', (chunk) => {
356
+ if (dead) return;
357
+ outBytes += chunk.length;
358
+ if (outBytes > OUTPUT_CAP_BYTES) {
359
+ fail(new ProbeFailure('failed', 'output too large'));
360
+ return;
361
+ }
362
+ const text = outDecoder.write(chunk);
363
+ if (!text.includes('\n')) {
364
+ outBuf += text;
365
+ return;
366
+ }
367
+ const lines = (outBuf + text).split('\n');
368
+ outBuf = lines.pop() ?? '';
369
+ for (const line of lines) {
370
+ if (dead) return;
371
+ const trimmed = line.trim();
372
+ if (trimmed) onLine(trimmed);
373
+ }
374
+ });
375
+ child.stderr.on('data', (chunk) => {
376
+ errTail += errDecoder.write(chunk);
377
+ if (errTail.length > STDERR_KEEP_CHARS) {
378
+ errTail = errTail.slice(-STDERR_KEEP_CHARS);
379
+ errTrimmed = true;
380
+ }
381
+ });
382
+ child.stdin.on('error', () => { /* EPIPE once the server is gone: 'exit' / 'close' report it */ });
383
+ child.on('error', (err) => fail(spawnFailure(err, command)));
384
+ child.on('exit', () => {
385
+ // 'close' (every pipe drained) normally follows at once, but a descendant
386
+ // still holding stdout open can delay it indefinitely.
387
+ if (!dead) drainTimer = setTimeout(() => fail(exitFailure()), EXIT_DRAIN_MS);
388
+ });
389
+ child.on('close', () => {
390
+ clearTimeout(drainTimer);
391
+ fail(exitFailure());
392
+ });
393
+
394
+ return {
395
+ request(method, params) {
396
+ if (dead) return Promise.reject(dead);
397
+ lastMethod = method;
398
+ const id = nextId++;
399
+ return new Promise((resolve, reject) => {
400
+ pending = { id, method, resolve, reject };
401
+ write({ jsonrpc: '2.0', id, method, params });
402
+ });
403
+ },
404
+ notify(method) {
405
+ if (dead) return Promise.reject(dead);
406
+ write({ jsonrpc: '2.0', method });
407
+ return Promise.resolve();
408
+ },
409
+ negotiated() { /* stdio carries no protocol-version header */ },
410
+ abort(reason) { fail(reason); },
411
+ async close() {
412
+ clearTimeout(drainTimer);
413
+ fail(new ProbeFailure('failed', 'closed'));
414
+ try { child.stdin.end(); } catch { /* already closed */ } // EOF: MCP's polite stdio shutdown
415
+ await stopProcessGroup(child);
416
+ },
417
+ };
418
+ }
419
+
420
+ // ── Streamable HTTP ─────────────────────────────────────────────────────────
421
+
422
+ /** Splits streamed text into lines. CRLF, LF and a lone CR all end a line (SSE),
423
+ * including a CRLF split across two chunks. */
424
+ function lineSplitter(onLine) {
425
+ let buf = '';
426
+ let afterCR = false;
427
+ return {
428
+ push(/** @type {string} */ text) {
429
+ let start = 0;
430
+ for (let i = 0; i < text.length; i++) {
431
+ const c = text.charCodeAt(i);
432
+ if (afterCR) {
433
+ afterCR = false;
434
+ if (c === 10) { start = i + 1; continue; }
435
+ }
436
+ if (c === 10 || c === 13) {
437
+ onLine(buf + text.slice(start, i));
438
+ buf = '';
439
+ start = i + 1;
440
+ afterCR = c === 13;
441
+ }
442
+ }
443
+ buf += text.slice(start);
444
+ },
445
+ end() {
446
+ if (buf) onLine(buf);
447
+ buf = '';
448
+ },
449
+ };
450
+ }
451
+
452
+ /** Frees a response body we won't read. @param {Response} res */
453
+ async function discard(res) {
454
+ try { await res.body?.cancel(); } catch { /* nothing left to free */ }
455
+ }
456
+
457
+ /** The useful part of a fetch failure: undici puts the socket / DNS / TLS error in `cause`. */
458
+ function networkDetail(err) {
459
+ const cause = isObject(err) ? err.cause : null;
460
+ if (isObject(cause)) return cause.message || cause.code || null;
461
+ return err instanceof Error ? err.message : err;
462
+ }
463
+
464
+ /** @returns {Transport} */
465
+ function openHttp(server) {
466
+ if (typeof server.url !== 'string' || !server.url) throw new ProbeFailure('failed', 'server has no url');
467
+ /** @type {URL} */
468
+ let url;
469
+ try { url = new URL(server.url); } catch { throw new ProbeFailure('failed', 'invalid url'); }
470
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ProbeFailure('failed', 'unsupported url scheme', url.protocol);
471
+ const configured = new Headers();
472
+ for (const [name, value] of Object.entries(stringMap(server.headers))) {
473
+ // The name only: a Headers error message quotes the value.
474
+ try { configured.set(name, value); } catch { throw new ProbeFailure('failed', 'invalid header', name); }
475
+ }
476
+ const legacySse = server.type === 'sse';
477
+ const controller = new AbortController();
478
+ /** @type {ProbeFailure | null} */
479
+ let aborted = null;
480
+ let sessionId = '';
481
+ let protocolVersion = '';
482
+ let nextId = 1;
483
+ let budget = OUTPUT_CAP_BYTES;
484
+
485
+ const spend = (/** @type {number} */ bytes) => {
486
+ budget -= bytes;
487
+ if (budget < 0) throw new ProbeFailure('failed', 'output too large');
488
+ };
489
+
490
+ const headers = (/** @type {boolean} */ withBody) => {
491
+ const h = new Headers(configured);
492
+ if (withBody) h.set('content-type', 'application/json');
493
+ h.set('accept', 'application/json, text/event-stream');
494
+ if (sessionId) h.set('mcp-session-id', sessionId);
495
+ if (protocolVersion) h.set('mcp-protocol-version', protocolVersion);
496
+ return h;
497
+ };
498
+
499
+ /** A body as text, counted against the cap; `limitChars` stops early (error bodies). */
500
+ async function readBody(res, limitChars = Infinity) {
501
+ if (limitChars === Infinity && Number(res.headers.get('content-length')) > budget) {
502
+ await discard(res);
503
+ throw new ProbeFailure('failed', 'output too large');
504
+ }
505
+ if (!res.body) return '';
506
+ const reader = res.body.getReader();
507
+ const decoder = new TextDecoder();
508
+ let text = '';
509
+ try {
510
+ for (;;) {
511
+ const { done, value } = await reader.read();
512
+ if (done) return text + decoder.decode();
513
+ spend(value.byteLength);
514
+ text += decoder.decode(value, { stream: true });
515
+ if (text.length >= limitChars) return text;
516
+ }
517
+ } finally {
518
+ reader.cancel().catch(() => {});
519
+ }
520
+ }
521
+
522
+ /** An error reply's most useful text: its JSON-RPC error message, else the status text. */
523
+ async function errorDetail(res) {
524
+ let text = '';
525
+ try { text = await readBody(res, ERROR_BODY_CHARS); } catch { /* the status says enough */ }
526
+ try {
527
+ const parsed = JSON.parse(text);
528
+ const error = (Array.isArray(parsed) ? parsed[0] : parsed)?.error;
529
+ if (isObject(error) && typeof error.message === 'string') return error.message;
530
+ if (typeof error === 'string') return error;
531
+ } catch { /* not JSON */ }
532
+ return res.statusText;
533
+ }
534
+
535
+ /** POSTs one JSON-RPC message; returns the response once it is 2xx. */
536
+ async function post(message) {
537
+ const res = await fetch(url, { method: 'POST', headers: headers(true), body: JSON.stringify(message), signal: controller.signal });
538
+ const sid = res.headers.get('mcp-session-id');
539
+ if (sid) sessionId = sid;
540
+ if (res.status === 401 || res.status === 403) {
541
+ await discard(res);
542
+ throw new ProbeFailure('needs-auth', `authentication required (HTTP ${res.status})`);
543
+ }
544
+ if (!res.ok) {
545
+ const unsupported = legacySse && res.status < 500 ? ' (legacy SSE transport is not supported)' : '';
546
+ throw new ProbeFailure('failed', `HTTP ${res.status}${unsupported}`, await errorDetail(res));
547
+ }
548
+ return res;
549
+ }
550
+
551
+ /** Reads SSE events until one carries the response to `id`, then stops,
552
+ * even if the server keeps the stream open. */
553
+ async function readEvents(res, id, method) {
554
+ if (!res.body) throw new ProbeFailure('failed', `empty ${method} event stream`);
555
+ const reader = res.body.getReader();
556
+ const decoder = new TextDecoder();
557
+ /** @type {string[]} */
558
+ let data = [];
559
+ let found = null;
560
+ const dispatch = () => {
561
+ const payload = data.join('\n');
562
+ data = [];
563
+ if (found || !payload) return;
564
+ try { found = findResponse(JSON.parse(payload), id); } catch { /* not JSON: skip the event */ }
565
+ };
566
+ const lines = lineSplitter((line) => {
567
+ if (line === '') { dispatch(); return; }
568
+ if (line.startsWith(':')) return; // comment / keep-alive
569
+ const colon = line.indexOf(':');
570
+ if ((colon === -1 ? line : line.slice(0, colon)) !== 'data') return; // event:, id:, retry:
571
+ const value = colon === -1 ? '' : line.slice(colon + 1);
572
+ data.push(value.startsWith(' ') ? value.slice(1) : value);
573
+ });
574
+ try {
575
+ while (!found) {
576
+ const { done, value } = await reader.read();
577
+ if (done) {
578
+ lines.end();
579
+ dispatch();
580
+ break;
581
+ }
582
+ spend(value.byteLength);
583
+ lines.push(decoder.decode(value, { stream: true }));
584
+ }
585
+ } finally {
586
+ reader.cancel().catch(() => {});
587
+ }
588
+ if (!found) throw new ProbeFailure('failed', `the ${method} event stream ended without a response`);
589
+ return found;
590
+ }
591
+
592
+ /** The response to request `id`, from a JSON or an SSE reply. */
593
+ async function readReply(res, id, method) {
594
+ const type = (res.headers.get('content-type') || '').toLowerCase();
595
+ if (type.includes('text/event-stream')) return readEvents(res, id, method);
596
+ if (type.includes('json')) {
597
+ const text = await readBody(res);
598
+ let parsed;
599
+ try { parsed = JSON.parse(text); } catch { throw new ProbeFailure('failed', `invalid JSON in the ${method} reply`); }
600
+ const reply = findResponse(parsed, id);
601
+ if (!reply) throw new ProbeFailure('failed', `no ${method} response in the reply`);
602
+ return reply;
603
+ }
604
+ await discard(res);
605
+ throw new ProbeFailure('failed', `unexpected ${method} reply type`, type || 'none');
606
+ }
607
+
608
+ /** After the deadline every failure is the timeout; otherwise network errors get a reason. */
609
+ const asFailure = (err, method) => aborted
610
+ || (err instanceof ProbeFailure ? err : new ProbeFailure('failed', `${method} request failed`, networkDetail(err)));
611
+
612
+ return {
613
+ async request(method, params) {
614
+ if (aborted) throw aborted;
615
+ const id = nextId++;
616
+ try {
617
+ const res = await post({ jsonrpc: '2.0', id, method, params });
618
+ return resultOf(await readReply(res, id, method), method);
619
+ } catch (err) {
620
+ throw asFailure(err, method);
621
+ }
622
+ },
623
+ async notify(method) {
624
+ if (aborted) throw aborted;
625
+ try {
626
+ await discard(await post({ jsonrpc: '2.0', method }));
627
+ } catch (err) {
628
+ throw asFailure(err, method);
629
+ }
630
+ },
631
+ negotiated(version) { protocolVersion = version; },
632
+ abort(reason) {
633
+ if (aborted) return;
634
+ aborted = reason;
635
+ controller.abort();
636
+ },
637
+ async close() {
638
+ // MCP: a client done with a session SHOULD end it with DELETE. Best
639
+ // effort, and skipped after a timeout: that server isn't answering.
640
+ if (!sessionId || aborted) return;
641
+ try {
642
+ await discard(await fetch(url, { method: 'DELETE', headers: headers(false), signal: AbortSignal.timeout(SESSION_DELETE_MS) }));
643
+ } catch { /* the server expires the session itself */ }
644
+ },
645
+ };
646
+ }
647
+
648
+ // ── entry point ─────────────────────────────────────────────────────────────
649
+
650
+ /** Picks the transport. An explicit `type` wins; otherwise a url means HTTP and a command means stdio. */
651
+ function openTransport(server, cwd) {
652
+ if (!isObject(server)) throw new ProbeFailure('failed', 'invalid server config');
653
+ const type = typeof server.type === 'string' ? server.type : '';
654
+ if (type === 'stdio') return openStdio(server, cwd);
655
+ if (HTTP_TYPES.has(type)) return openHttp(server);
656
+ if (type) throw new ProbeFailure('failed', 'unsupported transport', type);
657
+ if (server.url) return openHttp(server);
658
+ if (server.command) return openStdio(server, cwd);
659
+ throw new ProbeFailure('failed', 'server has no command or url');
660
+ }
661
+
662
+ /**
663
+ * Checks ONE MCP server: initialize → notifications/initialized → tools/list.
664
+ *
665
+ * @param {unknown} server one mcpServers entry: { type?, command?, args?, env?, url?, headers? }
666
+ * @param {{ timeoutMs?: number, clientVersion?: string, cwd?: string }} [options]
667
+ * timeoutMs bounds the whole exchange (stopping a stdio server afterwards can
668
+ * add up to ~2.5 s); clientVersion goes out as clientInfo.version; cwd is where
669
+ * a stdio server starts (default: the home directory; pass the project root
670
+ * for a project-scoped server whose command or args are relative).
671
+ * @returns {Promise<
672
+ * | { ok: true, status: 'connected', tools: { name: string, description: string }[], checkedAt: number }
673
+ * | { ok: false, status: 'failed' | 'needs-auth', error: string, checkedAt: number }>}
674
+ * Never rejects. A server listing more than MAX_TOOL_PAGES pages reports the tools of the first ones.
675
+ */
676
+ async function checkMcpServer(server, options) {
677
+ const { timeoutMs = DEFAULT_TIMEOUT_MS, clientVersion, cwd } = options || {};
678
+ const limit = typeof timeoutMs === 'number' && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_TIMEOUT_MS;
679
+ const version = typeof clientVersion === 'string' && clientVersion ? clientVersion : 'unknown';
680
+ /** @type {(text: string) => string} */
681
+ let redact = (text) => text;
682
+ /** @type {Transport | null} */
683
+ let transport = null;
684
+ /** @type {NodeJS.Timeout | undefined} */
685
+ let timer;
686
+ let outcome;
687
+ try {
688
+ redact = makeRedactor(server);
689
+ const open = openTransport(server, cwd);
690
+ transport = open;
691
+ const deadline = new ProbeFailure('failed', `timed out after ${formatSeconds(limit)}s`);
692
+ timer = setTimeout(() => open.abort(deadline), limit);
693
+ outcome = { ok: true, status: 'connected', tools: await runProtocol(open, version) };
694
+ } catch (err) {
695
+ outcome = failureResult(err, redact);
696
+ } finally {
697
+ clearTimeout(timer);
698
+ if (transport) await transport.close().catch(() => {});
699
+ }
700
+ return { ...outcome, checkedAt: Date.now() };
701
+ }
702
+
703
+ // ── configured servers (IPC mcp:check-server) ───────────────────────────────
704
+
705
+ /**
706
+ * @typedef {{ source: 'user' | 'project' | 'plugin', name: string, cwd?: string, pluginKey?: string }} McpServerRequest
707
+ * WHICH configured server: user = ~/.claude.json mcpServers, project =
708
+ * <cwd>/.mcp.json mcpServers, plugin = a server of the installed plugin keyed
709
+ * pluginKey (name@marketplace). cwd counts for a project server only.
710
+ */
711
+
712
+ const PLUGIN_ROOT_VAR = '${CLAUDE_PLUGIN_ROOT}';
713
+
714
+ /** @param {object} obj @param {string} key */
715
+ const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
716
+
717
+ /** map[name] when it is the map's own object entry — never an inherited key such as __proto__. */
718
+ function ownEntry(map, name) {
719
+ return isObject(map) && hasOwn(map, name) && isObject(map[name]) ? map[name] : null;
720
+ }
721
+
722
+ /** The manifest: .claude-plugin/plugin.json, else the legacy root plugin.json; null when the first one present doesn't parse. */
723
+ async function readPluginManifest(root) {
724
+ for (const file of [path.join(root, '.claude-plugin', 'plugin.json'), path.join(root, 'plugin.json')]) {
725
+ if (!(await fsp.access(file).then(() => true, () => false))) continue;
726
+ const data = await readJsonOr(file, null);
727
+ return isObject(data) ? data : null;
728
+ }
729
+ return null;
730
+ }
731
+
732
+ /** A server map from `{ mcpServers: {...} }`, or a bare map whose every value has a command or url. */
733
+ function pluginServerMap(data) {
734
+ if (!isObject(data)) return null;
735
+ if (isObject(data.mcpServers)) return data.mcpServers;
736
+ const values = Object.values(data);
737
+ const bare = values.length > 0 && values.every((d) => isObject(d) && (typeof d.command === 'string' || typeof d.url === 'string'));
738
+ return bare ? data : null;
739
+ }
740
+
741
+ /**
742
+ * A plugin's server maps in the order the Plugins tab reads them (renderer
743
+ * lib/pluginContents.ts listPluginMcpServers), so a server it lists is a server
744
+ * this finds: the manifest's inline mcpServers object, then each file the
745
+ * manifest declares inside the plugin root, then the default .mcp.json.
746
+ * Unreadable or malformed files are skipped.
747
+ * @param {string} root the resolved, absolute install dir
748
+ */
749
+ async function pluginServerMaps(root) {
750
+ const manifest = await readPluginManifest(root);
751
+ const decl = manifest ? manifest.mcpServers : undefined;
752
+ const declared = typeof decl === 'string' ? [decl] : Array.isArray(decl) ? decl.filter((d) => typeof d === 'string') : [];
753
+ /** @type {Set<string>} */
754
+ const files = new Set();
755
+ for (const rel of declared) {
756
+ const abs = path.resolve(root, rel);
757
+ if (abs === root || abs.startsWith(root + path.sep)) files.add(abs);
758
+ }
759
+ files.add(path.join(root, '.mcp.json'));
760
+ const bodies = await Promise.all([...files].map((file) => readJsonOr(file, null)));
761
+ return [isObject(decl) ? decl : null, ...bodies].map(pluginServerMap).filter(isObject);
762
+ }
763
+
764
+ /** A copy of a JSON value with ${CLAUDE_PLUGIN_ROOT} in every string replaced by root, as Claude Code expands a plugin's servers. */
765
+ function expandPluginRoot(value, root) {
766
+ if (typeof value === 'string') return value.split(PLUGIN_ROOT_VAR).join(root);
767
+ if (Array.isArray(value)) return value.map((v) => expandPluginRoot(v, root));
768
+ if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, expandPluginRoot(v, root)]));
769
+ return value;
770
+ }
771
+
772
+ /**
773
+ * The config of ONE configured MCP server, read from disk.
774
+ *
775
+ * @param {McpServerRequest} request
776
+ * @param {{ home?: string }} [options] home is injectable for tests
777
+ * @returns {Promise<{ server: Record<string, any>, cwd: string } | null>}
778
+ * null when no such server is configured. cwd is where a stdio server starts:
779
+ * the project root for a project server, else the home directory (Claude Code
780
+ * starts a server in its session's directory, and a check has none). Rejects
781
+ * when ~/.claude.json or <cwd>/.mcp.json exists but is not a JSON object.
782
+ */
783
+ async function resolveMcpServerConfig(request, options) {
784
+ const home = (options && options.home) || os.homedir();
785
+ const { source, name, cwd, pluginKey } = isObject(request) ? request : {};
786
+ if (typeof name !== 'string' || !name) return null;
787
+ if (source === 'user') {
788
+ const { data } = await claudeConfig.read({ fileId: 'claudeJson', scope: 'user', home });
789
+ const server = ownEntry(data.mcpServers, name);
790
+ return server ? { server, cwd: home } : null;
791
+ }
792
+ if (source === 'project') {
793
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return null;
794
+ const { data } = await claudeConfig.read({ fileId: 'mcpJson', scope: 'project', cwd });
795
+ const server = ownEntry(data.mcpServers, name);
796
+ return server ? { server, cwd } : null;
797
+ }
798
+ if (source === 'plugin') {
799
+ // Required here, not at the top: pluginInstall.cjs pulls in electron, node-pty
800
+ // and ipcSchemas.cjs, none of which a plain checkMcpServer caller needs.
801
+ const { listInstalled } = require('../pluginInstall.cjs');
802
+ const plugin = typeof pluginKey === 'string' ? listInstalled(home).find((p) => p.key === pluginKey) : undefined;
803
+ if (!plugin || typeof plugin.installPath !== 'string' || !path.isAbsolute(plugin.installPath)) return null;
804
+ const root = path.resolve(plugin.installPath);
805
+ for (const map of await pluginServerMaps(root)) {
806
+ // The first definition of a name wins, as in the Plugins tab's list.
807
+ if (hasOwn(map, name)) return isObject(map[name]) ? { server: expandPluginRoot(map[name], root), cwd: home } : null;
808
+ }
809
+ }
810
+ return null;
811
+ }
812
+
813
+ /**
814
+ * IPC mcp:check-server's body: resolves the request to ONE configured server
815
+ * and checks it.
816
+ *
817
+ * @param {McpServerRequest} request
818
+ * @param {{ home?: string, timeoutMs?: number, clientVersion?: string, check?: typeof checkMcpServer }} [options]
819
+ * home and check are injectable for tests; timeoutMs and clientVersion go to checkMcpServer.
820
+ * @returns {ReturnType<typeof checkMcpServer>} checkMcpServer's result, unchanged. A server
821
+ * that isn't configured resolves to { ok: false, status: 'failed', error: 'server not found' }
822
+ * with nothing spawned; a config file that can't be parsed rejects, also with nothing spawned.
823
+ */
824
+ async function checkConfiguredMcpServer(request, options) {
825
+ const { home, check = checkMcpServer, timeoutMs, clientVersion } = options || {};
826
+ const target = await resolveMcpServerConfig(request, { home });
827
+ if (!target) return { ok: false, status: 'failed', error: 'server not found', checkedAt: Date.now() };
828
+ return check(target.server, { timeoutMs, clientVersion, cwd: target.cwd });
829
+ }
830
+
831
+ module.exports = { checkMcpServer, resolveMcpServerConfig, checkConfiguredMcpServer };