toolscript-mcp 1.0.4 → 1.0.5

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.
@@ -40,8 +40,8 @@ var require_windows = __commonJS({
40
40
  "node_modules/isexe/windows.js"(exports, module) {
41
41
  module.exports = isexe;
42
42
  isexe.sync = sync;
43
- var fs3 = __require("fs");
44
- function checkPathExt(path2, options) {
43
+ var fs5 = __require("fs");
44
+ function checkPathExt(path4, options) {
45
45
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
46
46
  if (!pathext) {
47
47
  return true;
@@ -52,25 +52,25 @@ var require_windows = __commonJS({
52
52
  }
53
53
  for (var i = 0; i < pathext.length; i++) {
54
54
  var p = pathext[i].toLowerCase();
55
- if (p && path2.substr(-p.length).toLowerCase() === p) {
55
+ if (p && path4.substr(-p.length).toLowerCase() === p) {
56
56
  return true;
57
57
  }
58
58
  }
59
59
  return false;
60
60
  }
61
- function checkStat(stat, path2, options) {
61
+ function checkStat(stat, path4, options) {
62
62
  if (!stat.isSymbolicLink() && !stat.isFile()) {
63
63
  return false;
64
64
  }
65
- return checkPathExt(path2, options);
65
+ return checkPathExt(path4, options);
66
66
  }
67
- function isexe(path2, options, cb) {
68
- fs3.stat(path2, function(er, stat) {
69
- cb(er, er ? false : checkStat(stat, path2, options));
67
+ function isexe(path4, options, cb) {
68
+ fs5.stat(path4, function(er, stat) {
69
+ cb(er, er ? false : checkStat(stat, path4, options));
70
70
  });
71
71
  }
72
- function sync(path2, options) {
73
- return checkStat(fs3.statSync(path2), path2, options);
72
+ function sync(path4, options) {
73
+ return checkStat(fs5.statSync(path4), path4, options);
74
74
  }
75
75
  }
76
76
  });
@@ -80,14 +80,14 @@ var require_mode = __commonJS({
80
80
  "node_modules/isexe/mode.js"(exports, module) {
81
81
  module.exports = isexe;
82
82
  isexe.sync = sync;
83
- var fs3 = __require("fs");
84
- function isexe(path2, options, cb) {
85
- fs3.stat(path2, function(er, stat) {
83
+ var fs5 = __require("fs");
84
+ function isexe(path4, options, cb) {
85
+ fs5.stat(path4, function(er, stat) {
86
86
  cb(er, er ? false : checkStat(stat, options));
87
87
  });
88
88
  }
89
- function sync(path2, options) {
90
- return checkStat(fs3.statSync(path2), options);
89
+ function sync(path4, options) {
90
+ return checkStat(fs5.statSync(path4), options);
91
91
  }
92
92
  function checkStat(stat, options) {
93
93
  return stat.isFile() && checkMode(stat, options);
@@ -111,7 +111,7 @@ var require_mode = __commonJS({
111
111
  // node_modules/isexe/index.js
112
112
  var require_isexe = __commonJS({
113
113
  "node_modules/isexe/index.js"(exports, module) {
114
- var fs3 = __require("fs");
114
+ var fs5 = __require("fs");
115
115
  var core;
116
116
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
117
117
  core = require_windows();
@@ -120,7 +120,7 @@ var require_isexe = __commonJS({
120
120
  }
121
121
  module.exports = isexe;
122
122
  isexe.sync = sync;
123
- function isexe(path2, options, cb) {
123
+ function isexe(path4, options, cb) {
124
124
  if (typeof options === "function") {
125
125
  cb = options;
126
126
  options = {};
@@ -130,7 +130,7 @@ var require_isexe = __commonJS({
130
130
  throw new TypeError("callback not provided");
131
131
  }
132
132
  return new Promise(function(resolve, reject) {
133
- isexe(path2, options || {}, function(er, is) {
133
+ isexe(path4, options || {}, function(er, is) {
134
134
  if (er) {
135
135
  reject(er);
136
136
  } else {
@@ -139,7 +139,7 @@ var require_isexe = __commonJS({
139
139
  });
140
140
  });
141
141
  }
142
- core(path2, options || {}, function(er, is) {
142
+ core(path4, options || {}, function(er, is) {
143
143
  if (er) {
144
144
  if (er.code === "EACCES" || options && options.ignoreErrors) {
145
145
  er = null;
@@ -149,9 +149,9 @@ var require_isexe = __commonJS({
149
149
  cb(er, is);
150
150
  });
151
151
  }
152
- function sync(path2, options) {
152
+ function sync(path4, options) {
153
153
  try {
154
- return core.sync(path2, options || {});
154
+ return core.sync(path4, options || {});
155
155
  } catch (er) {
156
156
  if (options && options.ignoreErrors || er.code === "EACCES") {
157
157
  return false;
@@ -167,7 +167,7 @@ var require_isexe = __commonJS({
167
167
  var require_which = __commonJS({
168
168
  "node_modules/which/which.js"(exports, module) {
169
169
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
170
- var path2 = __require("path");
170
+ var path4 = __require("path");
171
171
  var COLON = isWindows ? ";" : ":";
172
172
  var isexe = require_isexe();
173
173
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -205,7 +205,7 @@ var require_which = __commonJS({
205
205
  return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
206
206
  const ppRaw = pathEnv[i];
207
207
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
208
- const pCmd = path2.join(pathPart, cmd);
208
+ const pCmd = path4.join(pathPart, cmd);
209
209
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
210
210
  resolve(subStep(p, i, 0));
211
211
  });
@@ -232,7 +232,7 @@ var require_which = __commonJS({
232
232
  for (let i = 0; i < pathEnv.length; i++) {
233
233
  const ppRaw = pathEnv[i];
234
234
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
235
- const pCmd = path2.join(pathPart, cmd);
235
+ const pCmd = path4.join(pathPart, cmd);
236
236
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
237
237
  for (let j = 0; j < pathExt.length; j++) {
238
238
  const cur = p + pathExt[j];
@@ -280,7 +280,7 @@ var require_path_key = __commonJS({
280
280
  var require_resolveCommand = __commonJS({
281
281
  "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
282
282
  "use strict";
283
- var path2 = __require("path");
283
+ var path4 = __require("path");
284
284
  var which = require_which();
285
285
  var getPathKey = require_path_key();
286
286
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -298,7 +298,7 @@ var require_resolveCommand = __commonJS({
298
298
  try {
299
299
  resolved = which.sync(parsed.command, {
300
300
  path: env[getPathKey({ env })],
301
- pathExt: withoutPathExt ? path2.delimiter : void 0
301
+ pathExt: withoutPathExt ? path4.delimiter : void 0
302
302
  });
303
303
  } catch (e) {
304
304
  } finally {
@@ -307,7 +307,7 @@ var require_resolveCommand = __commonJS({
307
307
  }
308
308
  }
309
309
  if (resolved) {
310
- resolved = path2.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
310
+ resolved = path4.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
311
311
  }
312
312
  return resolved;
313
313
  }
@@ -361,8 +361,8 @@ var require_shebang_command = __commonJS({
361
361
  if (!match) {
362
362
  return null;
363
363
  }
364
- const [path2, argument] = match[0].replace(/#! ?/, "").split(" ");
365
- const binary = path2.split("/").pop();
364
+ const [path4, argument] = match[0].replace(/#! ?/, "").split(" ");
365
+ const binary = path4.split("/").pop();
366
366
  if (binary === "env") {
367
367
  return argument;
368
368
  }
@@ -375,16 +375,16 @@ var require_shebang_command = __commonJS({
375
375
  var require_readShebang = __commonJS({
376
376
  "node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
377
377
  "use strict";
378
- var fs3 = __require("fs");
378
+ var fs5 = __require("fs");
379
379
  var shebangCommand = require_shebang_command();
380
380
  function readShebang(command) {
381
381
  const size = 150;
382
382
  const buffer = Buffer.alloc(size);
383
383
  let fd;
384
384
  try {
385
- fd = fs3.openSync(command, "r");
386
- fs3.readSync(fd, buffer, 0, size, 0);
387
- fs3.closeSync(fd);
385
+ fd = fs5.openSync(command, "r");
386
+ fs5.readSync(fd, buffer, 0, size, 0);
387
+ fs5.closeSync(fd);
388
388
  } catch (e) {
389
389
  }
390
390
  return shebangCommand(buffer.toString());
@@ -397,9 +397,9 @@ var require_readShebang = __commonJS({
397
397
  var require_parse = __commonJS({
398
398
  "node_modules/cross-spawn/lib/parse.js"(exports, module) {
399
399
  "use strict";
400
- var path2 = __require("path");
400
+ var path4 = __require("path");
401
401
  var resolveCommand = require_resolveCommand();
402
- var escape = require_escape();
402
+ var escape2 = require_escape();
403
403
  var readShebang = require_readShebang();
404
404
  var isWin = process.platform === "win32";
405
405
  var isExecutableRegExp = /\.(?:com|exe)$/i;
@@ -422,9 +422,9 @@ var require_parse = __commonJS({
422
422
  const needsShell = !isExecutableRegExp.test(commandFile);
423
423
  if (parsed.options.forceShell || needsShell) {
424
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));
425
+ parsed.command = path4.normalize(parsed.command);
426
+ parsed.command = escape2.command(parsed.command);
427
+ parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
428
428
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
429
429
  parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
430
430
  parsed.command = process.env.comspec || "cmd.exe";
@@ -512,7 +512,7 @@ var require_cross_spawn = __commonJS({
512
512
  var cp = __require("child_process");
513
513
  var parse = require_parse();
514
514
  var enoent = require_enoent();
515
- function spawn(command, args, options) {
515
+ function spawn2(command, args, options) {
516
516
  const parsed = parse(command, args, options);
517
517
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
518
518
  enoent.hookChildProcess(spawned, parsed);
@@ -524,8 +524,8 @@ var require_cross_spawn = __commonJS({
524
524
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
525
525
  return result;
526
526
  }
527
- module.exports = spawn;
528
- module.exports.spawn = spawn;
527
+ module.exports = spawn2;
528
+ module.exports.spawn = spawn2;
529
529
  module.exports.sync = spawnSync;
530
530
  module.exports._parse = parse;
531
531
  module.exports._enoent = enoent;
@@ -543,9 +543,10 @@ var LEARNED = "learned";
543
543
  var OAUTH = "oauth";
544
544
  var BROKER = "broker";
545
545
  var LOCKS = "locks";
546
- var normalizePath = (path2) => {
547
- const drive = /^[A-Za-z]:(?=[\\/]|$)/.exec(path2)?.[0];
548
- const rest = drive === void 0 ? path2 : path2.slice(drive.length).replaceAll("\\", "/");
546
+ var CHILD_GUARD = "guard";
547
+ var normalizePath = (path4) => {
548
+ const drive = /^[A-Za-z]:(?=[\\/]|$)/.exec(path4)?.[0];
549
+ const rest = drive === void 0 ? path4 : path4.slice(drive.length).replaceAll("\\", "/");
549
550
  const parts = [];
550
551
  for (const part of rest.split("/")) {
551
552
  if (part === "" || part === ".") continue;
@@ -556,7 +557,8 @@ var normalizePath = (path2) => {
556
557
  };
557
558
  var appPath = (root, ...parts) => normalizePath([root, APP, ...parts].join("/"));
558
559
  var brokerFolder = (home) => appPath(home, BROKER);
559
- var GUARD_MARKERS = [HINTS, FUNCTIONS, LEARNED, OAUTH, BROKER, LOCKS].map(
560
+ var childGuardFolder = (home) => appPath(home, CHILD_GUARD);
561
+ var GUARD_MARKERS = [HINTS, FUNCTIONS, LEARNED, OAUTH, BROKER, LOCKS, CHILD_GUARD].map(
560
562
  (name) => `${APP}/${name}`
561
563
  );
562
564
 
@@ -713,9 +715,351 @@ var lineSplitter = (onLine, max = () => LINE_MAX, onOverflow = () => {
713
715
  var import_cross_spawn = __toESM(require_cross_spawn(), 1);
714
716
  import { spawn as nodeSpawn } from "node:child_process";
715
717
  import crypto2 from "node:crypto";
716
- import fs2 from "node:fs";
718
+ import fs4 from "node:fs";
717
719
  import net from "node:net";
720
+ import path3 from "node:path";
721
+
722
+ // src/host/childguard.ts
723
+ import { spawn } from "node:child_process";
724
+ import { createHash, randomBytes } from "node:crypto";
725
+ import fs2 from "node:fs";
718
726
  import path from "node:path";
727
+ import { fileURLToPath } from "node:url";
728
+
729
+ // src/core/childguard.ts
730
+ var GUARD_ENV = "TOOLSCRIPT_CHILD_GUARD";
731
+ var ASR_RULE = "01443614-CD74-433A-B99E-2ECDC07BFC25";
732
+ var guardWanted = (platform, value) => platform === "win32" ? value === "1" : value !== "0";
733
+ var WATCHDOG = 'list=""; while IFS= read -r l; do case $l in +*) list="$list ${l#+}";; -*) p=${l#-}; new=""; for x in $list; do [ "$x" = "$p" ] || new="$new $x"; done; list=$new;; esac; done; for p in $list; do kill -s KILL -- -$p 2>/dev/null; done';
734
+ var isPid = (pid) => Number.isInteger(pid) && pid > 0;
735
+ var plusLine = (pid) => isPid(pid) ? `+${pid}
736
+ ` : void 0;
737
+ var minusLine = (pid) => isPid(pid) ? `-${pid}
738
+ ` : void 0;
739
+ var guardLine = (pid) => isPid(pid) ? `guard ${pid}
740
+ ` : void 0;
741
+ var guardExeName = (sourceHash) => `child-guard-${sourceHash.slice(0, 16)}.exe`;
742
+ var offLine = (why) => `child guard: off, ${why}. A host that is killed leaves its servers running`;
743
+ var windowsFailure = (why) => `${why}. A Defender rule such as ${ASR_RULE} (block executable files unless they meet a prevalence, age or trusted list criterion) can stop the program from starting. ${GUARD_ENV}=1 turns it on; unset it to turn it off`;
744
+
745
+ // src/host/brokerwire.ts
746
+ import crypto from "node:crypto";
747
+ import fs from "node:fs";
748
+ var KEY_BYTES = 32;
749
+ var BAD_KEY = "EBADKEY";
750
+ var makeCrypto = (key) => ({
751
+ mac: (text) => crypto.createHmac("sha256", key).update(text).digest("hex"),
752
+ nonce: () => crypto.randomBytes(16).toString("hex"),
753
+ same: (a, b) => {
754
+ const x = Buffer.from(a);
755
+ const y = Buffer.from(b);
756
+ return x.length === y.length && crypto.timingSafeEqual(x, y);
757
+ }
758
+ });
759
+ var stderrFrames = (data) => {
760
+ const out = [];
761
+ for (let at = 0; at < data.length; at += STDERR_CHUNK)
762
+ out.push(stderrFrame(data.subarray(at, at + STDERR_CHUNK).toString("base64")));
763
+ return out;
764
+ };
765
+ var buildId = (file2) => crypto.createHash("sha256").update(fs.readFileSync(file2)).digest("hex");
766
+ var loadKey = (home) => {
767
+ const dir = brokerFolder(home);
768
+ const file2 = `${dir}/key`;
769
+ const read = () => {
770
+ try {
771
+ const key2 = fs.readFileSync(file2);
772
+ return key2.length === KEY_BYTES ? key2 : void 0;
773
+ } catch (err) {
774
+ if (err.code === "ENOENT") return void 0;
775
+ throw err;
776
+ }
777
+ };
778
+ const have = read();
779
+ if (have !== void 0) return have;
780
+ privateFolder(dir);
781
+ const temp = `${dir}/key.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
782
+ try {
783
+ fs.writeFileSync(temp, crypto.randomBytes(KEY_BYTES), { flag: "wx", mode: 384 });
784
+ try {
785
+ fs.linkSync(temp, file2);
786
+ } catch (err) {
787
+ if (err.code !== "EEXIST") throw err;
788
+ }
789
+ } finally {
790
+ fs.rmSync(temp, { force: true });
791
+ }
792
+ const key = read();
793
+ if (key === void 0) throw Object.assign(new Error("the broker key file is not 32 bytes long"), { code: BAD_KEY });
794
+ return key;
795
+ };
796
+ var endpointFor = (home, key, id, platform = process.platform) => endpointOf(platform, home, makeCrypto(key).mac(`toolscript-mcp build ${id}`), process.getuid?.() ?? 0);
797
+ var privateFolder = (dir) => {
798
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
799
+ if (process.platform === "win32") return;
800
+ const problem = folderProblem(dir);
801
+ if (problem !== void 0) throw new Error(`the folder ${problem}`);
802
+ if ((fs.lstatSync(dir).mode & 63) !== 0) fs.chmodSync(dir, 448);
803
+ };
804
+ var folderProblem = (dir) => {
805
+ if (process.platform === "win32") return void 0;
806
+ let info;
807
+ try {
808
+ info = fs.lstatSync(dir);
809
+ } catch (err) {
810
+ const code = err.code;
811
+ return code === "ENOENT" ? void 0 : `cannot be read (${code ?? "error"})`;
812
+ }
813
+ if (!info.isDirectory()) return "is a link or a file, not a folder";
814
+ if (info.uid !== process.getuid?.()) return "belongs to another user";
815
+ return void 0;
816
+ };
817
+
818
+ // src/host/childguard.ts
819
+ var GUARD_SOURCE = fileURLToPath(new URL("../../runtime/child-guard.cs", import.meta.url));
820
+ var READY_MS = 15e3;
821
+ var COMPILE_MS = 6e4;
822
+ var isFile = (file2) => {
823
+ try {
824
+ return fs2.statSync(file2).isFile();
825
+ } catch {
826
+ return false;
827
+ }
828
+ };
829
+ var plainFile = (file2) => {
830
+ try {
831
+ return fs2.lstatSync(file2).isFile();
832
+ } catch {
833
+ return void 0;
834
+ }
835
+ };
836
+ var noGuard = {
837
+ add: () => {
838
+ },
839
+ remove: () => {
840
+ },
841
+ start: () => {
842
+ },
843
+ settled: () => Promise.resolve({ state: "unwanted" }),
844
+ close: () => {
845
+ },
846
+ state: () => ({ state: "unwanted" })
847
+ };
848
+ var createGuard = (options) => {
849
+ const platform = options.platform ?? process.platform;
850
+ const env = options.env ?? process.env;
851
+ if (!guardWanted(platform, env[GUARD_ENV])) return noGuard;
852
+ return platform === "win32" ? windowsGuard(options, env) : posixGuard(options);
853
+ };
854
+ var stateOf = (log, explain) => {
855
+ let state = { state: "starting" };
856
+ let settle = () => {
857
+ };
858
+ const settled = new Promise((resolve) => settle = resolve);
859
+ return {
860
+ get: () => state,
861
+ settled: () => settled,
862
+ on: (how) => {
863
+ if (state.state !== "starting") return;
864
+ state = { state: "on", how };
865
+ log(`child guard: on (${how})`);
866
+ settle(state);
867
+ },
868
+ fail: (why) => {
869
+ if (state.state === "failed") return;
870
+ const first = state.state === "starting" || state.state === "on";
871
+ state = { state: "failed", why };
872
+ if (first) log(offLine(explain(why)));
873
+ settle(state);
874
+ }
875
+ };
876
+ };
877
+ var posixGuard = (options) => {
878
+ const own2 = stateOf(options.log, (why) => why);
879
+ let proc;
880
+ let closed = false;
881
+ const start = () => {
882
+ if (proc !== void 0 || closed || own2.get().state === "failed") return;
883
+ const shell = options.shell ?? "/bin/sh";
884
+ try {
885
+ fs2.accessSync(shell, fs2.constants.X_OK);
886
+ } catch {
887
+ return own2.fail(`there is no ${shell}`);
888
+ }
889
+ const dog = spawn(shell, ["-c", WATCHDOG], { stdio: ["pipe", "ignore", "ignore"], detached: true });
890
+ proc = dog;
891
+ dog.on("error", (err) => own2.fail(`the watchdog could not start (${err.code ?? "error"})`));
892
+ dog.on("exit", () => {
893
+ if (!closed) own2.fail("the watchdog ended");
894
+ });
895
+ dog.stdin?.on("error", () => {
896
+ });
897
+ dog.unref();
898
+ dog.stdin?.unref?.();
899
+ own2.on("/bin/sh watchdog");
900
+ };
901
+ const write = (line) => {
902
+ if (line === void 0 || proc?.stdin === null || proc?.stdin === void 0 || proc.stdin.destroyed) return;
903
+ try {
904
+ proc.stdin.write(line);
905
+ } catch {
906
+ }
907
+ };
908
+ return {
909
+ add: (pid) => {
910
+ if (closed || pid === void 0) return;
911
+ start();
912
+ write(plusLine(pid));
913
+ },
914
+ remove: (pid) => {
915
+ if (pid !== void 0) write(minusLine(pid));
916
+ },
917
+ start,
918
+ settled: () => own2.settled(),
919
+ close: () => {
920
+ if (closed) return;
921
+ closed = true;
922
+ try {
923
+ proc?.stdin?.end();
924
+ } catch {
925
+ }
926
+ },
927
+ state: own2.get
928
+ };
929
+ };
930
+ var ensureProgram = async (options, env) => {
931
+ const sourceFile = options.source ?? GUARD_SOURCE;
932
+ let source;
933
+ try {
934
+ source = fs2.readFileSync(sourceFile);
935
+ } catch {
936
+ throw new Error("the source of the guard program is missing");
937
+ }
938
+ const dir = childGuardFolder(options.home);
939
+ const exe = path.join(dir, guardExeName(createHash("sha256").update(source).digest("hex")));
940
+ const found = plainFile(exe);
941
+ if (found === true) return exe;
942
+ if (found === false) throw new Error("the guard program is not a plain file");
943
+ const root = env.SystemRoot ?? env.SYSTEMROOT;
944
+ const csc = options.csc ?? (root !== void 0 && path.win32.isAbsolute(root) ? path.win32.join(root, "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe") : void 0);
945
+ if (csc === void 0 || !isFile(csc)) throw new Error("the csc.exe of .NET Framework 4 was not found");
946
+ privateFolder(dir);
947
+ const temp = path.join(dir, `tmp-${process.pid}-${randomBytes(4).toString("hex")}.exe`);
948
+ const text = await new Promise((resolve) => {
949
+ let out = "";
950
+ const compiler = spawn(csc, ["/nologo", "/optimize+", "/target:winexe", `/out:${temp}`, sourceFile], {
951
+ stdio: ["ignore", "pipe", "pipe"],
952
+ windowsHide: true,
953
+ timeout: COMPILE_MS
954
+ });
955
+ compiler.stdout?.on("data", (d) => out += d);
956
+ compiler.stderr?.on("data", (d) => out += d);
957
+ compiler.on(
958
+ "error",
959
+ (err) => resolve(`the compile could not start (${err.code ?? "error"})`)
960
+ );
961
+ compiler.on(
962
+ "close",
963
+ (code) => resolve(code === 0 ? void 0 : `the compile failed: ${out.replace(/\s+/g, " ").slice(0, 200)}`)
964
+ );
965
+ });
966
+ if (text !== void 0) {
967
+ fs2.rmSync(temp, { force: true });
968
+ throw new Error(text);
969
+ }
970
+ try {
971
+ fs2.renameSync(temp, exe);
972
+ } catch {
973
+ fs2.rmSync(temp, { force: true });
974
+ if (plainFile(exe) !== true) throw new Error("the compiled program could not be put in place");
975
+ }
976
+ return exe;
977
+ };
978
+ var windowsGuard = (options, env) => {
979
+ const own2 = stateOf(options.log, windowsFailure);
980
+ const waiting = /* @__PURE__ */ new Set();
981
+ let proc;
982
+ let began = false;
983
+ let closed = false;
984
+ let timer;
985
+ const send = (pid) => {
986
+ const line = guardLine(pid);
987
+ if (line === void 0 || proc?.stdin === null || proc?.stdin === void 0 || proc.stdin.destroyed) return;
988
+ try {
989
+ proc.stdin.write(line);
990
+ } catch {
991
+ }
992
+ };
993
+ const begin = async () => {
994
+ let exe;
995
+ try {
996
+ exe = await ensureProgram(options, env);
997
+ } catch (err) {
998
+ return own2.fail(err.message);
999
+ }
1000
+ if (closed) return;
1001
+ const guard = spawn(exe, [String(process.pid)], { stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
1002
+ proc = guard;
1003
+ timer = setTimeout(() => {
1004
+ own2.fail("the guard program did not say ready in time");
1005
+ guard.kill();
1006
+ }, options.readyMs ?? READY_MS);
1007
+ guard.on("error", (err) => {
1008
+ clearTimeout(timer);
1009
+ own2.fail(`the guard program could not start (${err.code ?? "error"})`);
1010
+ });
1011
+ guard.on("exit", (code) => {
1012
+ clearTimeout(timer);
1013
+ if (!closed) own2.fail(`the guard program ended with exit code ${String(code)}`);
1014
+ });
1015
+ guard.stdin?.on("error", () => {
1016
+ });
1017
+ guard.stdout?.setEncoding("utf8");
1018
+ let text = "";
1019
+ guard.stdout?.on("data", (chunk) => {
1020
+ text += chunk;
1021
+ if (!/^ready$/m.test(text)) return;
1022
+ clearTimeout(timer);
1023
+ guard.stdout?.removeAllListeners("data");
1024
+ guard.stdout?.resume();
1025
+ own2.on("Job Object, child-guard.exe");
1026
+ for (const pid of waiting) send(pid);
1027
+ waiting.clear();
1028
+ });
1029
+ guard.unref();
1030
+ guard.stdin?.unref?.();
1031
+ guard.stdout?.unref?.();
1032
+ };
1033
+ const start = () => {
1034
+ if (began || closed) return;
1035
+ began = true;
1036
+ void begin();
1037
+ };
1038
+ return {
1039
+ add: (pid) => {
1040
+ if (closed || pid === void 0 || own2.get().state === "failed") return;
1041
+ start();
1042
+ if (own2.get().state === "on") send(pid);
1043
+ else waiting.add(pid);
1044
+ },
1045
+ // A job drops a process that ended by itself: nothing to remove.
1046
+ remove: (pid) => {
1047
+ if (pid !== void 0) waiting.delete(pid);
1048
+ },
1049
+ start,
1050
+ settled: () => own2.settled(),
1051
+ close: () => {
1052
+ if (closed) return;
1053
+ closed = true;
1054
+ clearTimeout(timer);
1055
+ try {
1056
+ proc?.stdin?.end();
1057
+ } catch {
1058
+ }
1059
+ },
1060
+ state: own2.get
1061
+ };
1062
+ };
719
1063
 
720
1064
  // src/core/mux.ts
721
1065
  var DIED_CODE = -32e3;
@@ -906,77 +1250,415 @@ var createRouter = () => {
906
1250
  };
907
1251
  };
908
1252
 
909
- // src/host/brokerwire.ts
910
- import crypto from "node:crypto";
911
- import fs from "node:fs";
912
- var KEY_BYTES = 32;
913
- var BAD_KEY = "EBADKEY";
914
- var makeCrypto = (key) => ({
915
- mac: (text) => crypto.createHmac("sha256", key).update(text).digest("hex"),
916
- nonce: () => crypto.randomBytes(16).toString("hex"),
917
- same: (a, b) => {
918
- const x = Buffer.from(a);
919
- const y = Buffer.from(b);
920
- return x.length === y.length && crypto.timingSafeEqual(x, y);
1253
+ // src/core/protocol.ts
1254
+ var MAX_FILE_SIZE = 16 * 1024 * 1024;
1255
+ var MAX_RUN_ATTACHMENT_BYTES = 64 * 1024 * 1024;
1256
+ var QUOTE = '"'.charCodeAt(0);
1257
+ var SLASH = "\\".charCodeAt(0);
1258
+ var MINUS = "-".charCodeAt(0);
1259
+ var PLUS = "+".charCodeAt(0);
1260
+ var DOT = ".".charCodeAt(0);
1261
+ var EXP = "e".charCodeAt(0);
1262
+ var EXP_CAP = "E".charCodeAt(0);
1263
+ var startsWith = (bytes, at, head) => bytes.length >= at + head.length && [...head].every((c, i) => bytes[at + i] === c.charCodeAt(0));
1264
+ var IMAGE_HEADS = {
1265
+ "image/png": (b) => startsWith(b, 0, "\x89PNG\r\n\n"),
1266
+ "image/jpeg": (b) => startsWith(b, 0, "\xFF\xD8\xFF"),
1267
+ "image/gif": (b) => startsWith(b, 0, "GIF87a") || startsWith(b, 0, "GIF89a"),
1268
+ "image/webp": (b) => startsWith(b, 0, "RIFF") && startsWith(b, 8, "WEBP")
1269
+ };
1270
+ var SHOWN_IMAGE_TYPES = new Set(Object.keys(IMAGE_HEADS));
1271
+ var MAX_SHOWN_IMAGES = 4;
1272
+ var MAX_IMAGE_BYTES = 375e4;
1273
+ var MAX_SHOWN_IMAGE_BYTES = 8e6;
1274
+ var HIDDEN_TEXT = {
1275
+ type: "only PNG, JPEG, GIF and WebP images show",
1276
+ unreadable: "the file cannot be read",
1277
+ changed: "the file changed after the call wrote it",
1278
+ "not-image": "the file does not hold an image of its type",
1279
+ size: `it is more than ${MAX_IMAGE_BYTES} bytes`,
1280
+ count: `at most ${MAX_SHOWN_IMAGES} images show per run`,
1281
+ total: `the images of one run show at most ${MAX_SHOWN_IMAGE_BYTES} bytes`
1282
+ };
1283
+
1284
+ // src/core/workspace.ts
1285
+ var WORKSPACE_KEY = "workspace";
1286
+ var LIMITS = {
1287
+ /** `read` refuses a larger file. */
1288
+ readBytes: 4 * 1024 * 1024,
1289
+ /** `search` skips a larger file. */
1290
+ searchFileBytes: 1024 * 1024,
1291
+ searchFiles: 2e4,
1292
+ searchMs: 1e4,
1293
+ listEntries: 5e3,
1294
+ /**
1295
+ * Walks of `list` and `search` that run at one time in a provider at most (issue #160). Two were measured against one
1296
+ * (issue #180, `bench/RESULTS-walks.md`): they cut batch time on trees that fit the budget, but on a tree where a search
1297
+ * alone takes 55 to 75 % of `searchMs` two walks slow each other to the 10 s edge and cut calls that one slot did not.
1298
+ * A later raise needs a one-CPU floor (a count from the cores cut 7 of 8 searches on a multi-core laptop, issue #160) and a
1299
+ * bench near the budget: see `bench/RESULTS-walks.md`.
1300
+ */
1301
+ walkSlots: 1,
1302
+ /** Files of one `search` walk that are opened, proven and read at the same time. Each is proven by its own open. */
1303
+ searchInFlight: 4,
1304
+ /** `search` cuts the text of a line at this length. */
1305
+ lineChars: 400,
1306
+ parts: 64,
1307
+ pathChars: 1024,
1308
+ maxDepth: 8,
1309
+ maxMatches: 2e3,
1310
+ defaultMatches: 200,
1311
+ includes: 16,
1312
+ globChars: 200,
1313
+ globWildcards: 6,
1314
+ queryChars: 1e3,
1315
+ /** Texts in the `query` array of one `search`. */
1316
+ queryTerms: 20,
1317
+ roots: 16,
1318
+ configGlobs: 64,
1319
+ /** `edits` of one call. */
1320
+ edits: 50,
1321
+ /** Matches of one `old` with `all: true`. */
1322
+ replacements: 1e4,
1323
+ /** The unified diff is cut at this many characters. */
1324
+ diffChars: 64 * 1024,
1325
+ /** Lines of context around each change in a diff. */
1326
+ context: 3,
1327
+ /** A change waits this long for the lock of its file, then fails with `busy`. */
1328
+ lockWaitMs: 2e3,
1329
+ /** A lock file older than this, or of a dead process, is taken over. */
1330
+ lockStaleMs: 3e4,
1331
+ /** The `.gitignore` of the root: a larger file gives no rules. */
1332
+ ignoreBytes: 64 * 1024,
1333
+ /** Rules that count. The rest of the file is skipped. */
1334
+ ignoreRules: 500,
1335
+ /** A line of the `.gitignore` with more characters, or more wildcards, is skipped. */
1336
+ ignoreLineChars: 200,
1337
+ ignoreWildcards: 6
1338
+ };
1339
+ var entryType = { type: "string", enum: ["file", "folder", "link", "other"] };
1340
+ var pathArg = (description) => ({ type: "string", description });
1341
+ var hashArg = (description) => ({ type: "string", pattern: "^sha256:[0-9a-f]{64}$", description });
1342
+ var editsArg = {
1343
+ type: "array",
1344
+ minItems: 1,
1345
+ maxItems: LIMITS.edits,
1346
+ description: "The replacements. Each old is matched against the file as it was read, so no edit sees another.",
1347
+ items: {
1348
+ type: "object",
1349
+ properties: {
1350
+ old: { type: "string", description: "The exact text to replace, with its line ends and spaces." },
1351
+ new: { type: "string", description: "The text that replaces it." },
1352
+ all: { type: "boolean", description: "Replace each match, not only a single one. Default false." }
1353
+ },
1354
+ required: ["old", "new"],
1355
+ additionalProperties: false
921
1356
  }
922
- });
923
- var stderrFrames = (data) => {
924
- const out = [];
925
- for (let at = 0; at < data.length; at += STDERR_CHUNK)
926
- out.push(stderrFrame(data.subarray(at, at + STDERR_CHUNK).toString("base64")));
927
- return out;
928
1357
  };
929
- var buildId = (file2) => crypto.createHash("sha256").update(fs.readFileSync(file2)).digest("hex");
930
- var loadKey = (home) => {
931
- const dir = brokerFolder(home);
932
- const file2 = `${dir}/key`;
933
- const read = () => {
934
- try {
935
- const key2 = fs.readFileSync(file2);
936
- return key2.length === KEY_BYTES ? key2 : void 0;
937
- } catch (err) {
938
- if (err.code === "ENOENT") return void 0;
939
- throw err;
1358
+ var changeSchema = {
1359
+ type: "object",
1360
+ properties: {
1361
+ path: { type: "string" },
1362
+ applied: { type: "boolean" },
1363
+ created: { type: "boolean" },
1364
+ changed: { type: "boolean" },
1365
+ oldHash: { type: ["string", "null"] },
1366
+ newHash: { type: "string" },
1367
+ diff: { type: "string" },
1368
+ diffTruncated: { type: "boolean" },
1369
+ added: { type: "integer" },
1370
+ removed: { type: "integer" },
1371
+ warnings: { type: "array", items: { type: "string" } }
1372
+ },
1373
+ required: [
1374
+ "path",
1375
+ "applied",
1376
+ "created",
1377
+ "changed",
1378
+ "oldHash",
1379
+ "newHash",
1380
+ "diff",
1381
+ "diffTruncated",
1382
+ "added",
1383
+ "removed",
1384
+ "warnings"
1385
+ ]
1386
+ };
1387
+ var WORKSPACE_TOOLS = {
1388
+ list: {
1389
+ class: "read",
1390
+ description: "List files and folders under a folder of the workspace, sorted by path. A link is listed and never entered. Excluded paths such as .git and .env never show. The .gitignore of the root hides names too: name an ignored folder in path to list it. truncated is true when it stopped early (10 s, 20,000 names or 5,000 entries).",
1391
+ inputSchema: {
1392
+ type: "object",
1393
+ properties: {
1394
+ path: pathArg(
1395
+ 'The folder, relative to the workspace root. Default ".". Name the smallest folder that holds what you look for.'
1396
+ ),
1397
+ depth: {
1398
+ type: "integer",
1399
+ minimum: 1,
1400
+ maximum: LIMITS.maxDepth,
1401
+ description: "How many levels to list. Default 1."
1402
+ },
1403
+ include: {
1404
+ type: "array",
1405
+ items: { type: "string" },
1406
+ description: 'Globs over paths from the workspace root, also when path is set, such as "src/**/*.ts". * and ? stay inside a part, ** spans parts. A folder that no glob can reach is not read.'
1407
+ }
1408
+ },
1409
+ additionalProperties: false
1410
+ },
1411
+ outputSchema: {
1412
+ type: "object",
1413
+ properties: {
1414
+ entries: {
1415
+ type: "array",
1416
+ items: {
1417
+ type: "object",
1418
+ properties: { path: { type: "string" }, type: entryType, size: { type: "integer" } },
1419
+ required: ["path", "type"]
1420
+ }
1421
+ },
1422
+ truncated: { type: "boolean" },
1423
+ notStarted: { type: "boolean" }
1424
+ },
1425
+ required: ["entries", "truncated"]
940
1426
  }
941
- };
942
- const have = read();
943
- if (have !== void 0) return have;
944
- privateFolder(dir);
945
- const temp = `${dir}/key.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
946
- try {
947
- fs.writeFileSync(temp, crypto.randomBytes(KEY_BYTES), { flag: "wx", mode: 384 });
948
- try {
949
- fs.linkSync(temp, file2);
950
- } catch (err) {
951
- if (err.code !== "EEXIST") throw err;
1427
+ },
1428
+ search: {
1429
+ class: "read",
1430
+ description: "Find literal text, not a regular expression, in the text files under a folder. One match for each place, with its line and column. query can be an array of up to 20 texts: one walk finds all of them, and each match names its query. Filter the lines in your program. The .gitignore of the root hides files: name an ignored folder in path to search it. truncated is true when it stopped early (10 s, 20,000 names or maxMatches): the matches are then partial.",
1431
+ inputSchema: {
1432
+ type: "object",
1433
+ properties: {
1434
+ query: {
1435
+ anyOf: [
1436
+ { type: "string" },
1437
+ { type: "array", items: { type: "string" }, minItems: 1, maxItems: LIMITS.queryTerms }
1438
+ ],
1439
+ description: "The text to find, on one line. An array of texts is one walk for all of them."
1440
+ },
1441
+ path: pathArg(
1442
+ 'The folder to search, relative to the workspace root. Default ".". Name the smallest folder that holds what you look for.'
1443
+ ),
1444
+ include: {
1445
+ type: "array",
1446
+ items: { type: "string" },
1447
+ description: 'Globs over paths from the workspace root, also when path is set, such as "src/**/*.ts". * and ? stay inside a part, ** spans parts.'
1448
+ },
1449
+ ignoreCase: { type: "boolean", description: "Default false." },
1450
+ maxMatches: {
1451
+ type: "integer",
1452
+ minimum: 1,
1453
+ maximum: LIMITS.maxMatches,
1454
+ description: "For each query. Default 200, or 2,000 divided by the number of queries if less."
1455
+ }
1456
+ },
1457
+ required: ["query"],
1458
+ additionalProperties: false
1459
+ },
1460
+ outputSchema: {
1461
+ type: "object",
1462
+ properties: {
1463
+ matches: {
1464
+ type: "array",
1465
+ items: {
1466
+ type: "object",
1467
+ properties: {
1468
+ path: { type: "string" },
1469
+ line: { type: "integer" },
1470
+ column: { type: "integer" },
1471
+ text: { type: "string" },
1472
+ query: { type: "string", description: "The query that matched, when query was an array." }
1473
+ },
1474
+ required: ["path", "line", "column", "text"]
1475
+ }
1476
+ },
1477
+ truncated: { type: "boolean" },
1478
+ filesScanned: { type: "integer" },
1479
+ skipped: { type: "integer" },
1480
+ notStarted: { type: "boolean" }
1481
+ },
1482
+ required: ["matches", "truncated", "filesScanned", "skipped"]
952
1483
  }
953
- } finally {
954
- fs.rmSync(temp, { force: true });
1484
+ },
1485
+ read: {
1486
+ class: "read",
1487
+ description: "Read one text file whole, with its line ends as they are. Refuses a file over 4 MiB, a binary file, a link and an excluded path. The hash is of the bytes of the file.",
1488
+ inputSchema: {
1489
+ type: "object",
1490
+ properties: { path: pathArg("The file, relative to the workspace root, with /.") },
1491
+ required: ["path"],
1492
+ additionalProperties: false
1493
+ },
1494
+ outputSchema: {
1495
+ type: "object",
1496
+ properties: {
1497
+ path: { type: "string" },
1498
+ content: { type: "string" },
1499
+ hash: { type: "string" },
1500
+ encoding: { type: "string", enum: ["utf-8", "utf-8-bom"] },
1501
+ size: { type: "integer" }
1502
+ },
1503
+ required: ["path", "content", "hash", "encoding", "size"]
1504
+ }
1505
+ },
1506
+ stat: {
1507
+ class: "read",
1508
+ description: "Tell what a path is: file, folder, other or missing, and the size of a file. A link is refused.",
1509
+ inputSchema: {
1510
+ type: "object",
1511
+ properties: { path: pathArg('The path, relative to the workspace root, with /. "." is the root.') },
1512
+ required: ["path"],
1513
+ additionalProperties: false
1514
+ },
1515
+ outputSchema: {
1516
+ type: "object",
1517
+ properties: {
1518
+ path: { type: "string" },
1519
+ type: { type: "string", enum: ["file", "folder", "other", "missing"] },
1520
+ size: { type: "integer" }
1521
+ },
1522
+ required: ["path", "type"]
1523
+ }
1524
+ },
1525
+ // Listed only when the root entry of the session has a valid task. The provider adds the task names to the text.
1526
+ run_task: {
1527
+ class: "exec",
1528
+ description: "Run one named task of this project, such as its tests. The task is fixed in the config: you choose only the name. A non-zero exit code is a result, not an error. One task runs at a time.",
1529
+ inputSchema: {
1530
+ type: "object",
1531
+ properties: { task: { type: "string", description: "The name of the task." } },
1532
+ required: ["task"],
1533
+ additionalProperties: false
1534
+ },
1535
+ outputSchema: {
1536
+ type: "object",
1537
+ properties: {
1538
+ task: { type: "string" },
1539
+ exitCode: { type: ["integer", "null"] },
1540
+ signal: { type: ["string", "null"] },
1541
+ timedOut: { type: "boolean" },
1542
+ ms: { type: "integer" },
1543
+ stdout: { type: "string" },
1544
+ stderr: { type: "string" },
1545
+ stdoutTruncated: { type: "boolean" },
1546
+ stderrTruncated: { type: "boolean" }
1547
+ },
1548
+ required: [
1549
+ "task",
1550
+ "exitCode",
1551
+ "signal",
1552
+ "timedOut",
1553
+ "ms",
1554
+ "stdout",
1555
+ "stderr",
1556
+ "stdoutTruncated",
1557
+ "stderrTruncated"
1558
+ ]
1559
+ }
1560
+ },
1561
+ diff: {
1562
+ class: "read",
1563
+ description: "Preview a change to one file and write nothing. Give edits, as edit takes them, or content (a new file, or with expectedHash a whole replacement). Returns the unified diff, the counts and the hash the file would have.",
1564
+ inputSchema: {
1565
+ type: "object",
1566
+ properties: {
1567
+ path: pathArg("The file, relative to the workspace root, with /."),
1568
+ expectedHash: hashArg(
1569
+ "The hash that read returned. With content it selects a replacement of an existing file."
1570
+ ),
1571
+ edits: editsArg,
1572
+ content: { type: "string", description: "The whole new text of the file." }
1573
+ },
1574
+ required: ["path"],
1575
+ additionalProperties: false
1576
+ },
1577
+ outputSchema: changeSchema
1578
+ },
1579
+ edit: {
1580
+ class: "write",
1581
+ description: "Replace exact text in one existing file. Each old is matched against the file as read and must occur once, unless all is true. Needs the hash from read: a changed file fails with stale. Keeps line ends, the byte order mark and the mode. Needs approval.",
1582
+ inputSchema: {
1583
+ type: "object",
1584
+ properties: {
1585
+ path: pathArg("The file, relative to the workspace root, with /."),
1586
+ expectedHash: hashArg("The hash that read returned for this file."),
1587
+ edits: editsArg
1588
+ },
1589
+ required: ["path", "expectedHash", "edits"],
1590
+ additionalProperties: false
1591
+ },
1592
+ outputSchema: changeSchema
1593
+ },
1594
+ write: {
1595
+ class: "write",
1596
+ description: "Make a new file, or with expectedHash replace a whole file. Without it, an existing path fails with exists. Makes missing folders. Needs approval.",
1597
+ inputSchema: {
1598
+ type: "object",
1599
+ properties: {
1600
+ path: pathArg("The file, relative to the workspace root, with /."),
1601
+ content: { type: "string", description: "The whole text of the file." },
1602
+ expectedHash: hashArg("The hash that read returned, to replace an existing file.")
1603
+ },
1604
+ required: ["path", "content"],
1605
+ additionalProperties: false
1606
+ },
1607
+ outputSchema: changeSchema
955
1608
  }
956
- const key = read();
957
- if (key === void 0) throw Object.assign(new Error("the broker key file is not 32 bytes long"), { code: BAD_KEY });
958
- return key;
959
1609
  };
960
- var endpointFor = (home, key, id, platform = process.platform) => endpointOf(platform, home, makeCrypto(key).mac(`toolscript-mcp build ${id}`), process.getuid?.() ?? 0);
961
- var privateFolder = (dir) => {
962
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
963
- if (process.platform === "win32") return;
964
- const problem = folderProblem(dir);
965
- if (problem !== void 0) throw new Error(`the folder ${problem}`);
966
- if ((fs.lstatSync(dir).mode & 63) !== 0) fs.chmodSync(dir, 448);
1610
+ var WORKSPACE_TOOL_NAMES = Object.keys(WORKSPACE_TOOLS);
1611
+
1612
+ // src/core/policy.ts
1613
+ var escape = (c) => {
1614
+ const hex = c.codePointAt(0).toString(16);
1615
+ return hex.length <= 4 ? `\\u${hex.padStart(4, "0")}` : `\\u{${hex}}`;
967
1616
  };
968
- var folderProblem = (dir) => {
969
- if (process.platform === "win32") return void 0;
970
- let info;
971
- try {
972
- info = fs.lstatSync(dir);
973
- } catch (err) {
974
- const code = err.code;
975
- return code === "ENOENT" ? void 0 : `cannot be read (${code ?? "error"})`;
976
- }
977
- if (!info.isDirectory()) return "is a link or a file, not a folder";
978
- if (info.uid !== process.getuid?.()) return "belongs to another user";
979
- return void 0;
1617
+ var printable = (s) => s.replace(/[^\x20-\x7e]/gu, escape);
1618
+ var changeRule = `allow rule for a Workspace change tool must start with mcp__${WORKSPACE_KEY}__`;
1619
+
1620
+ // src/core/spawn.ts
1621
+ var COMMAND_SHOWN = 200;
1622
+ var spawnReason = (command, code) => {
1623
+ const shown = printable(command.slice(0, COMMAND_SHOWN));
1624
+ if (code === "ENOENT")
1625
+ return /[\\/]/u.test(command) ? `its command file was not found: ${shown}` : `its command was not found on PATH: ${shown}`;
1626
+ return `its command could not start (${code.replace(/[^A-Za-z0-9_]/gu, "").slice(0, 20) || "unknown"}): ${shown}`;
1627
+ };
1628
+ var spawnCode = (error) => {
1629
+ const { code, syscall } = error ?? {};
1630
+ return typeof code === "string" && typeof syscall === "string" && syscall.startsWith("spawn") ? code : void 0;
1631
+ };
1632
+ var trustedSpawnError = (error, platform, found) => {
1633
+ const { code, errno } = error ?? {};
1634
+ if (platform !== "win32" || code !== "ENOENT" || typeof errno !== "string") return true;
1635
+ return !found();
1636
+ };
1637
+
1638
+ // src/host/commandfind.ts
1639
+ import fs3 from "node:fs";
1640
+ import path2 from "node:path";
1641
+ var DEFAULT_EXT = ".COM;.EXE;.BAT;.CMD";
1642
+ var valueOf = (env, name) => {
1643
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name);
1644
+ return key === void 0 ? void 0 : env[key];
1645
+ };
1646
+ var findCommand = (command, env, cwd) => {
1647
+ const exts = (valueOf(env, "PATHEXT") ?? DEFAULT_EXT).split(";").filter((e) => e !== "");
1648
+ const names = [command, ...exts.map((e) => command + e)];
1649
+ const hasPath = /[\\/]/u.test(command) || /^[A-Za-z]:/u.test(command);
1650
+ const dirs = hasPath ? [cwd ?? process.cwd()] : [
1651
+ cwd ?? process.cwd(),
1652
+ ...(valueOf(env, "PATH") ?? "").split(path2.delimiter).map((d) => d.replace(/^"|"$/gu, "")).filter((d) => d !== "")
1653
+ ];
1654
+ for (const dir of dirs)
1655
+ for (const name of names)
1656
+ try {
1657
+ fs3.lstatSync(path2.resolve(cwd ?? process.cwd(), dir, name));
1658
+ return true;
1659
+ } catch {
1660
+ }
1661
+ return false;
980
1662
  };
981
1663
 
982
1664
  // src/host/broker.ts
@@ -989,8 +1671,8 @@ var PROBE_VERSION = "2025-11-25";
989
1671
  var makeLog = (file2) => {
990
1672
  let size = 0;
991
1673
  try {
992
- size = fs2.statSync(file2).size;
993
- if (size > LOG_MAX) fs2.writeFileSync(file2, "");
1674
+ size = fs4.statSync(file2).size;
1675
+ if (size > LOG_MAX) fs4.writeFileSync(file2, "");
994
1676
  if (size > LOG_MAX) size = 0;
995
1677
  } catch {
996
1678
  }
@@ -999,10 +1681,10 @@ var makeLog = (file2) => {
999
1681
  `;
1000
1682
  try {
1001
1683
  if (size + text.length > LOG_MAX) {
1002
- fs2.writeFileSync(file2, "");
1684
+ fs4.writeFileSync(file2, "");
1003
1685
  size = 0;
1004
1686
  }
1005
- fs2.appendFileSync(file2, text);
1687
+ fs4.appendFileSync(file2, text);
1006
1688
  size += text.length;
1007
1689
  } catch {
1008
1690
  }
@@ -1030,10 +1712,11 @@ var endTree = (proc) => {
1030
1712
  };
1031
1713
  var RECOVER_MS = 8e3;
1032
1714
  var LOCK_STALE_MS = 5e3;
1715
+ var SOCKET_GUARD_MS = 1e3;
1033
1716
  var fileId = (file2) => {
1034
1717
  try {
1035
- const info = fs2.statSync(file2, { bigint: true });
1036
- return `${info.dev}:${info.ino}`;
1718
+ const info = fs4.statSync(file2, { bigint: true });
1719
+ return `${info.dev}:${info.ino}:${info.birthtimeNs}`;
1037
1720
  } catch {
1038
1721
  return void 0;
1039
1722
  }
@@ -1050,7 +1733,7 @@ var takeLock = (file2, afterRead = () => {
1050
1733
  }) => {
1051
1734
  const id = crypto2.randomBytes(8).toString("hex");
1052
1735
  try {
1053
- fs2.writeFileSync(file2, JSON.stringify({ pid: process.pid, id, at: Date.now() }), { flag: "wx", mode: 384 });
1736
+ fs4.writeFileSync(file2, JSON.stringify({ pid: process.pid, id, at: Date.now() }), { flag: "wx", mode: 384 });
1054
1737
  return id;
1055
1738
  } catch (err) {
1056
1739
  if (err.code !== "EEXIST") throw err;
@@ -1058,14 +1741,14 @@ var takeLock = (file2, afterRead = () => {
1058
1741
  let seen;
1059
1742
  let stale;
1060
1743
  try {
1061
- seen = fs2.readFileSync(file2, "utf8");
1744
+ seen = fs4.readFileSync(file2, "utf8");
1062
1745
  try {
1063
1746
  const held = JSON.parse(seen);
1064
1747
  const dead = typeof held.pid !== "number" || !pidAlive(held.pid);
1065
1748
  const old = typeof held.at !== "number" || Math.abs(Date.now() - held.at) > LOCK_STALE_MS;
1066
1749
  stale = dead || old;
1067
1750
  } catch {
1068
- stale = Math.abs(Date.now() - fs2.statSync(file2).mtimeMs) > LOCK_STALE_MS;
1751
+ stale = Math.abs(Date.now() - fs4.statSync(file2).mtimeMs) > LOCK_STALE_MS;
1069
1752
  }
1070
1753
  } catch {
1071
1754
  return void 0;
@@ -1074,20 +1757,20 @@ var takeLock = (file2, afterRead = () => {
1074
1757
  afterRead();
1075
1758
  const aside = `${file2}.break.${process.pid}.${id}`;
1076
1759
  try {
1077
- fs2.renameSync(file2, aside);
1760
+ fs4.renameSync(file2, aside);
1078
1761
  } catch {
1079
1762
  return void 0;
1080
1763
  }
1081
1764
  try {
1082
- if (fs2.readFileSync(aside, "utf8") !== seen) fs2.linkSync(aside, file2);
1765
+ if (fs4.readFileSync(aside, "utf8") !== seen) fs4.linkSync(aside, file2);
1083
1766
  } catch {
1084
1767
  }
1085
- fs2.rmSync(aside, { force: true });
1768
+ fs4.rmSync(aside, { force: true });
1086
1769
  return void 0;
1087
1770
  };
1088
1771
  var dropLock = (file2, id) => {
1089
1772
  try {
1090
- if (JSON.parse(fs2.readFileSync(file2, "utf8")).id === id) fs2.rmSync(file2, { force: true });
1773
+ if (JSON.parse(fs4.readFileSync(file2, "utf8")).id === id) fs4.rmSync(file2, { force: true });
1091
1774
  } catch {
1092
1775
  }
1093
1776
  };
@@ -1099,25 +1782,40 @@ var dial = (endpoint) => new Promise((resolve) => {
1099
1782
  resolve(code === "ECONNREFUSED" ? "stale" : code === "ENOENT" ? "gone" : "alive");
1100
1783
  });
1101
1784
  });
1102
- var recoverSocket = async (endpoint, listen) => {
1785
+ var recoverSocket = async (endpoint, listen, guardMs) => {
1103
1786
  const lockFile = `${endpoint}.lock`;
1104
1787
  const end = Date.now() + RECOVER_MS;
1788
+ const nap = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1105
1789
  while (Date.now() < end) {
1106
1790
  const lock = takeLock(lockFile);
1107
1791
  if (lock === void 0) {
1108
- await new Promise((resolve) => setTimeout(resolve, 20 + Math.random() * 30));
1792
+ await nap(20 + Math.random() * 30);
1109
1793
  if (await dial(endpoint) === "alive") return false;
1110
1794
  continue;
1111
1795
  }
1112
1796
  try {
1113
- const state = await dial(endpoint);
1114
- if (state === "alive") return false;
1115
- if (state === "stale") fs2.rmSync(endpoint, { force: true });
1116
- try {
1117
- await listen();
1118
- return true;
1119
- } catch {
1120
- return false;
1797
+ let refused;
1798
+ for (; ; ) {
1799
+ const state = await dial(endpoint);
1800
+ if (state === "alive") return false;
1801
+ if (state === "stale") {
1802
+ const id = fileId(endpoint);
1803
+ if (id !== void 0) {
1804
+ if (refused?.id !== id) refused = { id, at: Date.now() };
1805
+ if (Date.now() - refused.at < guardMs) {
1806
+ if (Date.now() >= end) return false;
1807
+ await nap(Math.min(25, guardMs));
1808
+ continue;
1809
+ }
1810
+ fs4.rmSync(endpoint, { force: true });
1811
+ }
1812
+ }
1813
+ try {
1814
+ await listen();
1815
+ return true;
1816
+ } catch {
1817
+ return false;
1818
+ }
1121
1819
  }
1122
1820
  } finally {
1123
1821
  dropLock(lockFile, lock);
@@ -1126,11 +1824,11 @@ var recoverSocket = async (endpoint, listen) => {
1126
1824
  return false;
1127
1825
  };
1128
1826
  var adoptKept = async (endpoint) => {
1129
- const dir = path.dirname(endpoint);
1130
- const prefix = `${path.basename(endpoint)}.keep.`;
1827
+ const dir = path3.dirname(endpoint);
1828
+ const prefix = `${path3.basename(endpoint)}.keep.`;
1131
1829
  let names;
1132
1830
  try {
1133
- names = fs2.readdirSync(dir).filter((name) => name.startsWith(prefix));
1831
+ names = fs4.readdirSync(dir).filter((name) => name.startsWith(prefix));
1134
1832
  } catch {
1135
1833
  return false;
1136
1834
  }
@@ -1139,23 +1837,23 @@ var adoptKept = async (endpoint) => {
1139
1837
  const pid = Number(name.slice(prefix.length));
1140
1838
  if (Number.isInteger(pid) && pidAlive(pid)) continue;
1141
1839
  const keep = `${dir}/${name}`;
1142
- if (!adopted && !fs2.existsSync(endpoint) && await dial(keep) === "alive") {
1840
+ if (!adopted && !fs4.existsSync(endpoint) && await dial(keep) === "alive") {
1143
1841
  try {
1144
- fs2.linkSync(keep, endpoint);
1842
+ fs4.linkSync(keep, endpoint);
1145
1843
  adopted = true;
1146
1844
  } catch {
1147
1845
  }
1148
1846
  }
1149
- fs2.rmSync(keep, { force: true });
1847
+ fs4.rmSync(keep, { force: true });
1150
1848
  }
1151
1849
  return adopted;
1152
1850
  };
1153
1851
  var SWEEP_MIN_AGE_MS = 5e3;
1154
1852
  var sweepSockets = async (endpoint) => {
1155
- const dir = path.dirname(endpoint);
1853
+ const dir = path3.dirname(endpoint);
1156
1854
  let names;
1157
1855
  try {
1158
- names = fs2.readdirSync(dir).filter((name) => /^tsm-[0-9a-f]+\.sock$/.test(name));
1856
+ names = fs4.readdirSync(dir).filter((name) => /^tsm-[0-9a-f]+\.sock$/.test(name));
1159
1857
  } catch {
1160
1858
  return;
1161
1859
  }
@@ -1163,11 +1861,11 @@ var sweepSockets = async (endpoint) => {
1163
1861
  const file2 = `${dir}/${name}`;
1164
1862
  if (file2 === endpoint) continue;
1165
1863
  try {
1166
- if (Date.now() - fs2.lstatSync(file2).mtimeMs < SWEEP_MIN_AGE_MS) continue;
1864
+ if (Date.now() - fs4.lstatSync(file2).mtimeMs < SWEEP_MIN_AGE_MS) continue;
1167
1865
  } catch {
1168
1866
  continue;
1169
1867
  }
1170
- if (await dial(file2) === "stale") fs2.rmSync(file2, { force: true });
1868
+ if (await dial(file2) === "stale") fs4.rmSync(file2, { force: true });
1171
1869
  }
1172
1870
  };
1173
1871
  var startBroker = async ({
@@ -1177,15 +1875,19 @@ var startBroker = async ({
1177
1875
  initMs = CHILD_INIT_MS,
1178
1876
  maxLinks = LINKS_MAX,
1179
1877
  maxChildren = CHILDREN_MAX,
1180
- maxUnsent = UNSENT_MAX
1878
+ maxUnsent = UNSENT_MAX,
1879
+ guardMs = SOCKET_GUARD_MS,
1880
+ afterListen,
1881
+ findCommand: find = findCommand
1181
1882
  }) => {
1182
1883
  const dir = brokerFolder(home);
1183
1884
  privateFolder(dir);
1184
1885
  const log = makeLog(`${dir}/broker.log`);
1886
+ const guard = createGuard({ home, log });
1185
1887
  const key = loadKey(home);
1186
1888
  const wire = makeCrypto(key);
1187
1889
  const endpoint = endpointFor(home, key, buildId(file2));
1188
- if (process.platform !== "win32") privateFolder(path.dirname(endpoint));
1890
+ if (process.platform !== "win32") privateFolder(path3.dirname(endpoint));
1189
1891
  const children = /* @__PURE__ */ new Map();
1190
1892
  const sockets = /* @__PURE__ */ new Set();
1191
1893
  let seq = 0;
@@ -1222,6 +1924,7 @@ var startBroker = async ({
1222
1924
  child.proc.once("exit", () => resolve());
1223
1925
  const timer = setTimeout(() => {
1224
1926
  endTree(child.proc);
1927
+ guard.remove(child.proc.pid);
1225
1928
  setTimeout(resolve, 1e3);
1226
1929
  }, STOP_WAIT_MS);
1227
1930
  child.proc.once("exit", () => clearTimeout(timer));
@@ -1251,6 +1954,7 @@ var startBroker = async ({
1251
1954
  // The process group is how the tree of a child ends outside Windows. Windows ends it with taskkill.
1252
1955
  detached: process.platform !== "win32"
1253
1956
  });
1957
+ guard.add(proc.pid);
1254
1958
  const child = {
1255
1959
  id,
1256
1960
  proc,
@@ -1321,22 +2025,28 @@ var startBroker = async ({
1321
2025
  }
1322
2026
  )
1323
2027
  );
1324
- const gone = (why, code) => {
2028
+ const gone = (why, code, exact = false) => {
1325
2029
  if (child.dead) return;
1326
2030
  child.dead = true;
1327
2031
  clearTimeout(timer);
1328
2032
  clearTimeout(flush);
1329
2033
  if (children.get(id) === child) children.delete(id);
1330
2034
  log(`child ${tag(id)} exit ${String(code)}`);
1331
- const reason = `${why}. Run the command of the server by hand in a terminal to see why`;
2035
+ const reason = exact ? why : `${why}. Run the command of the server by hand in a terminal to see why`;
1332
2036
  settle(reason);
1333
2037
  apply(child, router.died());
1334
2038
  for (const conn of child.conns.values()) conn.close(reason);
1335
2039
  child.conns.clear();
1336
2040
  endTree(proc);
2041
+ guard.remove(proc.pid);
1337
2042
  checkEmpty();
1338
2043
  };
1339
- proc.on("error", (err) => gone("the server process could not start", err.code));
2044
+ proc.on("error", (err) => {
2045
+ const code = spawnCode(err);
2046
+ if (code !== void 0 && trustedSpawnError(err, process.platform, () => find(entry.command, entry.env, entry.folder)))
2047
+ gone(spawnReason(entry.command, code), code, true);
2048
+ else gone("the server process could not start", err.code);
2049
+ });
1340
2050
  proc.on("exit", (code) => {
1341
2051
  const end = () => gone(`the server process ended with exit code ${String(code)}`, code);
1342
2052
  if (child.up || proc.stderr === null || proc.stderr.destroyed) return end();
@@ -1437,27 +2147,27 @@ var startBroker = async ({
1437
2147
  socket.end(refusedFrame(`the server process could not start (${shown}). Run its command by hand in a terminal`));
1438
2148
  return;
1439
2149
  }
1440
- const mine2 = child;
1441
- clearTimeout(mine2.idle);
1442
- const waiting = !mine2.up && !mine2.dead;
2150
+ const mine = child;
2151
+ clearTimeout(mine.idle);
2152
+ const waiting = !mine.up && !mine.dead;
1443
2153
  const waiter = { send: () => {
1444
2154
  }, close: () => {
1445
2155
  }, stderr };
1446
2156
  if (waiting) {
1447
- mine2.waiters.add(waiter);
1448
- if (mine2.tail.length > 0) stderr(mine2.tail);
2157
+ mine.waiters.add(waiter);
2158
+ if (mine.tail.length > 0) stderr(mine.tail);
1449
2159
  }
1450
- const reason = await mine2.ready;
1451
- mine2.waiters.delete(waiter);
1452
- if (socket.destroyed) return void (mine2.conns.size === 0 && idleStart(mine2));
1453
- if (reason !== void 0 || mine2.dead) {
1454
- if (!waiting && mine2.tail.length > 0) stderr(mine2.tail);
2160
+ const reason = await mine.ready;
2161
+ mine.waiters.delete(waiter);
2162
+ if (socket.destroyed) return void (mine.conns.size === 0 && idleStart(mine));
2163
+ if (reason !== void 0 || mine.dead) {
2164
+ if (!waiting && mine.tail.length > 0) stderr(mine.tail);
1455
2165
  socket.end(refusedFrame(reason ?? "the server process ended"));
1456
2166
  return;
1457
2167
  }
1458
2168
  const name = `l${++seq}`;
1459
2169
  link = name;
1460
- mine2.conns.set(name, {
2170
+ mine.conns.set(name, {
1461
2171
  // The host reads at most LINE_MAX in a line. A child line under that cap can come out longer once written again
1462
2172
  // (1e9 becomes 1000000000), and then the link ends with the reason instead of a line the host cuts off.
1463
2173
  send: (msg) => {
@@ -1471,11 +2181,11 @@ var startBroker = async ({
1471
2181
  close,
1472
2182
  stderr
1473
2183
  });
1474
- mine2.router.attach(name);
1475
- log(`attach ${tag(id)} links=${mine2.conns.size}`);
2184
+ mine.router.attach(name);
2185
+ log(`attach ${tag(id)} links=${mine.conns.size}`);
1476
2186
  socket.write(attachedFrame);
1477
2187
  stage = "linked";
1478
- for (const line of queue.splice(0)) fromHost(mine2, name, line);
2188
+ for (const line of queue.splice(0)) fromHost(mine, name, line);
1479
2189
  };
1480
2190
  const fromHost = (target, name, line) => {
1481
2191
  const msg = parseFrame(line);
@@ -1536,39 +2246,46 @@ var startBroker = async ({
1536
2246
  child.idle = setTimeout(() => void stopChild(child).then(checkEmpty), idleMs2);
1537
2247
  };
1538
2248
  const server = net.createServer(onConnection);
2249
+ let bound;
1539
2250
  const listen = () => new Promise((resolve, reject) => {
1540
2251
  server.once("error", reject);
1541
2252
  server.listen(endpoint, () => {
1542
2253
  server.off("error", reject);
1543
2254
  resolve();
1544
2255
  });
2256
+ bound = process.platform === "win32" ? void 0 : fileId(endpoint);
1545
2257
  });
1546
2258
  try {
1547
2259
  if (process.platform !== "win32" && await adoptKept(endpoint)) return void 0;
1548
2260
  await listen();
1549
2261
  } catch (err) {
1550
2262
  if (err.code !== "EADDRINUSE") throw err;
1551
- if (process.platform === "win32" || !await recoverSocket(endpoint, listen)) return void 0;
2263
+ if (process.platform === "win32" || !await recoverSocket(endpoint, listen, guardMs)) return void 0;
1552
2264
  }
1553
- const mine = process.platform === "win32" ? void 0 : fileId(endpoint);
1554
2265
  const closeServer = () => {
1555
- const now = mine === void 0 ? void 0 : fileId(endpoint);
1556
- if (now === void 0 || now === mine) return void server.close();
2266
+ const now = bound === void 0 ? void 0 : fileId(endpoint);
2267
+ if (now === void 0 || now === bound) return void server.close();
1557
2268
  const aside = `${endpoint}.keep.${process.pid}`;
1558
2269
  let kept = false;
1559
2270
  try {
1560
- fs2.linkSync(endpoint, aside);
2271
+ fs4.linkSync(endpoint, aside);
1561
2272
  kept = true;
1562
2273
  } catch {
1563
2274
  }
1564
2275
  server.close();
1565
2276
  if (!kept) return;
1566
2277
  try {
1567
- fs2.linkSync(aside, endpoint);
2278
+ fs4.linkSync(aside, endpoint);
1568
2279
  } catch {
1569
2280
  }
1570
- fs2.rmSync(aside, { force: true });
2281
+ fs4.rmSync(aside, { force: true });
1571
2282
  };
2283
+ afterListen?.();
2284
+ if (bound !== void 0 && fileId(endpoint) !== bound) {
2285
+ closeServer();
2286
+ for (const socket of sockets) socket.destroy();
2287
+ return void 0;
2288
+ }
1572
2289
  log(`start pid ${process.pid}`);
1573
2290
  log("listen");
1574
2291
  if (process.platform !== "win32") void sweepSockets(endpoint);
@@ -1577,6 +2294,7 @@ var startBroker = async ({
1577
2294
  clearTimeout(emptyTimer);
1578
2295
  closeServer();
1579
2296
  await Promise.all([...children.values()].map(stopChild));
2297
+ guard.close();
1580
2298
  for (const socket of sockets) socket.destroy();
1581
2299
  log("exit");
1582
2300
  finish();