agentschat-mcp 0.36.24 → 0.36.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +8 -0
- package/codex/README.md +1 -1
- package/codex/app-server.ts +79 -22
- package/codex/bots-config.ts +31 -11
- package/codex/bridge.ts +123 -25
- package/codex/config.ts +128 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +65 -12
- package/codex/loop-grants.ts +41 -11
- package/codex/manager.ts +101 -25
- package/codex/owner.ts +81 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +41 -11
- package/codex/thread-history.ts +77 -30
- package/codex/transport.ts +122 -19
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/dist/codex-bots.js +410 -73
- package/dist/codex-bridge.js +1996 -576
- package/dist/connector.js +1286 -493
- package/dist/dsh.js +1776 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +7645 -1172
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +595 -146
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +990 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +3 -3
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/agentschat-team-lead/SKILL.md +1 -1
- package/skills/onboarding.md +14 -10
- package/src/argcheck.ts +1890 -1
- package/src/cli.mjs +98 -14
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +160 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +269 -18
- package/src/profile-store.ts +222 -28
- package/src/read-cursor.ts +256 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +2487 -342
- package/src/session-bind.ts +731 -132
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +22 -1
- package/src/wake.ts +524 -90
package/dist/codex-bots.js
CHANGED
|
@@ -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,
|
|
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 {
|
|
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
|
|
24
|
-
|
|
25
|
-
|
|
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,37 @@ 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
|
+
function blockedServerHost(url) {
|
|
937
|
+
const host = url.hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
|
|
938
|
+
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" || 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)) {
|
|
939
|
+
return true;
|
|
940
|
+
}
|
|
941
|
+
if (host.startsWith("::ffff:")) {
|
|
942
|
+
const rawTail = host.slice(7);
|
|
943
|
+
if (rawTail === "0:0" || rawTail === "0.0.0.0")
|
|
944
|
+
return true;
|
|
945
|
+
const tail = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(rawTail) ? rawTail.slice(2) : rawTail;
|
|
946
|
+
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" || tail === "6464:64c8") {
|
|
947
|
+
return true;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
return false;
|
|
951
|
+
}
|
|
952
|
+
|
|
906
953
|
// codex/config.ts
|
|
954
|
+
var CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
907
955
|
function reasoningEffort(value) {
|
|
908
956
|
if (value === undefined)
|
|
909
957
|
return;
|
|
910
|
-
if (typeof value !== "string" || !value.trim())
|
|
958
|
+
if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
|
|
911
959
|
throw new Error("effort must be a nonempty model-supported reasoning effort name");
|
|
912
960
|
return value.trim();
|
|
913
961
|
}
|
|
914
962
|
function modelName(value) {
|
|
915
963
|
if (value === undefined)
|
|
916
964
|
return;
|
|
917
|
-
if (typeof value !== "string" || !value.trim())
|
|
965
|
+
if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
|
|
918
966
|
throw new Error("model must be a nonempty model ID");
|
|
919
967
|
return value.trim();
|
|
920
968
|
}
|
|
@@ -932,26 +980,136 @@ function codexHomeMode(value) {
|
|
|
932
980
|
throw new Error("codex_home_mode must be linked, isolated or auth-only");
|
|
933
981
|
return value;
|
|
934
982
|
}
|
|
983
|
+
var MAX_CONFIG_BYTES = 1048576;
|
|
984
|
+
function reservedProfileStem(selector) {
|
|
985
|
+
return [
|
|
986
|
+
"__proto__",
|
|
987
|
+
"constructor",
|
|
988
|
+
"prototype",
|
|
989
|
+
"grok-binds",
|
|
990
|
+
"session-binds",
|
|
991
|
+
"agy-binds",
|
|
992
|
+
"cursor",
|
|
993
|
+
"read-cursors",
|
|
994
|
+
"wake-pids",
|
|
995
|
+
"config",
|
|
996
|
+
"codex-bots"
|
|
997
|
+
].includes(selector.replace(/\.json$/i, "").toLowerCase());
|
|
998
|
+
}
|
|
999
|
+
function checkSingleAncestorDir(path) {
|
|
1000
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
1001
|
+
if (!stat)
|
|
1002
|
+
return;
|
|
1003
|
+
if (stat.isSymbolicLink()) {
|
|
1004
|
+
const target = `/private${path}`;
|
|
1005
|
+
if (process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(path) && realpathSync(path) === target) {
|
|
1006
|
+
const priv = lstatSync("/private", { throwIfNoEntry: false });
|
|
1007
|
+
if (!priv || priv.isSymbolicLink() || !priv.isDirectory()) {
|
|
1008
|
+
throw new Error("Config path must be a non-symlink directory: /private");
|
|
1009
|
+
}
|
|
1010
|
+
assertDirectoryAncestors(target);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
throw new Error(`Config path must be a non-symlink directory: ${path}`);
|
|
1014
|
+
}
|
|
1015
|
+
if (!stat.isDirectory())
|
|
1016
|
+
throw new Error(`Config path must be a non-symlink directory: ${path}`);
|
|
1017
|
+
}
|
|
1018
|
+
function assertDirectoryAncestors(directory) {
|
|
1019
|
+
if (typeof directory !== "string" || !directory.trim() || CONTROL_CHAR_RE.test(directory)) {
|
|
1020
|
+
throw new Error(`Config path must be a non-symlink directory: ${String(directory)}`);
|
|
1021
|
+
}
|
|
1022
|
+
if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(directory)) {
|
|
1023
|
+
let cur;
|
|
1024
|
+
let remainder;
|
|
1025
|
+
if (isAbsolute(directory)) {
|
|
1026
|
+
const root = parsePath(directory).root || "/";
|
|
1027
|
+
cur = root;
|
|
1028
|
+
remainder = directory.slice(root.length);
|
|
1029
|
+
checkSingleAncestorDir(cur);
|
|
1030
|
+
} else {
|
|
1031
|
+
const base = resolve(process.cwd());
|
|
1032
|
+
assertDirectoryAncestors(base);
|
|
1033
|
+
cur = base;
|
|
1034
|
+
remainder = directory;
|
|
1035
|
+
}
|
|
1036
|
+
for (const seg of remainder.split(/[\\/]+/)) {
|
|
1037
|
+
if (!seg || seg === ".")
|
|
1038
|
+
continue;
|
|
1039
|
+
cur = seg === ".." ? dirname(cur) : join(cur, seg);
|
|
1040
|
+
checkSingleAncestorDir(cur);
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
const paths = [];
|
|
1044
|
+
for (let path = resolve(directory);; path = dirname(path)) {
|
|
1045
|
+
paths.unshift(path);
|
|
1046
|
+
if (dirname(path) === path)
|
|
1047
|
+
break;
|
|
1048
|
+
}
|
|
1049
|
+
for (const path of paths)
|
|
1050
|
+
checkSingleAncestorDir(path);
|
|
1051
|
+
}
|
|
1052
|
+
function atomicReplaceRegularFile(tmp, target, verifySafeTarget, opts) {
|
|
1053
|
+
verifySafeTarget();
|
|
1054
|
+
const rename = opts?.rename ?? renameSync;
|
|
1055
|
+
const platform = opts?.platform ?? process.platform;
|
|
1056
|
+
try {
|
|
1057
|
+
rename(tmp, target);
|
|
1058
|
+
} catch (err) {
|
|
1059
|
+
if (platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
|
|
1060
|
+
verifySafeTarget();
|
|
1061
|
+
copyFileSync(tmp, target);
|
|
1062
|
+
unlinkSync(tmp);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
throw err;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
function checkedPath(path, directory = false) {
|
|
1069
|
+
assertDirectoryAncestors(dirname(path));
|
|
1070
|
+
let stat;
|
|
1071
|
+
try {
|
|
1072
|
+
stat = lstatSync(path);
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
if (error.code === "ENOENT")
|
|
1075
|
+
return;
|
|
1076
|
+
throw error;
|
|
1077
|
+
}
|
|
1078
|
+
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
|
|
1079
|
+
throw new Error(directory ? `Config directory must be a non-symlink directory: ${path}` : `Selected profile is not a regular file: ${path}`);
|
|
1080
|
+
if (!directory && stat.size > MAX_CONFIG_BYTES)
|
|
1081
|
+
throw new Error(`Config file exceeds 1 MiB: ${path}`);
|
|
1082
|
+
return stat;
|
|
1083
|
+
}
|
|
935
1084
|
function readJson(file) {
|
|
1085
|
+
let value;
|
|
936
1086
|
try {
|
|
937
|
-
|
|
1087
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
938
1088
|
} catch {
|
|
939
1089
|
throw new Error(`Cannot read valid JSON: ${file}`);
|
|
940
1090
|
}
|
|
1091
|
+
if (value && typeof value === "object" && Object.hasOwn(value, "__proto__"))
|
|
1092
|
+
throw new Error("Invalid JSON prototype key");
|
|
1093
|
+
return value;
|
|
941
1094
|
}
|
|
942
1095
|
function strings(value, name) {
|
|
943
1096
|
if (value === undefined)
|
|
944
1097
|
return [];
|
|
945
|
-
if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim()))
|
|
1098
|
+
if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim() || CONTROL_CHAR_RE.test(x)))
|
|
946
1099
|
throw new Error(`${name} must be an array of nonempty strings`);
|
|
947
1100
|
return value;
|
|
948
1101
|
}
|
|
949
1102
|
function resolveConfig(opts, env = process.env, home = homedir()) {
|
|
1103
|
+
assertDirectoryAncestors(opts.cwd ?? process.cwd());
|
|
950
1104
|
const cwd = realpathSync(opts.cwd ?? process.cwd());
|
|
951
1105
|
const configFile = join(cwd, ".agentschat/config.json");
|
|
952
|
-
|
|
1106
|
+
if (opts.settings === undefined)
|
|
1107
|
+
checkedPath(join(cwd, ".agentschat"), true);
|
|
1108
|
+
const project = opts.settings ?? (checkedPath(configFile) ? readJson(configFile) : {});
|
|
953
1109
|
if (!project || typeof project !== "object" || Array.isArray(project))
|
|
954
1110
|
throw new Error("Invalid project config");
|
|
1111
|
+
if (["__proto__", "constructor", "prototype"].some((key2) => Object.hasOwn(project, key2)))
|
|
1112
|
+
throw new Error("Invalid project config prototype key");
|
|
955
1113
|
const allowed = new Set(["profile", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
|
|
956
1114
|
if (Object.keys(project).some((k) => !allowed.has(k)))
|
|
957
1115
|
throw new Error("Unknown project config field (credentials belong in a private profile)");
|
|
@@ -961,7 +1119,9 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
|
|
|
961
1119
|
const localProfile = join(cwd, ".agentschat/profile.json");
|
|
962
1120
|
let codexProfile;
|
|
963
1121
|
const codexFile = join(cwd, ".codex/config.toml");
|
|
964
|
-
if (opts.settings === undefined
|
|
1122
|
+
if (opts.settings === undefined)
|
|
1123
|
+
checkedPath(join(cwd, ".codex"), true);
|
|
1124
|
+
if (opts.settings === undefined && checkedPath(codexFile)) {
|
|
965
1125
|
let doc;
|
|
966
1126
|
try {
|
|
967
1127
|
doc = parse(readFileSync(codexFile, "utf8"));
|
|
@@ -981,29 +1141,38 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
|
|
|
981
1141
|
const choices = [
|
|
982
1142
|
[opts.profile, "flag"],
|
|
983
1143
|
[project.profile, "project-config"],
|
|
984
|
-
[opts.settings === undefined &&
|
|
1144
|
+
[opts.settings === undefined && checkedPath(localProfile) ? localProfile : undefined, "project-profile"],
|
|
985
1145
|
[codexProfile, "project-codex"],
|
|
986
1146
|
[env.AGENTSCHAT_PROFILE, "env"],
|
|
987
1147
|
[env.AGENTCHAT_PROFILE, "legacy-env"],
|
|
988
1148
|
["profile", "default"]
|
|
989
1149
|
];
|
|
990
1150
|
const [selector, source] = choices.find(([v]) => v !== undefined && v !== "");
|
|
1151
|
+
if (typeof selector !== "string" || CONTROL_CHAR_RE.test(selector))
|
|
1152
|
+
throw new Error("Invalid profile selector");
|
|
991
1153
|
let profileFile;
|
|
992
|
-
if (selector
|
|
1154
|
+
if (/^~[\\/]/.test(selector))
|
|
993
1155
|
profileFile = join(home, selector.slice(2));
|
|
994
|
-
else if (isAbsolute(selector) || selector.includes("/"))
|
|
1156
|
+
else if (isAbsolute(selector) || selector.includes("/") || selector.includes("\\"))
|
|
995
1157
|
profileFile = resolve(cwd, selector);
|
|
996
1158
|
else {
|
|
997
|
-
const
|
|
1159
|
+
const stem = selector.replace(/\.json$/i, "");
|
|
1160
|
+
if (!stem || selector.includes("..") || reservedProfileStem(selector)) {
|
|
1161
|
+
throw new Error("Invalid central profile selector");
|
|
1162
|
+
}
|
|
1163
|
+
const name = /\.json$/i.test(selector) ? selector : `${selector}.json`;
|
|
998
1164
|
profileFile = join(home, ".agentschat/profiles", name);
|
|
999
|
-
if (!
|
|
1165
|
+
if (!checkedPath(profileFile))
|
|
1000
1166
|
profileFile = join(home, ".agentschat", name);
|
|
1001
|
-
if (!
|
|
1167
|
+
if (!checkedPath(profileFile))
|
|
1002
1168
|
profileFile = join(home, ".agentchat", name);
|
|
1003
1169
|
}
|
|
1004
|
-
if (!
|
|
1170
|
+
if (!checkedPath(profileFile))
|
|
1005
1171
|
throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
|
|
1006
|
-
|
|
1172
|
+
const profileStat = checkedPath(profileFile);
|
|
1173
|
+
if (!profileStat.isFile())
|
|
1174
|
+
throw new Error(`Selected profile is not a regular file: ${profileFile}`);
|
|
1175
|
+
if (process.platform !== "win32" && profileStat.mode & 63)
|
|
1007
1176
|
throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
|
|
1008
1177
|
const profile = readJson(profileFile);
|
|
1009
1178
|
validateIdentityProfile(profile, profileFile);
|
|
@@ -1013,15 +1182,18 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
|
|
|
1013
1182
|
const wsUrl = project.ws_url ?? `${apiUrl.replace(/^http/, "ws").replace(/\/$/, "")}/ws`;
|
|
1014
1183
|
for (const [raw, protocols] of [[apiUrl, ["https:", "http:"]], [wsUrl, ["wss:", "ws:"]]]) {
|
|
1015
1184
|
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))
|
|
1185
|
+
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
1186
|
throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
|
|
1018
1187
|
}
|
|
1019
1188
|
const canonicalApi = new URL(apiUrl).href.replace(/\/$/, "");
|
|
1020
1189
|
const key = createHash("sha256").update(JSON.stringify([cwd, canonicalApi, profile.agent_id])).digest("hex").slice(0, 24);
|
|
1021
1190
|
const root = opts.stateRoot ?? project.state_root;
|
|
1022
|
-
if (root !== undefined && (typeof root !== "string" || !root.trim()))
|
|
1191
|
+
if (root !== undefined && (typeof root !== "string" || !root.trim() || CONTROL_CHAR_RE.test(root)))
|
|
1023
1192
|
throw new Error("Invalid state_root");
|
|
1024
|
-
const
|
|
1193
|
+
const codexBin = opts.codexBin ?? "codex";
|
|
1194
|
+
if (typeof codexBin !== "string" || !codexBin.trim() || CONTROL_CHAR_RE.test(codexBin))
|
|
1195
|
+
throw new Error("Invalid codex_bin");
|
|
1196
|
+
const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : /^~[\\/]/.test(root) ? join(home, root.slice(2)) : resolve(cwd, root);
|
|
1025
1197
|
return {
|
|
1026
1198
|
cwd,
|
|
1027
1199
|
profileFile,
|
|
@@ -1036,7 +1208,7 @@ function resolveConfig(opts, env = process.env, home = homedir()) {
|
|
|
1036
1208
|
wsUrl,
|
|
1037
1209
|
channels: strings(project.channels, "channels"),
|
|
1038
1210
|
senders: strings(project.senders, "senders"),
|
|
1039
|
-
codexBin
|
|
1211
|
+
codexBin,
|
|
1040
1212
|
stateDir: join(stateRoot, key)
|
|
1041
1213
|
};
|
|
1042
1214
|
}
|
|
@@ -1046,31 +1218,36 @@ function defaultRegistry(home = homedir2()) {
|
|
|
1046
1218
|
return join2(home, ".agentschat/codex-bots.json");
|
|
1047
1219
|
}
|
|
1048
1220
|
function loadBots(file = defaultRegistry(), home = homedir2()) {
|
|
1221
|
+
assertDirectoryAncestors(dirname2(file));
|
|
1049
1222
|
let doc;
|
|
1050
1223
|
try {
|
|
1224
|
+
const info = lstatSync2(file);
|
|
1225
|
+
if (info.isSymbolicLink() || !info.isFile() || info.size > 1048576)
|
|
1226
|
+
throw new Error("Invalid registry file");
|
|
1051
1227
|
doc = JSON.parse(readFileSync2(file, "utf8"));
|
|
1052
1228
|
} catch {
|
|
1053
1229
|
throw new Error("Cannot read bot registry JSON");
|
|
1054
1230
|
}
|
|
1055
1231
|
const object = (x) => x && typeof x === "object" && !Array.isArray(x);
|
|
1056
1232
|
const fields = (x, keys) => {
|
|
1057
|
-
if (!object(x) || Object.
|
|
1233
|
+
if (!object(x) || Object.getOwnPropertyNames(x).some((k) => !keys.includes(k)))
|
|
1058
1234
|
throw new Error("Unknown or invalid bot registry field");
|
|
1059
1235
|
};
|
|
1060
|
-
const text = (x) => typeof x === "string" && x.trim().length > 0;
|
|
1236
|
+
const text = (x) => typeof x === "string" && x.trim().length > 0 && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(x);
|
|
1237
|
+
const reserved = (s) => ["__proto__", "constructor", "prototype"].includes(s.toLowerCase());
|
|
1061
1238
|
fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
|
|
1062
|
-
if (doc.version !== 1 || !Array.isArray(doc.bots))
|
|
1239
|
+
if (doc.version !== 1 || !Array.isArray(doc.bots) || doc.bots.length > 128)
|
|
1063
1240
|
throw new Error("Registry requires version 1 and bots array");
|
|
1064
1241
|
for (const k of ["default_workdir", "codex_bin"])
|
|
1065
1242
|
if (doc[k] !== undefined && !text(doc[k]))
|
|
1066
1243
|
throw new Error(`Invalid ${k}`);
|
|
1067
|
-
const path = (value) => value
|
|
1244
|
+
const path = (value) => /^~[\\/]/.test(value) ? join2(home, value.slice(2)) : isAbsolute2(value) ? value : resolve2(dirname2(file), value);
|
|
1068
1245
|
const defaultDir = doc.default_workdir ? path(doc.default_workdir) : join2(home, ".agentschat/workspace");
|
|
1069
1246
|
const names = new Set, identities = new Set;
|
|
1070
1247
|
const bots = [];
|
|
1071
1248
|
for (const bot of doc.bots) {
|
|
1072
1249
|
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))
|
|
1250
|
+
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
1251
|
throw new Error("Bot names must be unique simple labels");
|
|
1075
1252
|
names.add(bot.name);
|
|
1076
1253
|
if (bot.enabled !== undefined && typeof bot.enabled !== "boolean")
|
|
@@ -1079,11 +1256,23 @@ function loadBots(file = defaultRegistry(), home = homedir2()) {
|
|
|
1079
1256
|
continue;
|
|
1080
1257
|
if (!text(bot.profile) || bot.workdir !== undefined && !text(bot.workdir))
|
|
1081
1258
|
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))
|
|
1259
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile) || bot.profile.includes("..") || reservedProfileStem(bot.profile)) {
|
|
1083
1260
|
throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
|
|
1084
|
-
|
|
1261
|
+
}
|
|
1262
|
+
const directoryLeaf = (dir) => {
|
|
1263
|
+
const info = lstatSync2(dir, { throwIfNoEntry: false });
|
|
1264
|
+
if (info && (info.isSymbolicLink() || !info.isDirectory()))
|
|
1265
|
+
throw new Error("Bot workdir must be a directory, not a symlink");
|
|
1266
|
+
assertDirectoryAncestors(dir);
|
|
1267
|
+
};
|
|
1268
|
+
if (!doc.default_workdir && !bot.workdir) {
|
|
1269
|
+
directoryLeaf(join2(home, ".agentschat"));
|
|
1270
|
+
directoryLeaf(defaultDir);
|
|
1085
1271
|
mkdirSync(defaultDir, { recursive: true, mode: 448 });
|
|
1086
|
-
|
|
1272
|
+
}
|
|
1273
|
+
const workdir = bot.workdir ? path(bot.workdir) : defaultDir;
|
|
1274
|
+
directoryLeaf(workdir);
|
|
1275
|
+
const cwd = realpathSync2(workdir);
|
|
1087
1276
|
const settings = {};
|
|
1088
1277
|
for (const k of ["agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "codex_home_mode"])
|
|
1089
1278
|
if (bot[k] !== undefined)
|
|
@@ -1106,86 +1295,190 @@ function loadBots(file = defaultRegistry(), home = homedir2()) {
|
|
|
1106
1295
|
// codex/processes.ts
|
|
1107
1296
|
import { execFile } from "node:child_process";
|
|
1108
1297
|
import { promisify } from "node:util";
|
|
1109
|
-
import { basename } from "node:path";
|
|
1110
1298
|
function parseProcesses(text) {
|
|
1111
|
-
|
|
1112
|
-
|
|
1299
|
+
if (typeof text !== "string" || !text)
|
|
1300
|
+
return [];
|
|
1301
|
+
return text.split(/\r?\n/, 65536).flatMap((line) => {
|
|
1302
|
+
if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(line))
|
|
1303
|
+
return [];
|
|
1113
1304
|
const m = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
|
|
1114
|
-
|
|
1305
|
+
if (!m)
|
|
1306
|
+
return [];
|
|
1307
|
+
const pid = Number(m[1]), ppid = Number(m[2]);
|
|
1308
|
+
return Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(ppid) && ppid >= 0 ? [{ pid, ppid, command: m[3].trim() }] : [];
|
|
1115
1309
|
});
|
|
1116
1310
|
}
|
|
1311
|
+
function commandBasename(cmd) {
|
|
1312
|
+
const trimmed = cmd.trim();
|
|
1313
|
+
const basename = (path) => (path.split(/[\\/]/).pop() || "").trim().replace(/\.(?:exe|cmd|bat)$/i, "").toLowerCase();
|
|
1314
|
+
if (trimmed.startsWith('"')) {
|
|
1315
|
+
const end = trimmed.indexOf('"', 1);
|
|
1316
|
+
return end < 0 ? "" : basename(trimmed.slice(1, end));
|
|
1317
|
+
}
|
|
1318
|
+
const first = trimmed.split(/\s+/, 1)[0];
|
|
1319
|
+
return basename(first) === "codex" ? "codex" : basename(trimmed);
|
|
1320
|
+
}
|
|
1117
1321
|
function externalCodexPresent(rows, managerPid) {
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1322
|
+
if (!Array.isArray(rows) || rows.length === 0)
|
|
1323
|
+
return false;
|
|
1324
|
+
const children = new Set(Number.isSafeInteger(managerPid) && managerPid > 0 ? [managerPid] : []);
|
|
1325
|
+
const byParent = new Map;
|
|
1326
|
+
for (const row of rows) {
|
|
1327
|
+
if (!row || !Number.isSafeInteger(row.pid) || row.pid <= 0)
|
|
1328
|
+
continue;
|
|
1329
|
+
const ppid = row.ppid;
|
|
1330
|
+
if (!Number.isSafeInteger(ppid) || ppid < 0)
|
|
1331
|
+
continue;
|
|
1332
|
+
const siblings = byParent.get(ppid);
|
|
1333
|
+
if (siblings)
|
|
1334
|
+
siblings.push(row.pid);
|
|
1335
|
+
else
|
|
1336
|
+
byParent.set(ppid, [row.pid]);
|
|
1127
1337
|
}
|
|
1128
|
-
|
|
1338
|
+
const queue = [...children];
|
|
1339
|
+
for (let i = 0;i < queue.length; i++) {
|
|
1340
|
+
for (const pid of byParent.get(queue[i]) ?? []) {
|
|
1341
|
+
if (children.has(pid))
|
|
1342
|
+
continue;
|
|
1343
|
+
children.add(pid);
|
|
1344
|
+
queue.push(pid);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
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
1348
|
}
|
|
1130
1349
|
async function codexPresent(managerPid = process.pid) {
|
|
1350
|
+
if (process.platform === "win32") {
|
|
1351
|
+
const { stdout: stdout2 } = await promisify(execFile)("powershell.exe", [
|
|
1352
|
+
"-NoProfile",
|
|
1353
|
+
"-NonInteractive",
|
|
1354
|
+
"-ExecutionPolicy",
|
|
1355
|
+
"Bypass",
|
|
1356
|
+
"-Command",
|
|
1357
|
+
'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId) $($_.Name)" }'
|
|
1358
|
+
], { timeout: 5000, maxBuffer: 4 * 1024 * 1024, windowsHide: true });
|
|
1359
|
+
return externalCodexPresent(parseProcesses(stdout2), managerPid);
|
|
1360
|
+
}
|
|
1131
1361
|
const { stdout } = await promisify(execFile)("/bin/ps", ["-axo", "pid=,ppid=,comm="], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 });
|
|
1132
1362
|
return externalCodexPresent(parseProcesses(stdout), managerPid);
|
|
1133
1363
|
}
|
|
1134
1364
|
|
|
1135
1365
|
// codex/manager.ts
|
|
1136
|
-
var
|
|
1366
|
+
var values = {};
|
|
1137
1367
|
var root = join3(homedir3(), ".agentschat/codex-bots");
|
|
1138
|
-
var registry =
|
|
1368
|
+
var registry = "";
|
|
1139
1369
|
var statusFile = join3(root, "status.json");
|
|
1140
1370
|
var lock = join3(root, "manager.lock");
|
|
1141
1371
|
var workers = new Map;
|
|
1142
1372
|
var stopping = false;
|
|
1143
1373
|
var missing = 0;
|
|
1374
|
+
var saveSeq = 0;
|
|
1144
1375
|
var timer;
|
|
1145
1376
|
function removeDeadLock(file) {
|
|
1146
|
-
|
|
1377
|
+
let raw;
|
|
1378
|
+
try {
|
|
1379
|
+
assertDirectoryAncestors(dirname3(file));
|
|
1380
|
+
const stat = lstatSync3(file);
|
|
1381
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 64 * 1024)
|
|
1382
|
+
return;
|
|
1383
|
+
raw = readFileSync3(file, "utf8").trim();
|
|
1384
|
+
} catch {
|
|
1147
1385
|
return;
|
|
1148
|
-
|
|
1149
|
-
|
|
1386
|
+
}
|
|
1387
|
+
const pid = Number(raw);
|
|
1388
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(pid) || pid <= 0) {
|
|
1389
|
+
try {
|
|
1390
|
+
unlinkSync2(file);
|
|
1391
|
+
} catch {}
|
|
1150
1392
|
return;
|
|
1393
|
+
}
|
|
1151
1394
|
try {
|
|
1152
1395
|
process.kill(pid, 0);
|
|
1153
1396
|
} catch (e) {
|
|
1154
1397
|
if (e.code === "ESRCH")
|
|
1155
|
-
|
|
1398
|
+
try {
|
|
1399
|
+
unlinkSync2(file);
|
|
1400
|
+
} catch {}
|
|
1156
1401
|
}
|
|
1157
1402
|
}
|
|
1158
|
-
function save() {
|
|
1159
|
-
|
|
1160
|
-
|
|
1403
|
+
function save(rootDir = root) {
|
|
1404
|
+
const statusFile2 = join3(rootDir, "status.json");
|
|
1405
|
+
const tmp = `${statusFile2}.${process.pid}.${++saveSeq}.tmp`;
|
|
1406
|
+
let created = false;
|
|
1407
|
+
try {
|
|
1408
|
+
assertDirectoryAncestors(rootDir);
|
|
1409
|
+
const dir = lstatSync3(rootDir);
|
|
1410
|
+
if (dir.isSymbolicLink() || !dir.isDirectory())
|
|
1411
|
+
return;
|
|
1412
|
+
try {
|
|
1413
|
+
if (lstatSync3(statusFile2).isSymbolicLink())
|
|
1414
|
+
return;
|
|
1415
|
+
} catch (e) {
|
|
1416
|
+
if (e.code !== "ENOENT")
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
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" });
|
|
1420
|
+
created = true;
|
|
1421
|
+
atomicReplaceRegularFile(tmp, statusFile2, () => {
|
|
1422
|
+
assertDirectoryAncestors(rootDir);
|
|
1423
|
+
const currentDir = lstatSync3(rootDir);
|
|
1424
|
+
const currentFile = lstatSync3(statusFile2, { throwIfNoEntry: false });
|
|
1425
|
+
if (currentDir.isSymbolicLink() || !currentDir.isDirectory() || currentFile && (currentFile.isSymbolicLink() || !currentFile.isFile()))
|
|
1426
|
+
throw new Error("Unsafe status destination");
|
|
1427
|
+
});
|
|
1428
|
+
} catch {
|
|
1429
|
+
if (created)
|
|
1430
|
+
try {
|
|
1431
|
+
unlinkSync2(tmp);
|
|
1432
|
+
} catch {}
|
|
1433
|
+
}
|
|
1161
1434
|
}
|
|
1162
1435
|
async function stop(w) {
|
|
1163
1436
|
const child = w.child;
|
|
1164
1437
|
if (child && child.exitCode === null && child.signalCode === null)
|
|
1165
1438
|
await new Promise((done) => {
|
|
1166
1439
|
const timeout = setTimeout(() => killGroup(child), 20000);
|
|
1167
|
-
|
|
1440
|
+
timeout.unref?.();
|
|
1441
|
+
const exited = () => {
|
|
1168
1442
|
clearTimeout(timeout);
|
|
1169
1443
|
killGroup(child);
|
|
1170
1444
|
done();
|
|
1171
|
-
}
|
|
1172
|
-
child.
|
|
1445
|
+
};
|
|
1446
|
+
child.once("exit", exited);
|
|
1447
|
+
try {
|
|
1448
|
+
child.kill("SIGTERM");
|
|
1449
|
+
} catch {
|
|
1450
|
+
clearTimeout(timeout);
|
|
1451
|
+
child.removeListener("exit", exited);
|
|
1452
|
+
done();
|
|
1453
|
+
}
|
|
1173
1454
|
});
|
|
1174
1455
|
w.child = undefined;
|
|
1175
1456
|
w.status = "stopped";
|
|
1176
1457
|
}
|
|
1177
1458
|
function killGroup(child) {
|
|
1178
|
-
if (child.pid)
|
|
1459
|
+
if (!child.pid)
|
|
1460
|
+
return;
|
|
1461
|
+
if (process.platform !== "win32") {
|
|
1179
1462
|
try {
|
|
1180
1463
|
process.kill(-child.pid, "SIGKILL");
|
|
1464
|
+
return;
|
|
1181
1465
|
} catch {}
|
|
1466
|
+
}
|
|
1467
|
+
try {
|
|
1468
|
+
child.kill("SIGKILL");
|
|
1469
|
+
} catch {}
|
|
1182
1470
|
}
|
|
1183
|
-
function start(w) {
|
|
1471
|
+
function start(w, spawnWorker = spawn) {
|
|
1184
1472
|
removeDeadLock(join3(w.config.stateDir, "bridge.lock"));
|
|
1185
1473
|
w.status = "starting";
|
|
1186
|
-
const child =
|
|
1474
|
+
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
1475
|
w.child = child;
|
|
1188
|
-
child.once("spawn", () =>
|
|
1476
|
+
child.once("spawn", () => {
|
|
1477
|
+
if (child.connected)
|
|
1478
|
+
try {
|
|
1479
|
+
child.send(w.config, () => {});
|
|
1480
|
+
} catch {}
|
|
1481
|
+
});
|
|
1189
1482
|
let buffer = "";
|
|
1190
1483
|
child.stderr?.on("data", (data) => {
|
|
1191
1484
|
buffer = (buffer + String(data)).slice(-8192);
|
|
@@ -1242,13 +1535,24 @@ async function tick() {
|
|
|
1242
1535
|
for (const w of workers.values()) {
|
|
1243
1536
|
if (stopping)
|
|
1244
1537
|
break;
|
|
1245
|
-
|
|
1538
|
+
const now = Date.now();
|
|
1539
|
+
if (w.next - now > 60000)
|
|
1540
|
+
w.next = now + 60000;
|
|
1541
|
+
if (active && !w.child && now >= w.next)
|
|
1246
1542
|
start(w);
|
|
1247
1543
|
else if (!active && missing >= 2 && w.child)
|
|
1248
1544
|
await stop(w);
|
|
1249
1545
|
}
|
|
1250
1546
|
save();
|
|
1251
1547
|
}
|
|
1548
|
+
function removeOwnedLock(file) {
|
|
1549
|
+
try {
|
|
1550
|
+
assertDirectoryAncestors(dirname3(file));
|
|
1551
|
+
const stat = lstatSync3(file);
|
|
1552
|
+
if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 && readFileSync3(file, "utf8").trim() === String(process.pid))
|
|
1553
|
+
unlinkSync2(file);
|
|
1554
|
+
} catch {}
|
|
1555
|
+
}
|
|
1252
1556
|
async function main() {
|
|
1253
1557
|
if (values.help) {
|
|
1254
1558
|
console.log(`agentschat-mcp --codex-bots [--config FILE] [--watch-codex] [--check|--status]
|
|
@@ -1257,7 +1561,19 @@ Watch polls external Codex processes every 5 seconds.`);
|
|
|
1257
1561
|
return;
|
|
1258
1562
|
}
|
|
1259
1563
|
if (values.status) {
|
|
1260
|
-
|
|
1564
|
+
try {
|
|
1565
|
+
assertDirectoryAncestors(root);
|
|
1566
|
+
const stat = lstatSync3(statusFile);
|
|
1567
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1048576)
|
|
1568
|
+
throw new Error("Unsafe status file");
|
|
1569
|
+
const raw = readFileSync3(statusFile, "utf8"), status = JSON.parse(raw);
|
|
1570
|
+
if (!status || typeof status !== "object" || Array.isArray(status) || Object.prototype.hasOwnProperty.call(status, "__proto__"))
|
|
1571
|
+
throw new Error("Invalid status file");
|
|
1572
|
+
console.log(raw);
|
|
1573
|
+
} catch {
|
|
1574
|
+
console.error("Bot manager status unavailable; status file is missing, unsafe, or unreadable");
|
|
1575
|
+
process.exitCode = 1;
|
|
1576
|
+
}
|
|
1261
1577
|
return;
|
|
1262
1578
|
}
|
|
1263
1579
|
const configs = loadBots(registry);
|
|
@@ -1265,8 +1581,19 @@ Watch polls external Codex processes every 5 seconds.`);
|
|
|
1265
1581
|
console.log(JSON.stringify(configs.map((c) => ({ name: c.name, agent_id: c.agentId, workdir: c.cwd, profile: c.profileFile }))));
|
|
1266
1582
|
return;
|
|
1267
1583
|
}
|
|
1584
|
+
for (const directory of [join3(homedir3(), ".agentschat"), root]) {
|
|
1585
|
+
const stat = lstatSync3(directory, { throwIfNoEntry: false });
|
|
1586
|
+
if (stat && (stat.isSymbolicLink() || !stat.isDirectory()))
|
|
1587
|
+
throw new Error("Unsafe manager directory");
|
|
1588
|
+
}
|
|
1589
|
+
assertDirectoryAncestors(root);
|
|
1268
1590
|
mkdirSync2(root, { recursive: true, mode: 448 });
|
|
1591
|
+
const dir = lstatSync3(root);
|
|
1592
|
+
if (dir.isSymbolicLink() || !dir.isDirectory())
|
|
1593
|
+
throw new Error("Unsafe manager directory");
|
|
1269
1594
|
removeDeadLock(lock);
|
|
1595
|
+
if (lstatSync3(lock, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
1596
|
+
throw new Error("Unsafe manager lock");
|
|
1270
1597
|
const fd = openSync(lock, "wx", 384);
|
|
1271
1598
|
writeFileSync(fd, String(process.pid));
|
|
1272
1599
|
closeSync(fd);
|
|
@@ -1285,14 +1612,24 @@ Watch polls external Codex processes every 5 seconds.`);
|
|
|
1285
1612
|
await running;
|
|
1286
1613
|
await Promise.all([...workers.values()].map(stop));
|
|
1287
1614
|
save();
|
|
1288
|
-
|
|
1289
|
-
unlinkSync(lock);
|
|
1615
|
+
removeOwnedLock(lock);
|
|
1290
1616
|
};
|
|
1291
1617
|
process.once("SIGINT", () => void shutdown());
|
|
1292
1618
|
process.once("SIGTERM", () => void shutdown());
|
|
1293
1619
|
loop();
|
|
1294
1620
|
}
|
|
1295
|
-
main().
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1621
|
+
if (__require.main == __require.module || process.argv.includes("--codex-bots") || process.argv[1] && resolve3(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1622
|
+
({ values } = parseArgs({ options: { "codex-bots": { type: "boolean" }, config: { type: "string" }, "watch-codex": { type: "boolean" }, check: { type: "boolean" }, status: { type: "boolean" }, help: { type: "boolean" } } }));
|
|
1623
|
+
registry = resolve3(values.config ?? defaultRegistry());
|
|
1624
|
+
main().catch(() => {
|
|
1625
|
+
console.error("Bot manager failed; check registry, profile permissions, and existing manager");
|
|
1626
|
+
process.exitCode = 1;
|
|
1627
|
+
});
|
|
1628
|
+
}
|
|
1629
|
+
export {
|
|
1630
|
+
stop,
|
|
1631
|
+
start,
|
|
1632
|
+
save,
|
|
1633
|
+
removeOwnedLock,
|
|
1634
|
+
removeDeadLock
|
|
1635
|
+
};
|