agentschat-mcp 0.36.25 → 0.36.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +10 -10
  3. package/codex/README.md +4 -4
  4. package/codex/app-server.ts +101 -22
  5. package/codex/bots-config.ts +32 -11
  6. package/codex/bridge.ts +127 -28
  7. package/codex/config.ts +137 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +77 -12
  10. package/codex/loop-grants.ts +49 -11
  11. package/codex/manager.ts +108 -27
  12. package/codex/owner.ts +106 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +51 -11
  16. package/codex/thread-history.ts +87 -30
  17. package/codex/transport.ts +135 -22
  18. package/connector/README.md +1 -1
  19. package/connector/auth.ts +57 -5
  20. package/connector/backfill.ts +92 -10
  21. package/connector/descriptor.ts +27 -1
  22. package/connector/identities.ts +82 -14
  23. package/connector/ingest.ts +11 -2
  24. package/connector/normalize.ts +32 -12
  25. package/connector/run.ts +314 -67
  26. package/connector/server.ts +95 -26
  27. package/cordis.patch.yml +4 -2
  28. package/dist/codex-bots.js +437 -75
  29. package/dist/codex-bridge.js +2111 -582
  30. package/dist/connector.js +1300 -493
  31. package/dist/dsh.js +1789 -299
  32. package/dist/muse.js +967 -221
  33. package/dist/server.js +4410 -919
  34. package/dsh/README.md +1 -1
  35. package/dsh/client.js +7 -5
  36. package/dsh/identity-ui/client.js +7 -5
  37. package/dsh/identity-ui/index.js +43 -8
  38. package/dsh/inbound-bridge/index.js +677 -154
  39. package/dsh/src/cli.ts +430 -91
  40. package/dsh/src/patch.ts +295 -15
  41. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  42. package/dsh/tests/dsh.test.ts +1174 -3
  43. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  44. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  45. package/muse/src/bridge.ts +54 -13
  46. package/muse/src/cli.ts +226 -41
  47. package/muse/src/client.ts +249 -34
  48. package/muse/src/config.ts +128 -12
  49. package/muse/src/policy.ts +28 -8
  50. package/muse/src/types.ts +1 -0
  51. package/muse/src/typing.ts +18 -1
  52. package/muse/src/wake.ts +237 -35
  53. package/muse/tests/bridge.test.mjs +131 -0
  54. package/muse/tests/client.test.mjs +327 -0
  55. package/muse/tests/config.test.mjs +78 -1
  56. package/muse/tests/hardening.test.mjs +199 -0
  57. package/muse/tests/hardening126.test.mjs +292 -0
  58. package/muse/tests/policy.test.mjs +83 -1
  59. package/muse/tests/wake.test.mjs +134 -6
  60. package/package.json +3 -3
  61. package/scripts/ensure-grok-wakes.mjs +93 -8
  62. package/scripts/example-url-wake-receiver.mjs +254 -61
  63. package/scripts/grok-bind-register.sh +38 -8
  64. package/skills/onboarding.md +15 -15
  65. package/src/argcheck.ts +113 -33
  66. package/src/cli.mjs +100 -16
  67. package/src/dedup.ts +57 -8
  68. package/src/grok-bind.ts +182 -33
  69. package/src/heartbeat.ts +39 -11
  70. package/src/identity-guard.ts +93 -20
  71. package/src/identity.ts +67 -11
  72. package/src/mentions.ts +26 -5
  73. package/src/onboarding-status.ts +134 -11
  74. package/src/profile-selection.ts +299 -18
  75. package/src/profile-store.ts +248 -30
  76. package/src/read-cursor.ts +280 -9
  77. package/src/reconnect.ts +98 -2
  78. package/src/redact.ts +34 -15
  79. package/src/rest-cli.ts +713 -159
  80. package/src/server.ts +286 -94
  81. package/src/session-bind.ts +777 -134
  82. package/src/session-route.ts +183 -12
  83. package/src/team-lead-skill.ts +3 -0
  84. package/src/timestamps.ts +56 -23
  85. package/src/tool-annotations.ts +10 -1
  86. package/src/wake.ts +510 -91
@@ -1,28 +1,57 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
+
2
5
  // codex/manager.ts
3
6
  import { spawn } from "node:child_process";
4
- import { mkdirSync as mkdirSync2, openSync, closeSync, readFileSync as readFileSync3, writeFileSync, unlinkSync, existsSync as existsSync2, renameSync } from "node:fs";
5
- import { join as join3, resolve as resolve3 } from "node:path";
7
+ import { mkdirSync as mkdirSync2, openSync, closeSync, readFileSync as readFileSync3, writeFileSync, unlinkSync as unlinkSync2, lstatSync as lstatSync3 } from "node:fs";
8
+ import { join as join3, resolve as resolve3, dirname as dirname3 } from "node:path";
6
9
  import { homedir as homedir3 } from "node:os";
7
10
  import { createHash as createHash2 } from "node:crypto";
11
+ import { fileURLToPath } from "node:url";
8
12
  import { parseArgs } from "node:util";
9
13
 
10
14
  // codex/bots-config.ts
11
- import { readFileSync as readFileSync2, realpathSync as realpathSync2, mkdirSync } from "node:fs";
15
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2, mkdirSync, lstatSync as lstatSync2 } from "node:fs";
12
16
  import { homedir as homedir2 } from "node:os";
13
- import { dirname, isAbsolute as isAbsolute2, join as join2, resolve as resolve2 } from "node:path";
17
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2, resolve as resolve2 } from "node:path";
14
18
 
15
19
  // codex/config.ts
16
- import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
20
+ import { copyFileSync, lstatSync, readFileSync, realpathSync, renameSync, unlinkSync } from "node:fs";
17
21
  import { homedir } from "node:os";
18
- import { isAbsolute, join, resolve } from "node:path";
22
+ import { dirname, isAbsolute, join, parse as parsePath, resolve } from "node:path";
19
23
  import { createHash } from "node:crypto";
20
24
 
25
+ // src/redact.ts
26
+ function redactSecrets(text, opts) {
27
+ if (typeof text !== "string" || !text)
28
+ return "";
29
+ const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
30
+ return step.replace(/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|$)/g, "***PRIVATE_KEY_REDACTED***").replace(/mcp_(?:at|rt|code)_[A-Za-z0-9_-]{16,}/g, "mcp_***REDACTED***").replace(/agent_key_[A-Za-z0-9_-]{12,}/g, "agent_key_***REDACTED***").replace(/whsec_[A-Za-z0-9_-]{12,}/g, "whsec_***REDACTED***").replace(/\bsk-(?:proj-|ant-|live-|test-)?[A-Za-z0-9_-]{16,}/g, "sk-***REDACTED***").replace(/\brk_(?:live|test)_[A-Za-z0-9]{12,}/g, "rk_***REDACTED***").replace(/\bgh[pousr]_[A-Za-z0-9_]{16,}/g, "gh_***REDACTED***").replace(/\bgithub_pat_[A-Za-z0-9_]{16,}/g, "github_pat_***REDACTED***").replace(/\bglpat-[A-Za-z0-9_-]{12,}/g, "glpat-***REDACTED***").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g, "xox-***REDACTED***").replace(/\bhf_[A-Za-z0-9]{20,}/g, "hf_***REDACTED***").replace(/\bnpm_[A-Za-z0-9]{20,}/g, "npm_***REDACTED***").replace(/\bAIza[0-9A-Za-z_-]{20,}/g, "AIza***REDACTED***").replace(/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g, "AKIA***REDACTED***").replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
31
+ }
32
+
21
33
  // src/identity.ts
34
+ var RESERVED_IDENTITY_IDS = new Set(["__proto__", "constructor", "prototype"]);
35
+ var MAX_AGENT_ID_LEN = 128;
36
+ var MAX_CAPABILITIES_LEN = 64;
37
+ var CONTROL_OR_SEP_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
38
+ function isValidProfileAgentId(raw) {
39
+ if (typeof raw !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029/\\\s]/.test(raw) || /(?:%2e|%2f|%5c|%00)/i.test(raw))
40
+ return false;
41
+ const trimmed = raw.trim();
42
+ return trimmed.length > 0 && trimmed === raw && trimmed.length <= MAX_AGENT_ID_LEN && trimmed !== "." && !trimmed.includes("..") && !RESERVED_IDENTITY_IDS.has(trimmed.toLowerCase());
43
+ }
44
+ function sanitizeDiagnosticField(raw, fallback = "(unknown)") {
45
+ if (typeof raw !== "string")
46
+ return fallback;
47
+ const cleaned = redactSecrets(raw).replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]").replace(/\b(?:agent_key_|sk-|whsec_|gh[pousr]_|github_pat_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g, "[REDACTED]").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ").trim();
48
+ return cleaned.length > 0 ? cleaned.slice(0, 256) : fallback;
49
+ }
22
50
  function validateIdentityProfile(profile, file, allowDevToken = false) {
23
- const nonempty = (value) => typeof value === "string" && value.trim().length > 0;
24
- if (!profile || typeof profile !== "object" || Array.isArray(profile) || !nonempty(profile.agent_id) || !nonempty(profile.token) || !allowDevToken && profile.token === "dev-token" || profile.capabilities !== undefined && (!Array.isArray(profile.capabilities) || !profile.capabilities.every(nonempty))) {
25
- throw new Error(`Invalid identity profile at ${file}. Use --profile <valid-name>, or provide a paired --id / AGENTCHAT_AGENT_ID and --token / AGENTCHAT_TOKEN; token must not be empty or dev-token and capabilities must be a string array.`);
51
+ const cleanNonempty = (value) => typeof value === "string" && value.trim().length > 0 && value.length <= 4096 && !CONTROL_OR_SEP_RE.test(value);
52
+ const safeFile = sanitizeDiagnosticField(file, "(unknown-path)");
53
+ if (!profile || typeof profile !== "object" || Array.isArray(profile) || Object.prototype.hasOwnProperty.call(profile, "__proto__") || !isValidProfileAgentId(profile.agent_id) || !cleanNonempty(profile.token) || !allowDevToken && profile.token.trim() === "dev-token" || profile.capabilities !== undefined && (!Array.isArray(profile.capabilities) || profile.capabilities.length > MAX_CAPABILITIES_LEN || !profile.capabilities.every((c) => cleanNonempty(c) && c.length <= 64))) {
54
+ throw new Error(`Invalid identity profile at ${safeFile}. Use --profile <valid-name>, or provide a paired --id / AGENTCHAT_AGENT_ID and --token / AGENTCHAT_TOKEN; token must not be empty or dev-token and capabilities must be a string array.`);
26
55
  }
27
56
  }
28
57
 
@@ -903,18 +932,61 @@ function parse(toml, { maxDepth = 1000, integersAsBigInt } = {}) {
903
932
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
904
933
  */
905
934
 
935
+ // codex/owner.ts
936
+ var OWNER_FORBIDDEN_KEYS = new Set([
937
+ "__proto__",
938
+ "prototype",
939
+ ...Object.getOwnPropertyNames(Object.prototype),
940
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
941
+ ]);
942
+ function blockedServerHost(url) {
943
+ const host = url.hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
944
+ if (!host || host === "0.0.0.0" || /^0\./.test(host) || host === "::" || host === "0:0:0:0:0:0:0:0" || /^169\.254\./.test(host) || host === "100.100.100.200" || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}$/.test(host) || host === "fd00:ec2::254" || host === "fd00:ec2:0:0:0:0:0:254" || host === "metadata" || host === "instance-data" || host === "metadata.google.internal" || host.endsWith(".metadata.google.internal") || host === "metadata.goog" || host.endsWith(".metadata.goog") || /^fe[89ab][0-9a-f]:/.test(host)) {
945
+ return true;
946
+ }
947
+ if (host.startsWith("::ffff:")) {
948
+ const rawTail = host.slice(7);
949
+ if (rawTail === "0:0" || rawTail === "0.0.0.0")
950
+ return true;
951
+ const tail = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(rawTail) ? rawTail.slice(2) : rawTail;
952
+ if (tail === "0:0" || tail === "0.0.0.0" || /^0\./.test(tail) || /^[0-9a-f]{1,2}:[0-9a-f]{1,4}$/.test(tail) || /^127\./.test(tail) || /^7f[0-9a-f]{2}:/.test(tail) || /^169\.254\./.test(tail) || /^a9fe:/.test(tail) || tail === "100.100.100.200" || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}$/.test(tail) || tail === "6464:64c8") {
953
+ return true;
954
+ }
955
+ const hexMatch = tail.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
956
+ if (hexMatch) {
957
+ const hi = parseInt(hexMatch[1], 16);
958
+ const lo = parseInt(hexMatch[2], 16);
959
+ const firstOctet = hi >> 8 & 255;
960
+ const secondOctet = hi & 255;
961
+ if (firstOctet === 0 || firstOctet === 127 || firstOctet === 169 && secondOctet === 254 || firstOctet === 100 && (secondOctet & 192) === 64 || hi === 25700 && lo === 25800) {
962
+ return true;
963
+ }
964
+ }
965
+ }
966
+ return false;
967
+ }
968
+
906
969
  // codex/config.ts
970
+ var CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
971
+ var PROTO_KEY_RE = /^(?:__proto__|constructor|prototype)$/i;
972
+ var RESERVED_OBJECT_STEMS = new Set([
973
+ "__proto__",
974
+ "constructor",
975
+ "prototype",
976
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
977
+ ]);
978
+ var WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
907
979
  function reasoningEffort(value) {
908
980
  if (value === undefined)
909
981
  return;
910
- if (typeof value !== "string" || !value.trim())
982
+ if (typeof value !== "string" || !value.trim() || value.trim().length > 64 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
911
983
  throw new Error("effort must be a nonempty model-supported reasoning effort name");
912
984
  return value.trim();
913
985
  }
914
986
  function modelName(value) {
915
987
  if (value === undefined)
916
988
  return;
917
- if (typeof value !== "string" || !value.trim())
989
+ if (typeof value !== "string" || !value.trim() || value.trim().length > 256 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
918
990
  throw new Error("model must be a nonempty model ID");
919
991
  return value.trim();
920
992
  }
@@ -932,26 +1004,134 @@ function codexHomeMode(value) {
932
1004
  throw new Error("codex_home_mode must be linked, isolated or auth-only");
933
1005
  return value;
934
1006
  }
1007
+ var MAX_CONFIG_BYTES = 1048576;
1008
+ function reservedProfileStem(selector) {
1009
+ const stem = selector.replace(/\.json$/i, "").toLowerCase();
1010
+ return RESERVED_OBJECT_STEMS.has(stem) || WINDOWS_DEVICE_STEM_RE.test(stem) || [
1011
+ "grok-binds",
1012
+ "session-binds",
1013
+ "agy-binds",
1014
+ "cursor",
1015
+ "read-cursors",
1016
+ "wake-pids",
1017
+ "config",
1018
+ "codex-bots"
1019
+ ].includes(stem);
1020
+ }
1021
+ function checkSingleAncestorDir(path) {
1022
+ const stat = lstatSync(path, { throwIfNoEntry: false });
1023
+ if (!stat)
1024
+ return;
1025
+ if (stat.isSymbolicLink()) {
1026
+ const target = `/private${path}`;
1027
+ if (process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(path) && realpathSync(path) === target) {
1028
+ const priv = lstatSync("/private", { throwIfNoEntry: false });
1029
+ if (!priv || priv.isSymbolicLink() || !priv.isDirectory()) {
1030
+ throw new Error("Config path must be a non-symlink directory: /private");
1031
+ }
1032
+ assertDirectoryAncestors(target);
1033
+ return;
1034
+ }
1035
+ throw new Error(`Config path must be a non-symlink directory: ${path}`);
1036
+ }
1037
+ if (!stat.isDirectory())
1038
+ throw new Error(`Config path must be a non-symlink directory: ${path}`);
1039
+ }
1040
+ function assertDirectoryAncestors(directory) {
1041
+ if (typeof directory !== "string" || !directory.trim() || CONTROL_CHAR_RE.test(directory)) {
1042
+ throw new Error(`Config path must be a non-symlink directory: ${String(directory)}`);
1043
+ }
1044
+ if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(directory)) {
1045
+ let cur;
1046
+ let remainder;
1047
+ if (isAbsolute(directory)) {
1048
+ const root = parsePath(directory).root || "/";
1049
+ cur = root;
1050
+ remainder = directory.slice(root.length);
1051
+ checkSingleAncestorDir(cur);
1052
+ } else {
1053
+ const base = resolve(process.cwd());
1054
+ assertDirectoryAncestors(base);
1055
+ cur = base;
1056
+ remainder = directory;
1057
+ }
1058
+ for (const seg of remainder.split(/[\\/]+/)) {
1059
+ if (!seg || seg === ".")
1060
+ continue;
1061
+ cur = seg === ".." ? dirname(cur) : join(cur, seg);
1062
+ checkSingleAncestorDir(cur);
1063
+ }
1064
+ }
1065
+ const paths = [];
1066
+ for (let path = resolve(directory);; path = dirname(path)) {
1067
+ paths.unshift(path);
1068
+ if (dirname(path) === path)
1069
+ break;
1070
+ }
1071
+ for (const path of paths)
1072
+ checkSingleAncestorDir(path);
1073
+ }
1074
+ function atomicReplaceRegularFile(tmp, target, verifySafeTarget, opts) {
1075
+ verifySafeTarget();
1076
+ const rename = opts?.rename ?? renameSync;
1077
+ const platform = opts?.platform ?? process.platform;
1078
+ try {
1079
+ rename(tmp, target);
1080
+ } catch (err) {
1081
+ if (platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
1082
+ verifySafeTarget();
1083
+ copyFileSync(tmp, target);
1084
+ unlinkSync(tmp);
1085
+ return;
1086
+ }
1087
+ throw err;
1088
+ }
1089
+ }
1090
+ function checkedPath(path, directory = false) {
1091
+ assertDirectoryAncestors(dirname(path));
1092
+ let stat;
1093
+ try {
1094
+ stat = lstatSync(path);
1095
+ } catch (error) {
1096
+ if (error.code === "ENOENT")
1097
+ return;
1098
+ throw error;
1099
+ }
1100
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
1101
+ throw new Error(directory ? `Config directory must be a non-symlink directory: ${path}` : `Selected profile is not a regular file: ${path}`);
1102
+ if (!directory && stat.size > MAX_CONFIG_BYTES)
1103
+ throw new Error(`Config file exceeds 1 MiB: ${path}`);
1104
+ return stat;
1105
+ }
935
1106
  function readJson(file) {
1107
+ let value;
936
1108
  try {
937
- return JSON.parse(readFileSync(file, "utf8"));
1109
+ value = JSON.parse(readFileSync(file, "utf8"));
938
1110
  } catch {
939
1111
  throw new Error(`Cannot read valid JSON: ${file}`);
940
1112
  }
1113
+ if (value && typeof value === "object" && Object.hasOwn(value, "__proto__"))
1114
+ throw new Error("Invalid JSON prototype key");
1115
+ return value;
941
1116
  }
942
1117
  function strings(value, name) {
943
1118
  if (value === undefined)
944
1119
  return [];
945
- if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim()))
1120
+ if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim() || CONTROL_CHAR_RE.test(x)))
946
1121
  throw new Error(`${name} must be an array of nonempty strings`);
947
1122
  return value;
948
1123
  }
949
1124
  function resolveConfig(opts, env = process.env, home = homedir()) {
1125
+ assertDirectoryAncestors(opts.cwd ?? process.cwd());
950
1126
  const cwd = realpathSync(opts.cwd ?? process.cwd());
951
1127
  const configFile = join(cwd, ".agentschat/config.json");
952
- const project = opts.settings ?? (existsSync(configFile) ? readJson(configFile) : {});
1128
+ if (opts.settings === undefined)
1129
+ checkedPath(join(cwd, ".agentschat"), true);
1130
+ const project = opts.settings ?? (checkedPath(configFile) ? readJson(configFile) : {});
953
1131
  if (!project || typeof project !== "object" || Array.isArray(project))
954
1132
  throw new Error("Invalid project config");
1133
+ if (["__proto__", "constructor", "prototype"].some((key2) => Object.hasOwn(project, key2)))
1134
+ throw new Error("Invalid project config prototype key");
955
1135
  const allowed = new Set(["profile", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
956
1136
  if (Object.keys(project).some((k) => !allowed.has(k)))
957
1137
  throw new Error("Unknown project config field (credentials belong in a private profile)");
@@ -961,7 +1141,9 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
961
1141
  const localProfile = join(cwd, ".agentschat/profile.json");
962
1142
  let codexProfile;
963
1143
  const codexFile = join(cwd, ".codex/config.toml");
964
- if (opts.settings === undefined && existsSync(codexFile)) {
1144
+ if (opts.settings === undefined)
1145
+ checkedPath(join(cwd, ".codex"), true);
1146
+ if (opts.settings === undefined && checkedPath(codexFile)) {
965
1147
  let doc;
966
1148
  try {
967
1149
  doc = parse(readFileSync(codexFile, "utf8"));
@@ -981,29 +1163,38 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
981
1163
  const choices = [
982
1164
  [opts.profile, "flag"],
983
1165
  [project.profile, "project-config"],
984
- [opts.settings === undefined && existsSync(localProfile) ? localProfile : undefined, "project-profile"],
1166
+ [opts.settings === undefined && checkedPath(localProfile) ? localProfile : undefined, "project-profile"],
985
1167
  [codexProfile, "project-codex"],
986
1168
  [env.AGENTSCHAT_PROFILE, "env"],
987
1169
  [env.AGENTCHAT_PROFILE, "legacy-env"],
988
1170
  ["profile", "default"]
989
1171
  ];
990
1172
  const [selector, source] = choices.find(([v]) => v !== undefined && v !== "");
1173
+ if (typeof selector !== "string" || CONTROL_CHAR_RE.test(selector))
1174
+ throw new Error("Invalid profile selector");
991
1175
  let profileFile;
992
- if (selector.startsWith("~/"))
1176
+ if (/^~[\\/]/.test(selector))
993
1177
  profileFile = join(home, selector.slice(2));
994
- else if (isAbsolute(selector) || selector.includes("/"))
1178
+ else if (isAbsolute(selector) || selector.includes("/") || selector.includes("\\"))
995
1179
  profileFile = resolve(cwd, selector);
996
1180
  else {
997
- const name = selector.endsWith(".json") ? selector : `${selector}.json`;
1181
+ const stem = selector.replace(/\.json$/i, "");
1182
+ if (!stem || selector.includes("..") || reservedProfileStem(selector)) {
1183
+ throw new Error("Invalid central profile selector");
1184
+ }
1185
+ const name = /\.json$/i.test(selector) ? selector : `${selector}.json`;
998
1186
  profileFile = join(home, ".agentschat/profiles", name);
999
- if (!existsSync(profileFile))
1187
+ if (!checkedPath(profileFile))
1000
1188
  profileFile = join(home, ".agentschat", name);
1001
- if (!existsSync(profileFile))
1189
+ if (!checkedPath(profileFile))
1002
1190
  profileFile = join(home, ".agentchat", name);
1003
1191
  }
1004
- if (!existsSync(profileFile))
1192
+ if (!checkedPath(profileFile))
1005
1193
  throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
1006
- if (process.platform !== "win32" && statSync(profileFile).mode & 63)
1194
+ const profileStat = checkedPath(profileFile);
1195
+ if (!profileStat.isFile())
1196
+ throw new Error(`Selected profile is not a regular file: ${profileFile}`);
1197
+ if (process.platform !== "win32" && profileStat.mode & 63)
1007
1198
  throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
1008
1199
  const profile = readJson(profileFile);
1009
1200
  validateIdentityProfile(profile, profileFile);
@@ -1013,15 +1204,18 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
1013
1204
  const wsUrl = project.ws_url ?? `${apiUrl.replace(/^http/, "ws").replace(/\/$/, "")}/ws`;
1014
1205
  for (const [raw, protocols] of [[apiUrl, ["https:", "http:"]], [wsUrl, ["wss:", "ws:"]]]) {
1015
1206
  const url = new URL(raw);
1016
- if (!protocols.includes(url.protocol) || url.username || url.password || url.search || url.hash || !url.protocol.endsWith("s:") && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))
1207
+ if (blockedServerHost(url) || !protocols.includes(url.protocol) || url.username || url.password || url.search || url.hash || url.port === "0" || !url.protocol.endsWith("s:") && !["127.0.0.1", "localhost", "[::1]", "::1"].includes(url.hostname.toLowerCase().replace(/\.$/, "")))
1017
1208
  throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
1018
1209
  }
1019
1210
  const canonicalApi = new URL(apiUrl).href.replace(/\/$/, "");
1020
1211
  const key = createHash("sha256").update(JSON.stringify([cwd, canonicalApi, profile.agent_id])).digest("hex").slice(0, 24);
1021
1212
  const root = opts.stateRoot ?? project.state_root;
1022
- if (root !== undefined && (typeof root !== "string" || !root.trim()))
1213
+ if (root !== undefined && (typeof root !== "string" || !root.trim() || CONTROL_CHAR_RE.test(root)))
1023
1214
  throw new Error("Invalid state_root");
1024
- const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : root.startsWith("~/") ? join(home, root.slice(2)) : resolve(cwd, root);
1215
+ const codexBin = opts.codexBin ?? "codex";
1216
+ if (typeof codexBin !== "string" || !codexBin.trim() || CONTROL_CHAR_RE.test(codexBin))
1217
+ throw new Error("Invalid codex_bin");
1218
+ const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : /^~[\\/]/.test(root) ? join(home, root.slice(2)) : resolve(cwd, root);
1025
1219
  return {
1026
1220
  cwd,
1027
1221
  profileFile,
@@ -1036,7 +1230,7 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
1036
1230
  wsUrl,
1037
1231
  channels: strings(project.channels, "channels"),
1038
1232
  senders: strings(project.senders, "senders"),
1039
- codexBin: opts.codexBin ?? "codex",
1233
+ codexBin,
1040
1234
  stateDir: join(stateRoot, key)
1041
1235
  };
1042
1236
  }
@@ -1046,31 +1240,37 @@ function defaultRegistry(home = homedir2()) {
1046
1240
  return join2(home, ".agentschat/codex-bots.json");
1047
1241
  }
1048
1242
  function loadBots(file = defaultRegistry(), home = homedir2()) {
1243
+ assertDirectoryAncestors(dirname2(file));
1049
1244
  let doc;
1050
1245
  try {
1246
+ const info = lstatSync2(file);
1247
+ if (info.isSymbolicLink() || !info.isFile() || info.size > 1048576)
1248
+ throw new Error("Invalid registry file");
1051
1249
  doc = JSON.parse(readFileSync2(file, "utf8"));
1052
1250
  } catch {
1053
1251
  throw new Error("Cannot read bot registry JSON");
1054
1252
  }
1055
1253
  const object = (x) => x && typeof x === "object" && !Array.isArray(x);
1056
1254
  const fields = (x, keys) => {
1057
- if (!object(x) || Object.keys(x).some((k) => !keys.includes(k)))
1255
+ if (!object(x) || Object.getOwnPropertyNames(x).some((k) => !keys.includes(k)))
1058
1256
  throw new Error("Unknown or invalid bot registry field");
1059
1257
  };
1060
- const text = (x) => typeof x === "string" && x.trim().length > 0;
1258
+ const text = (x, max = 4096) => typeof x === "string" && x.trim().length > 0 && x.length <= max && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(x);
1259
+ const reservedNames = new Set(["__proto__", "constructor", "prototype", ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())]);
1260
+ const reserved = (s) => reservedNames.has(s.toLowerCase());
1061
1261
  fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
1062
- if (doc.version !== 1 || !Array.isArray(doc.bots))
1262
+ if (doc.version !== 1 || !Array.isArray(doc.bots) || doc.bots.length > 128)
1063
1263
  throw new Error("Registry requires version 1 and bots array");
1064
1264
  for (const k of ["default_workdir", "codex_bin"])
1065
1265
  if (doc[k] !== undefined && !text(doc[k]))
1066
1266
  throw new Error(`Invalid ${k}`);
1067
- const path = (value) => value.startsWith("~/") ? join2(home, value.slice(2)) : isAbsolute2(value) ? value : resolve2(dirname(file), value);
1267
+ const path = (value) => /^~[\\/]/.test(value) ? join2(home, value.slice(2)) : isAbsolute2(value) ? value : resolve2(dirname2(file), value);
1068
1268
  const defaultDir = doc.default_workdir ? path(doc.default_workdir) : join2(home, ".agentschat/workspace");
1069
1269
  const names = new Set, identities = new Set;
1070
1270
  const bots = [];
1071
1271
  for (const bot of doc.bots) {
1072
1272
  fields(bot, ["name", "profile", "workdir", "enabled", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
1073
- if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || names.has(bot.name))
1273
+ if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || reserved(bot.name) || names.has(bot.name))
1074
1274
  throw new Error("Bot names must be unique simple labels");
1075
1275
  names.add(bot.name);
1076
1276
  if (bot.enabled !== undefined && typeof bot.enabled !== "boolean")
@@ -1079,11 +1279,23 @@ function loadBots(file = defaultRegistry(), home = homedir2()) {
1079
1279
  continue;
1080
1280
  if (!text(bot.profile) || bot.workdir !== undefined && !text(bot.workdir))
1081
1281
  throw new Error(`Bot ${bot.name} needs a profile and valid optional workdir`);
1082
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile))
1282
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile) || bot.profile.includes("..") || reservedProfileStem(bot.profile)) {
1083
1283
  throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
1084
- if (!doc.default_workdir && !bot.workdir)
1284
+ }
1285
+ const directoryLeaf = (dir) => {
1286
+ const info = lstatSync2(dir, { throwIfNoEntry: false });
1287
+ if (info && (info.isSymbolicLink() || !info.isDirectory()))
1288
+ throw new Error("Bot workdir must be a directory, not a symlink");
1289
+ assertDirectoryAncestors(dir);
1290
+ };
1291
+ if (!doc.default_workdir && !bot.workdir) {
1292
+ directoryLeaf(join2(home, ".agentschat"));
1293
+ directoryLeaf(defaultDir);
1085
1294
  mkdirSync(defaultDir, { recursive: true, mode: 448 });
1086
- const cwd = realpathSync2(bot.workdir ? path(bot.workdir) : defaultDir);
1295
+ }
1296
+ const workdir = bot.workdir ? path(bot.workdir) : defaultDir;
1297
+ directoryLeaf(workdir);
1298
+ const cwd = realpathSync2(workdir);
1087
1299
  const settings = {};
1088
1300
  for (const k of ["agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "codex_home_mode"])
1089
1301
  if (bot[k] !== undefined)
@@ -1106,95 +1318,201 @@ function loadBots(file = defaultRegistry(), home = homedir2()) {
1106
1318
  // codex/processes.ts
1107
1319
  import { execFile } from "node:child_process";
1108
1320
  import { promisify } from "node:util";
1109
- import { basename } from "node:path";
1110
1321
  function parseProcesses(text) {
1111
- return text.split(`
1112
- `).flatMap((line) => {
1322
+ if (typeof text !== "string" || !text)
1323
+ return [];
1324
+ return text.split(/\r?\n/, 65536).flatMap((line) => {
1325
+ if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(line))
1326
+ return [];
1113
1327
  const m = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
1114
- return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), command: m[3].trim() }] : [];
1328
+ if (!m)
1329
+ return [];
1330
+ const pid = Number(m[1]), ppid = Number(m[2]);
1331
+ return Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(ppid) && ppid >= 0 ? [{ pid, ppid, command: m[3].trim() }] : [];
1115
1332
  });
1116
1333
  }
1334
+ function commandBasename(cmd) {
1335
+ const trimmed = cmd.trim();
1336
+ const basename = (path) => (path.split(/[\\/]/).pop() || "").trim().replace(/\.(?:exe|cmd|bat)$/i, "").toLowerCase();
1337
+ if (trimmed.startsWith('"')) {
1338
+ const end = trimmed.indexOf('"', 1);
1339
+ return end < 0 ? "" : basename(trimmed.slice(1, end));
1340
+ }
1341
+ const first = trimmed.split(/\s+/, 1)[0];
1342
+ return basename(first) === "codex" ? "codex" : basename(trimmed);
1343
+ }
1117
1344
  function externalCodexPresent(rows, managerPid) {
1118
- const children = new Set([managerPid]);
1119
- let changed = true;
1120
- while (changed) {
1121
- changed = false;
1122
- for (const row of rows)
1123
- if (children.has(row.ppid) && !children.has(row.pid)) {
1124
- children.add(row.pid);
1125
- changed = true;
1126
- }
1345
+ if (!Array.isArray(rows) || rows.length === 0)
1346
+ return false;
1347
+ const children = new Set(Number.isSafeInteger(managerPid) && managerPid > 0 ? [managerPid] : []);
1348
+ const byParent = new Map;
1349
+ for (const row of rows) {
1350
+ if (!row || !Number.isSafeInteger(row.pid) || row.pid <= 0)
1351
+ continue;
1352
+ const ppid = row.ppid;
1353
+ if (!Number.isSafeInteger(ppid) || ppid < 0)
1354
+ continue;
1355
+ const siblings = byParent.get(ppid);
1356
+ if (siblings)
1357
+ siblings.push(row.pid);
1358
+ else
1359
+ byParent.set(ppid, [row.pid]);
1360
+ }
1361
+ const queue = [...children];
1362
+ for (let i = 0;i < queue.length; i++) {
1363
+ for (const pid of byParent.get(queue[i]) ?? []) {
1364
+ if (children.has(pid))
1365
+ continue;
1366
+ children.add(pid);
1367
+ queue.push(pid);
1368
+ }
1127
1369
  }
1128
- return rows.some((r) => !children.has(r.pid) && basename(r.command) === "codex");
1370
+ return rows.some((r) => Boolean(r) && typeof r.command === "string" && Number.isSafeInteger(r.pid) && r.pid > 0 && !children.has(r.pid) && commandBasename(r.command) === "codex");
1129
1371
  }
1130
1372
  async function codexPresent(managerPid = process.pid) {
1373
+ if (process.platform === "win32") {
1374
+ const { stdout: stdout2 } = await promisify(execFile)("powershell.exe", [
1375
+ "-NoProfile",
1376
+ "-NonInteractive",
1377
+ "-ExecutionPolicy",
1378
+ "Bypass",
1379
+ "-Command",
1380
+ 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId) $($_.Name)" }'
1381
+ ], { timeout: 5000, maxBuffer: 4 * 1024 * 1024, windowsHide: true });
1382
+ return externalCodexPresent(parseProcesses(stdout2), managerPid);
1383
+ }
1131
1384
  const { stdout } = await promisify(execFile)("/bin/ps", ["-axo", "pid=,ppid=,comm="], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 });
1132
1385
  return externalCodexPresent(parseProcesses(stdout), managerPid);
1133
1386
  }
1134
1387
 
1135
1388
  // codex/manager.ts
1136
- var { values } = parseArgs({ options: { "codex-bots": { type: "boolean" }, config: { type: "string" }, "watch-codex": { type: "boolean" }, check: { type: "boolean" }, status: { type: "boolean" }, help: { type: "boolean" } } });
1389
+ var values = {};
1137
1390
  var root = join3(homedir3(), ".agentschat/codex-bots");
1138
- var registry = resolve3(values.config ?? defaultRegistry());
1391
+ var registry = "";
1139
1392
  var statusFile = join3(root, "status.json");
1140
1393
  var lock = join3(root, "manager.lock");
1141
1394
  var workers = new Map;
1142
1395
  var stopping = false;
1143
1396
  var missing = 0;
1397
+ var saveSeq = 0;
1144
1398
  var timer;
1145
1399
  function removeDeadLock(file) {
1146
- if (!existsSync2(file))
1400
+ let raw;
1401
+ try {
1402
+ assertDirectoryAncestors(dirname3(file));
1403
+ const stat = lstatSync3(file);
1404
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 64 * 1024)
1405
+ return;
1406
+ raw = readFileSync3(file, "utf8").trim();
1407
+ } catch {
1147
1408
  return;
1148
- const pid = Number(readFileSync3(file, "utf8"));
1149
- if (!Number.isInteger(pid) || pid <= 0)
1409
+ }
1410
+ const pid = Number(raw);
1411
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(pid) || pid <= 0) {
1412
+ try {
1413
+ unlinkSync2(file);
1414
+ } catch {}
1150
1415
  return;
1416
+ }
1151
1417
  try {
1152
1418
  process.kill(pid, 0);
1153
1419
  } catch (e) {
1154
1420
  if (e.code === "ESRCH")
1155
- unlinkSync(file);
1421
+ try {
1422
+ unlinkSync2(file);
1423
+ } catch {}
1156
1424
  }
1157
1425
  }
1158
- function save() {
1159
- writeFileSync(statusFile + ".tmp", JSON.stringify({ pid: process.pid, updated_at: new Date().toISOString(), bots: [...workers.values()].map((w) => ({ name: w.config.name, agent_id: w.config.agentId, workdir: w.config.cwd, effort: w.config.effort, model: w.config.model, pid: w.child?.pid, status: w.status })) }, null, 2), { mode: 384 });
1160
- renameSync(statusFile + ".tmp", statusFile);
1426
+ function save(rootDir = root) {
1427
+ const statusFile2 = join3(rootDir, "status.json");
1428
+ const tmp = `${statusFile2}.${process.pid}.${++saveSeq}.tmp`;
1429
+ let created = false;
1430
+ try {
1431
+ assertDirectoryAncestors(rootDir);
1432
+ const dir = lstatSync3(rootDir);
1433
+ if (dir.isSymbolicLink() || !dir.isDirectory())
1434
+ return;
1435
+ try {
1436
+ if (lstatSync3(statusFile2).isSymbolicLink())
1437
+ return;
1438
+ } catch (e) {
1439
+ if (e.code !== "ENOENT")
1440
+ return;
1441
+ }
1442
+ writeFileSync(tmp, JSON.stringify({ pid: process.pid, updated_at: new Date().toISOString(), bots: [...workers.values()].map((w) => ({ name: w.config.name, agent_id: w.config.agentId, workdir: w.config.cwd, effort: w.config.effort, model: w.config.model, pid: w.child?.pid, status: w.status })) }, null, 2), { mode: 384, flag: "wx" });
1443
+ created = true;
1444
+ atomicReplaceRegularFile(tmp, statusFile2, () => {
1445
+ assertDirectoryAncestors(rootDir);
1446
+ const currentDir = lstatSync3(rootDir);
1447
+ const currentFile = lstatSync3(statusFile2, { throwIfNoEntry: false });
1448
+ if (currentDir.isSymbolicLink() || !currentDir.isDirectory() || currentFile && (currentFile.isSymbolicLink() || !currentFile.isFile()))
1449
+ throw new Error("Unsafe status destination");
1450
+ });
1451
+ } catch {
1452
+ if (created)
1453
+ try {
1454
+ unlinkSync2(tmp);
1455
+ } catch {}
1456
+ }
1161
1457
  }
1162
1458
  async function stop(w) {
1163
1459
  const child = w.child;
1164
1460
  if (child && child.exitCode === null && child.signalCode === null)
1165
1461
  await new Promise((done) => {
1166
1462
  const timeout = setTimeout(() => killGroup(child), 20000);
1167
- child.once("exit", () => {
1463
+ timeout.unref?.();
1464
+ const exited = () => {
1168
1465
  clearTimeout(timeout);
1169
1466
  killGroup(child);
1170
1467
  done();
1171
- });
1172
- child.kill("SIGTERM");
1468
+ };
1469
+ child.once("exit", exited);
1470
+ try {
1471
+ child.kill("SIGTERM");
1472
+ } catch {
1473
+ clearTimeout(timeout);
1474
+ child.removeListener("exit", exited);
1475
+ done();
1476
+ }
1173
1477
  });
1174
1478
  w.child = undefined;
1175
1479
  w.status = "stopped";
1176
1480
  }
1177
1481
  function killGroup(child) {
1178
- if (child.pid)
1482
+ if (!child.pid)
1483
+ return;
1484
+ if (process.platform !== "win32") {
1179
1485
  try {
1180
1486
  process.kill(-child.pid, "SIGKILL");
1487
+ return;
1181
1488
  } catch {}
1489
+ }
1490
+ try {
1491
+ child.kill("SIGKILL");
1492
+ } catch {}
1182
1493
  }
1183
- function start(w) {
1494
+ function start(w, spawnWorker = spawn) {
1184
1495
  removeDeadLock(join3(w.config.stateDir, "bridge.lock"));
1185
1496
  w.status = "starting";
1186
- const child = spawn(process.execPath, [resolve3(process.argv[1]), "--codex-bridge", "--managed-worker"], { cwd: w.config.cwd, detached: true, stdio: ["ignore", "pipe", "pipe", "ipc"] });
1497
+ const child = spawnWorker(process.execPath, [resolve3(process.argv[1]), "--codex-bridge", "--managed-worker"], { cwd: w.config.cwd, detached: process.platform !== "win32", windowsHide: true, stdio: ["ignore", "pipe", "pipe", "ipc"] });
1187
1498
  w.child = child;
1188
- child.once("spawn", () => child.send(w.config, () => {}));
1499
+ child.once("spawn", () => {
1500
+ if (child.connected)
1501
+ try {
1502
+ child.send(w.config, () => {});
1503
+ } catch {}
1504
+ });
1189
1505
  let buffer = "";
1506
+ const escapedAgentId = w.config.agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1507
+ const connectedRe = new RegExp(`(?:^|[\\r\\n])AgentsChat connected as ${escapedAgentId}(?![A-Za-z0-9_.-])`);
1190
1508
  child.stderr?.on("data", (data) => {
1191
1509
  buffer = (buffer + String(data)).slice(-8192);
1192
- if (buffer.includes(`AgentsChat connected as ${w.config.agentId}`)) {
1510
+ if (connectedRe.test(buffer)) {
1193
1511
  w.status = "connected";
1194
1512
  w.failures = 0;
1195
1513
  buffer = "";
1196
1514
  save();
1197
- } else if (buffer.includes("disconnected")) {
1515
+ } else if (/(?:^|[\r\n]).*\bdisconnected\b/i.test(buffer)) {
1198
1516
  w.status = "reconnecting";
1199
1517
  buffer = "";
1200
1518
  save();
@@ -1242,13 +1560,24 @@ async function tick() {
1242
1560
  for (const w of workers.values()) {
1243
1561
  if (stopping)
1244
1562
  break;
1245
- if (active && !w.child && Date.now() >= w.next)
1563
+ const now = Date.now();
1564
+ if (w.next - now > 60000)
1565
+ w.next = now + 60000;
1566
+ if (active && !w.child && now >= w.next)
1246
1567
  start(w);
1247
1568
  else if (!active && missing >= 2 && w.child)
1248
1569
  await stop(w);
1249
1570
  }
1250
1571
  save();
1251
1572
  }
1573
+ function removeOwnedLock(file) {
1574
+ try {
1575
+ assertDirectoryAncestors(dirname3(file));
1576
+ const stat = lstatSync3(file);
1577
+ if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 && readFileSync3(file, "utf8").trim() === String(process.pid))
1578
+ unlinkSync2(file);
1579
+ } catch {}
1580
+ }
1252
1581
  async function main() {
1253
1582
  if (values.help) {
1254
1583
  console.log(`agentschat-mcp --codex-bots [--config FILE] [--watch-codex] [--check|--status]
@@ -1257,7 +1586,19 @@ Watch polls external Codex processes every 5 seconds.`);
1257
1586
  return;
1258
1587
  }
1259
1588
  if (values.status) {
1260
- console.log(readFileSync3(statusFile, "utf8"));
1589
+ try {
1590
+ assertDirectoryAncestors(root);
1591
+ const stat = lstatSync3(statusFile);
1592
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1048576)
1593
+ throw new Error("Unsafe status file");
1594
+ const raw = readFileSync3(statusFile, "utf8"), status = JSON.parse(raw);
1595
+ if (!status || typeof status !== "object" || Array.isArray(status) || Object.prototype.hasOwnProperty.call(status, "__proto__") || status.pid !== undefined && (typeof status.pid !== "number" || !Number.isSafeInteger(status.pid) || status.pid <= 0) || !Array.isArray(status.bots) || status.bots.some((b) => !b || typeof b !== "object" || Array.isArray(b) || Object.prototype.hasOwnProperty.call(b, "__proto__")))
1596
+ throw new Error("Invalid status file");
1597
+ console.log(raw);
1598
+ } catch {
1599
+ console.error("Bot manager status unavailable; status file is missing, unsafe, or unreadable");
1600
+ process.exitCode = 1;
1601
+ }
1261
1602
  return;
1262
1603
  }
1263
1604
  const configs = loadBots(registry);
@@ -1265,8 +1606,19 @@ Watch polls external Codex processes every 5 seconds.`);
1265
1606
  console.log(JSON.stringify(configs.map((c) => ({ name: c.name, agent_id: c.agentId, workdir: c.cwd, profile: c.profileFile }))));
1266
1607
  return;
1267
1608
  }
1609
+ for (const directory of [join3(homedir3(), ".agentschat"), root]) {
1610
+ const stat = lstatSync3(directory, { throwIfNoEntry: false });
1611
+ if (stat && (stat.isSymbolicLink() || !stat.isDirectory()))
1612
+ throw new Error("Unsafe manager directory");
1613
+ }
1614
+ assertDirectoryAncestors(root);
1268
1615
  mkdirSync2(root, { recursive: true, mode: 448 });
1616
+ const dir = lstatSync3(root);
1617
+ if (dir.isSymbolicLink() || !dir.isDirectory())
1618
+ throw new Error("Unsafe manager directory");
1269
1619
  removeDeadLock(lock);
1620
+ if (lstatSync3(lock, { throwIfNoEntry: false })?.isSymbolicLink())
1621
+ throw new Error("Unsafe manager lock");
1270
1622
  const fd = openSync(lock, "wx", 384);
1271
1623
  writeFileSync(fd, String(process.pid));
1272
1624
  closeSync(fd);
@@ -1285,14 +1637,24 @@ Watch polls external Codex processes every 5 seconds.`);
1285
1637
  await running;
1286
1638
  await Promise.all([...workers.values()].map(stop));
1287
1639
  save();
1288
- if (readFileSync3(lock, "utf8") === String(process.pid))
1289
- unlinkSync(lock);
1640
+ removeOwnedLock(lock);
1290
1641
  };
1291
1642
  process.once("SIGINT", () => void shutdown());
1292
1643
  process.once("SIGTERM", () => void shutdown());
1293
1644
  loop();
1294
1645
  }
1295
- main().catch(() => {
1296
- console.error("Bot manager failed; check registry, profile permissions, and existing manager");
1297
- process.exitCode = 1;
1298
- });
1646
+ if (__require.main == __require.module || process.argv.includes("--codex-bots") || process.argv[1] && resolve3(process.argv[1]) === fileURLToPath(import.meta.url)) {
1647
+ ({ values } = parseArgs({ options: { "codex-bots": { type: "boolean" }, config: { type: "string" }, "watch-codex": { type: "boolean" }, check: { type: "boolean" }, status: { type: "boolean" }, help: { type: "boolean" } } }));
1648
+ registry = resolve3(values.config ?? defaultRegistry());
1649
+ main().catch(() => {
1650
+ console.error("Bot manager failed; check registry, profile permissions, and existing manager");
1651
+ process.exitCode = 1;
1652
+ });
1653
+ }
1654
+ export {
1655
+ stop,
1656
+ start,
1657
+ save,
1658
+ removeOwnedLock,
1659
+ removeDeadLock
1660
+ };