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.
- package/CHANGELOG.md +7 -0
- package/README.md +10 -10
- package/codex/README.md +4 -4
- package/codex/app-server.ts +101 -22
- package/codex/bots-config.ts +32 -11
- package/codex/bridge.ts +127 -28
- package/codex/config.ts +137 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +77 -12
- package/codex/loop-grants.ts +49 -11
- package/codex/manager.ts +108 -27
- package/codex/owner.ts +106 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +51 -11
- package/codex/thread-history.ts +87 -30
- package/codex/transport.ts +135 -22
- package/connector/README.md +1 -1
- 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/cordis.patch.yml +4 -2
- package/dist/codex-bots.js +437 -75
- package/dist/codex-bridge.js +2111 -582
- package/dist/connector.js +1300 -493
- package/dist/dsh.js +1789 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +4410 -919
- package/dsh/README.md +1 -1
- 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 +677 -154
- 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 +1174 -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/onboarding.md +15 -15
- package/src/argcheck.ts +113 -33
- package/src/cli.mjs +100 -16
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +182 -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 +299 -18
- package/src/profile-store.ts +248 -30
- package/src/read-cursor.ts +280 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +286 -94
- package/src/session-bind.ts +777 -134
- 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 +10 -1
- package/src/wake.ts +510 -91
package/dist/codex-bridge.js
CHANGED
|
@@ -1,318 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// codex/runtime-home.ts
|
|
3
|
-
import { existsSync, mkdirSync, readdirSync, accessSync, constants, lstatSync, readlinkSync, realpathSync, symlinkSync } from "node:fs";
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync, accessSync, constants, lstatSync as lstatSync2, readlinkSync, realpathSync as realpathSync2, symlinkSync } from "node:fs";
|
|
4
|
+
|
|
5
|
+
// codex/config.ts
|
|
6
|
+
import { copyFileSync, lstatSync, readFileSync, realpathSync, renameSync, unlinkSync } from "node:fs";
|
|
4
7
|
import { homedir } from "node:os";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
const candidates = isAbsolute(bin) || bin.includes("/") ? [resolve(bin)] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map((dir) => join(dir, bin));
|
|
8
|
-
for (const candidate of candidates) {
|
|
9
|
-
try {
|
|
10
|
-
accessSync(candidate, constants.X_OK);
|
|
11
|
-
return realpathSync(candidate);
|
|
12
|
-
} catch {}
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
function assertIndependentTree(home, allowedAuthOrigin, codexExecutable) {
|
|
16
|
-
if (lstatSync(home).isSymbolicLink())
|
|
17
|
-
throw new Error("Independent Codex home must not be a symlink");
|
|
18
|
-
const inspect = (dir) => {
|
|
19
|
-
for (const name of readdirSync(dir)) {
|
|
20
|
-
const path = join(dir, name), info = lstatSync(path);
|
|
21
|
-
if (info.isSymbolicLink()) {
|
|
22
|
-
if (dir === home && name === "auth.json" && allowedAuthOrigin && resolve(home, readlinkSync(path)) === allowedAuthOrigin)
|
|
23
|
-
continue;
|
|
24
|
-
const local = relative(home, path).split(sep).join("/");
|
|
25
|
-
if (codexExecutable && /^tmp\/arg0\/codex-arg0[A-Za-z0-9_-]+\/(apply_patch|applypatch|codex-execve-wrapper|codex-linux-sandbox)$/.test(local)) {
|
|
26
|
-
try {
|
|
27
|
-
if (realpathSync(path) === codexExecutable)
|
|
28
|
-
continue;
|
|
29
|
-
} catch {}
|
|
30
|
-
}
|
|
31
|
-
throw new Error("Independent Codex home must not link configuration or runtime state");
|
|
32
|
-
}
|
|
33
|
-
if (info.isDirectory())
|
|
34
|
-
inspect(path);
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
inspect(home);
|
|
38
|
-
}
|
|
39
|
-
function prepareRuntimeHome(stateDir, source = process.env.CODEX_HOME || join(homedir(), ".codex"), mode = "linked", codexBin = "codex") {
|
|
40
|
-
if (mode !== "linked" && mode !== "isolated" && mode !== "auth-only")
|
|
41
|
-
throw new Error("Invalid Codex home mode");
|
|
42
|
-
if (mode === "isolated") {
|
|
43
|
-
const home2 = join(stateDir, "codex-home-isolated");
|
|
44
|
-
mkdirSync(home2, { recursive: true, mode: 448 });
|
|
45
|
-
assertIndependentTree(home2, undefined, executablePath(codexBin));
|
|
46
|
-
return { home: realpathSync(home2) };
|
|
47
|
-
}
|
|
48
|
-
if (mode === "auth-only") {
|
|
49
|
-
const legacyHome2 = realpathSync(source);
|
|
50
|
-
const origin = join(legacyHome2, "auth.json");
|
|
51
|
-
if (!lstatSync(origin).isFile())
|
|
52
|
-
throw new Error("auth-only requires an existing regular auth.json; authorize its use explicitly");
|
|
53
|
-
const home2 = join(stateDir, "codex-home-auth-only");
|
|
54
|
-
mkdirSync(home2, { recursive: true, mode: 448 });
|
|
55
|
-
if (lstatSync(home2).isSymbolicLink() || realpathSync(home2) === legacyHome2)
|
|
56
|
-
throw new Error("auth-only home must be independent");
|
|
57
|
-
for (const name of ["config.toml", "AGENTS.md", "rules", "plugins", "hooks.json"]) {
|
|
58
|
-
try {
|
|
59
|
-
lstatSync(join(home2, name));
|
|
60
|
-
} catch (e) {
|
|
61
|
-
if (e.code === "ENOENT")
|
|
62
|
-
continue;
|
|
63
|
-
throw e;
|
|
64
|
-
}
|
|
65
|
-
throw new Error("auth-only home contains unexpected configuration; use a fresh state root");
|
|
66
|
-
}
|
|
67
|
-
const skills = join(home2, "skills");
|
|
68
|
-
if (existsSync(skills) && (!lstatSync(skills).isDirectory() || readdirSync(skills).some((name) => name !== ".system")))
|
|
69
|
-
throw new Error("auth-only home contains unexpected custom skills");
|
|
70
|
-
assertIndependentTree(home2, origin, executablePath(codexBin));
|
|
71
|
-
const target = join(home2, "auth.json");
|
|
72
|
-
try {
|
|
73
|
-
if (!lstatSync(target).isSymbolicLink() || resolve(home2, readlinkSync(target)) !== origin)
|
|
74
|
-
throw new Error("Unexpected auth-only login binding");
|
|
75
|
-
} catch (e) {
|
|
76
|
-
if (e.code !== "ENOENT")
|
|
77
|
-
throw e;
|
|
78
|
-
symlinkSync(origin, target);
|
|
79
|
-
}
|
|
80
|
-
assertIndependentTree(home2, origin, executablePath(codexBin));
|
|
81
|
-
return { home: realpathSync(home2) };
|
|
82
|
-
}
|
|
83
|
-
const legacyHome = existsSync(source) ? realpathSync(source) : resolve(source);
|
|
84
|
-
const home = join(stateDir, "codex-home");
|
|
85
|
-
mkdirSync(home, { recursive: true, mode: 448 });
|
|
86
|
-
if (realpathSync(home) === legacyHome)
|
|
87
|
-
throw new Error("Bot runtime home must differ from desktop Codex home");
|
|
88
|
-
for (const name of ["config.toml", "auth.json", "AGENTS.md", "skills", "rules", "plugins", "hooks.json", "models_cache.json"]) {
|
|
89
|
-
const origin = join(legacyHome, name), target = join(home, name);
|
|
90
|
-
if (!existsSync(origin))
|
|
91
|
-
continue;
|
|
92
|
-
let current;
|
|
93
|
-
try {
|
|
94
|
-
current = lstatSync(target);
|
|
95
|
-
} catch (e) {
|
|
96
|
-
if (e.code !== "ENOENT")
|
|
97
|
-
throw e;
|
|
98
|
-
}
|
|
99
|
-
if (current) {
|
|
100
|
-
if (!current.isSymbolicLink() || resolve(home, readlinkSync(target)) !== origin)
|
|
101
|
-
throw new Error(`Unexpected bot runtime configuration: ${name}`);
|
|
102
|
-
} else
|
|
103
|
-
symlinkSync(origin, target);
|
|
104
|
-
}
|
|
105
|
-
return { home, legacyHome };
|
|
106
|
-
}
|
|
8
|
+
import { dirname, isAbsolute, join, parse as parsePath, resolve } from "node:path";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
107
10
|
|
|
108
11
|
// src/redact.ts
|
|
109
12
|
function redactSecrets(text, opts) {
|
|
13
|
+
if (typeof text !== "string" || !text)
|
|
14
|
+
return "";
|
|
110
15
|
const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
|
|
111
|
-
return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// codex/owner.ts
|
|
115
|
-
async function getBotOwner(base, agentId, token, request = fetch) {
|
|
116
|
-
try {
|
|
117
|
-
const origin = base.replace(/\/+$/, "");
|
|
118
|
-
const options = {
|
|
119
|
-
method: "GET",
|
|
120
|
-
headers: { Authorization: `Bearer ${token}` },
|
|
121
|
-
cache: "no-store",
|
|
122
|
-
redirect: "error",
|
|
123
|
-
signal: AbortSignal.timeout(8000)
|
|
124
|
-
};
|
|
125
|
-
const [statusResponse, entitlementResponse] = await Promise.all([
|
|
126
|
-
request(`${origin}/api/account/onboarding`, options),
|
|
127
|
-
request(`${origin}/api/me/entitlements`, options)
|
|
128
|
-
]);
|
|
129
|
-
if (!statusResponse.ok || !entitlementResponse.ok)
|
|
130
|
-
return null;
|
|
131
|
-
const [status, entitlement] = await Promise.all([
|
|
132
|
-
statusResponse.json(),
|
|
133
|
-
entitlementResponse.json()
|
|
134
|
-
]);
|
|
135
|
-
if (!status || Array.isArray(status) || status.agent_id !== agentId || status.claimed !== true)
|
|
136
|
-
return null;
|
|
137
|
-
if (!entitlement || Array.isArray(entitlement))
|
|
138
|
-
return null;
|
|
139
|
-
const owner = entitlement.owner_account_id;
|
|
140
|
-
return typeof owner === "string" && owner.trim().length > 0 && owner !== agentId ? owner : null;
|
|
141
|
-
} catch {
|
|
142
|
-
return null;
|
|
143
|
-
}
|
|
16
|
+
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***");
|
|
144
17
|
}
|
|
145
18
|
|
|
146
|
-
// src/
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
};
|
|
157
|
-
try {
|
|
158
|
-
const r = await request(`${base.replace(/\/$/, "")}/api/account/onboarding`, {
|
|
159
|
-
headers: { Authorization: `Bearer ${token}` },
|
|
160
|
-
cache: "no-store",
|
|
161
|
-
signal: AbortSignal.timeout(8000),
|
|
162
|
-
redirect: "error"
|
|
163
|
-
});
|
|
164
|
-
if (r.status === 401 || r.status === 403) {
|
|
165
|
-
result.authentication = "failed";
|
|
166
|
-
return result;
|
|
167
|
-
}
|
|
168
|
-
if (!r.ok)
|
|
169
|
-
return result;
|
|
170
|
-
const data = await r.json();
|
|
171
|
-
if (data.agent_id !== agentId || typeof data.claimed !== "boolean")
|
|
172
|
-
return result;
|
|
173
|
-
result.authentication = "ok";
|
|
174
|
-
result.claimed = data.claimed;
|
|
175
|
-
result.next_step = data.claimed ? "verify_reply" : "join_public_chat";
|
|
176
|
-
} catch {}
|
|
177
|
-
return result;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// codex/gui-channel.ts
|
|
181
|
-
import { randomUUID } from "node:crypto";
|
|
182
|
-
import { mkdirSync as mkdirSync2, writeFileSync, readFileSync, renameSync, readdirSync as readdirSync2, rmSync } from "node:fs";
|
|
183
|
-
import { join as join2 } from "node:path";
|
|
184
|
-
function payload(result) {
|
|
185
|
-
if (result?.isError || result?.success === false || result?.error)
|
|
186
|
-
throw new Error("GUI tool rejected request");
|
|
187
|
-
if (Array.isArray(result?.content)) {
|
|
188
|
-
const text = result.content.find((c) => c.type === "text")?.text;
|
|
189
|
-
if (!text)
|
|
190
|
-
throw new Error("GUI tool returned no receipt");
|
|
191
|
-
return JSON.parse(text);
|
|
192
|
-
}
|
|
193
|
-
return result;
|
|
19
|
+
// src/identity.ts
|
|
20
|
+
var RESERVED_IDENTITY_IDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
21
|
+
var MAX_AGENT_ID_LEN = 128;
|
|
22
|
+
var MAX_CAPABILITIES_LEN = 64;
|
|
23
|
+
var CONTROL_OR_SEP_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
24
|
+
function isValidProfileAgentId(raw) {
|
|
25
|
+
if (typeof raw !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029/\\\s]/.test(raw) || /(?:%2e|%2f|%5c|%00)/i.test(raw))
|
|
26
|
+
return false;
|
|
27
|
+
const trimmed = raw.trim();
|
|
28
|
+
return trimmed.length > 0 && trimmed === raw && trimmed.length <= MAX_AGENT_ID_LEN && trimmed !== "." && !trimmed.includes("..") && !RESERVED_IDENTITY_IDS.has(trimmed.toLowerCase());
|
|
194
29
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
this.directory = directory;
|
|
201
|
-
this.allowedThreads = allowedThreads;
|
|
202
|
-
mkdirSync2(directory, { recursive: true, mode: 448 });
|
|
203
|
-
}
|
|
204
|
-
path(id) {
|
|
205
|
-
if (!/^[0-9a-f-]{36}$/.test(id))
|
|
206
|
-
throw new Error("Invalid delivery ID");
|
|
207
|
-
return join2(this.directory, `${id}.json`);
|
|
208
|
-
}
|
|
209
|
-
save(entry) {
|
|
210
|
-
const path = this.path(entry.id), temp = `${path}.${randomUUID()}.tmp`;
|
|
211
|
-
writeFileSync(temp, JSON.stringify(entry), { mode: 384 });
|
|
212
|
-
renameSync(temp, path);
|
|
213
|
-
}
|
|
214
|
-
get(id) {
|
|
215
|
-
return JSON.parse(readFileSync(this.path(id), "utf8"));
|
|
216
|
-
}
|
|
217
|
-
list() {
|
|
218
|
-
return readdirSync2(this.directory).filter((f) => /^[0-9a-f-]{36}\.json$/.test(f)).map((f) => this.get(f.slice(0, -5)));
|
|
219
|
-
}
|
|
220
|
-
enqueue(threadId, text, hostId) {
|
|
221
|
-
if (!this.allowedThreads.includes(threadId))
|
|
222
|
-
throw new Error("GUI target is not allowed");
|
|
223
|
-
if (!text.trim() || text.length > 24000)
|
|
224
|
-
throw new Error("GUI message must contain 1–24000 characters");
|
|
225
|
-
const id = randomUUID();
|
|
226
|
-
const entry = {
|
|
227
|
-
id,
|
|
228
|
-
threadId,
|
|
229
|
-
...hostId ? { hostId } : {},
|
|
230
|
-
prompt: `[AgentsChat delivery ${id}]
|
|
231
|
-
${text}`,
|
|
232
|
-
status: "pending",
|
|
233
|
-
createdAt: new Date().toISOString()
|
|
234
|
-
};
|
|
235
|
-
this.save(entry);
|
|
236
|
-
return entry;
|
|
237
|
-
}
|
|
238
|
-
async dispatch(id, call) {
|
|
239
|
-
const lock = `${this.path(id)}.lock`;
|
|
240
|
-
mkdirSync2(lock, { mode: 448 });
|
|
241
|
-
try {
|
|
242
|
-
const entry = this.get(id);
|
|
243
|
-
if (!this.allowedThreads.includes(entry.threadId))
|
|
244
|
-
throw new Error("GUI target is no longer allowed");
|
|
245
|
-
if (entry.status === "delivered")
|
|
246
|
-
return entry;
|
|
247
|
-
const target = { threadId: entry.threadId, ...entry.hostId ? { hostId: entry.hostId } : {} };
|
|
248
|
-
if (entry.status === "pending") {
|
|
249
|
-
entry.status = "sending";
|
|
250
|
-
this.save(entry);
|
|
251
|
-
try {
|
|
252
|
-
payload(await call("send_message_to_thread", { ...target, prompt: entry.prompt }));
|
|
253
|
-
entry.status = "submitted";
|
|
254
|
-
this.save(entry);
|
|
255
|
-
} catch {
|
|
256
|
-
entry.status = "uncertain";
|
|
257
|
-
this.save(entry);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
if (entry.status === "sending") {
|
|
261
|
-
entry.status = "uncertain";
|
|
262
|
-
this.save(entry);
|
|
263
|
-
}
|
|
264
|
-
try {
|
|
265
|
-
let cursor;
|
|
266
|
-
for (let page = 0;page < 5; page++) {
|
|
267
|
-
const history = payload(await call("read_thread", {
|
|
268
|
-
...target,
|
|
269
|
-
turnLimit: 10,
|
|
270
|
-
maxOutputCharsPerItem: 32000,
|
|
271
|
-
...cursor ? { cursor } : {}
|
|
272
|
-
}));
|
|
273
|
-
if (history?.thread?.id !== entry.threadId)
|
|
274
|
-
throw new Error("Wrong GUI thread in receipt");
|
|
275
|
-
const turn = history.turns?.find((t) => t.items?.some((item) => item.type === "userMessage" && item.content?.some((c) => c.type === "text" && c.text === entry.prompt)));
|
|
276
|
-
if (turn) {
|
|
277
|
-
entry.status = "delivered";
|
|
278
|
-
entry.deliveredAt = new Date().toISOString();
|
|
279
|
-
entry.turnId = turn.id;
|
|
280
|
-
this.save(entry);
|
|
281
|
-
break;
|
|
282
|
-
}
|
|
283
|
-
cursor = history.page?.nextCursor;
|
|
284
|
-
if (!cursor)
|
|
285
|
-
break;
|
|
286
|
-
}
|
|
287
|
-
} catch {}
|
|
288
|
-
return entry;
|
|
289
|
-
} finally {
|
|
290
|
-
rmSync(lock, { recursive: true });
|
|
291
|
-
}
|
|
292
|
-
}
|
|
30
|
+
function sanitizeDiagnosticField(raw, fallback = "(unknown)") {
|
|
31
|
+
if (typeof raw !== "string")
|
|
32
|
+
return fallback;
|
|
33
|
+
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();
|
|
34
|
+
return cleaned.length > 0 ? cleaned.slice(0, 256) : fallback;
|
|
293
35
|
}
|
|
294
|
-
|
|
295
|
-
// codex/run.ts
|
|
296
|
-
import { readFileSync as readFileSync10 } from "node:fs";
|
|
297
|
-
import { homedir as homedir5 } from "node:os";
|
|
298
|
-
import { join as join10 } from "node:path";
|
|
299
|
-
|
|
300
|
-
// codex/bots-config.ts
|
|
301
|
-
import { readFileSync as readFileSync3, realpathSync as realpathSync3, mkdirSync as mkdirSync3 } from "node:fs";
|
|
302
|
-
import { homedir as homedir3 } from "node:os";
|
|
303
|
-
import { dirname, isAbsolute as isAbsolute3, join as join4, resolve as resolve3 } from "node:path";
|
|
304
|
-
|
|
305
|
-
// codex/config.ts
|
|
306
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync as realpathSync2, statSync } from "node:fs";
|
|
307
|
-
import { homedir as homedir2 } from "node:os";
|
|
308
|
-
import { isAbsolute as isAbsolute2, join as join3, resolve as resolve2 } from "node:path";
|
|
309
|
-
import { createHash } from "node:crypto";
|
|
310
|
-
|
|
311
|
-
// src/identity.ts
|
|
312
36
|
function validateIdentityProfile(profile, file, allowDevToken = false) {
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
37
|
+
const cleanNonempty = (value) => typeof value === "string" && value.trim().length > 0 && value.length <= 4096 && !CONTROL_OR_SEP_RE.test(value);
|
|
38
|
+
const safeFile = sanitizeDiagnosticField(file, "(unknown-path)");
|
|
39
|
+
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))) {
|
|
40
|
+
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.`);
|
|
316
41
|
}
|
|
317
42
|
}
|
|
318
43
|
|
|
@@ -568,7 +293,7 @@ function skipVoid(ctx, banNewLines, banComments) {
|
|
|
568
293
|
skipComment(ctx);
|
|
569
294
|
}
|
|
570
295
|
}
|
|
571
|
-
function skipUntil(ctx,
|
|
296
|
+
function skipUntil(ctx, sep, end) {
|
|
572
297
|
let ptr = ctx.p;
|
|
573
298
|
if (!end) {
|
|
574
299
|
ptr = indexOfNewline(ctx.s, ptr);
|
|
@@ -579,7 +304,7 @@ function skipUntil(ctx, sep2, end) {
|
|
|
579
304
|
let c = ctx.s.charCodeAt(ctx.p);
|
|
580
305
|
if (c === 35) {
|
|
581
306
|
skipComment(ctx);
|
|
582
|
-
} else if (c === end || c ===
|
|
307
|
+
} else if (c === end || c === sep) {
|
|
583
308
|
return;
|
|
584
309
|
}
|
|
585
310
|
}
|
|
@@ -1193,18 +918,136 @@ function parse(toml, { maxDepth = 1000, integersAsBigInt } = {}) {
|
|
|
1193
918
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
1194
919
|
*/
|
|
1195
920
|
|
|
1196
|
-
// codex/
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
921
|
+
// codex/owner.ts
|
|
922
|
+
var OWNER_FORBIDDEN_KEYS = new Set([
|
|
923
|
+
"__proto__",
|
|
924
|
+
"prototype",
|
|
925
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
926
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
927
|
+
]);
|
|
928
|
+
var isOwnerForbiddenKey = (key) => OWNER_FORBIDDEN_KEYS.has(key) || OWNER_FORBIDDEN_KEYS.has(key.toLowerCase());
|
|
929
|
+
function blockedServerHost(url) {
|
|
930
|
+
const host = url.hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
|
|
931
|
+
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)) {
|
|
932
|
+
return true;
|
|
933
|
+
}
|
|
934
|
+
if (host.startsWith("::ffff:")) {
|
|
935
|
+
const rawTail = host.slice(7);
|
|
936
|
+
if (rawTail === "0:0" || rawTail === "0.0.0.0")
|
|
937
|
+
return true;
|
|
938
|
+
const tail = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(rawTail) ? rawTail.slice(2) : rawTail;
|
|
939
|
+
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") {
|
|
940
|
+
return true;
|
|
941
|
+
}
|
|
942
|
+
const hexMatch = tail.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
943
|
+
if (hexMatch) {
|
|
944
|
+
const hi = parseInt(hexMatch[1], 16);
|
|
945
|
+
const lo = parseInt(hexMatch[2], 16);
|
|
946
|
+
const firstOctet = hi >> 8 & 255;
|
|
947
|
+
const secondOctet = hi & 255;
|
|
948
|
+
if (firstOctet === 0 || firstOctet === 127 || firstOctet === 169 && secondOctet === 254 || firstOctet === 100 && (secondOctet & 192) === 64 || hi === 25700 && lo === 25800) {
|
|
949
|
+
return true;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return false;
|
|
1203
954
|
}
|
|
1204
|
-
function
|
|
1205
|
-
if (
|
|
955
|
+
async function ownerJson(response) {
|
|
956
|
+
if (!response.body)
|
|
957
|
+
throw new Error("Missing owner response");
|
|
958
|
+
const reader = response.body.getReader();
|
|
959
|
+
const chunks = [];
|
|
960
|
+
let size = 0;
|
|
961
|
+
try {
|
|
962
|
+
while (true) {
|
|
963
|
+
const { done, value } = await reader.read();
|
|
964
|
+
if (done)
|
|
965
|
+
break;
|
|
966
|
+
size += value.byteLength;
|
|
967
|
+
if (size > 65536) {
|
|
968
|
+
reader.cancel().catch(() => {});
|
|
969
|
+
throw new Error("Owner response exceeds size limit");
|
|
970
|
+
}
|
|
971
|
+
chunks.push(value);
|
|
972
|
+
}
|
|
973
|
+
} finally {
|
|
974
|
+
reader.releaseLock();
|
|
975
|
+
}
|
|
976
|
+
const bytes = new Uint8Array(size);
|
|
977
|
+
let offset = 0;
|
|
978
|
+
for (const chunk of chunks) {
|
|
979
|
+
bytes.set(chunk, offset);
|
|
980
|
+
offset += chunk.byteLength;
|
|
981
|
+
}
|
|
982
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
983
|
+
}
|
|
984
|
+
async function getBotOwner(base, agentId, token, request = fetch) {
|
|
985
|
+
try {
|
|
986
|
+
if (!base || base !== base.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(base) || !agentId || agentId !== agentId.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId) || /%(?:2e%2e|2f|5c|00)/i.test(agentId) || agentId === "." || agentId.includes("..") || isOwnerForbiddenKey(agentId) || /[\/\\\s]/.test(agentId) || !token || token !== token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token))
|
|
987
|
+
return null;
|
|
988
|
+
const parsed = new URL(base);
|
|
989
|
+
const loopback = ["127.0.0.1", "localhost", "[::1]", "::1"].includes(parsed.hostname.toLowerCase().replace(/\.$/, ""));
|
|
990
|
+
if (blockedServerHost(parsed) || parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback) || parsed.username || parsed.password || parsed.search || parsed.hash || parsed.port === "0")
|
|
991
|
+
return null;
|
|
992
|
+
const origin = parsed.href.replace(/\/+$/, "");
|
|
993
|
+
const options = {
|
|
994
|
+
method: "GET",
|
|
995
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
996
|
+
cache: "no-store",
|
|
997
|
+
redirect: "error",
|
|
998
|
+
signal: AbortSignal.timeout(8000)
|
|
999
|
+
};
|
|
1000
|
+
const [statusSettled, entitlementSettled] = await Promise.allSettled([
|
|
1001
|
+
request(`${origin}/api/account/onboarding`, options),
|
|
1002
|
+
request(`${origin}/api/me/entitlements`, options)
|
|
1003
|
+
]);
|
|
1004
|
+
const statusResponse = statusSettled.status === "fulfilled" ? statusSettled.value : null;
|
|
1005
|
+
const entitlementResponse = entitlementSettled.status === "fulfilled" ? entitlementSettled.value : null;
|
|
1006
|
+
if (!statusResponse?.ok || !entitlementResponse?.ok) {
|
|
1007
|
+
await Promise.allSettled([
|
|
1008
|
+
statusResponse?.body?.cancel(),
|
|
1009
|
+
entitlementResponse?.body?.cancel()
|
|
1010
|
+
]);
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
const [statusValue, entitlementValue] = await Promise.all([
|
|
1014
|
+
ownerJson(statusResponse),
|
|
1015
|
+
ownerJson(entitlementResponse)
|
|
1016
|
+
]);
|
|
1017
|
+
const status = statusValue;
|
|
1018
|
+
const entitlement = entitlementValue;
|
|
1019
|
+
if (!status || typeof status !== "object" || Array.isArray(status) || Object.hasOwn(status, "__proto__") || status.agent_id !== agentId || status.claimed !== true)
|
|
1020
|
+
return null;
|
|
1021
|
+
if (!entitlement || typeof entitlement !== "object" || Array.isArray(entitlement) || Object.hasOwn(entitlement, "__proto__"))
|
|
1022
|
+
return null;
|
|
1023
|
+
const owner = entitlement.owner_account_id;
|
|
1024
|
+
return typeof owner === "string" && owner.trim().length > 0 && owner === owner.trim() && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(owner) && !/%(?:2e%2e|2f|5c|00)/i.test(owner) && owner !== agentId && owner !== "." && !owner.includes("..") && !isOwnerForbiddenKey(owner) ? owner : null;
|
|
1025
|
+
} catch {
|
|
1026
|
+
return null;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// codex/config.ts
|
|
1031
|
+
var CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1032
|
+
var PROTO_KEY_RE = /^(?:__proto__|constructor|prototype)$/i;
|
|
1033
|
+
var RESERVED_OBJECT_STEMS = new Set([
|
|
1034
|
+
"__proto__",
|
|
1035
|
+
"constructor",
|
|
1036
|
+
"prototype",
|
|
1037
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
1038
|
+
]);
|
|
1039
|
+
var WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
1040
|
+
function reasoningEffort(value) {
|
|
1041
|
+
if (value === undefined)
|
|
1206
1042
|
return;
|
|
1207
|
-
if (typeof value !== "string" || !value.trim())
|
|
1043
|
+
if (typeof value !== "string" || !value.trim() || value.trim().length > 64 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
|
|
1044
|
+
throw new Error("effort must be a nonempty model-supported reasoning effort name");
|
|
1045
|
+
return value.trim();
|
|
1046
|
+
}
|
|
1047
|
+
function modelName(value) {
|
|
1048
|
+
if (value === undefined)
|
|
1049
|
+
return;
|
|
1050
|
+
if (typeof value !== "string" || !value.trim() || value.trim().length > 256 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
|
|
1208
1051
|
throw new Error("model must be a nonempty model ID");
|
|
1209
1052
|
return value.trim();
|
|
1210
1053
|
}
|
|
@@ -1222,39 +1065,149 @@ function codexHomeMode(value) {
|
|
|
1222
1065
|
throw new Error("codex_home_mode must be linked, isolated or auth-only");
|
|
1223
1066
|
return value;
|
|
1224
1067
|
}
|
|
1068
|
+
var MAX_CONFIG_BYTES = 1048576;
|
|
1069
|
+
function reservedProfileStem(selector) {
|
|
1070
|
+
const stem = selector.replace(/\.json$/i, "").toLowerCase();
|
|
1071
|
+
return RESERVED_OBJECT_STEMS.has(stem) || WINDOWS_DEVICE_STEM_RE.test(stem) || [
|
|
1072
|
+
"grok-binds",
|
|
1073
|
+
"session-binds",
|
|
1074
|
+
"agy-binds",
|
|
1075
|
+
"cursor",
|
|
1076
|
+
"read-cursors",
|
|
1077
|
+
"wake-pids",
|
|
1078
|
+
"config",
|
|
1079
|
+
"codex-bots"
|
|
1080
|
+
].includes(stem);
|
|
1081
|
+
}
|
|
1082
|
+
function checkSingleAncestorDir(path) {
|
|
1083
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
1084
|
+
if (!stat)
|
|
1085
|
+
return;
|
|
1086
|
+
if (stat.isSymbolicLink()) {
|
|
1087
|
+
const target = `/private${path}`;
|
|
1088
|
+
if (process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(path) && realpathSync(path) === target) {
|
|
1089
|
+
const priv = lstatSync("/private", { throwIfNoEntry: false });
|
|
1090
|
+
if (!priv || priv.isSymbolicLink() || !priv.isDirectory()) {
|
|
1091
|
+
throw new Error("Config path must be a non-symlink directory: /private");
|
|
1092
|
+
}
|
|
1093
|
+
assertDirectoryAncestors(target);
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
throw new Error(`Config path must be a non-symlink directory: ${path}`);
|
|
1097
|
+
}
|
|
1098
|
+
if (!stat.isDirectory())
|
|
1099
|
+
throw new Error(`Config path must be a non-symlink directory: ${path}`);
|
|
1100
|
+
}
|
|
1101
|
+
function assertDirectoryAncestors(directory) {
|
|
1102
|
+
if (typeof directory !== "string" || !directory.trim() || CONTROL_CHAR_RE.test(directory)) {
|
|
1103
|
+
throw new Error(`Config path must be a non-symlink directory: ${String(directory)}`);
|
|
1104
|
+
}
|
|
1105
|
+
if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(directory)) {
|
|
1106
|
+
let cur;
|
|
1107
|
+
let remainder;
|
|
1108
|
+
if (isAbsolute(directory)) {
|
|
1109
|
+
const root = parsePath(directory).root || "/";
|
|
1110
|
+
cur = root;
|
|
1111
|
+
remainder = directory.slice(root.length);
|
|
1112
|
+
checkSingleAncestorDir(cur);
|
|
1113
|
+
} else {
|
|
1114
|
+
const base = resolve(process.cwd());
|
|
1115
|
+
assertDirectoryAncestors(base);
|
|
1116
|
+
cur = base;
|
|
1117
|
+
remainder = directory;
|
|
1118
|
+
}
|
|
1119
|
+
for (const seg of remainder.split(/[\\/]+/)) {
|
|
1120
|
+
if (!seg || seg === ".")
|
|
1121
|
+
continue;
|
|
1122
|
+
cur = seg === ".." ? dirname(cur) : join(cur, seg);
|
|
1123
|
+
checkSingleAncestorDir(cur);
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
const paths = [];
|
|
1127
|
+
for (let path = resolve(directory);; path = dirname(path)) {
|
|
1128
|
+
paths.unshift(path);
|
|
1129
|
+
if (dirname(path) === path)
|
|
1130
|
+
break;
|
|
1131
|
+
}
|
|
1132
|
+
for (const path of paths)
|
|
1133
|
+
checkSingleAncestorDir(path);
|
|
1134
|
+
}
|
|
1135
|
+
function atomicReplaceRegularFile(tmp, target, verifySafeTarget, opts) {
|
|
1136
|
+
verifySafeTarget();
|
|
1137
|
+
const rename = opts?.rename ?? renameSync;
|
|
1138
|
+
const platform = opts?.platform ?? process.platform;
|
|
1139
|
+
try {
|
|
1140
|
+
rename(tmp, target);
|
|
1141
|
+
} catch (err) {
|
|
1142
|
+
if (platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
|
|
1143
|
+
verifySafeTarget();
|
|
1144
|
+
copyFileSync(tmp, target);
|
|
1145
|
+
unlinkSync(tmp);
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
1148
|
+
throw err;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
function checkedPath(path, directory = false) {
|
|
1152
|
+
assertDirectoryAncestors(dirname(path));
|
|
1153
|
+
let stat;
|
|
1154
|
+
try {
|
|
1155
|
+
stat = lstatSync(path);
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
if (error.code === "ENOENT")
|
|
1158
|
+
return;
|
|
1159
|
+
throw error;
|
|
1160
|
+
}
|
|
1161
|
+
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
|
|
1162
|
+
throw new Error(directory ? `Config directory must be a non-symlink directory: ${path}` : `Selected profile is not a regular file: ${path}`);
|
|
1163
|
+
if (!directory && stat.size > MAX_CONFIG_BYTES)
|
|
1164
|
+
throw new Error(`Config file exceeds 1 MiB: ${path}`);
|
|
1165
|
+
return stat;
|
|
1166
|
+
}
|
|
1225
1167
|
function readJson(file) {
|
|
1168
|
+
let value;
|
|
1226
1169
|
try {
|
|
1227
|
-
|
|
1170
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
1228
1171
|
} catch {
|
|
1229
1172
|
throw new Error(`Cannot read valid JSON: ${file}`);
|
|
1230
1173
|
}
|
|
1174
|
+
if (value && typeof value === "object" && Object.hasOwn(value, "__proto__"))
|
|
1175
|
+
throw new Error("Invalid JSON prototype key");
|
|
1176
|
+
return value;
|
|
1231
1177
|
}
|
|
1232
1178
|
function strings(value, name) {
|
|
1233
1179
|
if (value === undefined)
|
|
1234
1180
|
return [];
|
|
1235
|
-
if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim()))
|
|
1181
|
+
if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim() || CONTROL_CHAR_RE.test(x)))
|
|
1236
1182
|
throw new Error(`${name} must be an array of nonempty strings`);
|
|
1237
1183
|
return value;
|
|
1238
1184
|
}
|
|
1239
|
-
function resolveConfig(opts, env = process.env, home =
|
|
1240
|
-
|
|
1241
|
-
const
|
|
1242
|
-
const
|
|
1185
|
+
function resolveConfig(opts, env = process.env, home = homedir()) {
|
|
1186
|
+
assertDirectoryAncestors(opts.cwd ?? process.cwd());
|
|
1187
|
+
const cwd = realpathSync(opts.cwd ?? process.cwd());
|
|
1188
|
+
const configFile = join(cwd, ".agentschat/config.json");
|
|
1189
|
+
if (opts.settings === undefined)
|
|
1190
|
+
checkedPath(join(cwd, ".agentschat"), true);
|
|
1191
|
+
const project = opts.settings ?? (checkedPath(configFile) ? readJson(configFile) : {});
|
|
1243
1192
|
if (!project || typeof project !== "object" || Array.isArray(project))
|
|
1244
1193
|
throw new Error("Invalid project config");
|
|
1194
|
+
if (["__proto__", "constructor", "prototype"].some((key2) => Object.hasOwn(project, key2)))
|
|
1195
|
+
throw new Error("Invalid project config prototype key");
|
|
1245
1196
|
const allowed = new Set(["profile", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
|
|
1246
1197
|
if (Object.keys(project).some((k) => !allowed.has(k)))
|
|
1247
1198
|
throw new Error("Unknown project config field (credentials belong in a private profile)");
|
|
1248
1199
|
for (const k of ["profile", "agent_id", "api_url", "ws_url", "state_root"])
|
|
1249
1200
|
if (project[k] !== undefined && (typeof project[k] !== "string" || !project[k].trim()))
|
|
1250
1201
|
throw new Error(`Invalid project ${k}`);
|
|
1251
|
-
const localProfile =
|
|
1202
|
+
const localProfile = join(cwd, ".agentschat/profile.json");
|
|
1252
1203
|
let codexProfile;
|
|
1253
|
-
const codexFile =
|
|
1254
|
-
if (opts.settings === undefined
|
|
1204
|
+
const codexFile = join(cwd, ".codex/config.toml");
|
|
1205
|
+
if (opts.settings === undefined)
|
|
1206
|
+
checkedPath(join(cwd, ".codex"), true);
|
|
1207
|
+
if (opts.settings === undefined && checkedPath(codexFile)) {
|
|
1255
1208
|
let doc;
|
|
1256
1209
|
try {
|
|
1257
|
-
doc = parse(
|
|
1210
|
+
doc = parse(readFileSync(codexFile, "utf8"));
|
|
1258
1211
|
} catch {
|
|
1259
1212
|
throw new Error("Invalid project .codex/config.toml");
|
|
1260
1213
|
}
|
|
@@ -1271,29 +1224,38 @@ function resolveConfig(opts, env = process.env, home = homedir2()) {
|
|
|
1271
1224
|
const choices = [
|
|
1272
1225
|
[opts.profile, "flag"],
|
|
1273
1226
|
[project.profile, "project-config"],
|
|
1274
|
-
[opts.settings === undefined &&
|
|
1227
|
+
[opts.settings === undefined && checkedPath(localProfile) ? localProfile : undefined, "project-profile"],
|
|
1275
1228
|
[codexProfile, "project-codex"],
|
|
1276
1229
|
[env.AGENTSCHAT_PROFILE, "env"],
|
|
1277
1230
|
[env.AGENTCHAT_PROFILE, "legacy-env"],
|
|
1278
1231
|
["profile", "default"]
|
|
1279
1232
|
];
|
|
1280
1233
|
const [selector, source] = choices.find(([v]) => v !== undefined && v !== "");
|
|
1234
|
+
if (typeof selector !== "string" || CONTROL_CHAR_RE.test(selector))
|
|
1235
|
+
throw new Error("Invalid profile selector");
|
|
1281
1236
|
let profileFile;
|
|
1282
|
-
if (selector
|
|
1283
|
-
profileFile =
|
|
1284
|
-
else if (
|
|
1285
|
-
profileFile =
|
|
1237
|
+
if (/^~[\\/]/.test(selector))
|
|
1238
|
+
profileFile = join(home, selector.slice(2));
|
|
1239
|
+
else if (isAbsolute(selector) || selector.includes("/") || selector.includes("\\"))
|
|
1240
|
+
profileFile = resolve(cwd, selector);
|
|
1286
1241
|
else {
|
|
1287
|
-
const
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1242
|
+
const stem = selector.replace(/\.json$/i, "");
|
|
1243
|
+
if (!stem || selector.includes("..") || reservedProfileStem(selector)) {
|
|
1244
|
+
throw new Error("Invalid central profile selector");
|
|
1245
|
+
}
|
|
1246
|
+
const name = /\.json$/i.test(selector) ? selector : `${selector}.json`;
|
|
1247
|
+
profileFile = join(home, ".agentschat/profiles", name);
|
|
1248
|
+
if (!checkedPath(profileFile))
|
|
1249
|
+
profileFile = join(home, ".agentschat", name);
|
|
1250
|
+
if (!checkedPath(profileFile))
|
|
1251
|
+
profileFile = join(home, ".agentchat", name);
|
|
1252
|
+
}
|
|
1253
|
+
if (!checkedPath(profileFile))
|
|
1295
1254
|
throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
|
|
1296
|
-
|
|
1255
|
+
const profileStat = checkedPath(profileFile);
|
|
1256
|
+
if (!profileStat.isFile())
|
|
1257
|
+
throw new Error(`Selected profile is not a regular file: ${profileFile}`);
|
|
1258
|
+
if (process.platform !== "win32" && profileStat.mode & 63)
|
|
1297
1259
|
throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
|
|
1298
1260
|
const profile = readJson(profileFile);
|
|
1299
1261
|
validateIdentityProfile(profile, profileFile);
|
|
@@ -1303,15 +1265,18 @@ function resolveConfig(opts, env = process.env, home = homedir2()) {
|
|
|
1303
1265
|
const wsUrl = project.ws_url ?? `${apiUrl.replace(/^http/, "ws").replace(/\/$/, "")}/ws`;
|
|
1304
1266
|
for (const [raw, protocols] of [[apiUrl, ["https:", "http:"]], [wsUrl, ["wss:", "ws:"]]]) {
|
|
1305
1267
|
const url = new URL(raw);
|
|
1306
|
-
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))
|
|
1268
|
+
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(/\.$/, "")))
|
|
1307
1269
|
throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
|
|
1308
1270
|
}
|
|
1309
1271
|
const canonicalApi = new URL(apiUrl).href.replace(/\/$/, "");
|
|
1310
1272
|
const key = createHash("sha256").update(JSON.stringify([cwd, canonicalApi, profile.agent_id])).digest("hex").slice(0, 24);
|
|
1311
1273
|
const root = opts.stateRoot ?? project.state_root;
|
|
1312
|
-
if (root !== undefined && (typeof root !== "string" || !root.trim()))
|
|
1274
|
+
if (root !== undefined && (typeof root !== "string" || !root.trim() || CONTROL_CHAR_RE.test(root)))
|
|
1313
1275
|
throw new Error("Invalid state_root");
|
|
1314
|
-
const
|
|
1276
|
+
const codexBin = opts.codexBin ?? "codex";
|
|
1277
|
+
if (typeof codexBin !== "string" || !codexBin.trim() || CONTROL_CHAR_RE.test(codexBin))
|
|
1278
|
+
throw new Error("Invalid codex_bin");
|
|
1279
|
+
const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : /^~[\\/]/.test(root) ? join(home, root.slice(2)) : resolve(cwd, root);
|
|
1315
1280
|
return {
|
|
1316
1281
|
cwd,
|
|
1317
1282
|
profileFile,
|
|
@@ -1326,41 +1291,523 @@ function resolveConfig(opts, env = process.env, home = homedir2()) {
|
|
|
1326
1291
|
wsUrl,
|
|
1327
1292
|
channels: strings(project.channels, "channels"),
|
|
1328
1293
|
senders: strings(project.senders, "senders"),
|
|
1329
|
-
codexBin
|
|
1330
|
-
stateDir:
|
|
1294
|
+
codexBin,
|
|
1295
|
+
stateDir: join(stateRoot, key)
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
// codex/runtime-home.ts
|
|
1300
|
+
import { homedir as homedir2 } from "node:os";
|
|
1301
|
+
import { delimiter, isAbsolute as isAbsolute2, join as join2, relative, resolve as resolve2, sep } from "node:path";
|
|
1302
|
+
var RUNTIME_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1303
|
+
function executablePath(bin) {
|
|
1304
|
+
if (!bin || RUNTIME_CTRL_RE.test(bin))
|
|
1305
|
+
return;
|
|
1306
|
+
const exts = process.platform === "win32" && !/\.[A-Za-z0-9]+$/.test(bin) ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)] : [""];
|
|
1307
|
+
const bases = isAbsolute2(bin) || bin.includes("/") || bin.includes("\\") ? [resolve2(bin)] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map((dir) => join2(dir, bin));
|
|
1308
|
+
for (const base of bases) {
|
|
1309
|
+
for (const ext of exts) {
|
|
1310
|
+
const candidate = base + ext;
|
|
1311
|
+
try {
|
|
1312
|
+
accessSync(candidate, constants.X_OK);
|
|
1313
|
+
return realpathSync2(candidate);
|
|
1314
|
+
} catch {}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
function assertDirectoryLeaf(path, label) {
|
|
1319
|
+
const info = lstatSync2(path, { throwIfNoEntry: false });
|
|
1320
|
+
if (info?.isSymbolicLink())
|
|
1321
|
+
throw new Error(`${label} must not be a symlink`);
|
|
1322
|
+
if (info && !info.isDirectory())
|
|
1323
|
+
throw new Error(`${label} must be a directory`);
|
|
1324
|
+
}
|
|
1325
|
+
function prepareHomeDirectory(stateDir, home) {
|
|
1326
|
+
assertDirectoryLeaf(stateDir, "Bot state directory");
|
|
1327
|
+
assertDirectoryLeaf(home, "Bot runtime home");
|
|
1328
|
+
assertDirectoryAncestors(stateDir);
|
|
1329
|
+
assertDirectoryAncestors(home);
|
|
1330
|
+
mkdirSync(home, { recursive: true, mode: 448 });
|
|
1331
|
+
}
|
|
1332
|
+
function assertIndependentTree(home, allowedAuthOrigin, codexExecutable) {
|
|
1333
|
+
if (lstatSync2(home).isSymbolicLink())
|
|
1334
|
+
throw new Error("Independent Codex home must not be a symlink");
|
|
1335
|
+
const inspect = (dir, depth = 0) => {
|
|
1336
|
+
if (depth > 32)
|
|
1337
|
+
throw new Error("Independent Codex home directory depth exceeds 32");
|
|
1338
|
+
for (const name of readdirSync(dir)) {
|
|
1339
|
+
const path = join2(dir, name), info = lstatSync2(path);
|
|
1340
|
+
if (info.isSymbolicLink()) {
|
|
1341
|
+
if (dir === home && name === "auth.json" && allowedAuthOrigin && resolve2(home, readlinkSync(path)) === allowedAuthOrigin)
|
|
1342
|
+
continue;
|
|
1343
|
+
const local = relative(home, path).split(sep).join("/");
|
|
1344
|
+
if (codexExecutable && /^tmp\/arg0\/codex-arg0[A-Za-z0-9_-]+\/(apply_patch|applypatch|codex-execve-wrapper|codex-linux-sandbox)$/.test(local)) {
|
|
1345
|
+
try {
|
|
1346
|
+
if (realpathSync2(path) === codexExecutable)
|
|
1347
|
+
continue;
|
|
1348
|
+
} catch {}
|
|
1349
|
+
}
|
|
1350
|
+
throw new Error("Independent Codex home must not link configuration or runtime state");
|
|
1351
|
+
}
|
|
1352
|
+
if (info.isDirectory())
|
|
1353
|
+
inspect(path, depth + 1);
|
|
1354
|
+
else if (!info.isFile())
|
|
1355
|
+
throw new Error("Independent Codex home must contain only regular files and directories");
|
|
1356
|
+
}
|
|
1357
|
+
};
|
|
1358
|
+
inspect(home);
|
|
1359
|
+
}
|
|
1360
|
+
function prepareRuntimeHome(stateDir, source = process.env.CODEX_HOME || join2(homedir2(), ".codex"), mode = "linked", codexBin = "codex") {
|
|
1361
|
+
if (mode !== "linked" && mode !== "isolated" && mode !== "auth-only")
|
|
1362
|
+
throw new Error("Invalid Codex home mode");
|
|
1363
|
+
if (typeof stateDir !== "string" || !stateDir.trim() || stateDir.length > 4096 || RUNTIME_CTRL_RE.test(stateDir)) {
|
|
1364
|
+
throw new Error("Invalid bot state directory");
|
|
1365
|
+
}
|
|
1366
|
+
if (mode === "isolated") {
|
|
1367
|
+
const home2 = join2(stateDir, "codex-home-isolated");
|
|
1368
|
+
prepareHomeDirectory(stateDir, home2);
|
|
1369
|
+
assertIndependentTree(home2, undefined, executablePath(codexBin));
|
|
1370
|
+
return { home: realpathSync2(home2) };
|
|
1371
|
+
}
|
|
1372
|
+
if (typeof source !== "string" || !source.trim() || source.length > 4096 || RUNTIME_CTRL_RE.test(source)) {
|
|
1373
|
+
throw new Error("Invalid Codex source home");
|
|
1374
|
+
}
|
|
1375
|
+
assertDirectoryLeaf(source, "Source Codex home");
|
|
1376
|
+
assertDirectoryAncestors(source);
|
|
1377
|
+
if (mode === "auth-only") {
|
|
1378
|
+
const legacyHome2 = realpathSync2(source);
|
|
1379
|
+
const origin = join2(legacyHome2, "auth.json");
|
|
1380
|
+
const originStat = lstatSync2(origin, { throwIfNoEntry: false });
|
|
1381
|
+
if (!originStat || originStat.isSymbolicLink() || !originStat.isFile()) {
|
|
1382
|
+
throw new Error("auth-only requires an existing regular auth.json; authorize its use explicitly");
|
|
1383
|
+
}
|
|
1384
|
+
const home2 = join2(stateDir, "codex-home-auth-only");
|
|
1385
|
+
prepareHomeDirectory(stateDir, home2);
|
|
1386
|
+
if (lstatSync2(home2).isSymbolicLink() || realpathSync2(home2) === legacyHome2)
|
|
1387
|
+
throw new Error("auth-only home must be independent");
|
|
1388
|
+
for (const name of ["config.toml", "AGENTS.md", "rules", "plugins", "hooks.json"]) {
|
|
1389
|
+
try {
|
|
1390
|
+
lstatSync2(join2(home2, name));
|
|
1391
|
+
} catch (e) {
|
|
1392
|
+
if (e.code === "ENOENT")
|
|
1393
|
+
continue;
|
|
1394
|
+
throw e;
|
|
1395
|
+
}
|
|
1396
|
+
throw new Error("auth-only home contains unexpected configuration; use a fresh state root");
|
|
1397
|
+
}
|
|
1398
|
+
const skills = join2(home2, "skills");
|
|
1399
|
+
const skillsInfo = lstatSync2(skills, { throwIfNoEntry: false });
|
|
1400
|
+
if (skillsInfo && (skillsInfo.isSymbolicLink() || !skillsInfo.isDirectory() || readdirSync(skills).some((name) => name !== ".system")))
|
|
1401
|
+
throw new Error("auth-only home contains unexpected custom skills");
|
|
1402
|
+
assertIndependentTree(home2, origin, executablePath(codexBin));
|
|
1403
|
+
const target = join2(home2, "auth.json");
|
|
1404
|
+
try {
|
|
1405
|
+
if (!lstatSync2(target).isSymbolicLink() || resolve2(home2, readlinkSync(target)) !== origin)
|
|
1406
|
+
throw new Error("Unexpected auth-only login binding");
|
|
1407
|
+
} catch (e) {
|
|
1408
|
+
if (e.code !== "ENOENT")
|
|
1409
|
+
throw e;
|
|
1410
|
+
symlinkSync(origin, target);
|
|
1411
|
+
}
|
|
1412
|
+
assertIndependentTree(home2, origin, executablePath(codexBin));
|
|
1413
|
+
return { home: realpathSync2(home2) };
|
|
1414
|
+
}
|
|
1415
|
+
const legacyHome = existsSync(source) ? realpathSync2(source) : resolve2(source);
|
|
1416
|
+
const home = join2(stateDir, "codex-home");
|
|
1417
|
+
prepareHomeDirectory(stateDir, home);
|
|
1418
|
+
if (realpathSync2(home) === legacyHome)
|
|
1419
|
+
throw new Error("Bot runtime home must differ from desktop Codex home");
|
|
1420
|
+
if (lstatSync2(home).isSymbolicLink())
|
|
1421
|
+
throw new Error("Bot runtime home must not be a symlink");
|
|
1422
|
+
for (const name of ["config.toml", "auth.json", "AGENTS.md", "skills", "rules", "plugins", "hooks.json", "models_cache.json"]) {
|
|
1423
|
+
const origin = join2(legacyHome, name), target = join2(home, name);
|
|
1424
|
+
if (!existsSync(origin))
|
|
1425
|
+
continue;
|
|
1426
|
+
let current;
|
|
1427
|
+
try {
|
|
1428
|
+
current = lstatSync2(target);
|
|
1429
|
+
} catch (e) {
|
|
1430
|
+
if (e.code !== "ENOENT")
|
|
1431
|
+
throw e;
|
|
1432
|
+
}
|
|
1433
|
+
if (current) {
|
|
1434
|
+
if (!current.isSymbolicLink() || resolve2(home, readlinkSync(target)) !== origin)
|
|
1435
|
+
throw new Error(`Unexpected bot runtime configuration: ${name}`);
|
|
1436
|
+
} else
|
|
1437
|
+
symlinkSync(origin, target);
|
|
1438
|
+
}
|
|
1439
|
+
return { home, legacyHome };
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
// src/onboarding-status.ts
|
|
1443
|
+
var DEFAULT_PUBLIC_BASE = "https://agents-chat.com";
|
|
1444
|
+
function isForbiddenMetadataOrLinkLocalHost(host) {
|
|
1445
|
+
if (host === "metadata" || host === "instance-data" || host === "metadata.google.internal" || host.endsWith(".metadata.google.internal") || host === "metadata.goog" || host.endsWith(".metadata.goog") || host === "169.254.169.254" || host === "100.100.100.200" || host === "0.0.0.0") {
|
|
1446
|
+
return true;
|
|
1447
|
+
}
|
|
1448
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) {
|
|
1449
|
+
const [a, b] = host.split(".").map(Number);
|
|
1450
|
+
if (a === 0 || a === 169 && b === 254)
|
|
1451
|
+
return true;
|
|
1452
|
+
}
|
|
1453
|
+
if (host.startsWith("[") && host.endsWith("]")) {
|
|
1454
|
+
const inner = host.slice(1, -1).toLowerCase();
|
|
1455
|
+
if (inner === "::" || inner === "0:0:0:0:0:0:0:0" || inner === "fd00:ec2::254" || /^fe[89ab][0-9a-f]*:/i.test(inner)) {
|
|
1456
|
+
return true;
|
|
1457
|
+
}
|
|
1458
|
+
if (/^::ffff:(?:0:)?(?:0\.0\.0\.0|0:[0-9a-f]{1,4}$|169\.254\.|a9fe:|100\.100\.100\.200$|6464:64c8$)/i.test(inner)) {
|
|
1459
|
+
return true;
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
return false;
|
|
1463
|
+
}
|
|
1464
|
+
function isSafeOnboardingBase(base) {
|
|
1465
|
+
try {
|
|
1466
|
+
if (!base || base !== base.trim() || /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(base))
|
|
1467
|
+
return false;
|
|
1468
|
+
if (/:0(?:\/|$)/.test(base))
|
|
1469
|
+
return false;
|
|
1470
|
+
const parsed = new URL(base);
|
|
1471
|
+
const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
|
|
1472
|
+
if (!host || isForbiddenMetadataOrLinkLocalHost(host))
|
|
1473
|
+
return false;
|
|
1474
|
+
if (parsed.port !== "") {
|
|
1475
|
+
const p = Number(parsed.port);
|
|
1476
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535)
|
|
1477
|
+
return false;
|
|
1478
|
+
}
|
|
1479
|
+
const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
|
|
1480
|
+
if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback))
|
|
1481
|
+
return false;
|
|
1482
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash)
|
|
1483
|
+
return false;
|
|
1484
|
+
return true;
|
|
1485
|
+
} catch {
|
|
1486
|
+
return false;
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
function isSafeOnboardingAgentId(id) {
|
|
1490
|
+
if (!id || id.length > 128 || /[\x00-\x1f\x7f-\x9f\u2028\u2029\s/\\]/.test(id))
|
|
1491
|
+
return false;
|
|
1492
|
+
if (id === "." || id.includes(".."))
|
|
1493
|
+
return false;
|
|
1494
|
+
const lower = id.toLowerCase();
|
|
1495
|
+
if (lower === "__proto__" || lower === "constructor" || lower === "prototype")
|
|
1496
|
+
return false;
|
|
1497
|
+
return true;
|
|
1498
|
+
}
|
|
1499
|
+
var MAX_ONBOARDING_JSON_BYTES = 64 * 1024;
|
|
1500
|
+
async function readBoundedJson(r, maxBytes = MAX_ONBOARDING_JSON_BYTES) {
|
|
1501
|
+
const rawContentLen = r.headers?.get?.("content-length");
|
|
1502
|
+
if (rawContentLen !== null && rawContentLen !== undefined && rawContentLen.trim() !== "") {
|
|
1503
|
+
const trimmedLen = rawContentLen.trim();
|
|
1504
|
+
if (!/^\d+$/.test(trimmedLen) || Number(trimmedLen) > maxBytes) {
|
|
1505
|
+
try {
|
|
1506
|
+
await r.body?.cancel?.();
|
|
1507
|
+
} catch {}
|
|
1508
|
+
throw new Error("onboarding response too large");
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
if (!r.body) {
|
|
1512
|
+
const txt = await r.text();
|
|
1513
|
+
if (Buffer.byteLength(txt, "utf8") > maxBytes)
|
|
1514
|
+
throw new Error("onboarding response too large");
|
|
1515
|
+
return JSON.parse(txt);
|
|
1516
|
+
}
|
|
1517
|
+
const reader = r.body.getReader();
|
|
1518
|
+
const chunks = [];
|
|
1519
|
+
let total = 0;
|
|
1520
|
+
try {
|
|
1521
|
+
while (true) {
|
|
1522
|
+
const { done, value } = await reader.read();
|
|
1523
|
+
if (done)
|
|
1524
|
+
break;
|
|
1525
|
+
if (value) {
|
|
1526
|
+
total += value.byteLength;
|
|
1527
|
+
if (total > maxBytes) {
|
|
1528
|
+
await reader.cancel().catch(() => {});
|
|
1529
|
+
throw new Error("onboarding response too large");
|
|
1530
|
+
}
|
|
1531
|
+
chunks.push(value);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
} finally {
|
|
1535
|
+
try {
|
|
1536
|
+
reader.releaseLock();
|
|
1537
|
+
} catch {}
|
|
1538
|
+
}
|
|
1539
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1540
|
+
}
|
|
1541
|
+
async function getOnboardingStatus(base, agentId, token, request = fetch) {
|
|
1542
|
+
const cleanBase = typeof base === "string" ? base.trim().replace(/\/+$/, "") : "";
|
|
1543
|
+
const rawAgentId = typeof agentId === "string" ? agentId.trim() : "";
|
|
1544
|
+
const validAgent = isSafeOnboardingAgentId(rawAgentId);
|
|
1545
|
+
const safeAgentId = validAgent ? rawAgentId : "";
|
|
1546
|
+
const validBase = Boolean(cleanBase && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(cleanBase) && isSafeOnboardingBase(cleanBase));
|
|
1547
|
+
const safeDisplayBase = validBase ? cleanBase : DEFAULT_PUBLIC_BASE;
|
|
1548
|
+
const chat = `${safeDisplayBase}/chat/${encodeURIComponent(safeAgentId)}`;
|
|
1549
|
+
const result = {
|
|
1550
|
+
agent_id: safeAgentId,
|
|
1551
|
+
claimed: null,
|
|
1552
|
+
authentication: "unknown",
|
|
1553
|
+
chat_url: chat,
|
|
1554
|
+
claim_url: `${chat}?claim=1`,
|
|
1555
|
+
next_step: "check_identity"
|
|
1331
1556
|
};
|
|
1557
|
+
if (!validBase || !validAgent || typeof token !== "string" || !token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) {
|
|
1558
|
+
return result;
|
|
1559
|
+
}
|
|
1560
|
+
try {
|
|
1561
|
+
const r = await request(`${cleanBase}/api/account/onboarding`, {
|
|
1562
|
+
headers: { Authorization: `Bearer ${token.trim()}` },
|
|
1563
|
+
cache: "no-store",
|
|
1564
|
+
signal: AbortSignal.timeout(8000),
|
|
1565
|
+
redirect: "error"
|
|
1566
|
+
});
|
|
1567
|
+
if (r.status === 401 || r.status === 403) {
|
|
1568
|
+
try {
|
|
1569
|
+
await r.body?.cancel?.();
|
|
1570
|
+
} catch {}
|
|
1571
|
+
result.authentication = "failed";
|
|
1572
|
+
return result;
|
|
1573
|
+
}
|
|
1574
|
+
if (!r.ok) {
|
|
1575
|
+
try {
|
|
1576
|
+
await r.body?.cancel?.();
|
|
1577
|
+
} catch {}
|
|
1578
|
+
return result;
|
|
1579
|
+
}
|
|
1580
|
+
const data = await readBoundedJson(r);
|
|
1581
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || Object.prototype.hasOwnProperty.call(data, "__proto__") || data.agent_id !== safeAgentId || typeof data.claimed !== "boolean")
|
|
1582
|
+
return result;
|
|
1583
|
+
result.authentication = "ok";
|
|
1584
|
+
result.claimed = data.claimed;
|
|
1585
|
+
result.next_step = data.claimed ? "verify_reply" : "join_public_chat";
|
|
1586
|
+
} catch {}
|
|
1587
|
+
return result;
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// codex/gui-channel.ts
|
|
1591
|
+
import { randomUUID } from "node:crypto";
|
|
1592
|
+
import { mkdirSync as mkdirSync2, writeFileSync, readFileSync as readFileSync2, readdirSync as readdirSync2, rmSync, lstatSync as lstatSync3 } from "node:fs";
|
|
1593
|
+
import { join as join3 } from "node:path";
|
|
1594
|
+
function payload(result) {
|
|
1595
|
+
if (result?.isError || result?.success === false || result?.error)
|
|
1596
|
+
throw new Error("GUI tool rejected request");
|
|
1597
|
+
if (Array.isArray(result?.content)) {
|
|
1598
|
+
const text = result.content.find((c) => c.type === "text")?.text;
|
|
1599
|
+
if (!text)
|
|
1600
|
+
throw new Error("GUI tool returned no receipt");
|
|
1601
|
+
if (typeof text !== "string" || text.length > 1048576)
|
|
1602
|
+
throw new Error("GUI receipt exceeds size limit");
|
|
1603
|
+
const parsed = JSON.parse(text);
|
|
1604
|
+
if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__"))
|
|
1605
|
+
throw new Error("Invalid GUI receipt");
|
|
1606
|
+
return parsed;
|
|
1607
|
+
}
|
|
1608
|
+
return result;
|
|
1609
|
+
}
|
|
1610
|
+
function validTarget(value) {
|
|
1611
|
+
return typeof value === "string" && value.trim() === value && value.length >= 1 && value.length <= 256 && value !== "." && value !== ".." && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)|%25(?:2e|2f|5c|00)/i.test(value) && !["__proto__", "prototype", "constructor"].includes(value.toLowerCase());
|
|
1332
1612
|
}
|
|
1333
1613
|
|
|
1614
|
+
class GuiChannel {
|
|
1615
|
+
directory;
|
|
1616
|
+
allowedThreads;
|
|
1617
|
+
constructor(directory, allowedThreads) {
|
|
1618
|
+
this.directory = directory;
|
|
1619
|
+
this.allowedThreads = allowedThreads;
|
|
1620
|
+
const existing = lstatSync3(directory, { throwIfNoEntry: false });
|
|
1621
|
+
if (existing && (existing.isSymbolicLink() || !existing.isDirectory()))
|
|
1622
|
+
throw new Error("GUI outbox must be a real directory, not a symlink");
|
|
1623
|
+
assertDirectoryAncestors(directory);
|
|
1624
|
+
mkdirSync2(directory, { recursive: true, mode: 448 });
|
|
1625
|
+
const stat = lstatSync3(directory);
|
|
1626
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
1627
|
+
throw new Error("GUI outbox must be a real directory, not a symlink");
|
|
1628
|
+
}
|
|
1629
|
+
path(id) {
|
|
1630
|
+
if (!/^[0-9a-f-]{36}$/.test(id))
|
|
1631
|
+
throw new Error("Invalid delivery ID");
|
|
1632
|
+
return join3(this.directory, `${id}.json`);
|
|
1633
|
+
}
|
|
1634
|
+
save(entry) {
|
|
1635
|
+
const path = this.path(entry.id), temp = `${path}.${randomUUID()}.tmp`;
|
|
1636
|
+
const stat = lstatSync3(path, { throwIfNoEntry: false });
|
|
1637
|
+
if (stat?.isSymbolicLink() || stat && !stat.isFile())
|
|
1638
|
+
throw new Error("GUI receipt must be a regular file, not a symlink");
|
|
1639
|
+
try {
|
|
1640
|
+
writeFileSync(temp, JSON.stringify(entry), { mode: 384, flag: "wx" });
|
|
1641
|
+
atomicReplaceRegularFile(temp, path, () => {
|
|
1642
|
+
const current = lstatSync3(path, { throwIfNoEntry: false });
|
|
1643
|
+
if (current && (current.isSymbolicLink() || !current.isFile()))
|
|
1644
|
+
throw new Error("GUI receipt must be a regular file, not a symlink");
|
|
1645
|
+
});
|
|
1646
|
+
} catch (error) {
|
|
1647
|
+
if (error.code !== "EEXIST")
|
|
1648
|
+
rmSync(temp, { force: true });
|
|
1649
|
+
throw error;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
get(id) {
|
|
1653
|
+
const path = this.path(id), stat = lstatSync3(path);
|
|
1654
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
1655
|
+
throw new Error("GUI receipt must be a regular file, not a symlink");
|
|
1656
|
+
if (stat.size > 1048576)
|
|
1657
|
+
throw new Error("GUI receipt exceeds size limit");
|
|
1658
|
+
const entry = JSON.parse(readFileSync2(path, "utf8"));
|
|
1659
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.prototype.hasOwnProperty.call(entry, "__proto__") || entry.id !== id || !validTarget(entry.threadId) || typeof entry.prompt !== "string" || typeof entry.createdAt !== "string" || !["pending", "sending", "submitted", "delivered", "uncertain"].includes(entry.status) || entry.hostId !== undefined && !validTarget(entry.hostId) || entry.turnId !== undefined && typeof entry.turnId !== "string" || entry.deliveredAt !== undefined && typeof entry.deliveredAt !== "string")
|
|
1660
|
+
throw new Error("Invalid GUI receipt");
|
|
1661
|
+
return entry;
|
|
1662
|
+
}
|
|
1663
|
+
list() {
|
|
1664
|
+
const entries = [];
|
|
1665
|
+
for (const file of readdirSync2(this.directory)) {
|
|
1666
|
+
if (!/^[0-9a-f-]{36}\.json$/.test(file))
|
|
1667
|
+
continue;
|
|
1668
|
+
try {
|
|
1669
|
+
entries.push(this.get(file.slice(0, -5)));
|
|
1670
|
+
} catch {}
|
|
1671
|
+
}
|
|
1672
|
+
return entries;
|
|
1673
|
+
}
|
|
1674
|
+
enqueue(threadId, text, hostId) {
|
|
1675
|
+
if (!validTarget(threadId) || hostId !== undefined && !validTarget(hostId))
|
|
1676
|
+
throw new Error("Invalid GUI target");
|
|
1677
|
+
if (!this.allowedThreads.includes(threadId))
|
|
1678
|
+
throw new Error("GUI target is not allowed");
|
|
1679
|
+
if (!text.trim() || text.length > 24000)
|
|
1680
|
+
throw new Error("GUI message must contain 1–24000 characters");
|
|
1681
|
+
const id = randomUUID();
|
|
1682
|
+
const entry = {
|
|
1683
|
+
id,
|
|
1684
|
+
threadId,
|
|
1685
|
+
...hostId ? { hostId } : {},
|
|
1686
|
+
prompt: `[AgentsChat delivery ${id}]
|
|
1687
|
+
${text}`,
|
|
1688
|
+
status: "pending",
|
|
1689
|
+
createdAt: new Date().toISOString()
|
|
1690
|
+
};
|
|
1691
|
+
this.save(entry);
|
|
1692
|
+
return entry;
|
|
1693
|
+
}
|
|
1694
|
+
async dispatch(id, call) {
|
|
1695
|
+
const lock = `${this.path(id)}.lock`;
|
|
1696
|
+
try {
|
|
1697
|
+
mkdirSync2(lock, { mode: 448 });
|
|
1698
|
+
} catch (error) {
|
|
1699
|
+
if (error.code !== "EEXIST")
|
|
1700
|
+
throw error;
|
|
1701
|
+
const stat = lstatSync3(lock);
|
|
1702
|
+
if (stat.isSymbolicLink())
|
|
1703
|
+
throw new Error("GUI delivery lock must not be a symlink");
|
|
1704
|
+
const ageMs = Date.now() - stat.mtimeMs;
|
|
1705
|
+
if (!stat.isDirectory() || ageMs >= -5 * 60000 && ageMs <= 5 * 60000)
|
|
1706
|
+
throw error;
|
|
1707
|
+
rmSync(lock, { recursive: true, force: true });
|
|
1708
|
+
mkdirSync2(lock, { mode: 448 });
|
|
1709
|
+
}
|
|
1710
|
+
try {
|
|
1711
|
+
const entry = this.get(id);
|
|
1712
|
+
if (!this.allowedThreads.includes(entry.threadId))
|
|
1713
|
+
throw new Error("GUI target is no longer allowed");
|
|
1714
|
+
if (entry.status === "delivered")
|
|
1715
|
+
return entry;
|
|
1716
|
+
const target = { threadId: entry.threadId, ...entry.hostId ? { hostId: entry.hostId } : {} };
|
|
1717
|
+
if (entry.status === "pending") {
|
|
1718
|
+
entry.status = "sending";
|
|
1719
|
+
this.save(entry);
|
|
1720
|
+
try {
|
|
1721
|
+
payload(await call("send_message_to_thread", { ...target, prompt: entry.prompt }));
|
|
1722
|
+
entry.status = "submitted";
|
|
1723
|
+
this.save(entry);
|
|
1724
|
+
} catch {
|
|
1725
|
+
entry.status = "uncertain";
|
|
1726
|
+
this.save(entry);
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
if (entry.status === "sending") {
|
|
1730
|
+
entry.status = "uncertain";
|
|
1731
|
+
this.save(entry);
|
|
1732
|
+
}
|
|
1733
|
+
try {
|
|
1734
|
+
let cursor;
|
|
1735
|
+
const seenCursors = new Set;
|
|
1736
|
+
for (let page = 0;page < 5; page++) {
|
|
1737
|
+
const history = payload(await call("read_thread", {
|
|
1738
|
+
...target,
|
|
1739
|
+
turnLimit: 10,
|
|
1740
|
+
maxOutputCharsPerItem: 32000,
|
|
1741
|
+
...cursor ? { cursor } : {}
|
|
1742
|
+
}));
|
|
1743
|
+
if (history?.thread?.id !== entry.threadId)
|
|
1744
|
+
throw new Error("Wrong GUI thread in receipt");
|
|
1745
|
+
const turn = history.turns?.find((t) => t.items?.some((item) => item.type === "userMessage" && item.content?.some((c) => c.type === "text" && c.text === entry.prompt)));
|
|
1746
|
+
if (turn) {
|
|
1747
|
+
entry.status = "delivered";
|
|
1748
|
+
entry.deliveredAt = new Date().toISOString();
|
|
1749
|
+
entry.turnId = turn.id;
|
|
1750
|
+
this.save(entry);
|
|
1751
|
+
break;
|
|
1752
|
+
}
|
|
1753
|
+
const nextCursor = history.page?.nextCursor;
|
|
1754
|
+
if (typeof nextCursor !== "string" || !nextCursor.length || seenCursors.has(nextCursor))
|
|
1755
|
+
break;
|
|
1756
|
+
seenCursors.add(nextCursor);
|
|
1757
|
+
cursor = nextCursor;
|
|
1758
|
+
}
|
|
1759
|
+
} catch {}
|
|
1760
|
+
return entry;
|
|
1761
|
+
} finally {
|
|
1762
|
+
rmSync(lock, { recursive: true, force: true });
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
// codex/run.ts
|
|
1768
|
+
import { readFileSync as readFileSync11, lstatSync as lstatSync12 } from "node:fs";
|
|
1769
|
+
import { homedir as homedir6 } from "node:os";
|
|
1770
|
+
import { join as join12, dirname as dirname5 } from "node:path";
|
|
1771
|
+
|
|
1334
1772
|
// codex/bots-config.ts
|
|
1773
|
+
import { readFileSync as readFileSync3, realpathSync as realpathSync3, mkdirSync as mkdirSync3, lstatSync as lstatSync4 } from "node:fs";
|
|
1774
|
+
import { homedir as homedir3 } from "node:os";
|
|
1775
|
+
import { dirname as dirname2, isAbsolute as isAbsolute3, join as join4, resolve as resolve3 } from "node:path";
|
|
1335
1776
|
function defaultRegistry(home = homedir3()) {
|
|
1336
1777
|
return join4(home, ".agentschat/codex-bots.json");
|
|
1337
1778
|
}
|
|
1338
1779
|
function loadBots(file = defaultRegistry(), home = homedir3()) {
|
|
1780
|
+
assertDirectoryAncestors(dirname2(file));
|
|
1339
1781
|
let doc;
|
|
1340
1782
|
try {
|
|
1783
|
+
const info = lstatSync4(file);
|
|
1784
|
+
if (info.isSymbolicLink() || !info.isFile() || info.size > 1048576)
|
|
1785
|
+
throw new Error("Invalid registry file");
|
|
1341
1786
|
doc = JSON.parse(readFileSync3(file, "utf8"));
|
|
1342
1787
|
} catch {
|
|
1343
1788
|
throw new Error("Cannot read bot registry JSON");
|
|
1344
1789
|
}
|
|
1345
1790
|
const object = (x) => x && typeof x === "object" && !Array.isArray(x);
|
|
1346
1791
|
const fields = (x, keys) => {
|
|
1347
|
-
if (!object(x) || Object.
|
|
1792
|
+
if (!object(x) || Object.getOwnPropertyNames(x).some((k) => !keys.includes(k)))
|
|
1348
1793
|
throw new Error("Unknown or invalid bot registry field");
|
|
1349
1794
|
};
|
|
1350
|
-
const text = (x) => typeof x === "string" && x.trim().length > 0;
|
|
1795
|
+
const text = (x, max = 4096) => typeof x === "string" && x.trim().length > 0 && x.length <= max && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(x);
|
|
1796
|
+
const reservedNames = new Set(["__proto__", "constructor", "prototype", ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())]);
|
|
1797
|
+
const reserved = (s) => reservedNames.has(s.toLowerCase());
|
|
1351
1798
|
fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
|
|
1352
|
-
if (doc.version !== 1 || !Array.isArray(doc.bots))
|
|
1799
|
+
if (doc.version !== 1 || !Array.isArray(doc.bots) || doc.bots.length > 128)
|
|
1353
1800
|
throw new Error("Registry requires version 1 and bots array");
|
|
1354
1801
|
for (const k of ["default_workdir", "codex_bin"])
|
|
1355
1802
|
if (doc[k] !== undefined && !text(doc[k]))
|
|
1356
1803
|
throw new Error(`Invalid ${k}`);
|
|
1357
|
-
const path = (value) => value
|
|
1804
|
+
const path = (value) => /^~[\\/]/.test(value) ? join4(home, value.slice(2)) : isAbsolute3(value) ? value : resolve3(dirname2(file), value);
|
|
1358
1805
|
const defaultDir = doc.default_workdir ? path(doc.default_workdir) : join4(home, ".agentschat/workspace");
|
|
1359
1806
|
const names = new Set, identities = new Set;
|
|
1360
1807
|
const bots = [];
|
|
1361
1808
|
for (const bot of doc.bots) {
|
|
1362
1809
|
fields(bot, ["name", "profile", "workdir", "enabled", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
|
|
1363
|
-
if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || names.has(bot.name))
|
|
1810
|
+
if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || reserved(bot.name) || names.has(bot.name))
|
|
1364
1811
|
throw new Error("Bot names must be unique simple labels");
|
|
1365
1812
|
names.add(bot.name);
|
|
1366
1813
|
if (bot.enabled !== undefined && typeof bot.enabled !== "boolean")
|
|
@@ -1369,11 +1816,23 @@ function loadBots(file = defaultRegistry(), home = homedir3()) {
|
|
|
1369
1816
|
continue;
|
|
1370
1817
|
if (!text(bot.profile) || bot.workdir !== undefined && !text(bot.workdir))
|
|
1371
1818
|
throw new Error(`Bot ${bot.name} needs a profile and valid optional workdir`);
|
|
1372
|
-
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile))
|
|
1819
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile) || bot.profile.includes("..") || reservedProfileStem(bot.profile)) {
|
|
1373
1820
|
throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
|
|
1374
|
-
|
|
1821
|
+
}
|
|
1822
|
+
const directoryLeaf = (dir) => {
|
|
1823
|
+
const info = lstatSync4(dir, { throwIfNoEntry: false });
|
|
1824
|
+
if (info && (info.isSymbolicLink() || !info.isDirectory()))
|
|
1825
|
+
throw new Error("Bot workdir must be a directory, not a symlink");
|
|
1826
|
+
assertDirectoryAncestors(dir);
|
|
1827
|
+
};
|
|
1828
|
+
if (!doc.default_workdir && !bot.workdir) {
|
|
1829
|
+
directoryLeaf(join4(home, ".agentschat"));
|
|
1830
|
+
directoryLeaf(defaultDir);
|
|
1375
1831
|
mkdirSync3(defaultDir, { recursive: true, mode: 448 });
|
|
1376
|
-
|
|
1832
|
+
}
|
|
1833
|
+
const workdir = bot.workdir ? path(bot.workdir) : defaultDir;
|
|
1834
|
+
directoryLeaf(workdir);
|
|
1835
|
+
const cwd = realpathSync3(workdir);
|
|
1377
1836
|
const settings = {};
|
|
1378
1837
|
for (const k of ["agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "codex_home_mode"])
|
|
1379
1838
|
if (bot[k] !== undefined)
|
|
@@ -1401,12 +1860,94 @@ import { spawn } from "node:child_process";
|
|
|
1401
1860
|
import { fileURLToPath } from "node:url";
|
|
1402
1861
|
import { createInterface } from "node:readline";
|
|
1403
1862
|
|
|
1863
|
+
// src/wake.ts
|
|
1864
|
+
import { existsSync as existsSync2, lstatSync as lstatSync5, readFileSync as readFileSync4, readlinkSync as readlinkSync2 } from "node:fs";
|
|
1865
|
+
import { homedir as homedir4 } from "node:os";
|
|
1866
|
+
import { dirname as dirname3, isAbsolute as isAbsolute4, join as join5, parse as parse2, resolve as resolve4, win32 as pathWin32 } from "node:path";
|
|
1867
|
+
var PROTOTYPE_WAKE_KEYS = new Set([
|
|
1868
|
+
"prototype",
|
|
1869
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
1870
|
+
]);
|
|
1871
|
+
var GROK_GATEWAY_PATH_CANDIDATES = [
|
|
1872
|
+
join5(process.env.HOME || process.env.USERPROFILE || homedir4(), ".grok", "gateway.json"),
|
|
1873
|
+
"/home/box/sand-data/gateway.json"
|
|
1874
|
+
];
|
|
1875
|
+
var zcodeSessionQueues = new Map;
|
|
1876
|
+
function resolveWindowsCliSpawn(cmd, args, opts) {
|
|
1877
|
+
const platform = opts?.platform ?? process.platform;
|
|
1878
|
+
const trimmed = (cmd || "").trim();
|
|
1879
|
+
if (!trimmed)
|
|
1880
|
+
return { cmd, args };
|
|
1881
|
+
const execPath = opts?.execPath ?? process.execPath;
|
|
1882
|
+
if (/\.(?:cjs|mjs|js)$/i.test(trimmed)) {
|
|
1883
|
+
return { cmd: execPath, args: [trimmed, ...args] };
|
|
1884
|
+
}
|
|
1885
|
+
if (platform !== "win32") {
|
|
1886
|
+
return { cmd: trimmed, args };
|
|
1887
|
+
}
|
|
1888
|
+
const env = opts?.env ?? process.env;
|
|
1889
|
+
const exists = opts?.existsImpl ?? existsSync2;
|
|
1890
|
+
const readText = opts?.readTextImpl ?? ((p) => readFileSync4(p, "utf8"));
|
|
1891
|
+
const hasSep = /[\\/]/.test(trimmed) || /^[A-Za-z]:/.test(trimmed);
|
|
1892
|
+
const hasWinExt = /\.(?:exe|cmd|bat)$/i.test(trimmed);
|
|
1893
|
+
const candidates = [];
|
|
1894
|
+
if (hasSep) {
|
|
1895
|
+
if (hasWinExt) {
|
|
1896
|
+
candidates.push(trimmed);
|
|
1897
|
+
} else {
|
|
1898
|
+
candidates.push(`${trimmed}.exe`, `${trimmed}.cmd`, trimmed);
|
|
1899
|
+
}
|
|
1900
|
+
} else {
|
|
1901
|
+
const rawPath = env.PATH ?? env.Path ?? env.path ?? "";
|
|
1902
|
+
for (const rawDir of rawPath.split(";")) {
|
|
1903
|
+
const dir = rawDir.trim().replace(/^"+|"+$/g, "");
|
|
1904
|
+
if (!dir)
|
|
1905
|
+
continue;
|
|
1906
|
+
if (hasWinExt) {
|
|
1907
|
+
candidates.push(pathWin32.join(dir, trimmed));
|
|
1908
|
+
} else {
|
|
1909
|
+
candidates.push(pathWin32.join(dir, `${trimmed}.exe`), pathWin32.join(dir, `${trimmed}.cmd`));
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
for (const candidate of candidates) {
|
|
1914
|
+
if (!exists(candidate))
|
|
1915
|
+
continue;
|
|
1916
|
+
if (/\.exe$/i.test(candidate)) {
|
|
1917
|
+
return { cmd: candidate, args };
|
|
1918
|
+
}
|
|
1919
|
+
if (/\.(?:cmd|bat)$/i.test(candidate)) {
|
|
1920
|
+
try {
|
|
1921
|
+
const content = readText(candidate);
|
|
1922
|
+
const m = content.match(/%(?:~)?dp0%?[\\/]([^"\r\n]+?\.(?:cjs|mjs|js))/i);
|
|
1923
|
+
if (m && m[1]) {
|
|
1924
|
+
const cmdDir = pathWin32.dirname(candidate);
|
|
1925
|
+
const scriptPath = pathWin32.resolve(cmdDir, m[1].replace(/\//g, "\\"));
|
|
1926
|
+
if (exists(scriptPath)) {
|
|
1927
|
+
const bundledNode = pathWin32.join(cmdDir, "node.exe");
|
|
1928
|
+
const runner = exists(bundledNode) ? bundledNode : execPath;
|
|
1929
|
+
return { cmd: runner, args: [scriptPath, ...args] };
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
} catch {}
|
|
1933
|
+
return { cmd: candidate, args };
|
|
1934
|
+
}
|
|
1935
|
+
return { cmd: candidate, args };
|
|
1936
|
+
}
|
|
1937
|
+
return { cmd: trimmed, args };
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
// codex/app-server.ts
|
|
1404
1941
|
class ThreadBusyError extends Error {
|
|
1405
1942
|
constructor() {
|
|
1406
1943
|
super("This conversation has another active writer; waiting to resume the same task");
|
|
1407
1944
|
this.name = "ThreadBusyError";
|
|
1408
1945
|
}
|
|
1409
1946
|
}
|
|
1947
|
+
var APP_SERVER_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1948
|
+
function validThreadId(id) {
|
|
1949
|
+
return typeof id === "string" && id.trim().length > 0 && id.length <= 256 && !APP_SERVER_CTRL_RE.test(id);
|
|
1950
|
+
}
|
|
1410
1951
|
|
|
1411
1952
|
class AppServer {
|
|
1412
1953
|
bin;
|
|
@@ -1416,9 +1957,12 @@ class AppServer {
|
|
|
1416
1957
|
effort;
|
|
1417
1958
|
model;
|
|
1418
1959
|
toolIdentity;
|
|
1960
|
+
requestTimeoutMs;
|
|
1419
1961
|
onFatal;
|
|
1420
1962
|
closed = false;
|
|
1421
1963
|
child;
|
|
1964
|
+
rl;
|
|
1965
|
+
killTimer;
|
|
1422
1966
|
nextId = 0;
|
|
1423
1967
|
pending = new Map;
|
|
1424
1968
|
active;
|
|
@@ -1427,7 +1971,7 @@ class AppServer {
|
|
|
1427
1971
|
readonlyFilesystemReported = false;
|
|
1428
1972
|
diagnosticTail = "";
|
|
1429
1973
|
disabledMcp = {};
|
|
1430
|
-
constructor(bin = "codex", args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs, permissions = "full-access", runtime, effort, model, toolIdentity) {
|
|
1974
|
+
constructor(bin = "codex", args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs, permissions = "full-access", runtime, effort, model, toolIdentity, requestTimeoutMs = 30000) {
|
|
1431
1975
|
this.bin = bin;
|
|
1432
1976
|
this.args = args;
|
|
1433
1977
|
this.permissions = permissions;
|
|
@@ -1435,11 +1979,25 @@ class AppServer {
|
|
|
1435
1979
|
this.effort = effort;
|
|
1436
1980
|
this.model = model;
|
|
1437
1981
|
this.toolIdentity = toolIdentity;
|
|
1982
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
1438
1983
|
}
|
|
1439
1984
|
get namespace() {
|
|
1440
1985
|
return this.runtime?.home;
|
|
1441
1986
|
}
|
|
1442
1987
|
async start() {
|
|
1988
|
+
if (this.model !== undefined && (typeof this.model !== "string" || !this.model.trim() || this.model.length > 256 || APP_SERVER_CTRL_RE.test(this.model)))
|
|
1989
|
+
throw new Error("Invalid app-server model");
|
|
1990
|
+
if (this.runtime) {
|
|
1991
|
+
if (typeof this.runtime.home !== "string" || !this.runtime.home.trim() || this.runtime.home.length > 4096 || APP_SERVER_CTRL_RE.test(this.runtime.home) || this.runtime.legacyHome !== undefined && (typeof this.runtime.legacyHome !== "string" || !this.runtime.legacyHome.trim() || this.runtime.legacyHome.length > 4096 || APP_SERVER_CTRL_RE.test(this.runtime.legacyHome))) {
|
|
1992
|
+
throw new Error("Invalid app-server runtime home");
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
if (this.toolIdentity) {
|
|
1996
|
+
const { profileFile, agentId, apiUrl, wsUrl } = this.toolIdentity;
|
|
1997
|
+
if ([profileFile, agentId, apiUrl, wsUrl].some((v) => typeof v !== "string" || !v.trim() || v.length > 4096 || APP_SERVER_CTRL_RE.test(v)) || agentId.length > 256) {
|
|
1998
|
+
throw new Error("Invalid app-server tool identity");
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
1443
2001
|
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^AGENTS?CHAT_|^RELAY_/.test(k)));
|
|
1444
2002
|
env.AGENTSCHAT_LOCK_OWNER_PID = String(process.pid);
|
|
1445
2003
|
env.AGENTSCHAT_TOOL_ONLY = "1";
|
|
@@ -1467,7 +2025,8 @@ class AppServer {
|
|
|
1467
2025
|
const encode = (value) => value && typeof value === "object" && !Array.isArray(value) ? `{ ${Object.entries(value).map(([k, v]) => `${JSON.stringify(k)} = ${encode(v)}`).join(", ")} }` : JSON.stringify(value);
|
|
1468
2026
|
args.push("-c", `mcp_servers.agentschat=${encode(entry)}`);
|
|
1469
2027
|
}
|
|
1470
|
-
|
|
2028
|
+
const resolved = resolveWindowsCliSpawn(this.bin, args, { env });
|
|
2029
|
+
this.child = spawn(resolved.cmd, resolved.args, { env, stdio: "pipe", windowsHide: true });
|
|
1471
2030
|
this.child.stderr.on("data", (chunk) => {
|
|
1472
2031
|
if (this.initialized)
|
|
1473
2032
|
return;
|
|
@@ -1477,13 +2036,31 @@ class AppServer {
|
|
|
1477
2036
|
});
|
|
1478
2037
|
this.child.stdin.on("error", () => this.fatal(new Error("Codex input pipe closed")));
|
|
1479
2038
|
this.child.on("error", () => this.fatal(new Error("Could not start Codex app-server")));
|
|
1480
|
-
this.child.on("exit", () =>
|
|
1481
|
-
|
|
2039
|
+
this.child.on("exit", () => {
|
|
2040
|
+
if (this.killTimer) {
|
|
2041
|
+
clearTimeout(this.killTimer);
|
|
2042
|
+
this.killTimer = undefined;
|
|
2043
|
+
}
|
|
2044
|
+
this.fatal(new Error(!this.initialized && this.readonlyFilesystemReported ? "Codex app-server exited before initialization after reporting a read-only filesystem. CODEX_HOME must be writable (including installation_id); sqlite_home/log_dir overrides alone are insufficient. Use an authorized writable state_root and dedicated home; authentication is a separate step." : "Codex app-server exited"));
|
|
2045
|
+
});
|
|
2046
|
+
this.rl = createInterface({ input: this.child.stdout });
|
|
2047
|
+
this.rl.on("line", (line) => {
|
|
2048
|
+
if (line.length > 8 * 1024 * 1024) {
|
|
2049
|
+
this.fatal(new Error("Oversized app-server response"));
|
|
2050
|
+
return;
|
|
2051
|
+
}
|
|
2052
|
+
let parsed;
|
|
1482
2053
|
try {
|
|
1483
|
-
|
|
2054
|
+
parsed = JSON.parse(line);
|
|
1484
2055
|
} catch {
|
|
1485
2056
|
this.fatal(new Error("Invalid app-server response"));
|
|
2057
|
+
return;
|
|
1486
2058
|
}
|
|
2059
|
+
if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
2060
|
+
this.fatal(new Error("Invalid app-server response"));
|
|
2061
|
+
return;
|
|
2062
|
+
}
|
|
2063
|
+
this.receive(parsed);
|
|
1487
2064
|
});
|
|
1488
2065
|
await this.request("initialize", { clientInfo: { name: "agentschat_bridge", version: "0.1.0" } });
|
|
1489
2066
|
this.write({ method: "initialized" });
|
|
@@ -1508,26 +2085,42 @@ class AppServer {
|
|
|
1508
2085
|
this.child.stdin.write(JSON.stringify(value) + `
|
|
1509
2086
|
`);
|
|
1510
2087
|
}
|
|
1511
|
-
request(method, params) {
|
|
1512
|
-
return new Promise((
|
|
2088
|
+
request(method, params, timeoutMs = this.requestTimeoutMs) {
|
|
2089
|
+
return new Promise((resolve5, reject) => {
|
|
1513
2090
|
const id = ++this.nextId;
|
|
1514
|
-
|
|
2091
|
+
const timer = setTimeout(() => {
|
|
2092
|
+
if (!this.pending.delete(id))
|
|
2093
|
+
return;
|
|
2094
|
+
const err = new Error(`App-server request timed out (${method})`);
|
|
2095
|
+
this.fatal(err);
|
|
2096
|
+
reject(err);
|
|
2097
|
+
}, Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(Math.max(50, Math.floor(timeoutMs)), 2147483647) : 30000);
|
|
2098
|
+
timer.unref?.();
|
|
2099
|
+
this.pending.set(id, { method, timer, resolve: resolve5, reject });
|
|
1515
2100
|
try {
|
|
1516
2101
|
this.write({ id, method, params });
|
|
1517
2102
|
} catch (e) {
|
|
2103
|
+
clearTimeout(timer);
|
|
1518
2104
|
this.pending.delete(id);
|
|
1519
2105
|
reject(e);
|
|
1520
2106
|
}
|
|
1521
2107
|
});
|
|
1522
2108
|
}
|
|
1523
2109
|
receive(message) {
|
|
2110
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
|
2111
|
+
this.fatal(new Error("Invalid app-server response"));
|
|
2112
|
+
return;
|
|
2113
|
+
}
|
|
1524
2114
|
if (message.id !== undefined && message.method) {
|
|
1525
|
-
|
|
2115
|
+
try {
|
|
2116
|
+
this.write({ id: message.id, error: { code: -32601, message: "Interactive requests unsupported by bridge" } });
|
|
2117
|
+
} catch {}
|
|
1526
2118
|
return;
|
|
1527
2119
|
}
|
|
1528
2120
|
if (message.id !== undefined) {
|
|
1529
2121
|
const waiter = this.pending.get(message.id);
|
|
1530
2122
|
if (waiter) {
|
|
2123
|
+
clearTimeout(waiter.timer);
|
|
1531
2124
|
this.pending.delete(message.id);
|
|
1532
2125
|
if (message.error) {
|
|
1533
2126
|
const detail = typeof message.error.message === "string" ? message.error.message : "";
|
|
@@ -1542,36 +2135,46 @@ class AppServer {
|
|
|
1542
2135
|
if (!a || p?.threadId !== a.thread)
|
|
1543
2136
|
return;
|
|
1544
2137
|
if (!a.turn) {
|
|
1545
|
-
a.early.
|
|
2138
|
+
if (a.early.length < 500)
|
|
2139
|
+
a.early.push(message);
|
|
1546
2140
|
return;
|
|
1547
2141
|
}
|
|
1548
2142
|
if ((p.turnId ?? p.turn?.id) !== a.turn)
|
|
1549
2143
|
return;
|
|
1550
|
-
|
|
1551
|
-
a.items.
|
|
2144
|
+
const recordItem = (item) => {
|
|
2145
|
+
if (item?.type === "agentMessage" && (!item.phase || item.phase === "final_answer") && typeof item.id === "string" && item.id.length > 0 && typeof item.text === "string" && (a.items.has(item.id) || a.items.size < 512))
|
|
2146
|
+
a.items.set(item.id, item.text);
|
|
2147
|
+
};
|
|
2148
|
+
if (message.method === "item/completed")
|
|
2149
|
+
recordItem(p.item);
|
|
1552
2150
|
if (message.method === "turn/completed") {
|
|
1553
2151
|
this.active = undefined;
|
|
1554
|
-
if (p.turn
|
|
1555
|
-
a.reject(new Error(`Codex turn ${p.turn
|
|
2152
|
+
if (p.turn?.status !== "completed") {
|
|
2153
|
+
a.reject(new Error(`Codex turn ${p.turn?.status ?? "unknown"}`));
|
|
1556
2154
|
return;
|
|
1557
2155
|
}
|
|
1558
|
-
for (const item of p.turn.items
|
|
1559
|
-
|
|
1560
|
-
a.items.set(item.id, item.text);
|
|
2156
|
+
for (const item of Array.isArray(p.turn.items) ? p.turn.items : [])
|
|
2157
|
+
recordItem(item);
|
|
1561
2158
|
const text = [...a.items.values()].join(`
|
|
1562
2159
|
`).trim();
|
|
1563
2160
|
text ? a.resolve(text) : a.reject(new Error("Codex completed without a final reply"));
|
|
1564
2161
|
}
|
|
1565
2162
|
}
|
|
1566
2163
|
async thread(cwd, existing, ephemeral = false, permissions = this.permissions) {
|
|
2164
|
+
if (typeof cwd !== "string" || !cwd.trim() || cwd.length > 4096 || APP_SERVER_CTRL_RE.test(cwd))
|
|
2165
|
+
throw new Error("Invalid app-server cwd");
|
|
2166
|
+
if (existing !== undefined && !validThreadId(existing))
|
|
2167
|
+
throw new Error("Invalid app-server thread ID");
|
|
1567
2168
|
const configured = existing ? this.threadPermissions.get(existing) : undefined;
|
|
1568
2169
|
if (configured !== undefined && configured !== permissions) {
|
|
1569
2170
|
throw new Error("Cannot change permissions of a loaded thread; create a new thread");
|
|
1570
2171
|
}
|
|
1571
2172
|
const result = await this.request("config/read", { includeLayers: false, cwd });
|
|
1572
2173
|
this.disabledMcp = {};
|
|
1573
|
-
for (const name of Object.keys(result.config?.mcp_servers ?? {}))
|
|
1574
|
-
|
|
2174
|
+
for (const name of Object.keys(result.config?.mcp_servers ?? {})) {
|
|
2175
|
+
if (!/^(?:__proto__|constructor|prototype)$/i.test(name))
|
|
2176
|
+
this.disabledMcp[name] = { enabled: false };
|
|
2177
|
+
}
|
|
1575
2178
|
const r = await this.request(existing ? "thread/resume" : "thread/start", {
|
|
1576
2179
|
...existing ? { threadId: existing } : { ephemeral },
|
|
1577
2180
|
cwd,
|
|
@@ -1584,9 +2187,13 @@ class AppServer {
|
|
|
1584
2187
|
if (typeof r.thread?.id !== "string")
|
|
1585
2188
|
throw new Error("App-server returned no thread ID");
|
|
1586
2189
|
this.threadPermissions.set(r.thread.id, permissions);
|
|
2190
|
+
if (this.threadPermissions.size > 1024)
|
|
2191
|
+
this.threadPermissions.delete(this.threadPermissions.keys().next().value);
|
|
1587
2192
|
return r.thread.id;
|
|
1588
2193
|
}
|
|
1589
2194
|
async readThread(thread) {
|
|
2195
|
+
if (!validThreadId(thread))
|
|
2196
|
+
throw new Error("Invalid app-server thread ID");
|
|
1590
2197
|
const result = await this.request("thread/read", { threadId: thread, includeTurns: true });
|
|
1591
2198
|
if (result.thread?.id !== thread || !Array.isArray(result.thread.turns))
|
|
1592
2199
|
throw new Error("Original thread history unavailable");
|
|
@@ -1595,6 +2202,8 @@ class AppServer {
|
|
|
1595
2202
|
return { id: thread, createdAt: result.thread.createdAt, turns: result.thread.turns };
|
|
1596
2203
|
}
|
|
1597
2204
|
async readLegacyThread(thread) {
|
|
2205
|
+
if (!validThreadId(thread))
|
|
2206
|
+
throw new Error("Invalid app-server thread ID");
|
|
1598
2207
|
if (!this.runtime?.legacyHome)
|
|
1599
2208
|
return this.readThread(thread);
|
|
1600
2209
|
const reader = new AppServer(this.bin, undefined, undefined, this.permissions, { home: this.runtime.legacyHome });
|
|
@@ -1606,6 +2215,10 @@ class AppServer {
|
|
|
1606
2215
|
}
|
|
1607
2216
|
}
|
|
1608
2217
|
async nameThread(thread, name) {
|
|
2218
|
+
if (!validThreadId(thread))
|
|
2219
|
+
throw new Error("Invalid app-server thread ID");
|
|
2220
|
+
if (typeof name !== "string" || !name.trim() || name.length > 256 || APP_SERVER_CTRL_RE.test(name))
|
|
2221
|
+
throw new Error("Invalid app-server thread name");
|
|
1609
2222
|
await this.request("thread/name/set", { threadId: thread, name });
|
|
1610
2223
|
}
|
|
1611
2224
|
async generate(thread, text, effort = this.effort) {
|
|
@@ -1614,8 +2227,8 @@ class AppServer {
|
|
|
1614
2227
|
const permissions = this.threadPermissions.get(thread);
|
|
1615
2228
|
if (!permissions)
|
|
1616
2229
|
throw new Error("Thread permissions have not been configured");
|
|
1617
|
-
const completed = new Promise((
|
|
1618
|
-
this.active = { thread, items: new Map, early: [], resolve:
|
|
2230
|
+
const completed = new Promise((resolve5, reject) => {
|
|
2231
|
+
this.active = { thread, items: new Map, early: [], resolve: resolve5, reject };
|
|
1619
2232
|
});
|
|
1620
2233
|
completed.catch(() => {});
|
|
1621
2234
|
try {
|
|
@@ -1636,48 +2249,95 @@ class AppServer {
|
|
|
1636
2249
|
}
|
|
1637
2250
|
}
|
|
1638
2251
|
fail(error) {
|
|
1639
|
-
for (const p of this.pending.values())
|
|
2252
|
+
for (const p of this.pending.values()) {
|
|
2253
|
+
clearTimeout(p.timer);
|
|
1640
2254
|
p.reject(error);
|
|
2255
|
+
}
|
|
1641
2256
|
this.pending.clear();
|
|
1642
2257
|
if (this.active) {
|
|
1643
2258
|
this.active.reject(error);
|
|
1644
2259
|
this.active = undefined;
|
|
1645
2260
|
}
|
|
1646
2261
|
}
|
|
2262
|
+
terminateChild() {
|
|
2263
|
+
try {
|
|
2264
|
+
this.rl?.close();
|
|
2265
|
+
} catch {}
|
|
2266
|
+
this.rl = undefined;
|
|
2267
|
+
const child = this.child;
|
|
2268
|
+
if (!child)
|
|
2269
|
+
return;
|
|
2270
|
+
try {
|
|
2271
|
+
child.stdin.end();
|
|
2272
|
+
} catch {}
|
|
2273
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
2274
|
+
try {
|
|
2275
|
+
child.kill("SIGTERM");
|
|
2276
|
+
} catch {}
|
|
2277
|
+
if (!this.killTimer) {
|
|
2278
|
+
this.killTimer = setTimeout(() => {
|
|
2279
|
+
this.killTimer = undefined;
|
|
2280
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
2281
|
+
try {
|
|
2282
|
+
child.kill("SIGKILL");
|
|
2283
|
+
} catch {}
|
|
2284
|
+
}
|
|
2285
|
+
}, 2000);
|
|
2286
|
+
this.killTimer.unref?.();
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
1647
2290
|
fatal(error) {
|
|
1648
2291
|
if (this.closed)
|
|
1649
2292
|
return;
|
|
1650
2293
|
this.closed = true;
|
|
1651
2294
|
this.fail(error);
|
|
1652
2295
|
this.onFatal?.();
|
|
1653
|
-
this.
|
|
2296
|
+
this.terminateChild();
|
|
1654
2297
|
}
|
|
1655
2298
|
close() {
|
|
1656
2299
|
this.closed = true;
|
|
1657
2300
|
this.fail(new Error("App-server stopped"));
|
|
1658
|
-
this.
|
|
2301
|
+
this.terminateChild();
|
|
1659
2302
|
}
|
|
1660
2303
|
}
|
|
1661
2304
|
|
|
1662
2305
|
// src/team-lead-skill.ts
|
|
1663
|
-
import { readFileSync as
|
|
2306
|
+
import { readFileSync as readFileSync5 } from "node:fs";
|
|
1664
2307
|
var TEAM_LEAD_SKILL_ID = "agentschat-team-lead";
|
|
1665
|
-
var TEAM_LEAD_SKILL_BODY =
|
|
2308
|
+
var TEAM_LEAD_SKILL_BODY = readFileSync5(new URL("../skills/agentschat-team-lead/SKILL.md", import.meta.url), "utf8");
|
|
1666
2309
|
var TEAM_LEAD_NO_UPDATE = "[[AGENTSCHAT_NO_UPDATE]]";
|
|
1667
2310
|
function isTeamLeadSkillInvocation(prompt) {
|
|
2311
|
+
if (typeof prompt !== "string" || prompt.length > 256 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/.test(prompt)) {
|
|
2312
|
+
return false;
|
|
2313
|
+
}
|
|
1668
2314
|
return [TEAM_LEAD_SKILL_ID, `$${TEAM_LEAD_SKILL_ID}`, `执行 $${TEAM_LEAD_SKILL_ID}`].includes(prompt.trim());
|
|
1669
2315
|
}
|
|
1670
2316
|
|
|
1671
2317
|
// codex/bridge.ts
|
|
1672
|
-
import {
|
|
1673
|
-
import { join as
|
|
2318
|
+
import { lstatSync as lstatSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync9, writeFileSync as writeFileSync4, openSync as openSync2, closeSync as closeSync2, unlinkSync as unlinkSync5 } from "node:fs";
|
|
2319
|
+
import { join as join10 } from "node:path";
|
|
2320
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1674
2321
|
|
|
1675
2322
|
// codex/thread-history.ts
|
|
1676
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
1677
|
-
import { mkdirSync as mkdirSync4,
|
|
1678
|
-
import { join as
|
|
2323
|
+
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
2324
|
+
import { chmodSync, lstatSync as lstatSync6, mkdirSync as mkdirSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
2325
|
+
import { join as join6 } from "node:path";
|
|
2326
|
+
var HISTORY_FORBIDDEN_KEYS = new Set([
|
|
2327
|
+
"__proto__",
|
|
2328
|
+
"prototype",
|
|
2329
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
2330
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
2331
|
+
]);
|
|
2332
|
+
var isHistoryForbiddenKey = (key) => HISTORY_FORBIDDEN_KEYS.has(key) || HISTORY_FORBIDDEN_KEYS.has(key.toLowerCase());
|
|
1679
2333
|
function priorChannelThreads(threads, channel) {
|
|
1680
|
-
|
|
2334
|
+
if (!threads || typeof threads !== "object" || typeof channel !== "string" || !channel)
|
|
2335
|
+
return [];
|
|
2336
|
+
return [...new Set(Object.entries(threads).filter(([key, id]) => {
|
|
2337
|
+
if (isHistoryForbiddenKey(key))
|
|
2338
|
+
return false;
|
|
2339
|
+
if (typeof id !== "string" || !id.trim())
|
|
2340
|
+
return false;
|
|
1681
2341
|
if (key === channel)
|
|
1682
2342
|
return true;
|
|
1683
2343
|
try {
|
|
@@ -1689,28 +2349,84 @@ function priorChannelThreads(threads, channel) {
|
|
|
1689
2349
|
}).map(([, id]) => id))];
|
|
1690
2350
|
}
|
|
1691
2351
|
function preserveChannelHistory(directory, channel, histories, redact) {
|
|
1692
|
-
|
|
2352
|
+
if (typeof channel !== "string" || !channel.trim() || channel !== channel.trim() || channel.length > 256 || channel === "." || channel.includes("..") || /[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel) || /%(?:2e%2e|2f|5c|00)/i.test(channel) || isHistoryForbiddenKey(channel)) {
|
|
2353
|
+
throw new Error("Invalid history channel");
|
|
2354
|
+
}
|
|
2355
|
+
const checkDirectory = (path) => {
|
|
2356
|
+
try {
|
|
2357
|
+
const stat = lstatSync6(path);
|
|
2358
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
2359
|
+
throw new Error("History directory must be a non-symlink directory");
|
|
2360
|
+
} catch (error) {
|
|
2361
|
+
if (error.code !== "ENOENT")
|
|
2362
|
+
throw error;
|
|
2363
|
+
}
|
|
2364
|
+
};
|
|
2365
|
+
assertDirectoryAncestors(directory);
|
|
2366
|
+
const root = join6(directory, "history");
|
|
2367
|
+
checkDirectory(directory);
|
|
2368
|
+
checkDirectory(root);
|
|
1693
2369
|
mkdirSync4(root, { recursive: true, mode: 448 });
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
2370
|
+
checkDirectory(root);
|
|
2371
|
+
if (process.platform !== "win32")
|
|
2372
|
+
chmodSync(root, 448);
|
|
2373
|
+
const file = join6(root, createHash2("sha256").update(channel).digest("hex").slice(0, 24) + ".json");
|
|
2374
|
+
try {
|
|
2375
|
+
const stat = lstatSync6(file);
|
|
2376
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
2377
|
+
throw new Error("History archive must be a regular file, not a symlink");
|
|
2378
|
+
} catch (e) {
|
|
2379
|
+
if (e.code !== "ENOENT")
|
|
2380
|
+
throw e;
|
|
2381
|
+
}
|
|
2382
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${randomBytes(4).toString("hex")}.tmp`;
|
|
2383
|
+
try {
|
|
2384
|
+
writeFileSync2(tmp, redact(JSON.stringify({ channel_id: channel, threads: histories })), { flag: "wx", mode: 384 });
|
|
2385
|
+
if (process.platform !== "win32")
|
|
2386
|
+
chmodSync(tmp, 384);
|
|
2387
|
+
atomicReplaceRegularFile(tmp, file, () => {
|
|
2388
|
+
try {
|
|
2389
|
+
const stat = lstatSync6(file);
|
|
2390
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
2391
|
+
throw new Error("History archive must be a regular file, not a symlink");
|
|
2392
|
+
} catch (error) {
|
|
2393
|
+
if (error.code !== "ENOENT")
|
|
2394
|
+
throw error;
|
|
2395
|
+
}
|
|
2396
|
+
});
|
|
2397
|
+
} catch (err) {
|
|
2398
|
+
try {
|
|
2399
|
+
unlinkSync2(tmp);
|
|
2400
|
+
} catch {}
|
|
2401
|
+
throw err;
|
|
2402
|
+
}
|
|
1697
2403
|
const records = [];
|
|
1698
2404
|
let sequence = 0;
|
|
1699
|
-
for (const history of histories)
|
|
1700
|
-
|
|
2405
|
+
for (const history of Array.isArray(histories) ? histories : []) {
|
|
2406
|
+
if (!history || typeof history !== "object")
|
|
2407
|
+
continue;
|
|
2408
|
+
for (const turn of Array.isArray(history.turns) ? history.turns : []) {
|
|
2409
|
+
if (!turn || typeof turn !== "object")
|
|
2410
|
+
continue;
|
|
1701
2411
|
const order = String(turn.id ?? history.createdAt ?? history.id);
|
|
1702
|
-
for (const item of turn.items
|
|
2412
|
+
for (const item of Array.isArray(turn.items) ? turn.items : []) {
|
|
2413
|
+
if (!item || typeof item !== "object")
|
|
2414
|
+
continue;
|
|
1703
2415
|
if (item.type === "userMessage") {
|
|
1704
|
-
|
|
2416
|
+
const contentParts = Array.isArray(item.content) ? item.content : [];
|
|
2417
|
+
let text = contentParts.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
|
|
1705
2418
|
`);
|
|
1706
2419
|
const marker = `AgentsChat message:
|
|
1707
2420
|
`;
|
|
1708
2421
|
if (text.includes(marker)) {
|
|
1709
2422
|
try {
|
|
1710
|
-
|
|
1711
|
-
if (message
|
|
1712
|
-
|
|
1713
|
-
|
|
2423
|
+
let message = JSON.parse(text.slice(text.lastIndexOf(marker) + marker.length));
|
|
2424
|
+
if (message && typeof message === "object" && !Array.isArray(message)) {
|
|
2425
|
+
message = Object.fromEntries(Object.entries(message).filter(([key]) => !isHistoryForbiddenKey(key)));
|
|
2426
|
+
if (message.channel_id === channel)
|
|
2427
|
+
records.push({ order, sequence: sequence++, value: { ...message, role: "user" } });
|
|
2428
|
+
continue;
|
|
2429
|
+
}
|
|
1714
2430
|
} catch {}
|
|
1715
2431
|
}
|
|
1716
2432
|
if (text.startsWith("Previous conversations for this channel have been consolidated.")) {
|
|
@@ -1722,15 +2438,16 @@ function preserveChannelHistory(directory, channel, histories, redact) {
|
|
|
1722
2438
|
}
|
|
1723
2439
|
if (text.trim())
|
|
1724
2440
|
records.push({ order, sequence: sequence++, value: { role: "user", content: text } });
|
|
1725
|
-
} else if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer")) {
|
|
2441
|
+
} else if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer") && typeof item.text === "string") {
|
|
1726
2442
|
records.push({ order, sequence: sequence++, value: { role: "assistant", content: item.text } });
|
|
1727
2443
|
}
|
|
1728
2444
|
}
|
|
1729
2445
|
}
|
|
2446
|
+
}
|
|
1730
2447
|
records.sort((a, b) => a.order.localeCompare(b.order) || a.sequence - b.sequence);
|
|
1731
2448
|
const seen = new Set;
|
|
1732
2449
|
const lines = records.filter(({ value }) => {
|
|
1733
|
-
if (!value.id)
|
|
2450
|
+
if (typeof value.id !== "string" || !value.id)
|
|
1734
2451
|
return true;
|
|
1735
2452
|
if (seen.has(value.id))
|
|
1736
2453
|
return false;
|
|
@@ -1758,26 +2475,46 @@ End of historical context.
|
|
|
1758
2475
|
}
|
|
1759
2476
|
|
|
1760
2477
|
// codex/loop-grants.ts
|
|
1761
|
-
import { lstatSync as
|
|
1762
|
-
import { join as
|
|
1763
|
-
|
|
2478
|
+
import { lstatSync as lstatSync7, readFileSync as readFileSync6 } from "node:fs";
|
|
2479
|
+
import { join as join7 } from "node:path";
|
|
2480
|
+
var GRANT_FORBIDDEN_KEYS = new Set([
|
|
2481
|
+
"__proto__",
|
|
2482
|
+
"prototype",
|
|
2483
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
2484
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
2485
|
+
]);
|
|
2486
|
+
var isGrantForbiddenKey = (key) => GRANT_FORBIDDEN_KEYS.has(key) || GRANT_FORBIDDEN_KEYS.has(key.toLowerCase());
|
|
2487
|
+
var ownProto = (value) => Boolean(value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, "__proto__"));
|
|
2488
|
+
function grants(config, opts) {
|
|
1764
2489
|
try {
|
|
1765
|
-
const
|
|
1766
|
-
|
|
2490
|
+
const platform = opts?.platform ?? process.platform;
|
|
2491
|
+
const getuid = opts && "getuid" in opts ? opts.getuid : process.getuid;
|
|
2492
|
+
assertDirectoryAncestors(config.stateDir);
|
|
2493
|
+
const directory = lstatSync7(config.stateDir);
|
|
2494
|
+
if (directory.isSymbolicLink() || !directory.isDirectory())
|
|
1767
2495
|
return [];
|
|
1768
|
-
const
|
|
1769
|
-
if (
|
|
2496
|
+
const file = join7(config.stateDir, "loop-grants.json"), stat = lstatSync7(file);
|
|
2497
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1048576)
|
|
2498
|
+
return [];
|
|
2499
|
+
if (platform !== "win32") {
|
|
2500
|
+
if (typeof getuid !== "function" || (stat.mode & 63) !== 0 || stat.uid !== getuid())
|
|
2501
|
+
return [];
|
|
2502
|
+
}
|
|
2503
|
+
const doc = JSON.parse(readFileSync6(file, "utf8"));
|
|
2504
|
+
if (doc?.version !== 1 || ownProto(doc) || !Array.isArray(doc.grants) || doc.grants.length > 256)
|
|
1770
2505
|
return [];
|
|
1771
|
-
|
|
2506
|
+
const safeId = (value) => typeof value === "string" && value.length > 0 && value.length <= 128 && value.trim() === value && value !== "." && !value.includes("..") && !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) && !isGrantForbiddenKey(value);
|
|
2507
|
+
const safeOwnerId = (value) => typeof value === "string" && value.length > 0 && value.length <= 254 && value.trim() === value && value !== "." && !value.includes("..") && !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) && !isGrantForbiddenKey(value);
|
|
2508
|
+
return doc.grants.filter((g) => g && !ownProto(g) && [g.loop_id, g.channel_id, g.agent_id, g.owner_id, g.prompt].every((v) => typeof v === "string" && v.trim()) && /^loop_[A-Za-z0-9_-]+$/.test(g.loop_id) && [g.loop_id, g.channel_id, g.agent_id].every(safeId) && safeOwnerId(g.owner_id) && g.agent_id === config.agentId && g.prompt.length <= 4000 && Number.isSafeInteger(g.interval_ms) && g.interval_ms >= 60000 && g.interval_ms <= 86400000);
|
|
1772
2509
|
} catch {
|
|
1773
2510
|
return [];
|
|
1774
2511
|
}
|
|
1775
2512
|
}
|
|
1776
|
-
function authorizedLoopTick(raw, config) {
|
|
2513
|
+
function authorizedLoopTick(raw, config, opts) {
|
|
1777
2514
|
const tick = raw?.meta;
|
|
1778
2515
|
if (raw?.sender_id !== config.agentId || tick?.kind !== "loop_tick" || !Number.isSafeInteger(tick.next_tick_ms) || tick.next_tick_ms <= 0)
|
|
1779
2516
|
return null;
|
|
1780
|
-
const matches = grants(config).filter((g) => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
|
|
2517
|
+
const matches = grants(config, opts).filter((g) => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
|
|
1781
2518
|
if (matches.length !== 1)
|
|
1782
2519
|
return null;
|
|
1783
2520
|
const grant = matches[0];
|
|
@@ -1785,8 +2522,8 @@ function authorizedLoopTick(raw, config) {
|
|
|
1785
2522
|
return null;
|
|
1786
2523
|
return grant;
|
|
1787
2524
|
}
|
|
1788
|
-
async function verifyLoopTick(raw, config, owner, list) {
|
|
1789
|
-
const grant = authorizedLoopTick(raw, config);
|
|
2525
|
+
async function verifyLoopTick(raw, config, owner, list, opts) {
|
|
2526
|
+
const grant = authorizedLoopTick(raw, config, opts);
|
|
1790
2527
|
if (!grant || owner !== grant.owner_id || config.permissions !== "full-access")
|
|
1791
2528
|
return null;
|
|
1792
2529
|
let response;
|
|
@@ -1795,67 +2532,239 @@ async function verifyLoopTick(raw, config, owner, list) {
|
|
|
1795
2532
|
} catch {
|
|
1796
2533
|
return null;
|
|
1797
2534
|
}
|
|
1798
|
-
const rows = Array.isArray(response?.loops) ? response.loops.filter((r) => r?.loop_id === grant.loop_id) : [];
|
|
2535
|
+
const rows = Array.isArray(response?.loops) && response.loops.length <= 1024 ? response.loops.filter((r) => r?.loop_id === grant.loop_id) : [];
|
|
1799
2536
|
if (rows.length !== 1)
|
|
1800
2537
|
return null;
|
|
1801
2538
|
const loop = rows[0];
|
|
1802
|
-
if (loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt || loop.interval_ms !== grant.interval_ms || loop.expires_at !== null || loop.mode !== undefined && loop.mode !== "static" || !Number.isSafeInteger(loop.last_tick_at) || loop.last_tick_at <= 0 || loop.next_tick_ms !== raw.meta.next_tick_ms || loop.last_tick_at + grant.interval_ms !== loop.next_tick_ms)
|
|
2539
|
+
if (!loop || ownProto(loop) || loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt || loop.interval_ms !== grant.interval_ms || loop.expires_at !== null || loop.mode !== undefined && loop.mode !== "static" || !Number.isSafeInteger(loop.last_tick_at) || loop.last_tick_at <= 0 || !Number.isSafeInteger(loop.next_tick_ms) || loop.next_tick_ms !== raw.meta.next_tick_ms || loop.last_tick_at + grant.interval_ms !== loop.next_tick_ms)
|
|
1803
2540
|
return null;
|
|
1804
|
-
const current = authorizedLoopTick(raw, config);
|
|
2541
|
+
const current = authorizedLoopTick(raw, config, opts);
|
|
1805
2542
|
return current && current.owner_id === owner ? current : null;
|
|
1806
2543
|
}
|
|
1807
2544
|
|
|
1808
2545
|
// src/session-bind.ts
|
|
1809
2546
|
import { createHash as createHash3 } from "node:crypto";
|
|
1810
|
-
import { closeSync,
|
|
1811
|
-
import { homedir as
|
|
1812
|
-
import { join as
|
|
2547
|
+
import { closeSync, lstatSync as lstatSync9, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync8, readSync, readdirSync as readdirSync4, readlinkSync as readlinkSync3, realpathSync as realpathSync5, statSync, unlinkSync as unlinkSync4 } from "node:fs";
|
|
2548
|
+
import { homedir as homedir5, tmpdir } from "node:os";
|
|
2549
|
+
import { isAbsolute as isAbsolute5, join as join9, parse as parse3, resolve as resolve6 } from "node:path";
|
|
1813
2550
|
|
|
1814
2551
|
// src/profile-store.ts
|
|
1815
|
-
import {
|
|
2552
|
+
import {
|
|
2553
|
+
lstatSync as lstatSync8,
|
|
2554
|
+
realpathSync as realpathSync4,
|
|
2555
|
+
writeFileSync as writeFileSync3,
|
|
2556
|
+
renameSync as renameSync2,
|
|
2557
|
+
copyFileSync as copyFileSync2,
|
|
2558
|
+
chmodSync as chmodSync2,
|
|
2559
|
+
unlinkSync as unlinkSync3,
|
|
2560
|
+
readdirSync as readdirSync3,
|
|
2561
|
+
readFileSync as readFileSync7
|
|
2562
|
+
} from "fs";
|
|
2563
|
+
import { dirname as dirname4, join as join8, resolve as resolve5 } from "path";
|
|
1816
2564
|
var defaultWarn = (m) => process.stderr.write(m);
|
|
2565
|
+
var MAX_PROFILE_JSON_BYTES = 64 * 1024;
|
|
2566
|
+
var MAX_PROFILE_PATH_LEN = 4096;
|
|
2567
|
+
var CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g;
|
|
2568
|
+
var RESERVED_PROTO_STEMS = new Set([
|
|
2569
|
+
"__proto__",
|
|
2570
|
+
"constructor",
|
|
2571
|
+
"prototype",
|
|
2572
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
2573
|
+
]);
|
|
2574
|
+
var DARWIN_SYSTEM_SYMLINKS = new Set(["/var", "/tmp", "/etc"]);
|
|
2575
|
+
function sanitizeWarnPart(value) {
|
|
2576
|
+
return redactSecrets(String(value ?? "")).replace(/\b(https?:\/\/?)([^/\s@]*@)/gi, "$1[REDACTED]@").replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]").replace(/(?:ac_|mcp_at_|mcp_rt_|mcp_|agent_key_|sk-|whsec_|rk_(?:live|test)_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|mr_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g, "[REDACTED]").replace(CONTROL_CHAR_GLOBAL_RE, "?");
|
|
2577
|
+
}
|
|
2578
|
+
function safeLstat(target) {
|
|
2579
|
+
try {
|
|
2580
|
+
return lstatSync8(target);
|
|
2581
|
+
} catch (err) {
|
|
2582
|
+
if (err && err.code === "ENOENT")
|
|
2583
|
+
return;
|
|
2584
|
+
throw err;
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
function isAllowedDarwinSystemSymlink(dirPath) {
|
|
2588
|
+
if (process.platform !== "darwin" || !DARWIN_SYSTEM_SYMLINKS.has(dirPath))
|
|
2589
|
+
return false;
|
|
2590
|
+
try {
|
|
2591
|
+
const resolved = realpathSync4(dirPath);
|
|
2592
|
+
if (resolved !== `/private${dirPath}`)
|
|
2593
|
+
return false;
|
|
2594
|
+
const privSt = lstatSync8("/private");
|
|
2595
|
+
if (!privSt.isDirectory() || privSt.isSymbolicLink())
|
|
2596
|
+
return false;
|
|
2597
|
+
const realSt = lstatSync8(resolved);
|
|
2598
|
+
return realSt.isDirectory() && !realSt.isSymbolicLink();
|
|
2599
|
+
} catch {
|
|
2600
|
+
return false;
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
function hasSafeRawDotDotAncestors(targetPath) {
|
|
2604
|
+
if (!targetPath.includes(".."))
|
|
2605
|
+
return true;
|
|
2606
|
+
const rawParent = dirname4(targetPath);
|
|
2607
|
+
const parts = rawParent.split(/[\\/]+/);
|
|
2608
|
+
let acc = rawParent.startsWith("/") ? "/" : /^[A-Za-z]:/.test(rawParent) ? parts[0] + "\\" : process.cwd();
|
|
2609
|
+
const startIdx = rawParent.startsWith("/") ? 1 : /^[A-Za-z]:/.test(rawParent) ? 1 : 0;
|
|
2610
|
+
for (let i = startIdx;i < parts.length; i++) {
|
|
2611
|
+
const seg = parts[i];
|
|
2612
|
+
if (!seg || seg === ".")
|
|
2613
|
+
continue;
|
|
2614
|
+
acc = seg === ".." ? dirname4(acc) : join8(acc, seg);
|
|
2615
|
+
const st = safeLstat(acc);
|
|
2616
|
+
if (st) {
|
|
2617
|
+
if (st.isSymbolicLink()) {
|
|
2618
|
+
if (!isAllowedDarwinSystemSymlink(acc))
|
|
2619
|
+
return false;
|
|
2620
|
+
} else if (!st.isDirectory()) {
|
|
2621
|
+
return false;
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
return true;
|
|
2626
|
+
}
|
|
2627
|
+
function hasSafeAncestorDirs(targetPath) {
|
|
2628
|
+
if (!hasSafeRawDotDotAncestors(targetPath))
|
|
2629
|
+
return false;
|
|
2630
|
+
let cur = dirname4(resolve5(targetPath));
|
|
2631
|
+
for (let depth = 0;depth < 64; depth += 1) {
|
|
2632
|
+
const st = safeLstat(cur);
|
|
2633
|
+
if (st) {
|
|
2634
|
+
if (st.isSymbolicLink()) {
|
|
2635
|
+
if (!isAllowedDarwinSystemSymlink(cur))
|
|
2636
|
+
return false;
|
|
2637
|
+
} else if (!st.isDirectory()) {
|
|
2638
|
+
return false;
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
const parent = dirname4(cur);
|
|
2642
|
+
if (parent === cur)
|
|
2643
|
+
break;
|
|
2644
|
+
cur = parent;
|
|
2645
|
+
}
|
|
2646
|
+
return true;
|
|
2647
|
+
}
|
|
1817
2648
|
function safeWriteProfile(path, data, warn = defaultWarn) {
|
|
2649
|
+
if (typeof path !== "string" || !path || path.length > MAX_PROFILE_PATH_LEN || path.includes("\x00")) {
|
|
2650
|
+
throw new Error(`Refusing to write profile into invalid path: ${sanitizeWarnPart(path)}`);
|
|
2651
|
+
}
|
|
2652
|
+
const parentDir = dirname4(path);
|
|
2653
|
+
const parentStat = safeLstat(parentDir);
|
|
2654
|
+
if (!parentStat || parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(path)) {
|
|
2655
|
+
throw new Error(`Refusing to write profile into invalid or symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
|
|
2656
|
+
}
|
|
2657
|
+
const pathStat = safeLstat(path);
|
|
2658
|
+
if (pathStat?.isSymbolicLink()) {
|
|
2659
|
+
throw new Error(`Refusing to write profile through symlink: ${sanitizeWarnPart(path)}`);
|
|
2660
|
+
}
|
|
2661
|
+
if (pathStat && !pathStat.isFile() && !pathStat.isDirectory()) {
|
|
2662
|
+
throw new Error(`Refusing to write profile into non-regular target: ${sanitizeWarnPart(path)}`);
|
|
2663
|
+
}
|
|
1818
2664
|
const tmp = path + ".tmp";
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
2665
|
+
const tmpStat = safeLstat(tmp);
|
|
2666
|
+
if (tmpStat) {
|
|
2667
|
+
try {
|
|
2668
|
+
unlinkSync3(tmp);
|
|
2669
|
+
} catch (e) {
|
|
2670
|
+
warn(`[agentchat] WARNING: stale ${sanitizeWarnPart(tmp)} could not be removed: ${sanitizeWarnPart(e)}
|
|
1824
2671
|
`);
|
|
2672
|
+
}
|
|
1825
2673
|
}
|
|
1826
|
-
writeFileSync3(tmp, JSON.stringify(data, null, 2), { mode: 384 });
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
`);
|
|
2674
|
+
writeFileSync3(tmp, JSON.stringify(data, null, 2), { mode: 384, flag: "wx" });
|
|
2675
|
+
const currentParent = safeLstat(parentDir);
|
|
2676
|
+
if (!currentParent || currentParent.isSymbolicLink() || !currentParent.isDirectory() || !hasSafeAncestorDirs(path)) {
|
|
2677
|
+
try {
|
|
2678
|
+
unlinkSync3(tmp);
|
|
2679
|
+
} catch {}
|
|
2680
|
+
throw new Error(`Refusing to write profile into symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
|
|
2681
|
+
}
|
|
2682
|
+
if (safeLstat(path)?.isSymbolicLink()) {
|
|
2683
|
+
try {
|
|
2684
|
+
unlinkSync3(tmp);
|
|
2685
|
+
} catch {}
|
|
2686
|
+
throw new Error(`Refusing to overwrite symlinked profile: ${sanitizeWarnPart(path)}`);
|
|
1833
2687
|
}
|
|
1834
2688
|
try {
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
2689
|
+
renameSync2(tmp, path);
|
|
2690
|
+
} catch (err) {
|
|
2691
|
+
if (process.platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
|
|
2692
|
+
const winTarget = safeLstat(path);
|
|
2693
|
+
if (winTarget?.isSymbolicLink() || winTarget?.isDirectory()) {
|
|
2694
|
+
try {
|
|
2695
|
+
unlinkSync3(tmp);
|
|
2696
|
+
} catch {}
|
|
2697
|
+
throw new Error(`Refusing to overwrite symlinked or directory profile: ${sanitizeWarnPart(path)}`);
|
|
2698
|
+
}
|
|
2699
|
+
copyFileSync2(tmp, path);
|
|
2700
|
+
try {
|
|
2701
|
+
unlinkSync3(tmp);
|
|
2702
|
+
} catch {}
|
|
2703
|
+
} else {
|
|
2704
|
+
throw err;
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
if (process.platform !== "win32") {
|
|
2708
|
+
const postStat = safeLstat(path);
|
|
2709
|
+
if (!postStat || postStat.isSymbolicLink() || !postStat.isFile()) {
|
|
2710
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target
|
|
1838
2711
|
`);
|
|
2712
|
+
return;
|
|
1839
2713
|
}
|
|
1840
|
-
|
|
1841
|
-
|
|
2714
|
+
try {
|
|
2715
|
+
chmodSync2(path, 384);
|
|
2716
|
+
} catch (e) {
|
|
2717
|
+
warn(`[agentchat] WARNING: could not chmod ${sanitizeWarnPart(path)} to 0600: ${sanitizeWarnPart(e)}
|
|
2718
|
+
`);
|
|
2719
|
+
}
|
|
2720
|
+
try {
|
|
2721
|
+
const verified = safeLstat(path);
|
|
2722
|
+
if (!verified || verified.isSymbolicLink() || !verified.isFile()) {
|
|
2723
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target
|
|
1842
2724
|
`);
|
|
2725
|
+
return;
|
|
2726
|
+
}
|
|
2727
|
+
const mode = verified.mode & 511;
|
|
2728
|
+
if (mode !== 384) {
|
|
2729
|
+
warn(`[agentchat] WARNING: ${sanitizeWarnPart(path)} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${sanitizeWarnPart(path)}
|
|
2730
|
+
`);
|
|
2731
|
+
}
|
|
2732
|
+
} catch (e) {
|
|
2733
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: ${sanitizeWarnPart(e)}
|
|
2734
|
+
`);
|
|
2735
|
+
}
|
|
1843
2736
|
}
|
|
1844
2737
|
}
|
|
1845
2738
|
var NON_PROFILE_JSON_FILES = new Set([
|
|
1846
2739
|
"session-binds.json",
|
|
2740
|
+
"session-binds.meta.json",
|
|
2741
|
+
"session-binds-meta.json",
|
|
2742
|
+
"session-binds_meta.json",
|
|
2743
|
+
"agy-session-binds.json",
|
|
2744
|
+
"agy-session-binds.meta.json",
|
|
2745
|
+
"agy-session-binds_meta.json",
|
|
1847
2746
|
"agy-binds.json",
|
|
2747
|
+
"agy-binds.meta.json",
|
|
2748
|
+
"agy-binds-meta.json",
|
|
2749
|
+
"agy-binds_meta.json",
|
|
1848
2750
|
"grok-binds.json",
|
|
1849
2751
|
"grok-binds-meta.json",
|
|
1850
2752
|
"grok-binds.meta.json",
|
|
2753
|
+
"grok-binds_meta.json",
|
|
1851
2754
|
"identity-guard.json",
|
|
2755
|
+
"cursor.json",
|
|
2756
|
+
"read-cursors.json",
|
|
2757
|
+
"mention-timestamps.json",
|
|
2758
|
+
"wake-pids.json",
|
|
2759
|
+
"codex-bots.json",
|
|
1852
2760
|
"dsh.json",
|
|
1853
|
-
"config.json"
|
|
2761
|
+
"config.json",
|
|
2762
|
+
"muse.json"
|
|
1854
2763
|
]);
|
|
1855
2764
|
|
|
1856
2765
|
// src/session-bind.ts
|
|
1857
2766
|
function isPidAlive(pid) {
|
|
1858
|
-
if (typeof pid !== "number" || !Number.
|
|
2767
|
+
if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
|
|
1859
2768
|
return false;
|
|
1860
2769
|
try {
|
|
1861
2770
|
process.kill(pid, 0);
|
|
@@ -1868,35 +2777,201 @@ function isPidAlive(pid) {
|
|
|
1868
2777
|
}
|
|
1869
2778
|
function resolveLockDir(homeDir, env = process.env) {
|
|
1870
2779
|
const explicit = env.AGENTSCHAT_LOCK_DIR?.trim();
|
|
1871
|
-
if (explicit)
|
|
2780
|
+
if (explicit && explicit.length <= 4096 && !explicit.startsWith("-") && !CONTROL_CHAR_RE2.test(explicit) && isAbsolute5(explicit) && isSafeDirOrMissing(explicit)) {
|
|
1872
2781
|
return explicit;
|
|
2782
|
+
}
|
|
1873
2783
|
const hash = createHash3("sha256").update(homeDir || ".").digest("hex").slice(0, 12);
|
|
1874
2784
|
const baseTmp = process.platform === "win32" ? tmpdir() : "/tmp";
|
|
1875
|
-
return
|
|
2785
|
+
return join9(baseTmp, `agentschat-locks-${hash}`);
|
|
2786
|
+
}
|
|
2787
|
+
var LOCK_FILE_MAX_BYTES = 64 * 1024;
|
|
2788
|
+
var LOCK_KEY_MAX_CHARS = 128;
|
|
2789
|
+
var SESSION_BINDS_MAX_BYTES = 1024 * 1024;
|
|
2790
|
+
var CONTROL_CHAR_RE2 = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
2791
|
+
var UNSAFE_BIND_KEYS = new Set([
|
|
2792
|
+
"__proto__",
|
|
2793
|
+
"constructor",
|
|
2794
|
+
"prototype",
|
|
2795
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
2796
|
+
]);
|
|
2797
|
+
var RESERVED_BIND_SIDECARS = new Set([
|
|
2798
|
+
"session-binds",
|
|
2799
|
+
"session-binds.meta",
|
|
2800
|
+
"session-binds_meta",
|
|
2801
|
+
"agy-binds",
|
|
2802
|
+
"agy-binds.meta",
|
|
2803
|
+
"agy-binds_meta",
|
|
2804
|
+
"grok-binds",
|
|
2805
|
+
"grok-binds.meta",
|
|
2806
|
+
"grok-binds_meta",
|
|
2807
|
+
"agy-session-binds",
|
|
2808
|
+
"identity-guard",
|
|
2809
|
+
"cursor",
|
|
2810
|
+
"read-cursors",
|
|
2811
|
+
"mention-timestamps",
|
|
2812
|
+
"wake-pids",
|
|
2813
|
+
"config",
|
|
2814
|
+
"codex-bots",
|
|
2815
|
+
"dsh",
|
|
2816
|
+
"muse"
|
|
2817
|
+
]);
|
|
2818
|
+
function readBoundedRegularJson(path, maxBytes) {
|
|
2819
|
+
try {
|
|
2820
|
+
const st = lstatSync9(path);
|
|
2821
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > maxBytes)
|
|
2822
|
+
return null;
|
|
2823
|
+
const parsed = JSON.parse(readFileSync8(path, "utf8"));
|
|
2824
|
+
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
2825
|
+
return null;
|
|
2826
|
+
}
|
|
2827
|
+
return parsed;
|
|
2828
|
+
} catch {
|
|
2829
|
+
return null;
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
function isSafeTargetFileOrMissing(path) {
|
|
2833
|
+
try {
|
|
2834
|
+
const st = lstatSync9(path);
|
|
2835
|
+
return !st.isSymbolicLink() && st.isFile();
|
|
2836
|
+
} catch (e) {
|
|
2837
|
+
return Boolean(e && typeof e === "object" && e.code === "ENOENT");
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
function isAllowedDarwinSystemLink(dirPath) {
|
|
2841
|
+
if (process.platform !== "darwin")
|
|
2842
|
+
return false;
|
|
2843
|
+
if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc")
|
|
2844
|
+
return false;
|
|
2845
|
+
try {
|
|
2846
|
+
const expected = `/private${dirPath}`;
|
|
2847
|
+
return readlinkSync3(dirPath) === `private${dirPath}` && realpathSync5(dirPath) === expected && !lstatSync9("/private").isSymbolicLink() && lstatSync9("/private").isDirectory() && !lstatSync9(expected).isSymbolicLink() && statSync(expected).isDirectory();
|
|
2848
|
+
} catch {
|
|
2849
|
+
return false;
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
function hasSafeRawDotDotSegments(rawPath) {
|
|
2853
|
+
if (!rawPath.includes(".."))
|
|
2854
|
+
return true;
|
|
2855
|
+
const baseAbs = isAbsolute5(rawPath) ? rawPath : `${process.cwd()}/${rawPath}`;
|
|
2856
|
+
const root = parse3(baseAbs).root;
|
|
2857
|
+
const rawParts = baseAbs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
2858
|
+
let cur = root;
|
|
2859
|
+
for (const part of rawParts) {
|
|
2860
|
+
if (part === ".")
|
|
2861
|
+
continue;
|
|
2862
|
+
if (part === "..") {
|
|
2863
|
+
cur = resolve6(cur, "..");
|
|
2864
|
+
continue;
|
|
2865
|
+
}
|
|
2866
|
+
cur = join9(cur, part);
|
|
2867
|
+
try {
|
|
2868
|
+
const st = lstatSync9(cur);
|
|
2869
|
+
if (st.isSymbolicLink()) {
|
|
2870
|
+
if (isAllowedDarwinSystemLink(cur))
|
|
2871
|
+
continue;
|
|
2872
|
+
return false;
|
|
2873
|
+
}
|
|
2874
|
+
if (!st.isDirectory())
|
|
2875
|
+
return false;
|
|
2876
|
+
} catch (e) {
|
|
2877
|
+
if (e && typeof e === "object" && e.code === "ENOENT")
|
|
2878
|
+
continue;
|
|
2879
|
+
return false;
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
return true;
|
|
2883
|
+
}
|
|
2884
|
+
function isSafeDirOrMissing(dirPath) {
|
|
2885
|
+
if (!dirPath || CONTROL_CHAR_RE2.test(dirPath))
|
|
2886
|
+
return false;
|
|
2887
|
+
if (!hasSafeRawDotDotSegments(dirPath))
|
|
2888
|
+
return false;
|
|
2889
|
+
const abs = resolve6(dirPath);
|
|
2890
|
+
const root = parse3(abs).root;
|
|
2891
|
+
const segments = abs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
2892
|
+
let cur = root;
|
|
2893
|
+
for (let i = 0;i < segments.length; i++) {
|
|
2894
|
+
cur = join9(cur, segments[i]);
|
|
2895
|
+
try {
|
|
2896
|
+
const st = lstatSync9(cur);
|
|
2897
|
+
if (st.isSymbolicLink()) {
|
|
2898
|
+
if (isAllowedDarwinSystemLink(cur))
|
|
2899
|
+
continue;
|
|
2900
|
+
return false;
|
|
2901
|
+
}
|
|
2902
|
+
if (!st.isDirectory())
|
|
2903
|
+
return false;
|
|
2904
|
+
} catch (e) {
|
|
2905
|
+
if (e && typeof e === "object" && e.code === "ENOENT")
|
|
2906
|
+
return true;
|
|
2907
|
+
return false;
|
|
2908
|
+
}
|
|
2909
|
+
}
|
|
2910
|
+
return true;
|
|
1876
2911
|
}
|
|
1877
2912
|
function lockFilePath(lockDir, agentId) {
|
|
1878
|
-
const
|
|
1879
|
-
|
|
2913
|
+
const trimmed = String(agentId || "").trim();
|
|
2914
|
+
let safe = trimmed.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
2915
|
+
if (safe.length > LOCK_KEY_MAX_CHARS) {
|
|
2916
|
+
const digest = createHash3("sha256").update(trimmed).digest("hex").slice(0, 12);
|
|
2917
|
+
safe = `${safe.slice(0, LOCK_KEY_MAX_CHARS - 13)}_${digest}`;
|
|
2918
|
+
}
|
|
2919
|
+
if (!safe || isUnsafeBindKey(safe)) {
|
|
2920
|
+
safe = `_${safe}`;
|
|
2921
|
+
}
|
|
2922
|
+
return join9(lockDir, `${safe}.lock`);
|
|
1880
2923
|
}
|
|
1881
2924
|
function readAgentLock(lockDir, agentId) {
|
|
1882
|
-
if (!agentId)
|
|
2925
|
+
if (!agentId || !isSafeDirOrMissing(lockDir))
|
|
1883
2926
|
return null;
|
|
1884
2927
|
const file = lockFilePath(lockDir, agentId);
|
|
1885
|
-
|
|
2928
|
+
const raw = readBoundedRegularJson(file, LOCK_FILE_MAX_BYTES);
|
|
2929
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.prototype.hasOwnProperty.call(raw, "__proto__") || typeof raw.pid !== "number" || typeof raw.agentId !== "string") {
|
|
1886
2930
|
return null;
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
2931
|
+
}
|
|
2932
|
+
return raw;
|
|
2933
|
+
}
|
|
2934
|
+
function checkAgentLock(opts) {
|
|
2935
|
+
const { lockDir, agentId } = opts;
|
|
2936
|
+
const currentPid = opts.currentPid ?? process.pid;
|
|
2937
|
+
if (!agentId || !isSafeDirOrMissing(lockDir))
|
|
2938
|
+
return { locked: false };
|
|
2939
|
+
const file = lockFilePath(lockDir, agentId);
|
|
2940
|
+
const record = readAgentLock(lockDir, agentId);
|
|
2941
|
+
if (!record) {
|
|
2942
|
+
try {
|
|
2943
|
+
const st = lstatSync9(file);
|
|
2944
|
+
const ageMs = Date.now() - st.mtimeMs;
|
|
2945
|
+
if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1000 || ageMs < -1000))
|
|
2946
|
+
unlinkSync4(file);
|
|
2947
|
+
} catch {}
|
|
2948
|
+
return { locked: false };
|
|
2949
|
+
}
|
|
2950
|
+
if (!isPidAlive(record.pid)) {
|
|
2951
|
+
try {
|
|
2952
|
+
unlinkSync4(file);
|
|
2953
|
+
} catch {}
|
|
2954
|
+
return { locked: false, stale: true };
|
|
2955
|
+
}
|
|
2956
|
+
if (record.pid === currentPid) {
|
|
2957
|
+
if (opts.currentSessionId && record.sessionId && opts.currentSessionId !== record.sessionId) {
|
|
2958
|
+
return { locked: true, holder: record };
|
|
1891
2959
|
}
|
|
1892
|
-
return
|
|
1893
|
-
} catch {
|
|
1894
|
-
return null;
|
|
2960
|
+
return { locked: false, holder: record };
|
|
1895
2961
|
}
|
|
2962
|
+
if (opts.lockOwnerPid && record.pid === opts.lockOwnerPid)
|
|
2963
|
+
return { locked: false, holder: record };
|
|
2964
|
+
if (opts.currentSessionId && record.sessionId && opts.currentSessionId === record.sessionId) {
|
|
2965
|
+
return { locked: false, holder: record };
|
|
2966
|
+
}
|
|
2967
|
+
return { locked: true, holder: record };
|
|
1896
2968
|
}
|
|
1897
2969
|
function acquireAgentLock(opts) {
|
|
1898
2970
|
if (!opts.agentId)
|
|
1899
2971
|
return null;
|
|
2972
|
+
const file = lockFilePath(opts.lockDir, opts.agentId);
|
|
2973
|
+
if (!isSafeDirOrMissing(opts.lockDir) || !isSafeTargetFileOrMissing(file))
|
|
2974
|
+
return null;
|
|
1900
2975
|
const record = {
|
|
1901
2976
|
pid: opts.currentPid ?? process.pid,
|
|
1902
2977
|
agentId: opts.agentId,
|
|
@@ -1907,40 +2982,80 @@ function acquireAgentLock(opts) {
|
|
|
1907
2982
|
};
|
|
1908
2983
|
try {
|
|
1909
2984
|
mkdirSync5(opts.lockDir, { recursive: true, mode: 448 });
|
|
1910
|
-
safeWriteProfile(
|
|
2985
|
+
safeWriteProfile(file, record);
|
|
1911
2986
|
return record;
|
|
1912
2987
|
} catch {
|
|
1913
2988
|
return null;
|
|
1914
2989
|
}
|
|
1915
2990
|
}
|
|
1916
2991
|
function releaseAgentLock(opts) {
|
|
1917
|
-
if (!opts.agentId)
|
|
2992
|
+
if (!opts.agentId || !isSafeDirOrMissing(opts.lockDir))
|
|
1918
2993
|
return false;
|
|
1919
2994
|
const currentPid = opts.currentPid ?? process.pid;
|
|
2995
|
+
const file = lockFilePath(opts.lockDir, opts.agentId);
|
|
1920
2996
|
const existing = readAgentLock(opts.lockDir, opts.agentId);
|
|
1921
|
-
if (!existing)
|
|
2997
|
+
if (!existing) {
|
|
2998
|
+
try {
|
|
2999
|
+
const st = lstatSync9(file);
|
|
3000
|
+
const ageMs = Date.now() - st.mtimeMs;
|
|
3001
|
+
if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1000 || ageMs < -1000)) {
|
|
3002
|
+
unlinkSync4(file);
|
|
3003
|
+
return true;
|
|
3004
|
+
}
|
|
3005
|
+
} catch {}
|
|
1922
3006
|
return false;
|
|
3007
|
+
}
|
|
1923
3008
|
const samePid = existing.pid === currentPid;
|
|
1924
3009
|
const sameSession = Boolean(opts.currentSessionId && existing.sessionId && opts.currentSessionId === existing.sessionId);
|
|
1925
3010
|
const dead = !isPidAlive(existing.pid);
|
|
1926
3011
|
if (!samePid && !sameSession && !dead)
|
|
1927
3012
|
return false;
|
|
1928
3013
|
try {
|
|
1929
|
-
|
|
3014
|
+
unlinkSync4(file);
|
|
1930
3015
|
return true;
|
|
1931
3016
|
} catch {
|
|
1932
3017
|
return false;
|
|
1933
3018
|
}
|
|
1934
3019
|
}
|
|
3020
|
+
function isUnsafeBindKey(key) {
|
|
3021
|
+
return UNSAFE_BIND_KEYS.has(key.toLowerCase());
|
|
3022
|
+
}
|
|
3023
|
+
var DSH_HEALTH_MAX_BYTES = 256 * 1024;
|
|
1935
3024
|
|
|
1936
3025
|
// codex/bridge.ts
|
|
3026
|
+
var MAX_BRIDGE_TERMINAL_ENTRIES = 500;
|
|
1937
3027
|
function permitted(m, c) {
|
|
1938
3028
|
if (m.meta?.kind === "loop_tick")
|
|
1939
3029
|
return authorizedLoopTick(m, c) !== null;
|
|
1940
3030
|
return (!c.channels.length || c.channels.includes(m.channel_id)) && (!c.senders.length || c.senders.includes(m.sender_id));
|
|
1941
3031
|
}
|
|
3032
|
+
var isPrototypeKey = (key) => /^(?:__proto__|constructor|prototype)$/i.test(key);
|
|
3033
|
+
var cleanBridgeLog = (text) => text.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ");
|
|
3034
|
+
function isPlainObject(value) {
|
|
3035
|
+
return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
3036
|
+
}
|
|
3037
|
+
function safeMessageId(value) {
|
|
3038
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value && value !== "." && !value.includes("..") && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) && !isPrototypeKey(value);
|
|
3039
|
+
}
|
|
3040
|
+
function validMentions(value) {
|
|
3041
|
+
return value === undefined || Array.isArray(value) && value.length <= 128 && [...value].every((id) => typeof id === "string");
|
|
3042
|
+
}
|
|
3043
|
+
function checkStateDir(dir, allowMissing = false) {
|
|
3044
|
+
try {
|
|
3045
|
+
const stat = lstatSync10(dir);
|
|
3046
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
3047
|
+
throw new Error("Unsafe bridge state directory");
|
|
3048
|
+
} catch (error) {
|
|
3049
|
+
if (!allowMissing || error.code !== "ENOENT")
|
|
3050
|
+
throw error;
|
|
3051
|
+
}
|
|
3052
|
+
assertDirectoryAncestors(dir);
|
|
3053
|
+
}
|
|
3054
|
+
var entryStatuses = new Set(["pending", "running", "ready", "sending", "sent", "failed", "uncertain", "blocked", "skipped"]);
|
|
1942
3055
|
function addressed(m, c) {
|
|
1943
|
-
if (!m || ["id", "channel_id", "sender_id", "content"].some((k) => typeof m[k] !== "string" || !m[k].trim()))
|
|
3056
|
+
if (!isPlainObject(m) || Object.prototype.hasOwnProperty.call(m, "__proto__") || ["id", "channel_id", "sender_id", "content"].some((k) => typeof m[k] !== "string" || !m[k].trim()))
|
|
3057
|
+
return false;
|
|
3058
|
+
if (![m.id, m.channel_id, m.sender_id].every(safeMessageId) || !validMentions(m.mentions) || !validMentions(m.mentioned_ids))
|
|
1944
3059
|
return false;
|
|
1945
3060
|
if (m.content === "__typing__" || m.content.length > 32000)
|
|
1946
3061
|
return false;
|
|
@@ -1953,7 +3068,7 @@ function addressed(m, c) {
|
|
|
1953
3068
|
if (!permitted(m, c))
|
|
1954
3069
|
return false;
|
|
1955
3070
|
const escaped = c.agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1956
|
-
return m.channel_id
|
|
3071
|
+
return /^dm[-:]/i.test(m.channel_id) || [m.mentions, m.mentioned_ids].some((a) => Array.isArray(a) && a.includes(c.agentId)) || new RegExp(`@${escaped}(?![\\w-])|@[^\\n(]+\\(${escaped}\\)`).test(m.content);
|
|
1957
3072
|
}
|
|
1958
3073
|
|
|
1959
3074
|
class Bridge {
|
|
@@ -1979,16 +3094,20 @@ class Bridge {
|
|
|
1979
3094
|
this.activity = activity;
|
|
1980
3095
|
this.owner = owner;
|
|
1981
3096
|
this.loops = loops;
|
|
3097
|
+
checkStateDir(config.stateDir, true);
|
|
1982
3098
|
mkdirSync6(config.stateDir, { recursive: true, mode: 448 });
|
|
1983
|
-
|
|
1984
|
-
this.
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
3099
|
+
checkStateDir(config.stateDir);
|
|
3100
|
+
this.file = join10(config.stateDir, "state.json");
|
|
3101
|
+
this.lock = join10(config.stateDir, "bridge.lock");
|
|
3102
|
+
try {
|
|
3103
|
+
const stat = lstatSync10(this.lock);
|
|
3104
|
+
if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024) {
|
|
3105
|
+
const content = readFileSync9(this.lock, "utf8");
|
|
3106
|
+
const holderPid = /^\d+$/.test(content) && content.trim() === content ? Number(content) : NaN;
|
|
3107
|
+
if (!Number.isSafeInteger(holderPid) || holderPid <= 0 || !isPidAlive(holderPid))
|
|
3108
|
+
unlinkSync5(this.lock);
|
|
3109
|
+
}
|
|
3110
|
+
} catch {}
|
|
1992
3111
|
try {
|
|
1993
3112
|
const fd = openSync2(this.lock, "wx", 384);
|
|
1994
3113
|
writeFileSync4(fd, String(process.pid));
|
|
@@ -1997,16 +3116,24 @@ class Bridge {
|
|
|
1997
3116
|
throw new Error(`Bridge already locked: ${this.lock}. If its process has exited, remove that lock manually.`);
|
|
1998
3117
|
}
|
|
1999
3118
|
const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
2000
|
-
|
|
2001
|
-
lockDir: resolveLockDir(homeDir, process.env),
|
|
2002
|
-
agentId: config.agentId,
|
|
2003
|
-
runtime: "codex-bridge"
|
|
2004
|
-
});
|
|
3119
|
+
const lockDir = resolveLockDir(homeDir, process.env);
|
|
2005
3120
|
try {
|
|
2006
|
-
|
|
2007
|
-
|
|
3121
|
+
let hasState = false;
|
|
3122
|
+
try {
|
|
3123
|
+
const stat = lstatSync10(this.file);
|
|
3124
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024)
|
|
3125
|
+
throw new Error("Unsafe bridge state");
|
|
3126
|
+
hasState = true;
|
|
3127
|
+
} catch (error) {
|
|
3128
|
+
if (error.code !== "ENOENT")
|
|
3129
|
+
throw error;
|
|
3130
|
+
}
|
|
3131
|
+
this.state = hasState ? JSON.parse(readFileSync9(this.file, "utf8")) : { version: 1, threads: {}, entries: [] };
|
|
3132
|
+
if (this.state?.version !== 1 || Object.prototype.hasOwnProperty.call(this.state, "__proto__") || !isPlainObject(this.state.threads) || Object.prototype.hasOwnProperty.call(this.state.threads, "__proto__") || !Array.isArray(this.state.entries) || Object.prototype.hasOwnProperty.call(this.state, "channels") && (!isPlainObject(this.state.channels) || Object.prototype.hasOwnProperty.call(this.state.channels, "__proto__")))
|
|
2008
3133
|
throw new Error("Invalid bridge state");
|
|
2009
3134
|
for (const e of this.state.entries) {
|
|
3135
|
+
if (!isPlainObject(e) || Object.prototype.hasOwnProperty.call(e, "__proto__") || !entryStatuses.has(e.status) || !isPlainObject(e.message) || Object.prototype.hasOwnProperty.call(e.message, "__proto__") || ![e.message.id, e.message.channel_id, e.message.sender_id].every(safeMessageId) || typeof e.message.content !== "string" || !validMentions(e.message.mentions) || !validMentions(e.message.mentioned_ids))
|
|
3136
|
+
throw new Error("Invalid bridge entry");
|
|
2010
3137
|
if (e.status === "sending")
|
|
2011
3138
|
e.status = "uncertain";
|
|
2012
3139
|
if (e.status === "running")
|
|
@@ -2014,14 +3141,69 @@ class Bridge {
|
|
|
2014
3141
|
}
|
|
2015
3142
|
this.save();
|
|
2016
3143
|
} catch {
|
|
2017
|
-
|
|
3144
|
+
try {
|
|
3145
|
+
unlinkSync5(this.lock);
|
|
3146
|
+
} catch {}
|
|
2018
3147
|
throw new Error("Cannot load bridge state; refusing to discard history");
|
|
2019
3148
|
}
|
|
3149
|
+
try {
|
|
3150
|
+
const existingLock = checkAgentLock({ lockDir, agentId: config.agentId });
|
|
3151
|
+
if (existingLock.locked) {
|
|
3152
|
+
throw new Error(`Agent identity ${config.agentId} is already locked by live process ${existingLock.holder?.pid ?? "unknown"} (${existingLock.holder?.runtime ?? "unknown"})`);
|
|
3153
|
+
}
|
|
3154
|
+
if (!acquireAgentLock({
|
|
3155
|
+
lockDir,
|
|
3156
|
+
agentId: config.agentId,
|
|
3157
|
+
runtime: "codex-bridge"
|
|
3158
|
+
})) {
|
|
3159
|
+
throw new Error(`Cannot acquire agent lock for ${config.agentId}`);
|
|
3160
|
+
}
|
|
3161
|
+
} catch (err) {
|
|
3162
|
+
try {
|
|
3163
|
+
unlinkSync5(this.lock);
|
|
3164
|
+
} catch {}
|
|
3165
|
+
throw err;
|
|
3166
|
+
}
|
|
2020
3167
|
}
|
|
2021
3168
|
save() {
|
|
2022
|
-
const
|
|
2023
|
-
|
|
2024
|
-
|
|
3169
|
+
const isTerminal = (status) => status === "sent" || status === "skipped" || status === "blocked";
|
|
3170
|
+
let terminalCount = 0;
|
|
3171
|
+
for (const entry of this.state.entries) {
|
|
3172
|
+
if (isTerminal(entry.status))
|
|
3173
|
+
terminalCount++;
|
|
3174
|
+
}
|
|
3175
|
+
if (terminalCount > MAX_BRIDGE_TERMINAL_ENTRIES) {
|
|
3176
|
+
let dropRemaining = terminalCount - MAX_BRIDGE_TERMINAL_ENTRIES;
|
|
3177
|
+
this.state.entries = this.state.entries.filter((entry) => {
|
|
3178
|
+
if (dropRemaining > 0 && isTerminal(entry.status)) {
|
|
3179
|
+
dropRemaining--;
|
|
3180
|
+
return false;
|
|
3181
|
+
}
|
|
3182
|
+
return true;
|
|
3183
|
+
});
|
|
3184
|
+
}
|
|
3185
|
+
const tmp = `${this.file}.tmp.${process.pid}.${Date.now()}.${randomBytes2(16).toString("hex")}`;
|
|
3186
|
+
try {
|
|
3187
|
+
const serialized = JSON.stringify(this.state);
|
|
3188
|
+
checkStateDir(this.config.stateDir);
|
|
3189
|
+
writeFileSync4(tmp, serialized, { mode: 384, flag: "wx" });
|
|
3190
|
+
atomicReplaceRegularFile(tmp, this.file, () => {
|
|
3191
|
+
try {
|
|
3192
|
+
const stat = lstatSync10(this.file);
|
|
3193
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
3194
|
+
throw new Error("Bridge state must not be a symlink");
|
|
3195
|
+
} catch (error) {
|
|
3196
|
+
if (error.code !== "ENOENT")
|
|
3197
|
+
throw error;
|
|
3198
|
+
}
|
|
3199
|
+
checkStateDir(this.config.stateDir);
|
|
3200
|
+
});
|
|
3201
|
+
} catch (err) {
|
|
3202
|
+
try {
|
|
3203
|
+
unlinkSync5(tmp);
|
|
3204
|
+
} catch {}
|
|
3205
|
+
throw err;
|
|
3206
|
+
}
|
|
2025
3207
|
}
|
|
2026
3208
|
accept(raw) {
|
|
2027
3209
|
if (this.stopped || !addressed(raw, this.config))
|
|
@@ -2041,6 +3223,8 @@ class Bridge {
|
|
|
2041
3223
|
sender_id: raw.sender_id,
|
|
2042
3224
|
...Array.isArray(raw.mentioned_ids) ? { mentioned_ids: raw.mentioned_ids.filter((id) => typeof id === "string") } : {},
|
|
2043
3225
|
...Array.isArray(raw.mentions) ? { mentions: raw.mentions.filter((id) => typeof id === "string") } : {},
|
|
3226
|
+
...!tick && typeof raw.parent_id === "string" && safeMessageId(raw.parent_id.trim()) ? { parent_id: raw.parent_id.trim() } : {},
|
|
3227
|
+
...!tick && typeof raw.reply_to === "string" && safeMessageId(raw.reply_to.trim()) ? { reply_to: raw.reply_to.trim() } : {},
|
|
2044
3228
|
content: tick ? "Authorized scheduled loop" : this.redact(raw.content),
|
|
2045
3229
|
...tick ? { meta: {
|
|
2046
3230
|
kind: "loop_tick",
|
|
@@ -2056,7 +3240,7 @@ class Bridge {
|
|
|
2056
3240
|
return true;
|
|
2057
3241
|
}
|
|
2058
3242
|
redact(text) {
|
|
2059
|
-
return redactSecrets(text.split(this.config.token).join("[REDACTED]"));
|
|
3243
|
+
return redactSecrets(this.config.token ? text.split(this.config.token).join("[REDACTED]") : text);
|
|
2060
3244
|
}
|
|
2061
3245
|
recover(raw) {
|
|
2062
3246
|
if (this.stopped)
|
|
@@ -2080,8 +3264,10 @@ class Bridge {
|
|
|
2080
3264
|
return this.draining;
|
|
2081
3265
|
}
|
|
2082
3266
|
async prepareChannel(chat) {
|
|
3267
|
+
if (!safeMessageId(chat))
|
|
3268
|
+
throw new Error("Invalid channel ID");
|
|
2083
3269
|
this.state.channels ??= {};
|
|
2084
|
-
let channel = this.state.channels[chat];
|
|
3270
|
+
let channel = Object.prototype.hasOwnProperty.call(this.state.channels, chat) ? this.state.channels[chat] : undefined;
|
|
2085
3271
|
if (!this.loaded.has(chat)) {
|
|
2086
3272
|
const namespace = this.codex.namespace;
|
|
2087
3273
|
if (channel?.namespace && channel.namespace !== namespace)
|
|
@@ -2142,7 +3328,7 @@ This scheduled skill run supports ${TEAM_LEAD_NO_UPDATE}; return it alone only w
|
|
|
2142
3328
|
Authorized task:
|
|
2143
3329
|
${authorizedTask}` : `You are the online AgentsChat bot ${this.config.agentId}, running through Codex App Server in ${this.config.cwd}. This message was delivered to you live. If asked whether you are online, confirm your own availability.
|
|
2144
3330
|
Use this channel's shared conversation and configured tools to carry out the request.
|
|
2145
|
-
Recurring-task setup, only when requested: create the server loop as this bot in this same channel. Then verify its record with list_loops and confirm this bot is claimed with whoami and obtain its owner_account_id with my_entitlements. Maintain the private file ${
|
|
3331
|
+
Recurring-task setup, only when requested: create the server loop as this bot in this same channel. Then verify its record with list_loops and confirm this bot is claimed with whoami and obtain its owner_account_id with my_entitlements. Maintain the private file ${join10(this.config.stateDir, "loop-grants.json")} (mode 0600): {"version":1,"grants":[{"loop_id":"server loop ID","channel_id":"this channel ID","agent_id":"this bot ID","owner_id":"verified owner ID","interval_ms":60000,"prompt":"exact server prompt"}]}. Use the actual server interval, preserve other grants, and confirm setup only after both server registration and the matching local grant exist. Stopping a loop also removes its grant. Do not change unrelated loops.
|
|
2146
3332
|
AgentsChat message:
|
|
2147
3333
|
` + JSON.stringify(e.message);
|
|
2148
3334
|
e.answer = this.redact(await this.codex.generate(channel.thread, (channel.bootstrap ?? "") + prompt));
|
|
@@ -2154,7 +3340,7 @@ AgentsChat message:
|
|
|
2154
3340
|
delete e.answer;
|
|
2155
3341
|
e.message.content = "";
|
|
2156
3342
|
this.save();
|
|
2157
|
-
this.log(`Scheduled skill completed quietly in ${JSON.stringify(chat)}`);
|
|
3343
|
+
this.log(cleanBridgeLog(`Scheduled skill completed quietly in ${JSON.stringify(chat)}`));
|
|
2158
3344
|
continue;
|
|
2159
3345
|
}
|
|
2160
3346
|
e.status = "ready";
|
|
@@ -2169,24 +3355,26 @@ AgentsChat message:
|
|
|
2169
3355
|
delete e.answer;
|
|
2170
3356
|
e.message.content = "";
|
|
2171
3357
|
this.save();
|
|
2172
|
-
this.log(`Replied in ${JSON.stringify(e.message.channel_id)}`);
|
|
3358
|
+
this.log(cleanBridgeLog(`Replied in ${JSON.stringify(e.message.channel_id)}`));
|
|
2173
3359
|
} catch (error) {
|
|
2174
3360
|
if (error instanceof ThreadBusyError) {
|
|
2175
3361
|
e.status = "pending";
|
|
2176
3362
|
e.error = error.message;
|
|
2177
3363
|
this.save();
|
|
2178
3364
|
this.log("Conversation in use; queued message will resume in the same task");
|
|
2179
|
-
if (!this.stopped)
|
|
3365
|
+
if (!this.stopped) {
|
|
2180
3366
|
this.retry = setTimeout(() => {
|
|
2181
3367
|
this.retry = undefined;
|
|
2182
3368
|
this.drain();
|
|
2183
3369
|
}, 5000);
|
|
3370
|
+
this.retry.unref?.();
|
|
3371
|
+
}
|
|
2184
3372
|
return;
|
|
2185
3373
|
}
|
|
2186
3374
|
e.error = this.redact(error instanceof Error ? error.message : "Bridge operation failed").slice(0, 240);
|
|
2187
3375
|
e.status = e.status === "sending" ? "uncertain" : "failed";
|
|
2188
3376
|
this.save();
|
|
2189
|
-
this.log(`Message ${JSON.stringify(e.message.id)} ${e.status}; inspect private state before retrying`);
|
|
3377
|
+
this.log(cleanBridgeLog(`Message ${JSON.stringify(e.message.id)} ${e.status}; inspect private state before retrying`));
|
|
2190
3378
|
} finally {
|
|
2191
3379
|
this.activity(e.message.channel_id, false);
|
|
2192
3380
|
}
|
|
@@ -2200,8 +3388,14 @@ AgentsChat message:
|
|
|
2200
3388
|
async stop() {
|
|
2201
3389
|
this.pause();
|
|
2202
3390
|
await this.draining;
|
|
2203
|
-
|
|
2204
|
-
|
|
3391
|
+
try {
|
|
3392
|
+
const stat = lstatSync10(this.lock);
|
|
3393
|
+
if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 && readFileSync9(this.lock, "utf8") === String(process.pid))
|
|
3394
|
+
unlinkSync5(this.lock);
|
|
3395
|
+
} catch (error) {
|
|
3396
|
+
if (error.code !== "ENOENT")
|
|
3397
|
+
throw error;
|
|
3398
|
+
}
|
|
2205
3399
|
const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
2206
3400
|
releaseAgentLock({ lockDir: resolveLockDir(homeDir, process.env), agentId: this.config.agentId });
|
|
2207
3401
|
}
|
|
@@ -2217,18 +3411,18 @@ var WS_OPEN = 1;
|
|
|
2217
3411
|
var WS_CLOSING = 2;
|
|
2218
3412
|
class HeartbeatMonitor {
|
|
2219
3413
|
deps;
|
|
2220
|
-
pingInterval;
|
|
2221
|
-
pongTimeout;
|
|
2222
|
-
connectTimeout;
|
|
2223
3414
|
lastPong;
|
|
2224
3415
|
timer = null;
|
|
2225
3416
|
connectingSince = null;
|
|
2226
3417
|
reconnecting = false;
|
|
3418
|
+
pingInterval;
|
|
3419
|
+
pongTimeout;
|
|
3420
|
+
connectTimeout;
|
|
2227
3421
|
constructor(deps, pingInterval = 30000, pongTimeout = 90000, connectTimeout = 30000) {
|
|
2228
3422
|
this.deps = deps;
|
|
2229
|
-
this.pingInterval = pingInterval;
|
|
2230
|
-
this.pongTimeout = pongTimeout;
|
|
2231
|
-
this.connectTimeout = connectTimeout;
|
|
3423
|
+
this.pingInterval = Number.isFinite(pingInterval) && pingInterval > 0 ? Math.max(1, Math.min(Math.floor(pingInterval), 2147483647)) : 30000;
|
|
3424
|
+
this.pongTimeout = Number.isFinite(pongTimeout) && pongTimeout > 0 ? Math.max(1, Math.min(Math.floor(pongTimeout), 2147483647)) : 90000;
|
|
3425
|
+
this.connectTimeout = Number.isFinite(connectTimeout) && connectTimeout > 0 ? Math.max(1, Math.min(Math.floor(connectTimeout), 2147483647)) : 30000;
|
|
2232
3426
|
this.lastPong = Date.now();
|
|
2233
3427
|
}
|
|
2234
3428
|
receivedPong() {
|
|
@@ -2242,6 +3436,7 @@ class HeartbeatMonitor {
|
|
|
2242
3436
|
this.connectingSince = null;
|
|
2243
3437
|
this.reconnecting = false;
|
|
2244
3438
|
this.timer = setInterval(() => this.tick(), this.pingInterval);
|
|
3439
|
+
this.timer?.unref?.();
|
|
2245
3440
|
}
|
|
2246
3441
|
stop() {
|
|
2247
3442
|
if (this.timer) {
|
|
@@ -2253,20 +3448,35 @@ class HeartbeatMonitor {
|
|
|
2253
3448
|
this.reconnecting = false;
|
|
2254
3449
|
}
|
|
2255
3450
|
tick() {
|
|
2256
|
-
|
|
3451
|
+
let state;
|
|
3452
|
+
try {
|
|
3453
|
+
state = this.deps.getReadyState();
|
|
3454
|
+
} catch {
|
|
3455
|
+
this.connectingSince = null;
|
|
3456
|
+
this.safeReconnect("readyState failed");
|
|
3457
|
+
return;
|
|
3458
|
+
}
|
|
3459
|
+
const now = Date.now();
|
|
2257
3460
|
if (state === WS_OPEN) {
|
|
2258
3461
|
this.connectingSince = null;
|
|
2259
|
-
if (
|
|
3462
|
+
if (this.lastPong > now) {
|
|
3463
|
+
this.lastPong = now;
|
|
3464
|
+
}
|
|
3465
|
+
if (now - this.lastPong > this.pongTimeout) {
|
|
2260
3466
|
this.safeReconnect("pong timeout");
|
|
2261
3467
|
return;
|
|
2262
3468
|
}
|
|
2263
|
-
|
|
3469
|
+
try {
|
|
3470
|
+
this.deps.sendPing();
|
|
3471
|
+
} catch {
|
|
3472
|
+
this.safeReconnect("ping send failed");
|
|
3473
|
+
}
|
|
2264
3474
|
return;
|
|
2265
3475
|
}
|
|
2266
3476
|
if (state === WS_CONNECTING) {
|
|
2267
|
-
if (
|
|
2268
|
-
this.connectingSince =
|
|
2269
|
-
} else if (
|
|
3477
|
+
if (this.connectingSince === null || this.connectingSince > now) {
|
|
3478
|
+
this.connectingSince = now;
|
|
3479
|
+
} else if (now - this.connectingSince > this.connectTimeout) {
|
|
2270
3480
|
this.connectingSince = null;
|
|
2271
3481
|
this.safeReconnect("connect timeout");
|
|
2272
3482
|
}
|
|
@@ -2279,38 +3489,120 @@ class HeartbeatMonitor {
|
|
|
2279
3489
|
if (this.reconnecting)
|
|
2280
3490
|
return;
|
|
2281
3491
|
this.reconnecting = true;
|
|
2282
|
-
|
|
3492
|
+
try {
|
|
3493
|
+
this.deps.reconnect();
|
|
3494
|
+
} catch {
|
|
3495
|
+
this.reconnecting = false;
|
|
3496
|
+
}
|
|
3497
|
+
}
|
|
3498
|
+
}
|
|
3499
|
+
|
|
3500
|
+
// src/reconnect.ts
|
|
3501
|
+
function safeUnitRand(rand) {
|
|
3502
|
+
let r;
|
|
3503
|
+
try {
|
|
3504
|
+
r = rand();
|
|
3505
|
+
} catch {
|
|
3506
|
+
return 0;
|
|
2283
3507
|
}
|
|
3508
|
+
if (!Number.isFinite(r) || r <= 0)
|
|
3509
|
+
return 0;
|
|
3510
|
+
return r >= 1 ? 0.999999 : r;
|
|
3511
|
+
}
|
|
3512
|
+
function computePleaseReconnectDelay(jitterMs, rand = Math.random) {
|
|
3513
|
+
const maxJitter = typeof jitterMs === "number" && Number.isFinite(jitterMs) && jitterMs > 0 ? Math.min(Math.floor(jitterMs), 1e4) : 2000;
|
|
3514
|
+
return 200 + Math.floor(safeUnitRand(rand) * maxJitter);
|
|
3515
|
+
}
|
|
3516
|
+
function resolveDrainReconnectDelay(frame, rand = Math.random) {
|
|
3517
|
+
const safeFrame = frame && typeof frame === "object" && !Array.isArray(frame) && !Object.prototype.hasOwnProperty.call(frame, "__proto__") ? frame : null;
|
|
3518
|
+
return computePleaseReconnectDelay(safeFrame?.jitter_ms ?? safeFrame?.within_ms, rand);
|
|
2284
3519
|
}
|
|
2285
3520
|
|
|
2286
3521
|
// codex/inbox-sync.ts
|
|
2287
|
-
import {
|
|
2288
|
-
import {
|
|
3522
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync10, unlinkSync as unlinkSync6, writeFileSync as writeFileSync5 } from "node:fs";
|
|
3523
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
3524
|
+
import { join as join11 } from "node:path";
|
|
2289
3525
|
|
|
2290
3526
|
// src/timestamps.ts
|
|
3527
|
+
var ISO_OFFSET_RE = /^(\d{4}-\d{2}-\d{2})[Tt ](\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|z|[+-]\d{2}:\d{2})$/;
|
|
3528
|
+
function isValidCalendarDateTime(datePart, timePart, tzPart) {
|
|
3529
|
+
const year = Number(datePart.slice(0, 4));
|
|
3530
|
+
const month = Number(datePart.slice(5, 7));
|
|
3531
|
+
const day = Number(datePart.slice(8, 10));
|
|
3532
|
+
const hour = Number(timePart.slice(0, 2));
|
|
3533
|
+
const minute = Number(timePart.slice(3, 5));
|
|
3534
|
+
const second = Number(timePart.slice(6, 8));
|
|
3535
|
+
if (month < 1 || month > 12 || hour > 23 || minute > 59 || second > 59)
|
|
3536
|
+
return false;
|
|
3537
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
3538
|
+
const maxDay = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
|
|
3539
|
+
if (day < 1 || day > maxDay)
|
|
3540
|
+
return false;
|
|
3541
|
+
if (tzPart !== "Z" && tzPart !== "z") {
|
|
3542
|
+
const offHour = Number(tzPart.slice(1, 3));
|
|
3543
|
+
const offMin = Number(tzPart.slice(4, 6));
|
|
3544
|
+
if (offHour > 23 || offMin > 59)
|
|
3545
|
+
return false;
|
|
3546
|
+
}
|
|
3547
|
+
return true;
|
|
3548
|
+
}
|
|
2291
3549
|
function normalizeTimestampForCursor(ts, mode) {
|
|
2292
|
-
if (!ts || typeof ts !== "string")
|
|
3550
|
+
if (!ts || typeof ts !== "string" || ts.length > 128)
|
|
3551
|
+
return ts;
|
|
3552
|
+
if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(ts))
|
|
3553
|
+
return;
|
|
3554
|
+
if (mode !== "before" && mode !== "after")
|
|
2293
3555
|
return ts;
|
|
2294
3556
|
const padChar = mode === "before" ? "9" : "0";
|
|
2295
|
-
const
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
3557
|
+
const trimmed = ts.trim();
|
|
3558
|
+
const m = trimmed.match(ISO_OFFSET_RE);
|
|
3559
|
+
if (m) {
|
|
3560
|
+
const datePart = m[1];
|
|
3561
|
+
const timePart = m[2];
|
|
3562
|
+
const rawFrac = m[3] ?? "";
|
|
3563
|
+
const tzPart = m[4];
|
|
3564
|
+
if (!isValidCalendarDateTime(datePart, timePart, tzPart))
|
|
2299
3565
|
return ts;
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
3566
|
+
const frac9 = rawFrac.length === 9 ? rawFrac : rawFrac.length > 9 ? rawFrac.slice(0, 9) : rawFrac + padChar.repeat(9 - rawFrac.length);
|
|
3567
|
+
if (tzPart === "Z" || tzPart === "z") {
|
|
3568
|
+
return `${datePart}T${timePart}.${frac9}Z`;
|
|
3569
|
+
}
|
|
3570
|
+
const wholeUtcMs = Date.parse(`${datePart}T${timePart}${tzPart}`);
|
|
3571
|
+
if (Number.isFinite(wholeUtcMs)) {
|
|
3572
|
+
const iso = new Date(wholeUtcMs).toISOString();
|
|
3573
|
+
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(iso)) {
|
|
3574
|
+
return `${iso.slice(0, 19)}.${frac9}Z`;
|
|
3575
|
+
}
|
|
3576
|
+
}
|
|
2305
3577
|
}
|
|
2306
3578
|
return ts;
|
|
2307
3579
|
}
|
|
2308
3580
|
|
|
2309
3581
|
// codex/inbox-sync.ts
|
|
2310
3582
|
function timestamp(value) {
|
|
2311
|
-
if (typeof value !== "string" || !Number.isFinite(Date.parse(value)))
|
|
3583
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|z|[+-]\d{2}:\d{2})$/.test(value) || !Number.isFinite(Date.parse(value)))
|
|
3584
|
+
throw new Error("Invalid history timestamp");
|
|
3585
|
+
const normalized = normalizeTimestampForCursor(value, "after");
|
|
3586
|
+
if (!normalized || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/.test(normalized))
|
|
2312
3587
|
throw new Error("Invalid history timestamp");
|
|
2313
|
-
return
|
|
3588
|
+
return normalized;
|
|
3589
|
+
}
|
|
3590
|
+
var INBOX_FORBIDDEN_KEYS = new Set([
|
|
3591
|
+
"__proto__",
|
|
3592
|
+
"prototype",
|
|
3593
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
3594
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
3595
|
+
]);
|
|
3596
|
+
var isInboxForbiddenKey = (key) => INBOX_FORBIDDEN_KEYS.has(key) || INBOX_FORBIDDEN_KEYS.has(key.toLowerCase());
|
|
3597
|
+
function validChannel(channel) {
|
|
3598
|
+
return typeof channel === "string" && channel.length > 0 && channel.length <= 128 && channel === channel.trim() && channel !== "." && !channel.includes("..") && !/[\/\\]/.test(channel) && !/%(?:2e%2e|2f|5c|00)/i.test(channel) && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel) && !isInboxForbiddenKey(channel);
|
|
3599
|
+
}
|
|
3600
|
+
function validHistoryMessageId(id) {
|
|
3601
|
+
return typeof id === "string" && id.length > 0 && id.length <= 256 && id === id.trim() && id !== "." && !id.includes("..") && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(id) && !/%(?:2e%2e|2f|5c|00)/i.test(id) && !isInboxForbiddenKey(id);
|
|
3602
|
+
}
|
|
3603
|
+
function validateChannel(channel) {
|
|
3604
|
+
if (!validChannel(channel))
|
|
3605
|
+
throw new Error("Invalid inbound channel");
|
|
2314
3606
|
}
|
|
2315
3607
|
|
|
2316
3608
|
class InboxSync {
|
|
@@ -2327,20 +3619,64 @@ class InboxSync {
|
|
|
2327
3619
|
this.receive = receive;
|
|
2328
3620
|
this.active = active;
|
|
2329
3621
|
this.log = log;
|
|
3622
|
+
const existing = lstatSync11(stateDir, { throwIfNoEntry: false });
|
|
3623
|
+
if (existing && (existing.isSymbolicLink() || !existing.isDirectory()))
|
|
3624
|
+
throw new Error("Invalid inbound state directory");
|
|
3625
|
+
assertDirectoryAncestors(stateDir);
|
|
2330
3626
|
mkdirSync7(stateDir, { recursive: true, mode: 448 });
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
3627
|
+
const dirStat = lstatSync11(stateDir);
|
|
3628
|
+
if (dirStat.isSymbolicLink() || !dirStat.isDirectory())
|
|
3629
|
+
throw new Error("Invalid inbound state directory");
|
|
3630
|
+
if (process.platform !== "win32")
|
|
3631
|
+
chmodSync3(stateDir, 448);
|
|
3632
|
+
this.file = join11(stateDir, "inbound-cursors.json");
|
|
3633
|
+
let fileStat;
|
|
3634
|
+
try {
|
|
3635
|
+
fileStat = lstatSync11(this.file);
|
|
3636
|
+
} catch (err) {
|
|
3637
|
+
if (err.code !== "ENOENT")
|
|
3638
|
+
throw err;
|
|
3639
|
+
}
|
|
3640
|
+
if (fileStat && (fileStat.isSymbolicLink() || !fileStat.isFile()))
|
|
3641
|
+
throw new Error("Invalid inbound cursors file");
|
|
3642
|
+
if (fileStat && fileStat.size > 1048576)
|
|
3643
|
+
throw new Error("Inbound cursors exceed size limit");
|
|
3644
|
+
this.state = fileStat ? JSON.parse(readFileSync10(this.file, "utf8")) : { version: 1, channels: {} };
|
|
3645
|
+
if (!this.state || typeof this.state !== "object" || Array.isArray(this.state) || Object.hasOwn(this.state, "__proto__") || this.state.version !== 1 || !this.state.channels || typeof this.state.channels !== "object" || Array.isArray(this.state.channels) || Object.hasOwn(this.state.channels, "__proto__") || Object.keys(this.state.channels).length > 1024)
|
|
2334
3646
|
throw new Error("Invalid inbound cursors; refusing to discard checkpoint");
|
|
2335
|
-
|
|
3647
|
+
const channels = Object.create(null);
|
|
3648
|
+
for (const [channel, value] of Object.entries(this.state.channels)) {
|
|
3649
|
+
if (!validChannel(channel))
|
|
3650
|
+
continue;
|
|
2336
3651
|
timestamp(value);
|
|
2337
|
-
|
|
3652
|
+
channels[channel] = value;
|
|
3653
|
+
}
|
|
3654
|
+
this.state.channels = channels;
|
|
2338
3655
|
}
|
|
2339
3656
|
save() {
|
|
2340
|
-
|
|
2341
|
-
|
|
3657
|
+
const tmp = `${this.file}.${process.pid}.${Date.now()}.${randomBytes3(4).toString("hex")}.tmp`;
|
|
3658
|
+
let created = false;
|
|
3659
|
+
try {
|
|
3660
|
+
writeFileSync5(tmp, JSON.stringify(this.state), { mode: 384, flag: "wx" });
|
|
3661
|
+
created = true;
|
|
3662
|
+
atomicReplaceRegularFile(tmp, this.file, () => {
|
|
3663
|
+
const current = lstatSync11(this.file, { throwIfNoEntry: false });
|
|
3664
|
+
if (current && (current.isSymbolicLink() || !current.isFile()))
|
|
3665
|
+
throw new Error("Invalid inbound cursors file");
|
|
3666
|
+
});
|
|
3667
|
+
} catch (err) {
|
|
3668
|
+
if (created) {
|
|
3669
|
+
try {
|
|
3670
|
+
unlinkSync6(tmp);
|
|
3671
|
+
} catch {}
|
|
3672
|
+
}
|
|
3673
|
+
throw err;
|
|
3674
|
+
}
|
|
2342
3675
|
}
|
|
2343
3676
|
watch(channel) {
|
|
3677
|
+
validateChannel(channel);
|
|
3678
|
+
if (!Object.hasOwn(this.state.channels, channel) && Object.keys(this.state.channels).length >= 1024)
|
|
3679
|
+
throw new Error("Inbound channel limit exceeded");
|
|
2344
3680
|
this.channels.add(channel);
|
|
2345
3681
|
if (!Object.hasOwn(this.state.channels, channel)) {
|
|
2346
3682
|
this.state.channels[channel] = timestamp(new Date().toISOString());
|
|
@@ -2348,9 +3684,20 @@ class InboxSync {
|
|
|
2348
3684
|
}
|
|
2349
3685
|
}
|
|
2350
3686
|
memberships(channels) {
|
|
2351
|
-
this.channels.clear();
|
|
2352
3687
|
for (const channel of channels)
|
|
2353
|
-
|
|
3688
|
+
validateChannel(channel);
|
|
3689
|
+
if (new Set([...Object.keys(this.state.channels), ...channels]).size > 1024)
|
|
3690
|
+
throw new Error("Inbound channel limit exceeded");
|
|
3691
|
+
this.channels = new Set(channels);
|
|
3692
|
+
let changed = false;
|
|
3693
|
+
for (const channel of this.channels) {
|
|
3694
|
+
if (!Object.hasOwn(this.state.channels, channel)) {
|
|
3695
|
+
this.state.channels[channel] = timestamp(new Date().toISOString());
|
|
3696
|
+
changed = true;
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
if (changed)
|
|
3700
|
+
this.save();
|
|
2354
3701
|
}
|
|
2355
3702
|
sync() {
|
|
2356
3703
|
if (!this.running)
|
|
@@ -2377,7 +3724,7 @@ class InboxSync {
|
|
|
2377
3724
|
if (!Array.isArray(messages))
|
|
2378
3725
|
throw new Error("Invalid history response");
|
|
2379
3726
|
const rows = messages.map((m) => {
|
|
2380
|
-
if (!m || m.channel_id !== channel ||
|
|
3727
|
+
if (!m || typeof m !== "object" || Object.hasOwn(m, "__proto__") || m.channel_id !== channel || !validHistoryMessageId(m.id))
|
|
2381
3728
|
throw new Error("Invalid history message");
|
|
2382
3729
|
return { message: m, time: timestamp(m.timestamp) };
|
|
2383
3730
|
}).sort((a, b) => a.time.localeCompare(b.time));
|
|
@@ -2414,6 +3761,53 @@ class InboxSync {
|
|
|
2414
3761
|
}
|
|
2415
3762
|
|
|
2416
3763
|
// codex/transport.ts
|
|
3764
|
+
var TRANSPORT_FORBIDDEN_KEYS = new Set([
|
|
3765
|
+
"__proto__",
|
|
3766
|
+
"prototype",
|
|
3767
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
3768
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
3769
|
+
]);
|
|
3770
|
+
var cleanTransportLog = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ");
|
|
3771
|
+
function safeChannel(channel) {
|
|
3772
|
+
return typeof channel === "string" && channel.trim().length > 0 && channel === channel.trim() && channel.length <= 128 && !/[.\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel) && !/%(?:2e%2e|2f|5c|00)/i.test(channel) && !TRANSPORT_FORBIDDEN_KEYS.has(channel) && !TRANSPORT_FORBIDDEN_KEYS.has(channel.toLowerCase());
|
|
3773
|
+
}
|
|
3774
|
+
function requireChannel(channel) {
|
|
3775
|
+
if (!safeChannel(channel))
|
|
3776
|
+
throw new Error("Invalid AgentsChat channel");
|
|
3777
|
+
}
|
|
3778
|
+
function apiUrl(path, base) {
|
|
3779
|
+
const invalid = () => new Error("Invalid AgentsChat API path");
|
|
3780
|
+
if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//") || /[\x00-\x1f\x7f-\x9f\u2028\u2029\\]/.test(path))
|
|
3781
|
+
throw invalid();
|
|
3782
|
+
try {
|
|
3783
|
+
const pathname = path.split(/[?#]/, 1)[0];
|
|
3784
|
+
if (/%25(?:2e|2f|5c|00)/i.test(pathname))
|
|
3785
|
+
throw invalid();
|
|
3786
|
+
const decoded = decodeURIComponent(pathname);
|
|
3787
|
+
if ([pathname, decoded].some((value) => value.split("/").includes("..")) || /[\x00-\x1f\x7f-\x9f\u2028\u2029\\]/.test(decoded))
|
|
3788
|
+
throw invalid();
|
|
3789
|
+
const origin = new URL(base).origin, resolved = new URL(path, base);
|
|
3790
|
+
if (resolved.origin !== origin)
|
|
3791
|
+
throw invalid();
|
|
3792
|
+
return resolved;
|
|
3793
|
+
} catch {
|
|
3794
|
+
throw invalid();
|
|
3795
|
+
}
|
|
3796
|
+
}
|
|
3797
|
+
function rawWsFrameBytes(raw) {
|
|
3798
|
+
if (Buffer.isBuffer(raw))
|
|
3799
|
+
return raw.byteLength;
|
|
3800
|
+
if (raw instanceof ArrayBuffer)
|
|
3801
|
+
return raw.byteLength;
|
|
3802
|
+
if (Array.isArray(raw)) {
|
|
3803
|
+
let total = 0;
|
|
3804
|
+
for (const chunk of raw)
|
|
3805
|
+
total += chunk.byteLength;
|
|
3806
|
+
return total;
|
|
3807
|
+
}
|
|
3808
|
+
return Buffer.byteLength(String(raw), "utf8");
|
|
3809
|
+
}
|
|
3810
|
+
|
|
2417
3811
|
class AgentsChatTransport {
|
|
2418
3812
|
config;
|
|
2419
3813
|
receive;
|
|
@@ -2434,13 +3828,15 @@ class AgentsChatTransport {
|
|
|
2434
3828
|
this.receive = receive;
|
|
2435
3829
|
this.log = log;
|
|
2436
3830
|
this.syncIntervalMs = syncIntervalMs;
|
|
3831
|
+
this.syncIntervalMs = Number.isFinite(syncIntervalMs) && syncIntervalMs > 0 ? Math.min(Math.floor(syncIntervalMs), 2147483647) : 60000;
|
|
2437
3832
|
if (recover)
|
|
2438
3833
|
this.inboxSync = new InboxSync(config.stateDir, (path) => this.api(path), recover, () => !this.closed && this.authenticated, log);
|
|
2439
3834
|
}
|
|
2440
3835
|
async api(path, body) {
|
|
3836
|
+
const resolved = apiUrl(path, this.config.apiUrl);
|
|
2441
3837
|
let response;
|
|
2442
3838
|
try {
|
|
2443
|
-
response = await fetch(
|
|
3839
|
+
response = await fetch(resolved, {
|
|
2444
3840
|
method: body ? "POST" : "GET",
|
|
2445
3841
|
redirect: "error",
|
|
2446
3842
|
headers: { Authorization: `Bearer ${this.config.token}`, "Content-Type": "application/json" },
|
|
@@ -2450,25 +3846,66 @@ class AgentsChatTransport {
|
|
|
2450
3846
|
} catch {
|
|
2451
3847
|
throw new Error("AgentsChat request failed or timed out");
|
|
2452
3848
|
}
|
|
2453
|
-
if (!response.ok)
|
|
3849
|
+
if (!response.ok) {
|
|
3850
|
+
try {
|
|
3851
|
+
await response.body?.cancel?.();
|
|
3852
|
+
} catch {}
|
|
2454
3853
|
throw new Error(`AgentsChat HTTP ${response.status}`);
|
|
3854
|
+
}
|
|
3855
|
+
let reader;
|
|
2455
3856
|
try {
|
|
2456
|
-
|
|
3857
|
+
reader = response.body?.getReader();
|
|
3858
|
+
if (!reader)
|
|
3859
|
+
throw new Error("Missing response body");
|
|
3860
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
3861
|
+
let bytes = 0, text = "";
|
|
3862
|
+
while (true) {
|
|
3863
|
+
const { done, value: value2 } = await reader.read();
|
|
3864
|
+
if (done)
|
|
3865
|
+
break;
|
|
3866
|
+
bytes += value2.byteLength;
|
|
3867
|
+
if (bytes > 4 * 1024 * 1024) {
|
|
3868
|
+
try {
|
|
3869
|
+
await reader.cancel();
|
|
3870
|
+
} catch {}
|
|
3871
|
+
throw new Error("Response too large");
|
|
3872
|
+
}
|
|
3873
|
+
text += decoder.decode(value2, { stream: true });
|
|
3874
|
+
}
|
|
3875
|
+
const value = JSON.parse(text + decoder.decode());
|
|
3876
|
+
if (value && typeof value === "object" && Object.hasOwn(value, "__proto__"))
|
|
3877
|
+
throw new Error("Invalid JSON prototype key");
|
|
3878
|
+
return value;
|
|
2457
3879
|
} catch {
|
|
2458
3880
|
throw new Error("Invalid AgentsChat response");
|
|
3881
|
+
} finally {
|
|
3882
|
+
reader?.releaseLock();
|
|
2459
3883
|
}
|
|
2460
3884
|
}
|
|
2461
3885
|
setTyping(channel, active) {
|
|
3886
|
+
requireChannel(channel);
|
|
2462
3887
|
clearInterval(this.typing.get(channel));
|
|
2463
3888
|
this.typing.delete(channel);
|
|
2464
3889
|
if (!active || this.closed)
|
|
2465
3890
|
return;
|
|
3891
|
+
if (this.typing.size >= 64)
|
|
3892
|
+
throw new Error("AgentsChat typing limit reached");
|
|
2466
3893
|
const pulse = () => {
|
|
2467
|
-
if (this.authenticated && this.socket?.readyState === WebSocket.OPEN)
|
|
2468
|
-
|
|
3894
|
+
if (this.authenticated && this.socket?.readyState === WebSocket.OPEN) {
|
|
3895
|
+
try {
|
|
3896
|
+
this.socket.send(JSON.stringify({ type: "typing", channel_id: channel, sender_id: this.config.agentId, cross_pod: true }));
|
|
3897
|
+
} catch {}
|
|
3898
|
+
}
|
|
2469
3899
|
};
|
|
2470
3900
|
pulse();
|
|
2471
|
-
|
|
3901
|
+
const typingTimer = setInterval(pulse, 2000);
|
|
3902
|
+
typingTimer.unref?.();
|
|
3903
|
+
this.typing.set(channel, typingTimer);
|
|
3904
|
+
}
|
|
3905
|
+
clearTyping() {
|
|
3906
|
+
for (const timer of this.typing.values())
|
|
3907
|
+
clearInterval(timer);
|
|
3908
|
+
this.typing.clear();
|
|
2472
3909
|
}
|
|
2473
3910
|
rejectPending() {
|
|
2474
3911
|
for (const p of this.pending.values()) {
|
|
@@ -2478,29 +3915,39 @@ class AgentsChatTransport {
|
|
|
2478
3915
|
this.pending.clear();
|
|
2479
3916
|
}
|
|
2480
3917
|
async send(channel, text) {
|
|
3918
|
+
requireChannel(channel);
|
|
2481
3919
|
if (this.authenticated && this.socket?.readyState === WebSocket.OPEN) {
|
|
3920
|
+
if (this.pending.size >= 256)
|
|
3921
|
+
throw new Error("AgentsChat pending message limit reached");
|
|
2482
3922
|
const id = randomUUID2();
|
|
2483
|
-
await new Promise((
|
|
3923
|
+
await new Promise((resolve7, reject) => {
|
|
2484
3924
|
const timer = setTimeout(() => {
|
|
2485
3925
|
this.pending.delete(id);
|
|
2486
3926
|
reject(new Error("AgentsChat acknowledgement timed out"));
|
|
2487
3927
|
}, 15000);
|
|
2488
|
-
|
|
2489
|
-
this.
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
3928
|
+
timer.unref?.();
|
|
3929
|
+
this.pending.set(id, { resolve: resolve7, reject, timer });
|
|
3930
|
+
try {
|
|
3931
|
+
this.socket.send(JSON.stringify({
|
|
3932
|
+
type: "message",
|
|
3933
|
+
id,
|
|
3934
|
+
channel_id: channel,
|
|
3935
|
+
sender_id: this.config.agentId,
|
|
3936
|
+
sender_type: "agent",
|
|
3937
|
+
content_type: "text",
|
|
3938
|
+
content: text
|
|
3939
|
+
}), (error) => {
|
|
3940
|
+
if (error) {
|
|
3941
|
+
clearTimeout(timer);
|
|
3942
|
+
this.pending.delete(id);
|
|
3943
|
+
reject(new Error("AgentsChat socket send failed"));
|
|
3944
|
+
}
|
|
3945
|
+
});
|
|
3946
|
+
} catch {
|
|
3947
|
+
clearTimeout(timer);
|
|
3948
|
+
this.pending.delete(id);
|
|
3949
|
+
reject(new Error("AgentsChat socket send failed"));
|
|
3950
|
+
}
|
|
2504
3951
|
});
|
|
2505
3952
|
return;
|
|
2506
3953
|
}
|
|
@@ -2513,15 +3960,30 @@ class AgentsChatTransport {
|
|
|
2513
3960
|
start() {
|
|
2514
3961
|
if (this.closed)
|
|
2515
3962
|
return;
|
|
3963
|
+
clearTimeout(this.retry);
|
|
3964
|
+
this.retry = undefined;
|
|
3965
|
+
clearInterval(this.syncTimer);
|
|
3966
|
+
this.syncTimer = undefined;
|
|
3967
|
+
this.heartbeat?.stop();
|
|
3968
|
+
this.heartbeat = undefined;
|
|
3969
|
+
this.authenticated = false;
|
|
3970
|
+
this.clearTyping();
|
|
3971
|
+
this.rejectPending();
|
|
3972
|
+
const previous = this.socket;
|
|
3973
|
+
this.socket = undefined;
|
|
3974
|
+
previous?.terminate();
|
|
2516
3975
|
const socket = new WebSocket(this.config.wsUrl, { maxPayload: 1048576, handshakeTimeout: 15000 });
|
|
2517
3976
|
this.socket = socket;
|
|
2518
3977
|
const current = () => !this.closed && this.socket === socket;
|
|
2519
3978
|
const send = (value) => {
|
|
2520
|
-
if (current() && socket.readyState === WebSocket.OPEN)
|
|
2521
|
-
|
|
3979
|
+
if (current() && socket.readyState === WebSocket.OPEN) {
|
|
3980
|
+
try {
|
|
3981
|
+
socket.send(JSON.stringify(value));
|
|
3982
|
+
} catch {}
|
|
3983
|
+
}
|
|
2522
3984
|
};
|
|
2523
|
-
const
|
|
2524
|
-
if (!this.config.channels.length || this.config.channels.includes(channel)) {
|
|
3985
|
+
const join12 = (channel) => {
|
|
3986
|
+
if (safeChannel(channel) && (!this.config.channels.length || this.config.channels.includes(channel))) {
|
|
2525
3987
|
this.inboxSync?.watch(channel);
|
|
2526
3988
|
send({ type: "join_channel", channel_id: channel, agent_id: this.config.agentId });
|
|
2527
3989
|
}
|
|
@@ -2534,7 +3996,7 @@ class AgentsChatTransport {
|
|
|
2534
3996
|
this.heartbeat.start();
|
|
2535
3997
|
socket.on("open", () => send({ type: "auth", agent_id: this.config.agentId, token: this.config.token, capabilities: ["chat", "codex"] }));
|
|
2536
3998
|
socket.on("message", (raw) => {
|
|
2537
|
-
if (!current())
|
|
3999
|
+
if (!current() || rawWsFrameBytes(raw) > 1048576)
|
|
2538
4000
|
return;
|
|
2539
4001
|
let data;
|
|
2540
4002
|
try {
|
|
@@ -2542,25 +4004,30 @@ class AgentsChatTransport {
|
|
|
2542
4004
|
} catch {
|
|
2543
4005
|
return;
|
|
2544
4006
|
}
|
|
2545
|
-
|
|
4007
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || Object.hasOwn(data, "__proto__"))
|
|
4008
|
+
return;
|
|
4009
|
+
if (data.type !== "auth_error")
|
|
4010
|
+
this.heartbeat?.receivedPong();
|
|
2546
4011
|
if (data.type === "auth_ok") {
|
|
2547
4012
|
this.authenticated = true;
|
|
2548
4013
|
this.delay = 1000;
|
|
2549
|
-
this.log(`AgentsChat connected as ${this.config.agentId}`);
|
|
2550
|
-
if (this.inboxSync && !this.syncTimer)
|
|
4014
|
+
this.log(cleanTransportLog(`AgentsChat connected as ${this.config.agentId}`));
|
|
4015
|
+
if (this.inboxSync && !this.syncTimer) {
|
|
2551
4016
|
this.syncTimer = setInterval(() => {
|
|
2552
4017
|
this.inboxSync.sync();
|
|
2553
4018
|
}, this.syncIntervalMs);
|
|
4019
|
+
this.syncTimer.unref?.();
|
|
4020
|
+
}
|
|
2554
4021
|
this.api("/api/channels/mine").then((body) => {
|
|
2555
4022
|
if (!current())
|
|
2556
4023
|
return;
|
|
2557
4024
|
const channels = Array.isArray(body) ? body : body.channels;
|
|
2558
4025
|
if (!Array.isArray(channels))
|
|
2559
4026
|
throw new Error("Invalid membership response");
|
|
2560
|
-
const ids = channels.map((c) => c
|
|
4027
|
+
const ids = channels.map((c) => c?.id ?? c?.channel_id).filter((id) => safeChannel(id) && (!this.config.channels.length || this.config.channels.includes(id)));
|
|
2561
4028
|
this.inboxSync?.memberships(ids);
|
|
2562
4029
|
for (const id of ids)
|
|
2563
|
-
|
|
4030
|
+
join12(id);
|
|
2564
4031
|
this.inboxSync?.sync();
|
|
2565
4032
|
}).catch(() => {
|
|
2566
4033
|
if (current()) {
|
|
@@ -2569,44 +4036,59 @@ class AgentsChatTransport {
|
|
|
2569
4036
|
}
|
|
2570
4037
|
});
|
|
2571
4038
|
} else if (data.type === "message_ack") {
|
|
2572
|
-
const id = data.message_id ?? data.id
|
|
2573
|
-
if (
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
4039
|
+
const id = data.message_id ?? data.id;
|
|
4040
|
+
if (typeof id === "string") {
|
|
4041
|
+
const pending = this.pending.get(id);
|
|
4042
|
+
if (pending) {
|
|
4043
|
+
clearTimeout(pending.timer);
|
|
4044
|
+
this.pending.delete(id);
|
|
4045
|
+
pending.resolve();
|
|
4046
|
+
}
|
|
2577
4047
|
}
|
|
2578
4048
|
} else if (data.type === "channel_created" && typeof data.channel_id === "string")
|
|
2579
|
-
|
|
4049
|
+
join12(data.channel_id);
|
|
2580
4050
|
else if (["message", "thread_reply"].includes(data.type))
|
|
2581
4051
|
this.receive(data);
|
|
2582
|
-
else if (data.type === "shard_moved" || data.type === "please_reconnect")
|
|
4052
|
+
else if (data.type === "shard_moved" || data.type === "please_reconnect") {
|
|
4053
|
+
this.delay = resolveDrainReconnectDelay(data);
|
|
2583
4054
|
socket.terminate();
|
|
2584
|
-
else if (data.type === "auth_error"
|
|
4055
|
+
} else if (data.type === "auth_error") {
|
|
4056
|
+
this.log("AgentsChat authentication rejected; check profile token (backing off 30s)");
|
|
4057
|
+
this.delay = 30000;
|
|
4058
|
+
socket.close();
|
|
4059
|
+
} else if (data.type === "error")
|
|
2585
4060
|
this.log("AgentsChat returned an error; check account and channel permissions");
|
|
2586
4061
|
});
|
|
2587
4062
|
socket.on("error", () => this.log("AgentsChat socket error"));
|
|
2588
4063
|
socket.on("close", () => {
|
|
2589
4064
|
if (!current())
|
|
2590
4065
|
return;
|
|
4066
|
+
clearInterval(this.syncTimer);
|
|
4067
|
+
this.syncTimer = undefined;
|
|
2591
4068
|
this.authenticated = false;
|
|
4069
|
+
this.clearTyping();
|
|
2592
4070
|
this.rejectPending();
|
|
2593
4071
|
this.heartbeat?.stop();
|
|
2594
4072
|
this.log("AgentsChat disconnected; reconnecting with history reconciliation");
|
|
2595
4073
|
this.retry = setTimeout(() => this.start(), this.delay);
|
|
4074
|
+
this.retry.unref?.();
|
|
2596
4075
|
this.delay = Math.min(this.delay * 2, 30000);
|
|
2597
4076
|
});
|
|
2598
4077
|
}
|
|
2599
4078
|
stop() {
|
|
2600
|
-
for (const timer of this.typing.values())
|
|
2601
|
-
clearInterval(timer);
|
|
2602
|
-
this.typing.clear();
|
|
2603
4079
|
this.closed = true;
|
|
2604
4080
|
this.authenticated = false;
|
|
4081
|
+
this.clearTyping();
|
|
2605
4082
|
this.rejectPending();
|
|
2606
4083
|
clearTimeout(this.retry);
|
|
4084
|
+
this.retry = undefined;
|
|
2607
4085
|
clearInterval(this.syncTimer);
|
|
4086
|
+
this.syncTimer = undefined;
|
|
2608
4087
|
this.heartbeat?.stop();
|
|
2609
|
-
this.
|
|
4088
|
+
this.heartbeat = undefined;
|
|
4089
|
+
const socket = this.socket;
|
|
4090
|
+
this.socket = undefined;
|
|
4091
|
+
socket?.terminate();
|
|
2610
4092
|
}
|
|
2611
4093
|
}
|
|
2612
4094
|
|
|
@@ -2640,6 +4122,13 @@ See codex/README.md for setup, verification, limitations and recovery.
|
|
|
2640
4122
|
var codex;
|
|
2641
4123
|
var bridge;
|
|
2642
4124
|
var transport;
|
|
4125
|
+
function isPlainObject2(value) {
|
|
4126
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
4127
|
+
}
|
|
4128
|
+
var IPC_CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
4129
|
+
function isCleanIpcString(value, allowEmpty = false) {
|
|
4130
|
+
return typeof value === "string" && (allowEmpty || value.length > 0) && !IPC_CONTROL_CHAR_RE.test(value);
|
|
4131
|
+
}
|
|
2643
4132
|
async function main() {
|
|
2644
4133
|
const { values } = parseArgs({ options: {
|
|
2645
4134
|
"codex-bridge": { type: "boolean" },
|
|
@@ -2665,28 +4154,42 @@ async function main() {
|
|
|
2665
4154
|
return;
|
|
2666
4155
|
}
|
|
2667
4156
|
if (values["gui-thread"] || values["gui-message-file"] || values["gui-status"]) {
|
|
2668
|
-
const
|
|
4157
|
+
const parent = lstatSync12(join12(homedir6(), ".agentschat"), { throwIfNoEntry: false });
|
|
4158
|
+
if (parent && (parent.isSymbolicLink() || !parent.isDirectory()))
|
|
4159
|
+
throw new Error("GUI parent must be a real directory, not a symlink");
|
|
4160
|
+
const channel = new GuiChannel(join12(homedir6(), ".agentschat/codex-gui-outbox"), values["gui-thread"] ? [values["gui-thread"]] : []);
|
|
2669
4161
|
if (values["gui-status"]) {
|
|
2670
4162
|
console.log(JSON.stringify(channel.list().map(({ prompt: prompt2, ...receipt2 }) => receipt2)));
|
|
2671
4163
|
return;
|
|
2672
4164
|
}
|
|
2673
4165
|
if (!values["gui-thread"] || !values["gui-message-file"])
|
|
2674
4166
|
throw new Error("GUI submission requires --gui-thread and --gui-message-file");
|
|
2675
|
-
|
|
4167
|
+
assertDirectoryAncestors(dirname5(values["gui-message-file"]));
|
|
4168
|
+
const stat = lstatSync12(values["gui-message-file"]);
|
|
4169
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
4170
|
+
throw new Error("GUI message must be a regular file, not a symlink");
|
|
4171
|
+
if (stat.size > 256 * 1024)
|
|
4172
|
+
throw new Error("GUI message file exceeds 256 KiB");
|
|
4173
|
+
const { prompt, ...receipt } = channel.enqueue(values["gui-thread"], readFileSync11(values["gui-message-file"], "utf8"));
|
|
2676
4174
|
console.log(JSON.stringify(receipt));
|
|
2677
4175
|
return;
|
|
2678
4176
|
}
|
|
2679
4177
|
if ((values.bot || values["managed-worker"]) && (values["state-root"] || values["codex-home-mode"]))
|
|
2680
4178
|
throw new Error("For managed bots, configure state_root/codex_home_mode in the bot registry");
|
|
2681
|
-
const snapshot = values["managed-worker"] ? await new Promise((
|
|
4179
|
+
const snapshot = values["managed-worker"] ? await new Promise((resolve7, reject) => {
|
|
2682
4180
|
if (!process.connected) {
|
|
2683
4181
|
reject(new Error("Managed worker needs parent IPC"));
|
|
2684
4182
|
return;
|
|
2685
4183
|
}
|
|
2686
4184
|
const timer = setTimeout(() => reject(new Error("Parent configuration missing")), 1e4);
|
|
4185
|
+
timer.unref?.();
|
|
2687
4186
|
process.once("message", (config) => {
|
|
2688
4187
|
clearTimeout(timer);
|
|
2689
|
-
|
|
4188
|
+
if (!isPlainObject2(config) || Object.prototype.hasOwnProperty.call(config, "__proto__") || !isCleanIpcString(config.cwd) || !isCleanIpcString(config.stateDir) || !isCleanIpcString(config.agentId) || !isCleanIpcString(config.token) || !isCleanIpcString(config.apiUrl, true) || !isCleanIpcString(config.wsUrl, true) || config.codexBin !== undefined && !isCleanIpcString(config.codexBin) || config.model !== undefined && !isCleanIpcString(config.model) || config.effort !== undefined && !isCleanIpcString(config.effort) || config.permissions !== undefined && config.permissions !== "full-access" && config.permissions !== "read-only" || config.codexHomeMode !== undefined && config.codexHomeMode !== "linked" && config.codexHomeMode !== "isolated" && config.codexHomeMode !== "auth-only" || config.channels !== undefined && (!Array.isArray(config.channels) || config.channels.some((ch) => !isCleanIpcString(ch))) || config.senders !== undefined && (!Array.isArray(config.senders) || config.senders.some((s) => !isCleanIpcString(s)))) {
|
|
4189
|
+
reject(new Error("Invalid parent configuration"));
|
|
4190
|
+
return;
|
|
4191
|
+
}
|
|
4192
|
+
resolve7(config);
|
|
2690
4193
|
});
|
|
2691
4194
|
}) : undefined;
|
|
2692
4195
|
const c = snapshot ?? (values.bot ? loadBots(values.registry).find((b) => b.name === values.bot) : resolveConfig({ cwd: values.cwd, profile: values.profile, codexBin: values["codex-bin"], stateRoot: values["state-root"], codexHomeMode: values["codex-home-mode"] }));
|
|
@@ -2708,21 +4211,42 @@ async function main() {
|
|
|
2708
4211
|
const runtime = prepareRuntimeHome(c.stateDir, undefined, c.codexHomeMode, c.codexBin);
|
|
2709
4212
|
codex = new AppServer(c.codexBin, undefined, undefined, c.permissions, runtime, c.effort, c.model, { profileFile: c.profileFile, agentId: c.agentId, apiUrl: c.apiUrl, wsUrl: c.wsUrl });
|
|
2710
4213
|
if (values.conversations || values["read-conversation"]) {
|
|
2711
|
-
const
|
|
2712
|
-
|
|
4214
|
+
const dir = lstatSync12(c.stateDir), stateFile = join12(c.stateDir, "state.json");
|
|
4215
|
+
if (dir.isSymbolicLink() || !dir.isDirectory())
|
|
4216
|
+
throw new Error("Conversation state must use a real directory");
|
|
4217
|
+
assertDirectoryAncestors(c.stateDir);
|
|
4218
|
+
const stat = lstatSync12(stateFile);
|
|
4219
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024)
|
|
4220
|
+
throw new Error("Unsafe conversation state file");
|
|
4221
|
+
const state = JSON.parse(readFileSync11(stateFile, "utf8"));
|
|
4222
|
+
if (!isPlainObject2(state) || Object.prototype.hasOwnProperty.call(state, "__proto__"))
|
|
4223
|
+
throw new Error("Invalid conversation state");
|
|
4224
|
+
const channels = state?.channels === undefined ? {} : state.channels;
|
|
4225
|
+
if (!isPlainObject2(channels) || Object.prototype.hasOwnProperty.call(channels, "__proto__"))
|
|
4226
|
+
throw new Error("Invalid conversation channels");
|
|
4227
|
+
const safeOutput = (value) => {
|
|
4228
|
+
const text = JSON.stringify(value);
|
|
4229
|
+
return redactSecrets(typeof c.token === "string" && c.token.length > 0 ? text.split(c.token).join("[REDACTED]") : text);
|
|
4230
|
+
};
|
|
2713
4231
|
if (values.conversations) {
|
|
2714
|
-
console.log(
|
|
4232
|
+
console.log(safeOutput(Object.entries(channels).map(([channel2, data]) => ({ channel: channel2, thread: data.thread, isolated: data.namespace === runtime.home }))));
|
|
2715
4233
|
return;
|
|
2716
4234
|
}
|
|
2717
|
-
const
|
|
2718
|
-
if (!
|
|
4235
|
+
const key = values["read-conversation"];
|
|
4236
|
+
if (!Object.prototype.hasOwnProperty.call(channels, key))
|
|
2719
4237
|
throw new Error("Unknown conversation channel");
|
|
4238
|
+
const channel = channels[key];
|
|
4239
|
+
if (!isPlainObject2(channel) || typeof channel.thread !== "string" || !channel.thread)
|
|
4240
|
+
throw new Error("Invalid conversation channel");
|
|
2720
4241
|
if (channel.namespace && channel.namespace !== runtime.home)
|
|
2721
4242
|
throw new Error("Conversation belongs to a different runtime home");
|
|
2722
4243
|
await codex.start();
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
4244
|
+
try {
|
|
4245
|
+
const history = channel.namespace ? await codex.readThread(channel.thread) : await codex.readLegacyThread(channel.thread);
|
|
4246
|
+
console.log(safeOutput(history));
|
|
4247
|
+
} finally {
|
|
4248
|
+
codex.close();
|
|
4249
|
+
}
|
|
2726
4250
|
return;
|
|
2727
4251
|
}
|
|
2728
4252
|
if (c.permissions === "full-access") {
|
|
@@ -2733,9 +4257,12 @@ async function main() {
|
|
|
2733
4257
|
}
|
|
2734
4258
|
if (values.check) {
|
|
2735
4259
|
await codex.start();
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
4260
|
+
try {
|
|
4261
|
+
console.log("Official app-server initialization: OK (no chat connection or generation)");
|
|
4262
|
+
console.log(JSON.stringify({ authentication: await codex.authenticationStatus(), generation_verified: false, reply_verified: false, codex_home_mode: c.codexHomeMode ?? "linked" }));
|
|
4263
|
+
} finally {
|
|
4264
|
+
codex.close();
|
|
4265
|
+
}
|
|
2739
4266
|
return;
|
|
2740
4267
|
}
|
|
2741
4268
|
transport = new AgentsChatTransport(c, (m) => {
|
|
@@ -2779,7 +4306,9 @@ async function main() {
|
|
|
2779
4306
|
transport.start();
|
|
2780
4307
|
}
|
|
2781
4308
|
main().catch(async (e) => {
|
|
2782
|
-
|
|
4309
|
+
const rawMessage = e instanceof Error ? e.message.replace(/\x1b\[[0-9;]*[A-Za-z]|[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ").trim() : "";
|
|
4310
|
+
const diagnostic = rawMessage ? redactSecrets(rawMessage) : "invalid configuration";
|
|
4311
|
+
console.error(`Bridge startup failed: ${/token|secret|bearer|password|key|cookie|authorization|credential/i.test(diagnostic) ? "invalid configuration" : diagnostic}`);
|
|
2783
4312
|
transport?.stop();
|
|
2784
4313
|
codex?.close();
|
|
2785
4314
|
await bridge?.stop();
|