toolscript-mcp 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/NOTICE +1 -0
- package/README.md +1266 -2
- package/demo/data.mjs +68 -0
- package/demo/server.mjs +83 -0
- package/dist/host/broker.js +1602 -0
- package/dist/host/main.js +34226 -0
- package/dist/third-party-licenses.txt +397 -0
- package/hints/datadog.md +9 -0
- package/hints/jira.md +6 -0
- package/hints/sha256.json +4 -0
- package/package.json +52 -4
- package/runtime/runner.mjs +329 -0
|
@@ -0,0 +1,1602 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
9
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
10
|
+
}) : x)(function(x) {
|
|
11
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
12
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
13
|
+
});
|
|
14
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
15
|
+
try {
|
|
16
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
17
|
+
} catch (e) {
|
|
18
|
+
throw mod = 0, e;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var __copyProps = (to, from, except, desc) => {
|
|
22
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
23
|
+
for (let key of __getOwnPropNames(from))
|
|
24
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
25
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
26
|
+
}
|
|
27
|
+
return to;
|
|
28
|
+
};
|
|
29
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
30
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
31
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
32
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
33
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
34
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
35
|
+
mod
|
|
36
|
+
));
|
|
37
|
+
|
|
38
|
+
// node_modules/isexe/windows.js
|
|
39
|
+
var require_windows = __commonJS({
|
|
40
|
+
"node_modules/isexe/windows.js"(exports, module) {
|
|
41
|
+
module.exports = isexe;
|
|
42
|
+
isexe.sync = sync;
|
|
43
|
+
var fs3 = __require("fs");
|
|
44
|
+
function checkPathExt(path2, options) {
|
|
45
|
+
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
|
|
46
|
+
if (!pathext) {
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
pathext = pathext.split(";");
|
|
50
|
+
if (pathext.indexOf("") !== -1) {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
for (var i = 0; i < pathext.length; i++) {
|
|
54
|
+
var p = pathext[i].toLowerCase();
|
|
55
|
+
if (p && path2.substr(-p.length).toLowerCase() === p) {
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
function checkStat(stat, path2, options) {
|
|
62
|
+
if (!stat.isSymbolicLink() && !stat.isFile()) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
return checkPathExt(path2, options);
|
|
66
|
+
}
|
|
67
|
+
function isexe(path2, options, cb) {
|
|
68
|
+
fs3.stat(path2, function(er, stat) {
|
|
69
|
+
cb(er, er ? false : checkStat(stat, path2, options));
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function sync(path2, options) {
|
|
73
|
+
return checkStat(fs3.statSync(path2), path2, options);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// node_modules/isexe/mode.js
|
|
79
|
+
var require_mode = __commonJS({
|
|
80
|
+
"node_modules/isexe/mode.js"(exports, module) {
|
|
81
|
+
module.exports = isexe;
|
|
82
|
+
isexe.sync = sync;
|
|
83
|
+
var fs3 = __require("fs");
|
|
84
|
+
function isexe(path2, options, cb) {
|
|
85
|
+
fs3.stat(path2, function(er, stat) {
|
|
86
|
+
cb(er, er ? false : checkStat(stat, options));
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function sync(path2, options) {
|
|
90
|
+
return checkStat(fs3.statSync(path2), options);
|
|
91
|
+
}
|
|
92
|
+
function checkStat(stat, options) {
|
|
93
|
+
return stat.isFile() && checkMode(stat, options);
|
|
94
|
+
}
|
|
95
|
+
function checkMode(stat, options) {
|
|
96
|
+
var mod = stat.mode;
|
|
97
|
+
var uid = stat.uid;
|
|
98
|
+
var gid = stat.gid;
|
|
99
|
+
var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
|
|
100
|
+
var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
|
|
101
|
+
var u = parseInt("100", 8);
|
|
102
|
+
var g = parseInt("010", 8);
|
|
103
|
+
var o = parseInt("001", 8);
|
|
104
|
+
var ug = u | g;
|
|
105
|
+
var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
|
|
106
|
+
return ret;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// node_modules/isexe/index.js
|
|
112
|
+
var require_isexe = __commonJS({
|
|
113
|
+
"node_modules/isexe/index.js"(exports, module) {
|
|
114
|
+
var fs3 = __require("fs");
|
|
115
|
+
var core;
|
|
116
|
+
if (process.platform === "win32" || global.TESTING_WINDOWS) {
|
|
117
|
+
core = require_windows();
|
|
118
|
+
} else {
|
|
119
|
+
core = require_mode();
|
|
120
|
+
}
|
|
121
|
+
module.exports = isexe;
|
|
122
|
+
isexe.sync = sync;
|
|
123
|
+
function isexe(path2, options, cb) {
|
|
124
|
+
if (typeof options === "function") {
|
|
125
|
+
cb = options;
|
|
126
|
+
options = {};
|
|
127
|
+
}
|
|
128
|
+
if (!cb) {
|
|
129
|
+
if (typeof Promise !== "function") {
|
|
130
|
+
throw new TypeError("callback not provided");
|
|
131
|
+
}
|
|
132
|
+
return new Promise(function(resolve, reject) {
|
|
133
|
+
isexe(path2, options || {}, function(er, is) {
|
|
134
|
+
if (er) {
|
|
135
|
+
reject(er);
|
|
136
|
+
} else {
|
|
137
|
+
resolve(is);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
core(path2, options || {}, function(er, is) {
|
|
143
|
+
if (er) {
|
|
144
|
+
if (er.code === "EACCES" || options && options.ignoreErrors) {
|
|
145
|
+
er = null;
|
|
146
|
+
is = false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
cb(er, is);
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
function sync(path2, options) {
|
|
153
|
+
try {
|
|
154
|
+
return core.sync(path2, options || {});
|
|
155
|
+
} catch (er) {
|
|
156
|
+
if (options && options.ignoreErrors || er.code === "EACCES") {
|
|
157
|
+
return false;
|
|
158
|
+
} else {
|
|
159
|
+
throw er;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// node_modules/which/which.js
|
|
167
|
+
var require_which = __commonJS({
|
|
168
|
+
"node_modules/which/which.js"(exports, module) {
|
|
169
|
+
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
|
|
170
|
+
var path2 = __require("path");
|
|
171
|
+
var COLON = isWindows ? ";" : ":";
|
|
172
|
+
var isexe = require_isexe();
|
|
173
|
+
var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
|
|
174
|
+
var getPathInfo = (cmd, opt) => {
|
|
175
|
+
const colon = opt.colon || COLON;
|
|
176
|
+
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
|
|
177
|
+
// windows always checks the cwd first
|
|
178
|
+
...isWindows ? [process.cwd()] : [],
|
|
179
|
+
...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
|
|
180
|
+
"").split(colon)
|
|
181
|
+
];
|
|
182
|
+
const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
|
|
183
|
+
const pathExt = isWindows ? pathExtExe.split(colon) : [""];
|
|
184
|
+
if (isWindows) {
|
|
185
|
+
if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
|
|
186
|
+
pathExt.unshift("");
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
pathEnv,
|
|
190
|
+
pathExt,
|
|
191
|
+
pathExtExe
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
var which = (cmd, opt, cb) => {
|
|
195
|
+
if (typeof opt === "function") {
|
|
196
|
+
cb = opt;
|
|
197
|
+
opt = {};
|
|
198
|
+
}
|
|
199
|
+
if (!opt)
|
|
200
|
+
opt = {};
|
|
201
|
+
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
202
|
+
const found = [];
|
|
203
|
+
const step = (i) => new Promise((resolve, reject) => {
|
|
204
|
+
if (i === pathEnv.length)
|
|
205
|
+
return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
|
|
206
|
+
const ppRaw = pathEnv[i];
|
|
207
|
+
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
208
|
+
const pCmd = path2.join(pathPart, cmd);
|
|
209
|
+
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
210
|
+
resolve(subStep(p, i, 0));
|
|
211
|
+
});
|
|
212
|
+
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
|
|
213
|
+
if (ii === pathExt.length)
|
|
214
|
+
return resolve(step(i + 1));
|
|
215
|
+
const ext = pathExt[ii];
|
|
216
|
+
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
|
|
217
|
+
if (!er && is) {
|
|
218
|
+
if (opt.all)
|
|
219
|
+
found.push(p + ext);
|
|
220
|
+
else
|
|
221
|
+
return resolve(p + ext);
|
|
222
|
+
}
|
|
223
|
+
return resolve(subStep(p, i, ii + 1));
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
|
|
227
|
+
};
|
|
228
|
+
var whichSync = (cmd, opt) => {
|
|
229
|
+
opt = opt || {};
|
|
230
|
+
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
231
|
+
const found = [];
|
|
232
|
+
for (let i = 0; i < pathEnv.length; i++) {
|
|
233
|
+
const ppRaw = pathEnv[i];
|
|
234
|
+
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
235
|
+
const pCmd = path2.join(pathPart, cmd);
|
|
236
|
+
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
237
|
+
for (let j = 0; j < pathExt.length; j++) {
|
|
238
|
+
const cur = p + pathExt[j];
|
|
239
|
+
try {
|
|
240
|
+
const is = isexe.sync(cur, { pathExt: pathExtExe });
|
|
241
|
+
if (is) {
|
|
242
|
+
if (opt.all)
|
|
243
|
+
found.push(cur);
|
|
244
|
+
else
|
|
245
|
+
return cur;
|
|
246
|
+
}
|
|
247
|
+
} catch (ex) {
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (opt.all && found.length)
|
|
252
|
+
return found;
|
|
253
|
+
if (opt.nothrow)
|
|
254
|
+
return null;
|
|
255
|
+
throw getNotFoundError(cmd);
|
|
256
|
+
};
|
|
257
|
+
module.exports = which;
|
|
258
|
+
which.sync = whichSync;
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// node_modules/path-key/index.js
|
|
263
|
+
var require_path_key = __commonJS({
|
|
264
|
+
"node_modules/path-key/index.js"(exports, module) {
|
|
265
|
+
"use strict";
|
|
266
|
+
var pathKey = (options = {}) => {
|
|
267
|
+
const environment = options.env || process.env;
|
|
268
|
+
const platform = options.platform || process.platform;
|
|
269
|
+
if (platform !== "win32") {
|
|
270
|
+
return "PATH";
|
|
271
|
+
}
|
|
272
|
+
return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
|
|
273
|
+
};
|
|
274
|
+
module.exports = pathKey;
|
|
275
|
+
module.exports.default = pathKey;
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
// node_modules/cross-spawn/lib/util/resolveCommand.js
|
|
280
|
+
var require_resolveCommand = __commonJS({
|
|
281
|
+
"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
|
|
282
|
+
"use strict";
|
|
283
|
+
var path2 = __require("path");
|
|
284
|
+
var which = require_which();
|
|
285
|
+
var getPathKey = require_path_key();
|
|
286
|
+
function resolveCommandAttempt(parsed, withoutPathExt) {
|
|
287
|
+
const env = parsed.options.env || process.env;
|
|
288
|
+
const cwd = process.cwd();
|
|
289
|
+
const hasCustomCwd = parsed.options.cwd != null;
|
|
290
|
+
const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
|
|
291
|
+
if (shouldSwitchCwd) {
|
|
292
|
+
try {
|
|
293
|
+
process.chdir(parsed.options.cwd);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
let resolved;
|
|
298
|
+
try {
|
|
299
|
+
resolved = which.sync(parsed.command, {
|
|
300
|
+
path: env[getPathKey({ env })],
|
|
301
|
+
pathExt: withoutPathExt ? path2.delimiter : void 0
|
|
302
|
+
});
|
|
303
|
+
} catch (e) {
|
|
304
|
+
} finally {
|
|
305
|
+
if (shouldSwitchCwd) {
|
|
306
|
+
process.chdir(cwd);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (resolved) {
|
|
310
|
+
resolved = path2.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
|
|
311
|
+
}
|
|
312
|
+
return resolved;
|
|
313
|
+
}
|
|
314
|
+
function resolveCommand(parsed) {
|
|
315
|
+
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
|
|
316
|
+
}
|
|
317
|
+
module.exports = resolveCommand;
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
// node_modules/cross-spawn/lib/util/escape.js
|
|
322
|
+
var require_escape = __commonJS({
|
|
323
|
+
"node_modules/cross-spawn/lib/util/escape.js"(exports, module) {
|
|
324
|
+
"use strict";
|
|
325
|
+
var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
|
|
326
|
+
function escapeCommand(arg) {
|
|
327
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
328
|
+
return arg;
|
|
329
|
+
}
|
|
330
|
+
function escapeArgument(arg, doubleEscapeMetaChars) {
|
|
331
|
+
arg = `${arg}`;
|
|
332
|
+
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
|
|
333
|
+
arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
|
|
334
|
+
arg = `"${arg}"`;
|
|
335
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
336
|
+
if (doubleEscapeMetaChars) {
|
|
337
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
338
|
+
}
|
|
339
|
+
return arg;
|
|
340
|
+
}
|
|
341
|
+
module.exports.command = escapeCommand;
|
|
342
|
+
module.exports.argument = escapeArgument;
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
// node_modules/shebang-regex/index.js
|
|
347
|
+
var require_shebang_regex = __commonJS({
|
|
348
|
+
"node_modules/shebang-regex/index.js"(exports, module) {
|
|
349
|
+
"use strict";
|
|
350
|
+
module.exports = /^#!(.*)/;
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
// node_modules/shebang-command/index.js
|
|
355
|
+
var require_shebang_command = __commonJS({
|
|
356
|
+
"node_modules/shebang-command/index.js"(exports, module) {
|
|
357
|
+
"use strict";
|
|
358
|
+
var shebangRegex = require_shebang_regex();
|
|
359
|
+
module.exports = (string = "") => {
|
|
360
|
+
const match = string.match(shebangRegex);
|
|
361
|
+
if (!match) {
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
const [path2, argument] = match[0].replace(/#! ?/, "").split(" ");
|
|
365
|
+
const binary = path2.split("/").pop();
|
|
366
|
+
if (binary === "env") {
|
|
367
|
+
return argument;
|
|
368
|
+
}
|
|
369
|
+
return argument ? `${binary} ${argument}` : binary;
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
// node_modules/cross-spawn/lib/util/readShebang.js
|
|
375
|
+
var require_readShebang = __commonJS({
|
|
376
|
+
"node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
|
|
377
|
+
"use strict";
|
|
378
|
+
var fs3 = __require("fs");
|
|
379
|
+
var shebangCommand = require_shebang_command();
|
|
380
|
+
function readShebang(command) {
|
|
381
|
+
const size = 150;
|
|
382
|
+
const buffer = Buffer.alloc(size);
|
|
383
|
+
let fd;
|
|
384
|
+
try {
|
|
385
|
+
fd = fs3.openSync(command, "r");
|
|
386
|
+
fs3.readSync(fd, buffer, 0, size, 0);
|
|
387
|
+
fs3.closeSync(fd);
|
|
388
|
+
} catch (e) {
|
|
389
|
+
}
|
|
390
|
+
return shebangCommand(buffer.toString());
|
|
391
|
+
}
|
|
392
|
+
module.exports = readShebang;
|
|
393
|
+
}
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
// node_modules/cross-spawn/lib/parse.js
|
|
397
|
+
var require_parse = __commonJS({
|
|
398
|
+
"node_modules/cross-spawn/lib/parse.js"(exports, module) {
|
|
399
|
+
"use strict";
|
|
400
|
+
var path2 = __require("path");
|
|
401
|
+
var resolveCommand = require_resolveCommand();
|
|
402
|
+
var escape = require_escape();
|
|
403
|
+
var readShebang = require_readShebang();
|
|
404
|
+
var isWin = process.platform === "win32";
|
|
405
|
+
var isExecutableRegExp = /\.(?:com|exe)$/i;
|
|
406
|
+
var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
|
|
407
|
+
function detectShebang(parsed) {
|
|
408
|
+
parsed.file = resolveCommand(parsed);
|
|
409
|
+
const shebang = parsed.file && readShebang(parsed.file);
|
|
410
|
+
if (shebang) {
|
|
411
|
+
parsed.args.unshift(parsed.file);
|
|
412
|
+
parsed.command = shebang;
|
|
413
|
+
return resolveCommand(parsed);
|
|
414
|
+
}
|
|
415
|
+
return parsed.file;
|
|
416
|
+
}
|
|
417
|
+
function parseNonShell(parsed) {
|
|
418
|
+
if (!isWin) {
|
|
419
|
+
return parsed;
|
|
420
|
+
}
|
|
421
|
+
const commandFile = detectShebang(parsed);
|
|
422
|
+
const needsShell = !isExecutableRegExp.test(commandFile);
|
|
423
|
+
if (parsed.options.forceShell || needsShell) {
|
|
424
|
+
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
|
|
425
|
+
parsed.command = path2.normalize(parsed.command);
|
|
426
|
+
parsed.command = escape.command(parsed.command);
|
|
427
|
+
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
|
|
428
|
+
const shellCommand = [parsed.command].concat(parsed.args).join(" ");
|
|
429
|
+
parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
|
|
430
|
+
parsed.command = process.env.comspec || "cmd.exe";
|
|
431
|
+
parsed.options.windowsVerbatimArguments = true;
|
|
432
|
+
}
|
|
433
|
+
return parsed;
|
|
434
|
+
}
|
|
435
|
+
function parse(command, args, options) {
|
|
436
|
+
if (args && !Array.isArray(args)) {
|
|
437
|
+
options = args;
|
|
438
|
+
args = null;
|
|
439
|
+
}
|
|
440
|
+
args = args ? args.slice(0) : [];
|
|
441
|
+
options = Object.assign({}, options);
|
|
442
|
+
const parsed = {
|
|
443
|
+
command,
|
|
444
|
+
args,
|
|
445
|
+
options,
|
|
446
|
+
file: void 0,
|
|
447
|
+
original: {
|
|
448
|
+
command,
|
|
449
|
+
args
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
return options.shell ? parsed : parseNonShell(parsed);
|
|
453
|
+
}
|
|
454
|
+
module.exports = parse;
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
// node_modules/cross-spawn/lib/enoent.js
|
|
459
|
+
var require_enoent = __commonJS({
|
|
460
|
+
"node_modules/cross-spawn/lib/enoent.js"(exports, module) {
|
|
461
|
+
"use strict";
|
|
462
|
+
var isWin = process.platform === "win32";
|
|
463
|
+
function notFoundError(original, syscall) {
|
|
464
|
+
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
|
|
465
|
+
code: "ENOENT",
|
|
466
|
+
errno: "ENOENT",
|
|
467
|
+
syscall: `${syscall} ${original.command}`,
|
|
468
|
+
path: original.command,
|
|
469
|
+
spawnargs: original.args
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
function hookChildProcess(cp, parsed) {
|
|
473
|
+
if (!isWin) {
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
const originalEmit = cp.emit;
|
|
477
|
+
cp.emit = function(name, arg1) {
|
|
478
|
+
if (name === "exit") {
|
|
479
|
+
const err = verifyENOENT(arg1, parsed);
|
|
480
|
+
if (err) {
|
|
481
|
+
return originalEmit.call(cp, "error", err);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return originalEmit.apply(cp, arguments);
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function verifyENOENT(status, parsed) {
|
|
488
|
+
if (isWin && status === 1 && !parsed.file) {
|
|
489
|
+
return notFoundError(parsed.original, "spawn");
|
|
490
|
+
}
|
|
491
|
+
return null;
|
|
492
|
+
}
|
|
493
|
+
function verifyENOENTSync(status, parsed) {
|
|
494
|
+
if (isWin && status === 1 && !parsed.file) {
|
|
495
|
+
return notFoundError(parsed.original, "spawnSync");
|
|
496
|
+
}
|
|
497
|
+
return null;
|
|
498
|
+
}
|
|
499
|
+
module.exports = {
|
|
500
|
+
hookChildProcess,
|
|
501
|
+
verifyENOENT,
|
|
502
|
+
verifyENOENTSync,
|
|
503
|
+
notFoundError
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
// node_modules/cross-spawn/index.js
|
|
509
|
+
var require_cross_spawn = __commonJS({
|
|
510
|
+
"node_modules/cross-spawn/index.js"(exports, module) {
|
|
511
|
+
"use strict";
|
|
512
|
+
var cp = __require("child_process");
|
|
513
|
+
var parse = require_parse();
|
|
514
|
+
var enoent = require_enoent();
|
|
515
|
+
function spawn(command, args, options) {
|
|
516
|
+
const parsed = parse(command, args, options);
|
|
517
|
+
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
|
|
518
|
+
enoent.hookChildProcess(spawned, parsed);
|
|
519
|
+
return spawned;
|
|
520
|
+
}
|
|
521
|
+
function spawnSync(command, args, options) {
|
|
522
|
+
const parsed = parse(command, args, options);
|
|
523
|
+
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
|
|
524
|
+
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
|
|
525
|
+
return result;
|
|
526
|
+
}
|
|
527
|
+
module.exports = spawn;
|
|
528
|
+
module.exports.spawn = spawn;
|
|
529
|
+
module.exports.sync = spawnSync;
|
|
530
|
+
module.exports._parse = parse;
|
|
531
|
+
module.exports._enoent = enoent;
|
|
532
|
+
}
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
// src/host/brokermain.ts
|
|
536
|
+
import os from "node:os";
|
|
537
|
+
|
|
538
|
+
// src/core/paths.ts
|
|
539
|
+
var APP = ".toolscript-mcp";
|
|
540
|
+
var HINTS = "hints";
|
|
541
|
+
var FUNCTIONS = "functions";
|
|
542
|
+
var LEARNED = "learned";
|
|
543
|
+
var OAUTH = "oauth";
|
|
544
|
+
var BROKER = "broker";
|
|
545
|
+
var normalizePath = (path2) => {
|
|
546
|
+
const drive = /^[A-Za-z]:(?=[\\/]|$)/.exec(path2)?.[0];
|
|
547
|
+
const rest = drive === void 0 ? path2 : path2.slice(drive.length).replaceAll("\\", "/");
|
|
548
|
+
const parts = [];
|
|
549
|
+
for (const part of rest.split("/")) {
|
|
550
|
+
if (part === "" || part === ".") continue;
|
|
551
|
+
if (part === "..") parts.pop();
|
|
552
|
+
else parts.push(part);
|
|
553
|
+
}
|
|
554
|
+
return `${drive ?? ""}/${parts.join("/")}`;
|
|
555
|
+
};
|
|
556
|
+
var appPath = (root, ...parts) => normalizePath([root, APP, ...parts].join("/"));
|
|
557
|
+
var brokerFolder = (home) => appPath(home, BROKER);
|
|
558
|
+
var GUARD_MARKERS = [HINTS, FUNCTIONS, LEARNED, OAUTH, BROKER].map((name) => `${APP}/${name}`);
|
|
559
|
+
|
|
560
|
+
// src/core/share.ts
|
|
561
|
+
var STATE_WORDS = [
|
|
562
|
+
["playwright", "drives a browser"],
|
|
563
|
+
["puppeteer", "drives a browser"],
|
|
564
|
+
["chrome-devtools", "drives a browser"],
|
|
565
|
+
["browsermcp", "drives a browser"],
|
|
566
|
+
["browser", "drives a browser"],
|
|
567
|
+
["selenium", "drives a browser"],
|
|
568
|
+
["desktop-commander", "runs a shell"],
|
|
569
|
+
["shell", "runs a shell"],
|
|
570
|
+
["terminal", "runs a shell"]
|
|
571
|
+
];
|
|
572
|
+
var STATE_WORD = new RegExp(`(?<![a-z])(${STATE_WORDS.map(([word]) => word).join("|")})s?(?![a-z])`, "i");
|
|
573
|
+
var shareText = (class_, server, env, at) => {
|
|
574
|
+
const names = Object.keys(env).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
575
|
+
const folder = server.cwd ?? (class_.class === "shared" ? at.home : at.folder);
|
|
576
|
+
return JSON.stringify(["toolscript-share", server.command, server.args, names.map((n) => [n, env[n]]), folder]);
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
// src/core/broker.ts
|
|
580
|
+
var WIRE = 2;
|
|
581
|
+
var PROOF_BYTES = 4096;
|
|
582
|
+
var PROOF_MS = 2e3;
|
|
583
|
+
var PROOF_CONNECTIONS = 16;
|
|
584
|
+
var CHILD_INIT_MS = 3e4;
|
|
585
|
+
var CHILD_IDLE_MS = 6e5;
|
|
586
|
+
var STOP_WAIT_MS = 2e3;
|
|
587
|
+
var SOCKET_MAX_BYTES = 100;
|
|
588
|
+
var idleMs = (text) => {
|
|
589
|
+
const n = text !== void 0 && /^\d+$/.test(text) ? Number(text) : CHILD_IDLE_MS;
|
|
590
|
+
return n >= 1e3 ? n : CHILD_IDLE_MS;
|
|
591
|
+
};
|
|
592
|
+
var utf8Length = (text) => {
|
|
593
|
+
let n = 0;
|
|
594
|
+
for (const ch of text) {
|
|
595
|
+
const c = ch.codePointAt(0);
|
|
596
|
+
n += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4;
|
|
597
|
+
}
|
|
598
|
+
return n;
|
|
599
|
+
};
|
|
600
|
+
var shortSocketFolder = (uid) => `/tmp/tsm-${uid}`;
|
|
601
|
+
var endpointOf = (platform, home, mac, uid) => {
|
|
602
|
+
const name = `tsm-${mac.slice(0, 12)}.sock`;
|
|
603
|
+
if (platform === "win32") return `\\\\.\\pipe\\toolscript-mcp-${mac.slice(0, 12)}`;
|
|
604
|
+
const near = `${brokerFolder(home)}/${name}`;
|
|
605
|
+
return utf8Length(near) <= SOCKET_MAX_BYTES ? near : `${shortSocketFolder(uid)}/${name}`;
|
|
606
|
+
};
|
|
607
|
+
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
608
|
+
var parseEntry = (frame2) => {
|
|
609
|
+
if (!isObj(frame2) || frame2.t !== "entry") return "the first frame after the proof is not an entry";
|
|
610
|
+
const { command, args, env, folder } = frame2;
|
|
611
|
+
if (typeof command !== "string" || command === "" || typeof folder !== "string" || folder === "")
|
|
612
|
+
return "the entry has no command or no folder";
|
|
613
|
+
if (!Array.isArray(args) || !args.every((a) => typeof a === "string")) return "the entry has bad arguments";
|
|
614
|
+
if (!isObj(env) || !Object.values(env).every((v) => typeof v === "string")) return "the entry has a bad environment";
|
|
615
|
+
return { command, args, env, folder };
|
|
616
|
+
};
|
|
617
|
+
var entryText = (entry) => shareText(
|
|
618
|
+
{ class: "folder", rule: 5 },
|
|
619
|
+
{ kind: "stdio", command: entry.command, args: entry.args, env: {}, cwd: entry.folder },
|
|
620
|
+
entry.env,
|
|
621
|
+
{ home: entry.folder, folder: entry.folder }
|
|
622
|
+
);
|
|
623
|
+
var proofText = (role, host, broker2) => `toolscript-mcp ${WIRE} ${role} ${host} ${broker2}`;
|
|
624
|
+
var NONCE = /^[0-9a-f]{32}$/;
|
|
625
|
+
var isNonce = (v) => typeof v === "string" && NONCE.test(v);
|
|
626
|
+
var isProof = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
|
|
627
|
+
var frame = (value) => `${JSON.stringify(value)}
|
|
628
|
+
`;
|
|
629
|
+
var parseFrame = (line) => {
|
|
630
|
+
try {
|
|
631
|
+
return JSON.parse(line);
|
|
632
|
+
} catch {
|
|
633
|
+
return void 0;
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
var brokerSide = (c) => {
|
|
637
|
+
let state = "hello";
|
|
638
|
+
let host = "";
|
|
639
|
+
let broker2 = "";
|
|
640
|
+
return {
|
|
641
|
+
start: () => "",
|
|
642
|
+
step: (line) => {
|
|
643
|
+
const msg = parseFrame(line);
|
|
644
|
+
if (state === "hello") {
|
|
645
|
+
if (!isObj(msg) || msg.t !== "hello" || msg.v !== WIRE || !isNonce(msg.n)) return { fail: "bad hello" };
|
|
646
|
+
state = "proof";
|
|
647
|
+
host = msg.n;
|
|
648
|
+
broker2 = c.nonce();
|
|
649
|
+
return { send: frame({ t: "hello", n: broker2, p: c.mac(proofText("broker", host, broker2)) }) };
|
|
650
|
+
}
|
|
651
|
+
if (state === "proof") {
|
|
652
|
+
if (!isObj(msg) || msg.t !== "proof" || !isProof(msg.p) || !c.same(msg.p, c.mac(proofText("host", host, broker2))))
|
|
653
|
+
return { fail: "wrong proof" };
|
|
654
|
+
state = "done";
|
|
655
|
+
return { send: frame({ t: "ok" }), done: true };
|
|
656
|
+
}
|
|
657
|
+
return { fail: "extra frame" };
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
};
|
|
661
|
+
var MARK = "";
|
|
662
|
+
var marked = (value) => `${MARK}${JSON.stringify(value)}
|
|
663
|
+
`;
|
|
664
|
+
var attachedFrame = marked({ t: "attached" });
|
|
665
|
+
var refusedFrame = (reason) => marked({ t: "refused", reason });
|
|
666
|
+
var STDERR_CHUNK = 6144;
|
|
667
|
+
var STDERR_RATE = 256 * 1024;
|
|
668
|
+
var STDERR_WINDOW_MS = 1e4;
|
|
669
|
+
var STDERR_BACKLOG = 256 * 1024;
|
|
670
|
+
var STDERR_TAIL = 8 * 1024;
|
|
671
|
+
var UNSENT_MAX = 64 * 1024 * 1024;
|
|
672
|
+
var LINKS_MAX = 256;
|
|
673
|
+
var CHILDREN_MAX = 32;
|
|
674
|
+
var stderrFrame = (base64) => marked({ t: "stderr", d: base64 });
|
|
675
|
+
var droppedFrame = (bytes) => marked({ t: "stderr", dropped: bytes });
|
|
676
|
+
var LINE_MAX = 10 * 1024 * 1024;
|
|
677
|
+
var lineSplitter = (onLine, max = () => LINE_MAX, onOverflow = () => {
|
|
678
|
+
}) => {
|
|
679
|
+
let parts = [];
|
|
680
|
+
let size = 0;
|
|
681
|
+
let over = false;
|
|
682
|
+
const overflow = () => {
|
|
683
|
+
over = true;
|
|
684
|
+
parts = [];
|
|
685
|
+
size = 0;
|
|
686
|
+
onOverflow();
|
|
687
|
+
};
|
|
688
|
+
return (chunk) => {
|
|
689
|
+
if (over) return;
|
|
690
|
+
let from = 0;
|
|
691
|
+
for (let at = chunk.indexOf("\n", from); at >= 0; at = chunk.indexOf("\n", from)) {
|
|
692
|
+
if (size + (at - from) > max()) return overflow();
|
|
693
|
+
parts.push(chunk.slice(from, at));
|
|
694
|
+
const line = parts.length === 1 ? parts[0] : parts.join("");
|
|
695
|
+
parts = [];
|
|
696
|
+
size = 0;
|
|
697
|
+
from = at + 1;
|
|
698
|
+
if (line.trim() !== "") onLine(line);
|
|
699
|
+
}
|
|
700
|
+
if (from < chunk.length) {
|
|
701
|
+
const tail = from === 0 ? chunk : chunk.slice(from);
|
|
702
|
+
size += tail.length;
|
|
703
|
+
if (size > max()) return overflow();
|
|
704
|
+
parts.push(tail);
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
};
|
|
708
|
+
|
|
709
|
+
// src/host/broker.ts
|
|
710
|
+
var import_cross_spawn = __toESM(require_cross_spawn(), 1);
|
|
711
|
+
import { spawn as nodeSpawn } from "node:child_process";
|
|
712
|
+
import crypto2 from "node:crypto";
|
|
713
|
+
import fs2 from "node:fs";
|
|
714
|
+
import net from "node:net";
|
|
715
|
+
import path from "node:path";
|
|
716
|
+
|
|
717
|
+
// src/core/mux.ts
|
|
718
|
+
var DIED_CODE = -32e3;
|
|
719
|
+
var NOT_FOUND_CODE = -32601;
|
|
720
|
+
var VERSION = "2.0";
|
|
721
|
+
var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
722
|
+
var isId = (v) => typeof v === "string" || typeof v === "number" && Number.isFinite(v);
|
|
723
|
+
var own = (o, key) => Object.hasOwn(o, key) ? o[key] : void 0;
|
|
724
|
+
var answer = (id, result) => ({ jsonrpc: VERSION, id, result });
|
|
725
|
+
var failure = (id, code, message) => ({ jsonrpc: VERSION, id, error: { code, message } });
|
|
726
|
+
var createRouter = () => {
|
|
727
|
+
const links = /* @__PURE__ */ new Map();
|
|
728
|
+
const open = /* @__PURE__ */ new Map();
|
|
729
|
+
let nextId = 1;
|
|
730
|
+
let dead = false;
|
|
731
|
+
let cached;
|
|
732
|
+
let opening;
|
|
733
|
+
let initialized = false;
|
|
734
|
+
const holder = (held, id) => typeof id === "number" ? held.numbers.get(id) : held.strings.get(id);
|
|
735
|
+
const hold = (held, id, rid) => {
|
|
736
|
+
if (typeof id === "number") held.numbers.set(id, rid);
|
|
737
|
+
else held.strings.set(id, rid);
|
|
738
|
+
};
|
|
739
|
+
const release = (held, id) => {
|
|
740
|
+
if (typeof id === "number") held.numbers.delete(id);
|
|
741
|
+
else held.strings.delete(id);
|
|
742
|
+
};
|
|
743
|
+
const close = (rid, link, id) => {
|
|
744
|
+
const entry = open.get(rid);
|
|
745
|
+
const held = links.get(link);
|
|
746
|
+
if (held !== void 0) release(held, id);
|
|
747
|
+
if (entry?.kind === "call") {
|
|
748
|
+
open.delete(rid);
|
|
749
|
+
} else if (entry !== void 0) {
|
|
750
|
+
const at = entry.waiters.findIndex((w) => w.link === link && w.id === id);
|
|
751
|
+
if (at >= 0) entry.waiters.splice(at, 1);
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
const cancelChild = (rid, reason) => ({
|
|
755
|
+
to: "child",
|
|
756
|
+
msg: {
|
|
757
|
+
jsonrpc: VERSION,
|
|
758
|
+
method: "notifications/cancelled",
|
|
759
|
+
params: { requestId: rid, ...typeof reason === "string" && { reason } }
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
const cancel = (link, id, reason) => {
|
|
763
|
+
const held = links.get(link);
|
|
764
|
+
const rid = held === void 0 ? void 0 : holder(held, id);
|
|
765
|
+
const entry = rid === void 0 ? void 0 : open.get(rid);
|
|
766
|
+
if (rid === void 0 || entry === void 0) return [];
|
|
767
|
+
close(rid, link, id);
|
|
768
|
+
return entry.kind === "call" ? [cancelChild(rid, reason)] : [];
|
|
769
|
+
};
|
|
770
|
+
const withToken = (msg, params, rid) => {
|
|
771
|
+
const meta = isObj2(params) ? own(params, "_meta") : void 0;
|
|
772
|
+
const original = isObj2(meta) ? own(meta, "progressToken") : void 0;
|
|
773
|
+
if (!isObj2(params) || !isObj2(meta) || !isId(original)) return { msg };
|
|
774
|
+
return { msg: { ...msg, params: { ...params, _meta: { ...meta, progressToken: rid } } }, token: original };
|
|
775
|
+
};
|
|
776
|
+
const request = (link, id, msg, held) => {
|
|
777
|
+
const method = own(msg, "method");
|
|
778
|
+
if (method === "ping") return [{ to: "link", link, msg: answer(id, {}) }];
|
|
779
|
+
if (holder(held, id) !== void 0) return [];
|
|
780
|
+
if (method === "initialize") {
|
|
781
|
+
if (cached !== void 0) return [{ to: "link", link, msg: answer(id, cached.result) }];
|
|
782
|
+
if (opening !== void 0) {
|
|
783
|
+
const entry = open.get(opening);
|
|
784
|
+
entry.waiters.push({ link, id });
|
|
785
|
+
hold(held, id, opening);
|
|
786
|
+
return [];
|
|
787
|
+
}
|
|
788
|
+
const rid2 = nextId++;
|
|
789
|
+
opening = rid2;
|
|
790
|
+
open.set(rid2, { kind: "init", waiters: [{ link, id }] });
|
|
791
|
+
hold(held, id, rid2);
|
|
792
|
+
const params = own(msg, "params");
|
|
793
|
+
const { _meta, ...rest } = isObj2(params) ? params : { _meta: void 0 };
|
|
794
|
+
const forwarded = { ...msg, id: rid2, params: { ...rest, capabilities: {} } };
|
|
795
|
+
return [{ to: "child", msg: forwarded }];
|
|
796
|
+
}
|
|
797
|
+
const rid = nextId++;
|
|
798
|
+
const { msg: changed, token } = withToken(msg, own(msg, "params"), rid);
|
|
799
|
+
open.set(rid, { kind: "call", link, id, ...token !== void 0 && { token } });
|
|
800
|
+
hold(held, id, rid);
|
|
801
|
+
return [{ to: "child", msg: { ...changed, id: rid } }];
|
|
802
|
+
};
|
|
803
|
+
const notice = (link, msg, method) => {
|
|
804
|
+
if (method === "notifications/cancelled") {
|
|
805
|
+
const params = own(msg, "params");
|
|
806
|
+
const id = isObj2(params) ? own(params, "requestId") : void 0;
|
|
807
|
+
return isId(id) ? cancel(link, id, isObj2(params) ? own(params, "reason") : void 0) : [];
|
|
808
|
+
}
|
|
809
|
+
if (method === "notifications/initialized" && cached !== void 0 && !initialized) {
|
|
810
|
+
initialized = true;
|
|
811
|
+
return [{ to: "child", msg }];
|
|
812
|
+
}
|
|
813
|
+
return [];
|
|
814
|
+
};
|
|
815
|
+
const fromLink = (link, msg) => {
|
|
816
|
+
const held = links.get(link);
|
|
817
|
+
if (dead || held === void 0 || !isObj2(msg)) return [];
|
|
818
|
+
const method = own(msg, "method");
|
|
819
|
+
if (typeof method !== "string") return [];
|
|
820
|
+
const id = own(msg, "id");
|
|
821
|
+
if (id === void 0) return notice(link, msg, method);
|
|
822
|
+
return isId(id) ? request(link, id, msg, held) : [];
|
|
823
|
+
};
|
|
824
|
+
const answerInit = (rid, entry, msg) => {
|
|
825
|
+
open.delete(rid);
|
|
826
|
+
opening = void 0;
|
|
827
|
+
const result = own(msg, "result");
|
|
828
|
+
const good = Object.hasOwn(msg, "result") && !Object.hasOwn(msg, "error");
|
|
829
|
+
if (good) cached = { result };
|
|
830
|
+
return entry.waiters.flatMap(({ link, id }) => {
|
|
831
|
+
const held = links.get(link);
|
|
832
|
+
if (held !== void 0) release(held, id);
|
|
833
|
+
return [{ to: "link", link, msg: good ? answer(id, result) : { ...msg, id } }];
|
|
834
|
+
});
|
|
835
|
+
};
|
|
836
|
+
const response = (rid, msg) => {
|
|
837
|
+
const entry = open.get(rid);
|
|
838
|
+
if (entry === void 0) return [];
|
|
839
|
+
if (entry.kind === "init") return answerInit(rid, entry, msg);
|
|
840
|
+
open.delete(rid);
|
|
841
|
+
const held = links.get(entry.link);
|
|
842
|
+
if (held !== void 0) release(held, entry.id);
|
|
843
|
+
return [{ to: "link", link: entry.link, msg: { ...msg, id: entry.id } }];
|
|
844
|
+
};
|
|
845
|
+
const progress = (msg) => {
|
|
846
|
+
const params = own(msg, "params");
|
|
847
|
+
const sent = isObj2(params) ? own(params, "progressToken") : void 0;
|
|
848
|
+
const entry = typeof sent === "number" ? open.get(sent) : void 0;
|
|
849
|
+
if (!isObj2(params) || entry?.kind !== "call" || entry.token === void 0) return [];
|
|
850
|
+
const changed = { ...msg, params: { ...params, progressToken: entry.token } };
|
|
851
|
+
return [{ to: "link", link: entry.link, msg: changed }];
|
|
852
|
+
};
|
|
853
|
+
const fromChild = (msg) => {
|
|
854
|
+
if (dead || !isObj2(msg)) return [];
|
|
855
|
+
const method = own(msg, "method");
|
|
856
|
+
const id = own(msg, "id");
|
|
857
|
+
if (typeof method === "string") {
|
|
858
|
+
if (id === void 0) {
|
|
859
|
+
if (method === "notifications/progress") return progress(msg);
|
|
860
|
+
if (method !== "notifications/tools/list_changed") return [];
|
|
861
|
+
return [...links.keys()].map((link) => ({ to: "link", link, msg }));
|
|
862
|
+
}
|
|
863
|
+
if (!isId(id)) return [];
|
|
864
|
+
return [
|
|
865
|
+
{ to: "child", msg: method === "ping" ? answer(id, {}) : failure(id, NOT_FOUND_CODE, "Method not found") }
|
|
866
|
+
];
|
|
867
|
+
}
|
|
868
|
+
const done = Object.hasOwn(msg, "result") || Object.hasOwn(msg, "error");
|
|
869
|
+
return typeof id === "number" && done ? response(id, msg) : [];
|
|
870
|
+
};
|
|
871
|
+
return {
|
|
872
|
+
attach: (link) => {
|
|
873
|
+
if (!dead && !links.has(link)) links.set(link, { numbers: /* @__PURE__ */ new Map(), strings: /* @__PURE__ */ new Map() });
|
|
874
|
+
return [];
|
|
875
|
+
},
|
|
876
|
+
detach: (link) => {
|
|
877
|
+
const held = links.get(link);
|
|
878
|
+
if (dead || held === void 0) return [];
|
|
879
|
+
const mine = [...open.entries()].flatMap(
|
|
880
|
+
([rid, entry]) => entry.kind === "call" ? entry.link === link ? [[rid, entry.id]] : [] : entry.waiters.filter((w) => w.link === link).map((w) => [rid, w.id])
|
|
881
|
+
).sort((a, b) => a[0] - b[0]);
|
|
882
|
+
const effects = mine.flatMap(([, id]) => cancel(link, id, void 0));
|
|
883
|
+
links.delete(link);
|
|
884
|
+
return effects;
|
|
885
|
+
},
|
|
886
|
+
fromLink,
|
|
887
|
+
fromChild,
|
|
888
|
+
died: () => {
|
|
889
|
+
if (dead) return [];
|
|
890
|
+
dead = true;
|
|
891
|
+
const effects = [...open.entries()].sort((a, b) => a[0] - b[0]).flatMap(
|
|
892
|
+
([, entry]) => (entry.kind === "call" ? [entry] : entry.waiters).map((w) => ({
|
|
893
|
+
to: "link",
|
|
894
|
+
link: w.link,
|
|
895
|
+
msg: failure(w.id, DIED_CODE, "the server process ended")
|
|
896
|
+
}))
|
|
897
|
+
);
|
|
898
|
+
open.clear();
|
|
899
|
+
links.clear();
|
|
900
|
+
return effects;
|
|
901
|
+
},
|
|
902
|
+
open: () => [...open.values()].reduce((n, entry) => n + (entry.kind === "call" ? 1 : entry.waiters.length), 0)
|
|
903
|
+
};
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
// src/host/brokerwire.ts
|
|
907
|
+
import crypto from "node:crypto";
|
|
908
|
+
import fs from "node:fs";
|
|
909
|
+
var KEY_BYTES = 32;
|
|
910
|
+
var BAD_KEY = "EBADKEY";
|
|
911
|
+
var makeCrypto = (key) => ({
|
|
912
|
+
mac: (text) => crypto.createHmac("sha256", key).update(text).digest("hex"),
|
|
913
|
+
nonce: () => crypto.randomBytes(16).toString("hex"),
|
|
914
|
+
same: (a, b) => {
|
|
915
|
+
const x = Buffer.from(a);
|
|
916
|
+
const y = Buffer.from(b);
|
|
917
|
+
return x.length === y.length && crypto.timingSafeEqual(x, y);
|
|
918
|
+
}
|
|
919
|
+
});
|
|
920
|
+
var stderrFrames = (data) => {
|
|
921
|
+
const out = [];
|
|
922
|
+
for (let at = 0; at < data.length; at += STDERR_CHUNK)
|
|
923
|
+
out.push(stderrFrame(data.subarray(at, at + STDERR_CHUNK).toString("base64")));
|
|
924
|
+
return out;
|
|
925
|
+
};
|
|
926
|
+
var buildId = (file2) => crypto.createHash("sha256").update(fs.readFileSync(file2)).digest("hex");
|
|
927
|
+
var loadKey = (home) => {
|
|
928
|
+
const dir = brokerFolder(home);
|
|
929
|
+
const file2 = `${dir}/key`;
|
|
930
|
+
const read = () => {
|
|
931
|
+
try {
|
|
932
|
+
const key2 = fs.readFileSync(file2);
|
|
933
|
+
return key2.length === KEY_BYTES ? key2 : void 0;
|
|
934
|
+
} catch (err) {
|
|
935
|
+
if (err.code === "ENOENT") return void 0;
|
|
936
|
+
throw err;
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
const have = read();
|
|
940
|
+
if (have !== void 0) return have;
|
|
941
|
+
privateFolder(dir);
|
|
942
|
+
const temp = `${dir}/key.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
943
|
+
try {
|
|
944
|
+
fs.writeFileSync(temp, crypto.randomBytes(KEY_BYTES), { flag: "wx", mode: 384 });
|
|
945
|
+
try {
|
|
946
|
+
fs.linkSync(temp, file2);
|
|
947
|
+
} catch (err) {
|
|
948
|
+
if (err.code !== "EEXIST") throw err;
|
|
949
|
+
}
|
|
950
|
+
} finally {
|
|
951
|
+
fs.rmSync(temp, { force: true });
|
|
952
|
+
}
|
|
953
|
+
const key = read();
|
|
954
|
+
if (key === void 0) throw Object.assign(new Error("the broker key file is not 32 bytes long"), { code: BAD_KEY });
|
|
955
|
+
return key;
|
|
956
|
+
};
|
|
957
|
+
var endpointFor = (home, key, id, platform = process.platform) => endpointOf(platform, home, makeCrypto(key).mac(`toolscript-mcp build ${id}`), process.getuid?.() ?? 0);
|
|
958
|
+
var privateFolder = (dir) => {
|
|
959
|
+
fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
960
|
+
if (process.platform === "win32") return;
|
|
961
|
+
const problem = folderProblem(dir);
|
|
962
|
+
if (problem !== void 0) throw new Error(`the folder ${problem}`);
|
|
963
|
+
if ((fs.lstatSync(dir).mode & 63) !== 0) fs.chmodSync(dir, 448);
|
|
964
|
+
};
|
|
965
|
+
var folderProblem = (dir) => {
|
|
966
|
+
if (process.platform === "win32") return void 0;
|
|
967
|
+
let info;
|
|
968
|
+
try {
|
|
969
|
+
info = fs.lstatSync(dir);
|
|
970
|
+
} catch (err) {
|
|
971
|
+
const code = err.code;
|
|
972
|
+
return code === "ENOENT" ? void 0 : `cannot be read (${code ?? "error"})`;
|
|
973
|
+
}
|
|
974
|
+
if (!info.isDirectory()) return "is a link or a file, not a folder";
|
|
975
|
+
if (info.uid !== process.getuid?.()) return "belongs to another user";
|
|
976
|
+
return void 0;
|
|
977
|
+
};
|
|
978
|
+
|
|
979
|
+
// src/host/broker.ts
|
|
980
|
+
var LOG_MAX = 1 << 20;
|
|
981
|
+
var ENTRY_BYTES = 1 << 20;
|
|
982
|
+
var QUEUE_MAX = 4 * LINE_MAX;
|
|
983
|
+
var tag = (id) => id.slice(0, 8);
|
|
984
|
+
var PROBE = "probe";
|
|
985
|
+
var PROBE_VERSION = "2025-11-25";
|
|
986
|
+
var makeLog = (file2) => {
|
|
987
|
+
let size = 0;
|
|
988
|
+
try {
|
|
989
|
+
size = fs2.statSync(file2).size;
|
|
990
|
+
if (size > LOG_MAX) fs2.writeFileSync(file2, "");
|
|
991
|
+
if (size > LOG_MAX) size = 0;
|
|
992
|
+
} catch {
|
|
993
|
+
}
|
|
994
|
+
return (line) => {
|
|
995
|
+
const text = `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
996
|
+
`;
|
|
997
|
+
try {
|
|
998
|
+
if (size + text.length > LOG_MAX) {
|
|
999
|
+
fs2.writeFileSync(file2, "");
|
|
1000
|
+
size = 0;
|
|
1001
|
+
}
|
|
1002
|
+
fs2.appendFileSync(file2, text);
|
|
1003
|
+
size += text.length;
|
|
1004
|
+
} catch {
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
};
|
|
1008
|
+
var endTree = (proc) => {
|
|
1009
|
+
if (proc.pid === void 0) return;
|
|
1010
|
+
if (process.platform === "win32") {
|
|
1011
|
+
if (proc.exitCode !== null || proc.signalCode !== null) return;
|
|
1012
|
+
nodeSpawn("taskkill", ["/pid", String(proc.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }).on(
|
|
1013
|
+
"error",
|
|
1014
|
+
() => {
|
|
1015
|
+
}
|
|
1016
|
+
);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
try {
|
|
1020
|
+
process.kill(-proc.pid, "SIGKILL");
|
|
1021
|
+
} catch {
|
|
1022
|
+
proc.kill("SIGKILL");
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
var RECOVER_MS = 8e3;
|
|
1026
|
+
var LOCK_STALE_MS = 5e3;
|
|
1027
|
+
var fileId = (file2) => {
|
|
1028
|
+
try {
|
|
1029
|
+
const info = fs2.statSync(file2, { bigint: true });
|
|
1030
|
+
return `${info.dev}:${info.ino}`;
|
|
1031
|
+
} catch {
|
|
1032
|
+
return void 0;
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
var pidAlive = (pid) => {
|
|
1036
|
+
try {
|
|
1037
|
+
process.kill(pid, 0);
|
|
1038
|
+
return true;
|
|
1039
|
+
} catch (err) {
|
|
1040
|
+
return err.code === "EPERM";
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
var takeLock = (file2, afterRead = () => {
|
|
1044
|
+
}) => {
|
|
1045
|
+
const id = crypto2.randomBytes(8).toString("hex");
|
|
1046
|
+
try {
|
|
1047
|
+
fs2.writeFileSync(file2, JSON.stringify({ pid: process.pid, id, at: Date.now() }), { flag: "wx", mode: 384 });
|
|
1048
|
+
return id;
|
|
1049
|
+
} catch (err) {
|
|
1050
|
+
if (err.code !== "EEXIST") throw err;
|
|
1051
|
+
}
|
|
1052
|
+
let seen;
|
|
1053
|
+
let stale;
|
|
1054
|
+
try {
|
|
1055
|
+
seen = fs2.readFileSync(file2, "utf8");
|
|
1056
|
+
try {
|
|
1057
|
+
const held = JSON.parse(seen);
|
|
1058
|
+
const dead = typeof held.pid !== "number" || !pidAlive(held.pid);
|
|
1059
|
+
const old = typeof held.at !== "number" || Math.abs(Date.now() - held.at) > LOCK_STALE_MS;
|
|
1060
|
+
stale = dead || old;
|
|
1061
|
+
} catch {
|
|
1062
|
+
stale = Math.abs(Date.now() - fs2.statSync(file2).mtimeMs) > LOCK_STALE_MS;
|
|
1063
|
+
}
|
|
1064
|
+
} catch {
|
|
1065
|
+
return void 0;
|
|
1066
|
+
}
|
|
1067
|
+
if (!stale) return void 0;
|
|
1068
|
+
afterRead();
|
|
1069
|
+
const aside = `${file2}.break.${process.pid}.${id}`;
|
|
1070
|
+
try {
|
|
1071
|
+
fs2.renameSync(file2, aside);
|
|
1072
|
+
} catch {
|
|
1073
|
+
return void 0;
|
|
1074
|
+
}
|
|
1075
|
+
try {
|
|
1076
|
+
if (fs2.readFileSync(aside, "utf8") !== seen) fs2.linkSync(aside, file2);
|
|
1077
|
+
} catch {
|
|
1078
|
+
}
|
|
1079
|
+
fs2.rmSync(aside, { force: true });
|
|
1080
|
+
return void 0;
|
|
1081
|
+
};
|
|
1082
|
+
var dropLock = (file2, id) => {
|
|
1083
|
+
try {
|
|
1084
|
+
if (JSON.parse(fs2.readFileSync(file2, "utf8")).id === id) fs2.rmSync(file2, { force: true });
|
|
1085
|
+
} catch {
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
var dial = (endpoint) => new Promise((resolve) => {
|
|
1089
|
+
const probe = net.connect(endpoint);
|
|
1090
|
+
probe.once("connect", () => (probe.destroy(), resolve("alive")));
|
|
1091
|
+
probe.once("error", (e) => {
|
|
1092
|
+
const code = e.code;
|
|
1093
|
+
resolve(code === "ECONNREFUSED" ? "stale" : code === "ENOENT" ? "gone" : "alive");
|
|
1094
|
+
});
|
|
1095
|
+
});
|
|
1096
|
+
var recoverSocket = async (endpoint, listen) => {
|
|
1097
|
+
const lockFile = `${endpoint}.lock`;
|
|
1098
|
+
const end = Date.now() + RECOVER_MS;
|
|
1099
|
+
while (Date.now() < end) {
|
|
1100
|
+
const lock = takeLock(lockFile);
|
|
1101
|
+
if (lock === void 0) {
|
|
1102
|
+
await new Promise((resolve) => setTimeout(resolve, 20 + Math.random() * 30));
|
|
1103
|
+
if (await dial(endpoint) === "alive") return false;
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
try {
|
|
1107
|
+
const state = await dial(endpoint);
|
|
1108
|
+
if (state === "alive") return false;
|
|
1109
|
+
if (state === "stale") fs2.rmSync(endpoint, { force: true });
|
|
1110
|
+
try {
|
|
1111
|
+
await listen();
|
|
1112
|
+
return true;
|
|
1113
|
+
} catch {
|
|
1114
|
+
return false;
|
|
1115
|
+
}
|
|
1116
|
+
} finally {
|
|
1117
|
+
dropLock(lockFile, lock);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
return false;
|
|
1121
|
+
};
|
|
1122
|
+
var adoptKept = async (endpoint) => {
|
|
1123
|
+
const dir = path.dirname(endpoint);
|
|
1124
|
+
const prefix = `${path.basename(endpoint)}.keep.`;
|
|
1125
|
+
let names;
|
|
1126
|
+
try {
|
|
1127
|
+
names = fs2.readdirSync(dir).filter((name) => name.startsWith(prefix));
|
|
1128
|
+
} catch {
|
|
1129
|
+
return false;
|
|
1130
|
+
}
|
|
1131
|
+
let adopted = false;
|
|
1132
|
+
for (const name of names) {
|
|
1133
|
+
const pid = Number(name.slice(prefix.length));
|
|
1134
|
+
if (Number.isInteger(pid) && pidAlive(pid)) continue;
|
|
1135
|
+
const keep = `${dir}/${name}`;
|
|
1136
|
+
if (!adopted && !fs2.existsSync(endpoint) && await dial(keep) === "alive") {
|
|
1137
|
+
try {
|
|
1138
|
+
fs2.linkSync(keep, endpoint);
|
|
1139
|
+
adopted = true;
|
|
1140
|
+
} catch {
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
fs2.rmSync(keep, { force: true });
|
|
1144
|
+
}
|
|
1145
|
+
return adopted;
|
|
1146
|
+
};
|
|
1147
|
+
var SWEEP_MIN_AGE_MS = 5e3;
|
|
1148
|
+
var sweepSockets = async (endpoint) => {
|
|
1149
|
+
const dir = path.dirname(endpoint);
|
|
1150
|
+
let names;
|
|
1151
|
+
try {
|
|
1152
|
+
names = fs2.readdirSync(dir).filter((name) => /^tsm-[0-9a-f]+\.sock$/.test(name));
|
|
1153
|
+
} catch {
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
for (const name of names) {
|
|
1157
|
+
const file2 = `${dir}/${name}`;
|
|
1158
|
+
if (file2 === endpoint) continue;
|
|
1159
|
+
try {
|
|
1160
|
+
if (Date.now() - fs2.lstatSync(file2).mtimeMs < SWEEP_MIN_AGE_MS) continue;
|
|
1161
|
+
} catch {
|
|
1162
|
+
continue;
|
|
1163
|
+
}
|
|
1164
|
+
if (await dial(file2) === "stale") fs2.rmSync(file2, { force: true });
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
var startBroker = async ({
|
|
1168
|
+
home,
|
|
1169
|
+
idleMs: idleMs2,
|
|
1170
|
+
file: file2,
|
|
1171
|
+
initMs = CHILD_INIT_MS,
|
|
1172
|
+
maxLinks = LINKS_MAX,
|
|
1173
|
+
maxChildren = CHILDREN_MAX,
|
|
1174
|
+
maxUnsent = UNSENT_MAX
|
|
1175
|
+
}) => {
|
|
1176
|
+
const dir = brokerFolder(home);
|
|
1177
|
+
privateFolder(dir);
|
|
1178
|
+
const log = makeLog(`${dir}/broker.log`);
|
|
1179
|
+
const key = loadKey(home);
|
|
1180
|
+
const wire = makeCrypto(key);
|
|
1181
|
+
const endpoint = endpointFor(home, key, buildId(file2));
|
|
1182
|
+
if (process.platform !== "win32") privateFolder(path.dirname(endpoint));
|
|
1183
|
+
const children = /* @__PURE__ */ new Map();
|
|
1184
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
1185
|
+
let seq = 0;
|
|
1186
|
+
let pending = 0;
|
|
1187
|
+
let attached = 0;
|
|
1188
|
+
let exiting;
|
|
1189
|
+
let emptyTimer;
|
|
1190
|
+
let finish = () => {
|
|
1191
|
+
};
|
|
1192
|
+
const done = new Promise((resolve) => finish = resolve);
|
|
1193
|
+
const write = (stream, msg) => {
|
|
1194
|
+
try {
|
|
1195
|
+
if (stream !== null && stream.destroyed !== true) stream.write(`${JSON.stringify(msg)}
|
|
1196
|
+
`);
|
|
1197
|
+
} catch {
|
|
1198
|
+
}
|
|
1199
|
+
};
|
|
1200
|
+
const apply = (child, effects) => {
|
|
1201
|
+
for (const effect of effects) {
|
|
1202
|
+
if (effect.to === "child") {
|
|
1203
|
+
write(child.proc.stdin, effect.msg);
|
|
1204
|
+
if ((child.proc.stdin?.writableLength ?? 0) > maxUnsent)
|
|
1205
|
+
child.abort("the server did not read its input", "input over the cap");
|
|
1206
|
+
} else child.conns.get(effect.link)?.send(effect.msg);
|
|
1207
|
+
}
|
|
1208
|
+
};
|
|
1209
|
+
const stopChild = (child) => {
|
|
1210
|
+
if (child.stopping !== void 0) return child.stopping;
|
|
1211
|
+
log(`child ${tag(child.id)} stop`);
|
|
1212
|
+
children.delete(child.id);
|
|
1213
|
+
clearTimeout(child.idle);
|
|
1214
|
+
child.stopping = new Promise((resolve) => {
|
|
1215
|
+
if (child.dead) return resolve();
|
|
1216
|
+
child.proc.once("exit", () => resolve());
|
|
1217
|
+
const timer = setTimeout(() => {
|
|
1218
|
+
endTree(child.proc);
|
|
1219
|
+
setTimeout(resolve, 1e3);
|
|
1220
|
+
}, STOP_WAIT_MS);
|
|
1221
|
+
child.proc.once("exit", () => clearTimeout(timer));
|
|
1222
|
+
try {
|
|
1223
|
+
child.proc.stdin?.end();
|
|
1224
|
+
} catch {
|
|
1225
|
+
}
|
|
1226
|
+
});
|
|
1227
|
+
return child.stopping;
|
|
1228
|
+
};
|
|
1229
|
+
const checkEmpty = () => {
|
|
1230
|
+
clearTimeout(emptyTimer);
|
|
1231
|
+
if (sockets.size > 0 || children.size > 0 || exiting !== void 0) return;
|
|
1232
|
+
emptyTimer = setTimeout(() => void stop(), Math.min(idleMs2, 2e3));
|
|
1233
|
+
};
|
|
1234
|
+
const startChild = (entry, id) => {
|
|
1235
|
+
const router = createRouter();
|
|
1236
|
+
let settle = (_reason) => {
|
|
1237
|
+
};
|
|
1238
|
+
const ready = new Promise((resolve) => settle = resolve);
|
|
1239
|
+
const proc = (0, import_cross_spawn.default)(entry.command, [...entry.args], {
|
|
1240
|
+
cwd: entry.folder,
|
|
1241
|
+
env: { ...entry.env },
|
|
1242
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1243
|
+
shell: false,
|
|
1244
|
+
windowsHide: true,
|
|
1245
|
+
// The process group is how the tree of a child ends outside Windows. Windows ends it with taskkill.
|
|
1246
|
+
detached: process.platform !== "win32"
|
|
1247
|
+
});
|
|
1248
|
+
const child = {
|
|
1249
|
+
id,
|
|
1250
|
+
proc,
|
|
1251
|
+
router,
|
|
1252
|
+
conns: /* @__PURE__ */ new Map(),
|
|
1253
|
+
waiters: /* @__PURE__ */ new Set(),
|
|
1254
|
+
ready,
|
|
1255
|
+
settle,
|
|
1256
|
+
idle: void 0,
|
|
1257
|
+
dead: false,
|
|
1258
|
+
up: false,
|
|
1259
|
+
tail: Buffer.alloc(0),
|
|
1260
|
+
stopping: void 0,
|
|
1261
|
+
abort: (why, code) => {
|
|
1262
|
+
endTree(proc);
|
|
1263
|
+
gone(why, code);
|
|
1264
|
+
}
|
|
1265
|
+
};
|
|
1266
|
+
children.set(id, child);
|
|
1267
|
+
log(`child ${tag(id)} start`);
|
|
1268
|
+
for (const stream of [proc.stdin, proc.stdout, proc.stderr]) stream?.on("error", () => {
|
|
1269
|
+
});
|
|
1270
|
+
let windowStart = Date.now();
|
|
1271
|
+
let windowBytes = 0;
|
|
1272
|
+
let missed = 0;
|
|
1273
|
+
let flush;
|
|
1274
|
+
const fanOut = (data) => {
|
|
1275
|
+
for (const conn of child.conns.values()) conn.stderr?.(data);
|
|
1276
|
+
for (const conn of child.waiters) conn.stderr?.(data);
|
|
1277
|
+
};
|
|
1278
|
+
proc.stderr?.on("data", (data) => {
|
|
1279
|
+
if (Date.now() - windowStart >= STDERR_WINDOW_MS) {
|
|
1280
|
+
windowStart = Date.now();
|
|
1281
|
+
windowBytes = 0;
|
|
1282
|
+
}
|
|
1283
|
+
const kept = data.subarray(0, Math.max(0, STDERR_RATE - windowBytes));
|
|
1284
|
+
windowBytes += kept.length;
|
|
1285
|
+
if (kept.length > 0) {
|
|
1286
|
+
if (!child.up) child.tail = Buffer.concat([child.tail, kept]).subarray(-STDERR_TAIL);
|
|
1287
|
+
fanOut(kept);
|
|
1288
|
+
}
|
|
1289
|
+
if (kept.length < data.length) {
|
|
1290
|
+
missed += data.length - kept.length;
|
|
1291
|
+
flush ??= setTimeout(
|
|
1292
|
+
() => {
|
|
1293
|
+
flush = void 0;
|
|
1294
|
+
fanOut(missed);
|
|
1295
|
+
missed = 0;
|
|
1296
|
+
},
|
|
1297
|
+
Math.max(0, windowStart + STDERR_WINDOW_MS - Date.now())
|
|
1298
|
+
);
|
|
1299
|
+
flush.unref();
|
|
1300
|
+
}
|
|
1301
|
+
});
|
|
1302
|
+
proc.stdout?.setEncoding("utf8");
|
|
1303
|
+
proc.stdout?.on(
|
|
1304
|
+
"data",
|
|
1305
|
+
lineSplitter(
|
|
1306
|
+
(line) => {
|
|
1307
|
+
const msg = parseFrame(line);
|
|
1308
|
+
if (msg !== void 0) apply(child, router.fromChild(msg));
|
|
1309
|
+
},
|
|
1310
|
+
() => LINE_MAX,
|
|
1311
|
+
// A line over the cap that the SDK reader would refuse: the child is dead, and its links get the reason.
|
|
1312
|
+
() => {
|
|
1313
|
+
endTree(proc);
|
|
1314
|
+
gone("the server wrote a line longer than 10 MB", "line over the cap");
|
|
1315
|
+
}
|
|
1316
|
+
)
|
|
1317
|
+
);
|
|
1318
|
+
const gone = (why, code) => {
|
|
1319
|
+
if (child.dead) return;
|
|
1320
|
+
child.dead = true;
|
|
1321
|
+
clearTimeout(timer);
|
|
1322
|
+
clearTimeout(flush);
|
|
1323
|
+
if (children.get(id) === child) children.delete(id);
|
|
1324
|
+
log(`child ${tag(id)} exit ${String(code)}`);
|
|
1325
|
+
const reason = `${why}. Run the command of the server by hand in a terminal to see why`;
|
|
1326
|
+
settle(reason);
|
|
1327
|
+
apply(child, router.died());
|
|
1328
|
+
for (const conn of child.conns.values()) conn.close(reason);
|
|
1329
|
+
child.conns.clear();
|
|
1330
|
+
endTree(proc);
|
|
1331
|
+
checkEmpty();
|
|
1332
|
+
};
|
|
1333
|
+
proc.on("error", (err) => gone("the server process could not start", err.code));
|
|
1334
|
+
proc.on("exit", (code) => {
|
|
1335
|
+
const end = () => gone(`the server process ended with exit code ${String(code)}`, code);
|
|
1336
|
+
if (child.up || proc.stderr === null || proc.stderr.destroyed) return end();
|
|
1337
|
+
const timer2 = setTimeout(end, 200);
|
|
1338
|
+
proc.stderr.once("close", () => {
|
|
1339
|
+
clearTimeout(timer2);
|
|
1340
|
+
end();
|
|
1341
|
+
});
|
|
1342
|
+
});
|
|
1343
|
+
const timer = setTimeout(() => {
|
|
1344
|
+
settle(`the server gave no initialize answer in ${Math.round(initMs / 1e3)} s. Run its command by hand`);
|
|
1345
|
+
void stopChild(child);
|
|
1346
|
+
}, initMs);
|
|
1347
|
+
child.conns.set(PROBE, {
|
|
1348
|
+
close: () => {
|
|
1349
|
+
},
|
|
1350
|
+
send: (msg) => {
|
|
1351
|
+
if (typeof msg !== "object" || msg === null || msg.id !== 0) return;
|
|
1352
|
+
if (!("result" in msg) && !("error" in msg)) return;
|
|
1353
|
+
const failed = "error" in msg;
|
|
1354
|
+
child.conns.delete(PROBE);
|
|
1355
|
+
clearTimeout(timer);
|
|
1356
|
+
if (failed) {
|
|
1357
|
+
settle("the server answered the initialize with an error. Run its command by hand");
|
|
1358
|
+
void stopChild(child);
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1361
|
+
apply(child, router.fromLink(PROBE, { jsonrpc: "2.0", method: "notifications/initialized" }));
|
|
1362
|
+
apply(child, router.detach(PROBE));
|
|
1363
|
+
child.up = true;
|
|
1364
|
+
child.tail = Buffer.alloc(0);
|
|
1365
|
+
settle(void 0);
|
|
1366
|
+
}
|
|
1367
|
+
});
|
|
1368
|
+
router.attach(PROBE);
|
|
1369
|
+
apply(
|
|
1370
|
+
child,
|
|
1371
|
+
router.fromLink(PROBE, {
|
|
1372
|
+
jsonrpc: "2.0",
|
|
1373
|
+
id: 0,
|
|
1374
|
+
method: "initialize",
|
|
1375
|
+
params: {
|
|
1376
|
+
protocolVersion: PROBE_VERSION,
|
|
1377
|
+
capabilities: {},
|
|
1378
|
+
clientInfo: { name: "toolscript-mcp-broker", version: "1" }
|
|
1379
|
+
}
|
|
1380
|
+
})
|
|
1381
|
+
);
|
|
1382
|
+
return child;
|
|
1383
|
+
};
|
|
1384
|
+
const onConnection = (socket) => {
|
|
1385
|
+
if (pending >= PROOF_CONNECTIONS) return void socket.destroy();
|
|
1386
|
+
sockets.add(socket);
|
|
1387
|
+
clearTimeout(emptyTimer);
|
|
1388
|
+
socket.setEncoding("utf8");
|
|
1389
|
+
pending++;
|
|
1390
|
+
let proven = false;
|
|
1391
|
+
let link;
|
|
1392
|
+
let child;
|
|
1393
|
+
const side = brokerSide(wire);
|
|
1394
|
+
const queue = [];
|
|
1395
|
+
let stage = "proof";
|
|
1396
|
+
let queued = 0;
|
|
1397
|
+
let counted = false;
|
|
1398
|
+
const leave2 = () => {
|
|
1399
|
+
if (!proven) pending--;
|
|
1400
|
+
proven = true;
|
|
1401
|
+
};
|
|
1402
|
+
const timer = setTimeout(() => socket.destroy(), PROOF_MS);
|
|
1403
|
+
const close = (reason) => void (reason === void 0 ? socket.end() : socket.end(refusedFrame(reason)));
|
|
1404
|
+
let skipped = 0;
|
|
1405
|
+
const stderr = (data) => {
|
|
1406
|
+
if (socket.destroyed) return;
|
|
1407
|
+
if (typeof data === "number") skipped += data;
|
|
1408
|
+
else if (socket.writableLength > STDERR_BACKLOG) return void (skipped += data.length);
|
|
1409
|
+
if (socket.writableLength > STDERR_BACKLOG) return;
|
|
1410
|
+
if (skipped > 0) {
|
|
1411
|
+
socket.write(droppedFrame(skipped));
|
|
1412
|
+
skipped = 0;
|
|
1413
|
+
}
|
|
1414
|
+
if (typeof data !== "number") for (const frame2 of stderrFrames(data)) socket.write(frame2);
|
|
1415
|
+
};
|
|
1416
|
+
const attach = async (entry) => {
|
|
1417
|
+
const id = crypto2.createHash("sha256").update(entryText(entry)).digest("hex");
|
|
1418
|
+
try {
|
|
1419
|
+
const known = children.get(id);
|
|
1420
|
+
if (known === void 0 && children.size >= maxChildren)
|
|
1421
|
+
return void socket.end(
|
|
1422
|
+
refusedFrame(
|
|
1423
|
+
`this broker already holds ${maxChildren} shared servers. Set "share": false on this server, or end sessions that use others`
|
|
1424
|
+
)
|
|
1425
|
+
);
|
|
1426
|
+
child = known ?? startChild(entry, id);
|
|
1427
|
+
} catch (err) {
|
|
1428
|
+
const code = err.code;
|
|
1429
|
+
const shown = typeof code === "string" && /^\w{1,40}$/.test(code) ? code : "error";
|
|
1430
|
+
log(`child ${tag(id)} exit ${shown}`);
|
|
1431
|
+
socket.end(refusedFrame(`the server process could not start (${shown}). Run its command by hand in a terminal`));
|
|
1432
|
+
return;
|
|
1433
|
+
}
|
|
1434
|
+
const mine2 = child;
|
|
1435
|
+
clearTimeout(mine2.idle);
|
|
1436
|
+
const waiting = !mine2.up && !mine2.dead;
|
|
1437
|
+
const waiter = { send: () => {
|
|
1438
|
+
}, close: () => {
|
|
1439
|
+
}, stderr };
|
|
1440
|
+
if (waiting) {
|
|
1441
|
+
mine2.waiters.add(waiter);
|
|
1442
|
+
if (mine2.tail.length > 0) stderr(mine2.tail);
|
|
1443
|
+
}
|
|
1444
|
+
const reason = await mine2.ready;
|
|
1445
|
+
mine2.waiters.delete(waiter);
|
|
1446
|
+
if (socket.destroyed) return void (mine2.conns.size === 0 && idleStart(mine2));
|
|
1447
|
+
if (reason !== void 0 || mine2.dead) {
|
|
1448
|
+
if (!waiting && mine2.tail.length > 0) stderr(mine2.tail);
|
|
1449
|
+
socket.end(refusedFrame(reason ?? "the server process ended"));
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
const name = `l${++seq}`;
|
|
1453
|
+
link = name;
|
|
1454
|
+
mine2.conns.set(name, {
|
|
1455
|
+
// The host reads at most LINE_MAX in a line. A child line under that cap can come out longer once written again
|
|
1456
|
+
// (1e9 becomes 1000000000), and then the link ends with the reason instead of a line the host cuts off.
|
|
1457
|
+
send: (msg) => {
|
|
1458
|
+
const line = JSON.stringify(msg);
|
|
1459
|
+
if (line.length > LINE_MAX) close("the server sent a message longer than 10 MB");
|
|
1460
|
+
else if (socket.destroyed) return;
|
|
1461
|
+
else if (socket.writableLength > maxUnsent) socket.destroy();
|
|
1462
|
+
else socket.write(`${line}
|
|
1463
|
+
`);
|
|
1464
|
+
},
|
|
1465
|
+
close,
|
|
1466
|
+
stderr
|
|
1467
|
+
});
|
|
1468
|
+
mine2.router.attach(name);
|
|
1469
|
+
log(`attach ${tag(id)} links=${mine2.conns.size}`);
|
|
1470
|
+
socket.write(attachedFrame);
|
|
1471
|
+
stage = "linked";
|
|
1472
|
+
for (const line of queue.splice(0)) fromHost(mine2, name, line);
|
|
1473
|
+
};
|
|
1474
|
+
const fromHost = (target, name, line) => {
|
|
1475
|
+
const msg = parseFrame(line);
|
|
1476
|
+
if (msg !== void 0) apply(target, target.router.fromLink(name, msg));
|
|
1477
|
+
};
|
|
1478
|
+
const lines = lineSplitter(
|
|
1479
|
+
(line) => {
|
|
1480
|
+
if (stage === "proof") {
|
|
1481
|
+
const step = side.step(line);
|
|
1482
|
+
if (step.fail !== void 0) return void socket.destroy();
|
|
1483
|
+
if (step.send !== void 0) socket.write(step.send);
|
|
1484
|
+
if (step.done) {
|
|
1485
|
+
leave2();
|
|
1486
|
+
stage = "entry";
|
|
1487
|
+
}
|
|
1488
|
+
} else if (stage === "entry") {
|
|
1489
|
+
const entry = parseEntry(parseFrame(line));
|
|
1490
|
+
clearTimeout(timer);
|
|
1491
|
+
if (typeof entry === "string") return void socket.end(refusedFrame(entry));
|
|
1492
|
+
if (attached >= maxLinks)
|
|
1493
|
+
return void socket.end(
|
|
1494
|
+
refusedFrame(
|
|
1495
|
+
`this broker already holds ${maxLinks} shared links. Set "share": false on this server, or end other sessions`
|
|
1496
|
+
)
|
|
1497
|
+
);
|
|
1498
|
+
attached++;
|
|
1499
|
+
counted = true;
|
|
1500
|
+
stage = "attaching";
|
|
1501
|
+
attach(entry).catch(() => socket.destroy());
|
|
1502
|
+
} else if (stage === "attaching") {
|
|
1503
|
+
queued += line.length;
|
|
1504
|
+
if (queued > QUEUE_MAX) return void socket.destroy();
|
|
1505
|
+
queue.push(line);
|
|
1506
|
+
} else if (child !== void 0 && link !== void 0) fromHost(child, link, line);
|
|
1507
|
+
},
|
|
1508
|
+
() => stage === "proof" ? PROOF_BYTES : stage === "entry" ? ENTRY_BYTES : LINE_MAX,
|
|
1509
|
+
() => socket.destroy()
|
|
1510
|
+
);
|
|
1511
|
+
socket.on("data", lines);
|
|
1512
|
+
socket.on("error", () => socket.destroy());
|
|
1513
|
+
socket.on("close", () => {
|
|
1514
|
+
clearTimeout(timer);
|
|
1515
|
+
leave2();
|
|
1516
|
+
if (counted) attached--;
|
|
1517
|
+
sockets.delete(socket);
|
|
1518
|
+
if (child !== void 0 && link !== void 0) {
|
|
1519
|
+
apply(child, child.router.detach(link));
|
|
1520
|
+
child.conns.delete(link);
|
|
1521
|
+
log(`detach ${tag(child.id)} links=${child.conns.size}`);
|
|
1522
|
+
if (child.conns.size === 0) idleStart(child);
|
|
1523
|
+
}
|
|
1524
|
+
checkEmpty();
|
|
1525
|
+
});
|
|
1526
|
+
};
|
|
1527
|
+
const idleStart = (child) => {
|
|
1528
|
+
clearTimeout(child.idle);
|
|
1529
|
+
if (child.dead || child.stopping !== void 0) return;
|
|
1530
|
+
child.idle = setTimeout(() => void stopChild(child).then(checkEmpty), idleMs2);
|
|
1531
|
+
};
|
|
1532
|
+
const server = net.createServer(onConnection);
|
|
1533
|
+
const listen = () => new Promise((resolve, reject) => {
|
|
1534
|
+
server.once("error", reject);
|
|
1535
|
+
server.listen(endpoint, () => {
|
|
1536
|
+
server.off("error", reject);
|
|
1537
|
+
resolve();
|
|
1538
|
+
});
|
|
1539
|
+
});
|
|
1540
|
+
try {
|
|
1541
|
+
if (process.platform !== "win32" && await adoptKept(endpoint)) return void 0;
|
|
1542
|
+
await listen();
|
|
1543
|
+
} catch (err) {
|
|
1544
|
+
if (err.code !== "EADDRINUSE") throw err;
|
|
1545
|
+
if (process.platform === "win32" || !await recoverSocket(endpoint, listen)) return void 0;
|
|
1546
|
+
}
|
|
1547
|
+
const mine = process.platform === "win32" ? void 0 : fileId(endpoint);
|
|
1548
|
+
const closeServer = () => {
|
|
1549
|
+
const now = mine === void 0 ? void 0 : fileId(endpoint);
|
|
1550
|
+
if (now === void 0 || now === mine) return void server.close();
|
|
1551
|
+
const aside = `${endpoint}.keep.${process.pid}`;
|
|
1552
|
+
let kept = false;
|
|
1553
|
+
try {
|
|
1554
|
+
fs2.linkSync(endpoint, aside);
|
|
1555
|
+
kept = true;
|
|
1556
|
+
} catch {
|
|
1557
|
+
}
|
|
1558
|
+
server.close();
|
|
1559
|
+
if (!kept) return;
|
|
1560
|
+
try {
|
|
1561
|
+
fs2.linkSync(aside, endpoint);
|
|
1562
|
+
} catch {
|
|
1563
|
+
}
|
|
1564
|
+
fs2.rmSync(aside, { force: true });
|
|
1565
|
+
};
|
|
1566
|
+
log(`start pid ${process.pid}`);
|
|
1567
|
+
log("listen");
|
|
1568
|
+
if (process.platform !== "win32") void sweepSockets(endpoint);
|
|
1569
|
+
server.on("error", (err) => log(`listen error ${err.code ?? "error"}`));
|
|
1570
|
+
const stop = () => exiting ??= (async () => {
|
|
1571
|
+
clearTimeout(emptyTimer);
|
|
1572
|
+
closeServer();
|
|
1573
|
+
await Promise.all([...children.values()].map(stopChild));
|
|
1574
|
+
for (const socket of sockets) socket.destroy();
|
|
1575
|
+
log("exit");
|
|
1576
|
+
finish();
|
|
1577
|
+
})();
|
|
1578
|
+
checkEmpty();
|
|
1579
|
+
return { endpoint, done, stop, log };
|
|
1580
|
+
};
|
|
1581
|
+
|
|
1582
|
+
// src/host/brokermain.ts
|
|
1583
|
+
var file = process.argv[1];
|
|
1584
|
+
var broker = file === void 0 ? void 0 : await startBroker({
|
|
1585
|
+
home: os.homedir(),
|
|
1586
|
+
idleMs: idleMs(process.env.TOOLSCRIPT_BROKER_IDLE_MS),
|
|
1587
|
+
file
|
|
1588
|
+
}).catch(() => void 0);
|
|
1589
|
+
if (broker === void 0) process.exit(0);
|
|
1590
|
+
var leave = () => void broker.stop();
|
|
1591
|
+
process.on("SIGTERM", leave);
|
|
1592
|
+
process.on("SIGINT", leave);
|
|
1593
|
+
var crash = (err) => {
|
|
1594
|
+
const { name, code } = typeof err === "object" && err !== null ? err : {};
|
|
1595
|
+
const word = (v, fallback) => typeof v === "string" && /^\w{1,40}$/.test(v) ? v : fallback;
|
|
1596
|
+
broker.log(`crash ${word(name, "Error")} ${word(code, "-")}`);
|
|
1597
|
+
process.exit(1);
|
|
1598
|
+
};
|
|
1599
|
+
process.on("uncaughtException", crash);
|
|
1600
|
+
process.on("unhandledRejection", crash);
|
|
1601
|
+
await broker.done;
|
|
1602
|
+
process.exit(0);
|