agentschat-mcp 0.36.25 → 0.36.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/codex/README.md +1 -1
  3. package/codex/app-server.ts +79 -22
  4. package/codex/bots-config.ts +31 -11
  5. package/codex/bridge.ts +123 -25
  6. package/codex/config.ts +128 -21
  7. package/codex/gui-channel.ts +66 -9
  8. package/codex/inbox-sync.ts +65 -12
  9. package/codex/loop-grants.ts +41 -11
  10. package/codex/manager.ts +101 -25
  11. package/codex/owner.ts +81 -9
  12. package/codex/processes.ts +51 -7
  13. package/codex/run.ts +70 -17
  14. package/codex/runtime-home.ts +41 -11
  15. package/codex/thread-history.ts +77 -30
  16. package/codex/transport.ts +122 -19
  17. package/connector/auth.ts +57 -5
  18. package/connector/backfill.ts +92 -10
  19. package/connector/descriptor.ts +27 -1
  20. package/connector/identities.ts +82 -14
  21. package/connector/ingest.ts +11 -2
  22. package/connector/normalize.ts +32 -12
  23. package/connector/run.ts +314 -67
  24. package/connector/server.ts +95 -26
  25. package/dist/codex-bots.js +410 -73
  26. package/dist/codex-bridge.js +1996 -576
  27. package/dist/connector.js +1286 -493
  28. package/dist/dsh.js +1776 -299
  29. package/dist/muse.js +967 -221
  30. package/dist/server.js +4277 -929
  31. package/dsh/client.js +7 -5
  32. package/dsh/identity-ui/client.js +7 -5
  33. package/dsh/identity-ui/index.js +43 -8
  34. package/dsh/inbound-bridge/index.js +595 -146
  35. package/dsh/src/cli.ts +430 -91
  36. package/dsh/src/patch.ts +295 -15
  37. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  38. package/dsh/tests/dsh.test.ts +990 -3
  39. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  40. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  41. package/muse/src/bridge.ts +54 -13
  42. package/muse/src/cli.ts +226 -41
  43. package/muse/src/client.ts +249 -34
  44. package/muse/src/config.ts +128 -12
  45. package/muse/src/policy.ts +28 -8
  46. package/muse/src/types.ts +1 -0
  47. package/muse/src/typing.ts +18 -1
  48. package/muse/src/wake.ts +237 -35
  49. package/muse/tests/bridge.test.mjs +131 -0
  50. package/muse/tests/client.test.mjs +327 -0
  51. package/muse/tests/config.test.mjs +78 -1
  52. package/muse/tests/hardening.test.mjs +199 -0
  53. package/muse/tests/hardening126.test.mjs +292 -0
  54. package/muse/tests/policy.test.mjs +83 -1
  55. package/muse/tests/wake.test.mjs +134 -6
  56. package/package.json +1 -1
  57. package/scripts/ensure-grok-wakes.mjs +93 -8
  58. package/scripts/example-url-wake-receiver.mjs +254 -61
  59. package/scripts/grok-bind-register.sh +38 -8
  60. package/skills/onboarding.md +9 -9
  61. package/src/argcheck.ts +113 -33
  62. package/src/cli.mjs +98 -14
  63. package/src/dedup.ts +57 -8
  64. package/src/grok-bind.ts +160 -33
  65. package/src/heartbeat.ts +39 -11
  66. package/src/identity-guard.ts +93 -20
  67. package/src/identity.ts +67 -11
  68. package/src/mentions.ts +26 -5
  69. package/src/onboarding-status.ts +134 -11
  70. package/src/profile-selection.ts +269 -18
  71. package/src/profile-store.ts +222 -28
  72. package/src/read-cursor.ts +256 -9
  73. package/src/reconnect.ts +98 -2
  74. package/src/redact.ts +34 -15
  75. package/src/rest-cli.ts +713 -159
  76. package/src/server.ts +285 -93
  77. package/src/session-bind.ts +731 -132
  78. package/src/session-route.ts +183 -12
  79. package/src/team-lead-skill.ts +3 -0
  80. package/src/timestamps.ts +56 -23
  81. package/src/tool-annotations.ts +10 -1
  82. package/src/wake.ts +510 -91
@@ -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 { delimiter, isAbsolute, join, relative, resolve, sep } from "node:path";
6
- function executablePath(bin) {
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/onboarding-status.ts
147
- async function getOnboardingStatus(base, agentId, token, request = fetch) {
148
- const chat = `${base.replace(/\/$/, "")}/chat/${encodeURIComponent(agentId)}`;
149
- const result = {
150
- agent_id: agentId,
151
- claimed: null,
152
- authentication: "unknown",
153
- chat_url: chat,
154
- claim_url: `${chat}?claim=1`,
155
- next_step: "check_identity"
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
- class GuiChannel {
197
- directory;
198
- allowedThreads;
199
- constructor(directory, allowedThreads) {
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 nonempty = (value) => typeof value === "string" && value.trim().length > 0;
314
- if (!profile || typeof profile !== "object" || Array.isArray(profile) || !nonempty(profile.agent_id) || !nonempty(profile.token) || !allowDevToken && profile.token === "dev-token" || profile.capabilities !== undefined && (!Array.isArray(profile.capabilities) || !profile.capabilities.every(nonempty))) {
315
- throw new Error(`Invalid identity profile at ${file}. Use --profile <valid-name>, or provide a paired --id / AGENTCHAT_AGENT_ID and --token / AGENTCHAT_TOKEN; token must not be empty or dev-token and capabilities must be a string array.`);
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, sep2, end) {
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 === sep2) {
307
+ } else if (c === end || c === sep) {
583
308
  return;
584
309
  }
585
310
  }
@@ -1193,20 +918,113 @@ 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/config.ts
1197
- function reasoningEffort(value) {
1198
- if (value === undefined)
1199
- return;
1200
- if (typeof value !== "string" || !value.trim())
1201
- throw new Error("effort must be a nonempty model-supported reasoning effort name");
1202
- return value.trim();
921
+ // codex/owner.ts
922
+ function blockedServerHost(url) {
923
+ const host = url.hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
924
+ if (!host || host === "0.0.0.0" || /^0\./.test(host) || host === "::" || host === "0:0:0:0:0:0:0:0" || /^169\.254\./.test(host) || host === "100.100.100.200" || host === "fd00:ec2::254" || host === "fd00:ec2:0:0:0:0:0:254" || host === "metadata" || host === "instance-data" || host === "metadata.google.internal" || host.endsWith(".metadata.google.internal") || host === "metadata.goog" || host.endsWith(".metadata.goog") || /^fe[89ab][0-9a-f]:/.test(host)) {
925
+ return true;
926
+ }
927
+ if (host.startsWith("::ffff:")) {
928
+ const rawTail = host.slice(7);
929
+ if (rawTail === "0:0" || rawTail === "0.0.0.0")
930
+ return true;
931
+ const tail = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(rawTail) ? rawTail.slice(2) : rawTail;
932
+ if (tail === "0:0" || tail === "0.0.0.0" || /^0\./.test(tail) || /^[0-9a-f]{1,2}:[0-9a-f]{1,4}$/.test(tail) || /^127\./.test(tail) || /^7f[0-9a-f]{2}:/.test(tail) || /^169\.254\./.test(tail) || /^a9fe:/.test(tail) || tail === "100.100.100.200" || tail === "6464:64c8") {
933
+ return true;
934
+ }
935
+ }
936
+ return false;
1203
937
  }
1204
- function modelName(value) {
1205
- if (value === undefined)
1206
- return;
1207
- if (typeof value !== "string" || !value.trim())
1208
- throw new Error("model must be a nonempty model ID");
1209
- return value.trim();
938
+ async function ownerJson(response) {
939
+ if (!response.body)
940
+ throw new Error("Missing owner response");
941
+ const reader = response.body.getReader();
942
+ const chunks = [];
943
+ let size = 0;
944
+ try {
945
+ while (true) {
946
+ const { done, value } = await reader.read();
947
+ if (done)
948
+ break;
949
+ size += value.byteLength;
950
+ if (size > 65536) {
951
+ reader.cancel().catch(() => {});
952
+ throw new Error("Owner response exceeds size limit");
953
+ }
954
+ chunks.push(value);
955
+ }
956
+ } finally {
957
+ reader.releaseLock();
958
+ }
959
+ const bytes = new Uint8Array(size);
960
+ let offset = 0;
961
+ for (const chunk of chunks) {
962
+ bytes.set(chunk, offset);
963
+ offset += chunk.byteLength;
964
+ }
965
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
966
+ }
967
+ async function getBotOwner(base, agentId, token, request = fetch) {
968
+ try {
969
+ 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) || [".", "..", "__proto__", "constructor", "prototype"].includes(agentId.toLowerCase()) || /[\/\\\s]/.test(agentId) || !token || token !== token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token))
970
+ return null;
971
+ const parsed = new URL(base);
972
+ const loopback = ["127.0.0.1", "localhost", "[::1]", "::1"].includes(parsed.hostname.toLowerCase().replace(/\.$/, ""));
973
+ if (blockedServerHost(parsed) || parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback) || parsed.username || parsed.password || parsed.search || parsed.hash || parsed.port === "0")
974
+ return null;
975
+ const origin = parsed.href.replace(/\/+$/, "");
976
+ const options = {
977
+ method: "GET",
978
+ headers: { Authorization: `Bearer ${token}` },
979
+ cache: "no-store",
980
+ redirect: "error",
981
+ signal: AbortSignal.timeout(8000)
982
+ };
983
+ const [statusSettled, entitlementSettled] = await Promise.allSettled([
984
+ request(`${origin}/api/account/onboarding`, options),
985
+ request(`${origin}/api/me/entitlements`, options)
986
+ ]);
987
+ const statusResponse = statusSettled.status === "fulfilled" ? statusSettled.value : null;
988
+ const entitlementResponse = entitlementSettled.status === "fulfilled" ? entitlementSettled.value : null;
989
+ if (!statusResponse?.ok || !entitlementResponse?.ok) {
990
+ await Promise.allSettled([
991
+ statusResponse?.body?.cancel(),
992
+ entitlementResponse?.body?.cancel()
993
+ ]);
994
+ return null;
995
+ }
996
+ const [statusValue, entitlementValue] = await Promise.all([
997
+ ownerJson(statusResponse),
998
+ ownerJson(entitlementResponse)
999
+ ]);
1000
+ const status = statusValue;
1001
+ const entitlement = entitlementValue;
1002
+ if (!status || typeof status !== "object" || Array.isArray(status) || Object.hasOwn(status, "__proto__") || status.agent_id !== agentId || status.claimed !== true)
1003
+ return null;
1004
+ if (!entitlement || typeof entitlement !== "object" || Array.isArray(entitlement) || Object.hasOwn(entitlement, "__proto__"))
1005
+ return null;
1006
+ const owner = entitlement.owner_account_id;
1007
+ 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 && ![".", "..", "__proto__", "constructor", "prototype"].includes(owner.toLowerCase()) ? owner : null;
1008
+ } catch {
1009
+ return null;
1010
+ }
1011
+ }
1012
+
1013
+ // codex/config.ts
1014
+ var CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
1015
+ function reasoningEffort(value) {
1016
+ if (value === undefined)
1017
+ return;
1018
+ if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
1019
+ throw new Error("effort must be a nonempty model-supported reasoning effort name");
1020
+ return value.trim();
1021
+ }
1022
+ function modelName(value) {
1023
+ if (value === undefined)
1024
+ return;
1025
+ if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
1026
+ throw new Error("model must be a nonempty model ID");
1027
+ return value.trim();
1210
1028
  }
1211
1029
  function permissionMode(value) {
1212
1030
  if (value === undefined)
@@ -1222,39 +1040,151 @@ function codexHomeMode(value) {
1222
1040
  throw new Error("codex_home_mode must be linked, isolated or auth-only");
1223
1041
  return value;
1224
1042
  }
1043
+ var MAX_CONFIG_BYTES = 1048576;
1044
+ function reservedProfileStem(selector) {
1045
+ return [
1046
+ "__proto__",
1047
+ "constructor",
1048
+ "prototype",
1049
+ "grok-binds",
1050
+ "session-binds",
1051
+ "agy-binds",
1052
+ "cursor",
1053
+ "read-cursors",
1054
+ "wake-pids",
1055
+ "config",
1056
+ "codex-bots"
1057
+ ].includes(selector.replace(/\.json$/i, "").toLowerCase());
1058
+ }
1059
+ function checkSingleAncestorDir(path) {
1060
+ const stat = lstatSync(path, { throwIfNoEntry: false });
1061
+ if (!stat)
1062
+ return;
1063
+ if (stat.isSymbolicLink()) {
1064
+ const target = `/private${path}`;
1065
+ if (process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(path) && realpathSync(path) === target) {
1066
+ const priv = lstatSync("/private", { throwIfNoEntry: false });
1067
+ if (!priv || priv.isSymbolicLink() || !priv.isDirectory()) {
1068
+ throw new Error("Config path must be a non-symlink directory: /private");
1069
+ }
1070
+ assertDirectoryAncestors(target);
1071
+ return;
1072
+ }
1073
+ throw new Error(`Config path must be a non-symlink directory: ${path}`);
1074
+ }
1075
+ if (!stat.isDirectory())
1076
+ throw new Error(`Config path must be a non-symlink directory: ${path}`);
1077
+ }
1078
+ function assertDirectoryAncestors(directory) {
1079
+ if (typeof directory !== "string" || !directory.trim() || CONTROL_CHAR_RE.test(directory)) {
1080
+ throw new Error(`Config path must be a non-symlink directory: ${String(directory)}`);
1081
+ }
1082
+ if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(directory)) {
1083
+ let cur;
1084
+ let remainder;
1085
+ if (isAbsolute(directory)) {
1086
+ const root = parsePath(directory).root || "/";
1087
+ cur = root;
1088
+ remainder = directory.slice(root.length);
1089
+ checkSingleAncestorDir(cur);
1090
+ } else {
1091
+ const base = resolve(process.cwd());
1092
+ assertDirectoryAncestors(base);
1093
+ cur = base;
1094
+ remainder = directory;
1095
+ }
1096
+ for (const seg of remainder.split(/[\\/]+/)) {
1097
+ if (!seg || seg === ".")
1098
+ continue;
1099
+ cur = seg === ".." ? dirname(cur) : join(cur, seg);
1100
+ checkSingleAncestorDir(cur);
1101
+ }
1102
+ }
1103
+ const paths = [];
1104
+ for (let path = resolve(directory);; path = dirname(path)) {
1105
+ paths.unshift(path);
1106
+ if (dirname(path) === path)
1107
+ break;
1108
+ }
1109
+ for (const path of paths)
1110
+ checkSingleAncestorDir(path);
1111
+ }
1112
+ function atomicReplaceRegularFile(tmp, target, verifySafeTarget, opts) {
1113
+ verifySafeTarget();
1114
+ const rename = opts?.rename ?? renameSync;
1115
+ const platform = opts?.platform ?? process.platform;
1116
+ try {
1117
+ rename(tmp, target);
1118
+ } catch (err) {
1119
+ if (platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
1120
+ verifySafeTarget();
1121
+ copyFileSync(tmp, target);
1122
+ unlinkSync(tmp);
1123
+ return;
1124
+ }
1125
+ throw err;
1126
+ }
1127
+ }
1128
+ function checkedPath(path, directory = false) {
1129
+ assertDirectoryAncestors(dirname(path));
1130
+ let stat;
1131
+ try {
1132
+ stat = lstatSync(path);
1133
+ } catch (error) {
1134
+ if (error.code === "ENOENT")
1135
+ return;
1136
+ throw error;
1137
+ }
1138
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
1139
+ throw new Error(directory ? `Config directory must be a non-symlink directory: ${path}` : `Selected profile is not a regular file: ${path}`);
1140
+ if (!directory && stat.size > MAX_CONFIG_BYTES)
1141
+ throw new Error(`Config file exceeds 1 MiB: ${path}`);
1142
+ return stat;
1143
+ }
1225
1144
  function readJson(file) {
1145
+ let value;
1226
1146
  try {
1227
- return JSON.parse(readFileSync2(file, "utf8"));
1147
+ value = JSON.parse(readFileSync(file, "utf8"));
1228
1148
  } catch {
1229
1149
  throw new Error(`Cannot read valid JSON: ${file}`);
1230
1150
  }
1151
+ if (value && typeof value === "object" && Object.hasOwn(value, "__proto__"))
1152
+ throw new Error("Invalid JSON prototype key");
1153
+ return value;
1231
1154
  }
1232
1155
  function strings(value, name) {
1233
1156
  if (value === undefined)
1234
1157
  return [];
1235
- if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim()))
1158
+ if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim() || CONTROL_CHAR_RE.test(x)))
1236
1159
  throw new Error(`${name} must be an array of nonempty strings`);
1237
1160
  return value;
1238
1161
  }
1239
- function resolveConfig(opts, env = process.env, home = homedir2()) {
1240
- const cwd = realpathSync2(opts.cwd ?? process.cwd());
1241
- const configFile = join3(cwd, ".agentschat/config.json");
1242
- const project = opts.settings ?? (existsSync2(configFile) ? readJson(configFile) : {});
1162
+ function resolveConfig(opts, env = process.env, home = homedir()) {
1163
+ assertDirectoryAncestors(opts.cwd ?? process.cwd());
1164
+ const cwd = realpathSync(opts.cwd ?? process.cwd());
1165
+ const configFile = join(cwd, ".agentschat/config.json");
1166
+ if (opts.settings === undefined)
1167
+ checkedPath(join(cwd, ".agentschat"), true);
1168
+ const project = opts.settings ?? (checkedPath(configFile) ? readJson(configFile) : {});
1243
1169
  if (!project || typeof project !== "object" || Array.isArray(project))
1244
1170
  throw new Error("Invalid project config");
1171
+ if (["__proto__", "constructor", "prototype"].some((key2) => Object.hasOwn(project, key2)))
1172
+ throw new Error("Invalid project config prototype key");
1245
1173
  const allowed = new Set(["profile", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
1246
1174
  if (Object.keys(project).some((k) => !allowed.has(k)))
1247
1175
  throw new Error("Unknown project config field (credentials belong in a private profile)");
1248
1176
  for (const k of ["profile", "agent_id", "api_url", "ws_url", "state_root"])
1249
1177
  if (project[k] !== undefined && (typeof project[k] !== "string" || !project[k].trim()))
1250
1178
  throw new Error(`Invalid project ${k}`);
1251
- const localProfile = join3(cwd, ".agentschat/profile.json");
1179
+ const localProfile = join(cwd, ".agentschat/profile.json");
1252
1180
  let codexProfile;
1253
- const codexFile = join3(cwd, ".codex/config.toml");
1254
- if (opts.settings === undefined && existsSync2(codexFile)) {
1181
+ const codexFile = join(cwd, ".codex/config.toml");
1182
+ if (opts.settings === undefined)
1183
+ checkedPath(join(cwd, ".codex"), true);
1184
+ if (opts.settings === undefined && checkedPath(codexFile)) {
1255
1185
  let doc;
1256
1186
  try {
1257
- doc = parse(readFileSync2(codexFile, "utf8"));
1187
+ doc = parse(readFileSync(codexFile, "utf8"));
1258
1188
  } catch {
1259
1189
  throw new Error("Invalid project .codex/config.toml");
1260
1190
  }
@@ -1271,29 +1201,38 @@ function resolveConfig(opts, env = process.env, home = homedir2()) {
1271
1201
  const choices = [
1272
1202
  [opts.profile, "flag"],
1273
1203
  [project.profile, "project-config"],
1274
- [opts.settings === undefined && existsSync2(localProfile) ? localProfile : undefined, "project-profile"],
1204
+ [opts.settings === undefined && checkedPath(localProfile) ? localProfile : undefined, "project-profile"],
1275
1205
  [codexProfile, "project-codex"],
1276
1206
  [env.AGENTSCHAT_PROFILE, "env"],
1277
1207
  [env.AGENTCHAT_PROFILE, "legacy-env"],
1278
1208
  ["profile", "default"]
1279
1209
  ];
1280
1210
  const [selector, source] = choices.find(([v]) => v !== undefined && v !== "");
1211
+ if (typeof selector !== "string" || CONTROL_CHAR_RE.test(selector))
1212
+ throw new Error("Invalid profile selector");
1281
1213
  let profileFile;
1282
- if (selector.startsWith("~/"))
1283
- profileFile = join3(home, selector.slice(2));
1284
- else if (isAbsolute2(selector) || selector.includes("/"))
1285
- profileFile = resolve2(cwd, selector);
1214
+ if (/^~[\\/]/.test(selector))
1215
+ profileFile = join(home, selector.slice(2));
1216
+ else if (isAbsolute(selector) || selector.includes("/") || selector.includes("\\"))
1217
+ profileFile = resolve(cwd, selector);
1286
1218
  else {
1287
- const name = selector.endsWith(".json") ? selector : `${selector}.json`;
1288
- profileFile = join3(home, ".agentschat/profiles", name);
1289
- if (!existsSync2(profileFile))
1290
- profileFile = join3(home, ".agentschat", name);
1291
- if (!existsSync2(profileFile))
1292
- profileFile = join3(home, ".agentchat", name);
1293
- }
1294
- if (!existsSync2(profileFile))
1219
+ const stem = selector.replace(/\.json$/i, "");
1220
+ if (!stem || selector.includes("..") || reservedProfileStem(selector)) {
1221
+ throw new Error("Invalid central profile selector");
1222
+ }
1223
+ const name = /\.json$/i.test(selector) ? selector : `${selector}.json`;
1224
+ profileFile = join(home, ".agentschat/profiles", name);
1225
+ if (!checkedPath(profileFile))
1226
+ profileFile = join(home, ".agentschat", name);
1227
+ if (!checkedPath(profileFile))
1228
+ profileFile = join(home, ".agentchat", name);
1229
+ }
1230
+ if (!checkedPath(profileFile))
1295
1231
  throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
1296
- if (process.platform !== "win32" && statSync(profileFile).mode & 63)
1232
+ const profileStat = checkedPath(profileFile);
1233
+ if (!profileStat.isFile())
1234
+ throw new Error(`Selected profile is not a regular file: ${profileFile}`);
1235
+ if (process.platform !== "win32" && profileStat.mode & 63)
1297
1236
  throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
1298
1237
  const profile = readJson(profileFile);
1299
1238
  validateIdentityProfile(profile, profileFile);
@@ -1303,15 +1242,18 @@ function resolveConfig(opts, env = process.env, home = homedir2()) {
1303
1242
  const wsUrl = project.ws_url ?? `${apiUrl.replace(/^http/, "ws").replace(/\/$/, "")}/ws`;
1304
1243
  for (const [raw, protocols] of [[apiUrl, ["https:", "http:"]], [wsUrl, ["wss:", "ws:"]]]) {
1305
1244
  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))
1245
+ 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
1246
  throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
1308
1247
  }
1309
1248
  const canonicalApi = new URL(apiUrl).href.replace(/\/$/, "");
1310
1249
  const key = createHash("sha256").update(JSON.stringify([cwd, canonicalApi, profile.agent_id])).digest("hex").slice(0, 24);
1311
1250
  const root = opts.stateRoot ?? project.state_root;
1312
- if (root !== undefined && (typeof root !== "string" || !root.trim()))
1251
+ if (root !== undefined && (typeof root !== "string" || !root.trim() || CONTROL_CHAR_RE.test(root)))
1313
1252
  throw new Error("Invalid state_root");
1314
- const stateRoot = root === undefined ? join3(home, ".agentschat/codex-bridge") : root.startsWith("~/") ? join3(home, root.slice(2)) : resolve2(cwd, root);
1253
+ const codexBin = opts.codexBin ?? "codex";
1254
+ if (typeof codexBin !== "string" || !codexBin.trim() || CONTROL_CHAR_RE.test(codexBin))
1255
+ throw new Error("Invalid codex_bin");
1256
+ const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : /^~[\\/]/.test(root) ? join(home, root.slice(2)) : resolve(cwd, root);
1315
1257
  return {
1316
1258
  cwd,
1317
1259
  profileFile,
@@ -1326,41 +1268,513 @@ function resolveConfig(opts, env = process.env, home = homedir2()) {
1326
1268
  wsUrl,
1327
1269
  channels: strings(project.channels, "channels"),
1328
1270
  senders: strings(project.senders, "senders"),
1329
- codexBin: opts.codexBin ?? "codex",
1330
- stateDir: join3(stateRoot, key)
1271
+ codexBin,
1272
+ stateDir: join(stateRoot, key)
1273
+ };
1274
+ }
1275
+
1276
+ // codex/runtime-home.ts
1277
+ import { homedir as homedir2 } from "node:os";
1278
+ import { delimiter, isAbsolute as isAbsolute2, join as join2, relative, resolve as resolve2, sep } from "node:path";
1279
+ function executablePath(bin) {
1280
+ if (!bin || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(bin))
1281
+ return;
1282
+ const exts = process.platform === "win32" && !/\.[A-Za-z0-9]+$/.test(bin) ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)] : [""];
1283
+ const bases = isAbsolute2(bin) || bin.includes("/") || bin.includes("\\") ? [resolve2(bin)] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map((dir) => join2(dir, bin));
1284
+ for (const base of bases) {
1285
+ for (const ext of exts) {
1286
+ const candidate = base + ext;
1287
+ try {
1288
+ accessSync(candidate, constants.X_OK);
1289
+ return realpathSync2(candidate);
1290
+ } catch {}
1291
+ }
1292
+ }
1293
+ }
1294
+ function assertDirectoryLeaf(path, label) {
1295
+ const info = lstatSync2(path, { throwIfNoEntry: false });
1296
+ if (info?.isSymbolicLink())
1297
+ throw new Error(`${label} must not be a symlink`);
1298
+ if (info && !info.isDirectory())
1299
+ throw new Error(`${label} must be a directory`);
1300
+ }
1301
+ function prepareHomeDirectory(stateDir, home) {
1302
+ assertDirectoryLeaf(stateDir, "Bot state directory");
1303
+ assertDirectoryLeaf(home, "Bot runtime home");
1304
+ assertDirectoryAncestors(stateDir);
1305
+ assertDirectoryAncestors(home);
1306
+ mkdirSync(home, { recursive: true, mode: 448 });
1307
+ }
1308
+ function assertIndependentTree(home, allowedAuthOrigin, codexExecutable) {
1309
+ if (lstatSync2(home).isSymbolicLink())
1310
+ throw new Error("Independent Codex home must not be a symlink");
1311
+ const inspect = (dir, depth = 0) => {
1312
+ if (depth > 32)
1313
+ throw new Error("Independent Codex home directory depth exceeds 32");
1314
+ for (const name of readdirSync(dir)) {
1315
+ const path = join2(dir, name), info = lstatSync2(path);
1316
+ if (info.isSymbolicLink()) {
1317
+ if (dir === home && name === "auth.json" && allowedAuthOrigin && resolve2(home, readlinkSync(path)) === allowedAuthOrigin)
1318
+ continue;
1319
+ const local = relative(home, path).split(sep).join("/");
1320
+ if (codexExecutable && /^tmp\/arg0\/codex-arg0[A-Za-z0-9_-]+\/(apply_patch|applypatch|codex-execve-wrapper|codex-linux-sandbox)$/.test(local)) {
1321
+ try {
1322
+ if (realpathSync2(path) === codexExecutable)
1323
+ continue;
1324
+ } catch {}
1325
+ }
1326
+ throw new Error("Independent Codex home must not link configuration or runtime state");
1327
+ }
1328
+ if (info.isDirectory())
1329
+ inspect(path, depth + 1);
1330
+ else if (!info.isFile())
1331
+ throw new Error("Independent Codex home must contain only regular files and directories");
1332
+ }
1333
+ };
1334
+ inspect(home);
1335
+ }
1336
+ function prepareRuntimeHome(stateDir, source = process.env.CODEX_HOME || join2(homedir2(), ".codex"), mode = "linked", codexBin = "codex") {
1337
+ if (mode !== "linked" && mode !== "isolated" && mode !== "auth-only")
1338
+ throw new Error("Invalid Codex home mode");
1339
+ if (mode === "isolated") {
1340
+ const home2 = join2(stateDir, "codex-home-isolated");
1341
+ prepareHomeDirectory(stateDir, home2);
1342
+ assertIndependentTree(home2, undefined, executablePath(codexBin));
1343
+ return { home: realpathSync2(home2) };
1344
+ }
1345
+ if (mode === "auth-only") {
1346
+ const legacyHome2 = realpathSync2(source);
1347
+ const origin = join2(legacyHome2, "auth.json");
1348
+ const originStat = lstatSync2(origin, { throwIfNoEntry: false });
1349
+ if (!originStat || originStat.isSymbolicLink() || !originStat.isFile()) {
1350
+ throw new Error("auth-only requires an existing regular auth.json; authorize its use explicitly");
1351
+ }
1352
+ const home2 = join2(stateDir, "codex-home-auth-only");
1353
+ prepareHomeDirectory(stateDir, home2);
1354
+ if (lstatSync2(home2).isSymbolicLink() || realpathSync2(home2) === legacyHome2)
1355
+ throw new Error("auth-only home must be independent");
1356
+ for (const name of ["config.toml", "AGENTS.md", "rules", "plugins", "hooks.json"]) {
1357
+ try {
1358
+ lstatSync2(join2(home2, name));
1359
+ } catch (e) {
1360
+ if (e.code === "ENOENT")
1361
+ continue;
1362
+ throw e;
1363
+ }
1364
+ throw new Error("auth-only home contains unexpected configuration; use a fresh state root");
1365
+ }
1366
+ const skills = join2(home2, "skills");
1367
+ const skillsInfo = lstatSync2(skills, { throwIfNoEntry: false });
1368
+ if (skillsInfo && (skillsInfo.isSymbolicLink() || !skillsInfo.isDirectory() || readdirSync(skills).some((name) => name !== ".system")))
1369
+ throw new Error("auth-only home contains unexpected custom skills");
1370
+ assertIndependentTree(home2, origin, executablePath(codexBin));
1371
+ const target = join2(home2, "auth.json");
1372
+ try {
1373
+ if (!lstatSync2(target).isSymbolicLink() || resolve2(home2, readlinkSync(target)) !== origin)
1374
+ throw new Error("Unexpected auth-only login binding");
1375
+ } catch (e) {
1376
+ if (e.code !== "ENOENT")
1377
+ throw e;
1378
+ symlinkSync(origin, target);
1379
+ }
1380
+ assertIndependentTree(home2, origin, executablePath(codexBin));
1381
+ return { home: realpathSync2(home2) };
1382
+ }
1383
+ const legacyHome = existsSync(source) ? realpathSync2(source) : resolve2(source);
1384
+ const home = join2(stateDir, "codex-home");
1385
+ prepareHomeDirectory(stateDir, home);
1386
+ if (realpathSync2(home) === legacyHome)
1387
+ throw new Error("Bot runtime home must differ from desktop Codex home");
1388
+ if (lstatSync2(home).isSymbolicLink())
1389
+ throw new Error("Bot runtime home must not be a symlink");
1390
+ for (const name of ["config.toml", "auth.json", "AGENTS.md", "skills", "rules", "plugins", "hooks.json", "models_cache.json"]) {
1391
+ const origin = join2(legacyHome, name), target = join2(home, name);
1392
+ if (!existsSync(origin))
1393
+ continue;
1394
+ let current;
1395
+ try {
1396
+ current = lstatSync2(target);
1397
+ } catch (e) {
1398
+ if (e.code !== "ENOENT")
1399
+ throw e;
1400
+ }
1401
+ if (current) {
1402
+ if (!current.isSymbolicLink() || resolve2(home, readlinkSync(target)) !== origin)
1403
+ throw new Error(`Unexpected bot runtime configuration: ${name}`);
1404
+ } else
1405
+ symlinkSync(origin, target);
1406
+ }
1407
+ return { home, legacyHome };
1408
+ }
1409
+
1410
+ // src/onboarding-status.ts
1411
+ var DEFAULT_PUBLIC_BASE = "https://agents-chat.com";
1412
+ function isForbiddenMetadataOrLinkLocalHost(host) {
1413
+ 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") {
1414
+ return true;
1415
+ }
1416
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) {
1417
+ const [a, b] = host.split(".").map(Number);
1418
+ if (a === 0 || a === 169 && b === 254)
1419
+ return true;
1420
+ }
1421
+ if (host.startsWith("[") && host.endsWith("]")) {
1422
+ const inner = host.slice(1, -1).toLowerCase();
1423
+ if (inner === "::" || inner === "0:0:0:0:0:0:0:0" || inner === "fd00:ec2::254" || /^fe[89ab][0-9a-f]*:/i.test(inner)) {
1424
+ return true;
1425
+ }
1426
+ 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)) {
1427
+ return true;
1428
+ }
1429
+ }
1430
+ return false;
1431
+ }
1432
+ function isSafeOnboardingBase(base) {
1433
+ try {
1434
+ if (!base || base !== base.trim() || /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(base))
1435
+ return false;
1436
+ if (/:0(?:\/|$)/.test(base))
1437
+ return false;
1438
+ const parsed = new URL(base);
1439
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
1440
+ if (!host || isForbiddenMetadataOrLinkLocalHost(host))
1441
+ return false;
1442
+ if (parsed.port !== "") {
1443
+ const p = Number(parsed.port);
1444
+ if (!Number.isInteger(p) || p < 1 || p > 65535)
1445
+ return false;
1446
+ }
1447
+ const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
1448
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback))
1449
+ return false;
1450
+ if (parsed.username || parsed.password || parsed.search || parsed.hash)
1451
+ return false;
1452
+ return true;
1453
+ } catch {
1454
+ return false;
1455
+ }
1456
+ }
1457
+ function isSafeOnboardingAgentId(id) {
1458
+ if (!id || id.length > 128 || /[\x00-\x1f\x7f-\x9f\u2028\u2029\s/\\]/.test(id))
1459
+ return false;
1460
+ if (id === "." || id.includes(".."))
1461
+ return false;
1462
+ const lower = id.toLowerCase();
1463
+ if (lower === "__proto__" || lower === "constructor" || lower === "prototype")
1464
+ return false;
1465
+ return true;
1466
+ }
1467
+ var MAX_ONBOARDING_JSON_BYTES = 64 * 1024;
1468
+ async function readBoundedJson(r, maxBytes = MAX_ONBOARDING_JSON_BYTES) {
1469
+ const rawContentLen = r.headers?.get?.("content-length");
1470
+ if (rawContentLen !== null && rawContentLen !== undefined && rawContentLen.trim() !== "") {
1471
+ const trimmedLen = rawContentLen.trim();
1472
+ if (!/^\d+$/.test(trimmedLen) || Number(trimmedLen) > maxBytes) {
1473
+ try {
1474
+ await r.body?.cancel?.();
1475
+ } catch {}
1476
+ throw new Error("onboarding response too large");
1477
+ }
1478
+ }
1479
+ if (!r.body) {
1480
+ const txt = await r.text();
1481
+ if (Buffer.byteLength(txt, "utf8") > maxBytes)
1482
+ throw new Error("onboarding response too large");
1483
+ return JSON.parse(txt);
1484
+ }
1485
+ const reader = r.body.getReader();
1486
+ const chunks = [];
1487
+ let total = 0;
1488
+ try {
1489
+ while (true) {
1490
+ const { done, value } = await reader.read();
1491
+ if (done)
1492
+ break;
1493
+ if (value) {
1494
+ total += value.byteLength;
1495
+ if (total > maxBytes) {
1496
+ await reader.cancel().catch(() => {});
1497
+ throw new Error("onboarding response too large");
1498
+ }
1499
+ chunks.push(value);
1500
+ }
1501
+ }
1502
+ } finally {
1503
+ try {
1504
+ reader.releaseLock();
1505
+ } catch {}
1506
+ }
1507
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
1508
+ }
1509
+ async function getOnboardingStatus(base, agentId, token, request = fetch) {
1510
+ const cleanBase = typeof base === "string" ? base.trim().replace(/\/+$/, "") : "";
1511
+ const rawAgentId = typeof agentId === "string" ? agentId.trim() : "";
1512
+ const validAgent = isSafeOnboardingAgentId(rawAgentId);
1513
+ const safeAgentId = validAgent ? rawAgentId : "";
1514
+ const validBase = Boolean(cleanBase && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(cleanBase) && isSafeOnboardingBase(cleanBase));
1515
+ const safeDisplayBase = validBase ? cleanBase : DEFAULT_PUBLIC_BASE;
1516
+ const chat = `${safeDisplayBase}/chat/${encodeURIComponent(safeAgentId)}`;
1517
+ const result = {
1518
+ agent_id: safeAgentId,
1519
+ claimed: null,
1520
+ authentication: "unknown",
1521
+ chat_url: chat,
1522
+ claim_url: `${chat}?claim=1`,
1523
+ next_step: "check_identity"
1331
1524
  };
1525
+ if (!validBase || !validAgent || typeof token !== "string" || !token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) {
1526
+ return result;
1527
+ }
1528
+ try {
1529
+ const r = await request(`${cleanBase}/api/account/onboarding`, {
1530
+ headers: { Authorization: `Bearer ${token.trim()}` },
1531
+ cache: "no-store",
1532
+ signal: AbortSignal.timeout(8000),
1533
+ redirect: "error"
1534
+ });
1535
+ if (r.status === 401 || r.status === 403) {
1536
+ try {
1537
+ await r.body?.cancel?.();
1538
+ } catch {}
1539
+ result.authentication = "failed";
1540
+ return result;
1541
+ }
1542
+ if (!r.ok) {
1543
+ try {
1544
+ await r.body?.cancel?.();
1545
+ } catch {}
1546
+ return result;
1547
+ }
1548
+ const data = await readBoundedJson(r);
1549
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.prototype.hasOwnProperty.call(data, "__proto__") || data.agent_id !== safeAgentId || typeof data.claimed !== "boolean")
1550
+ return result;
1551
+ result.authentication = "ok";
1552
+ result.claimed = data.claimed;
1553
+ result.next_step = data.claimed ? "verify_reply" : "join_public_chat";
1554
+ } catch {}
1555
+ return result;
1556
+ }
1557
+
1558
+ // codex/gui-channel.ts
1559
+ import { randomUUID } from "node:crypto";
1560
+ import { mkdirSync as mkdirSync2, writeFileSync, readFileSync as readFileSync2, readdirSync as readdirSync2, rmSync, lstatSync as lstatSync3 } from "node:fs";
1561
+ import { join as join3 } from "node:path";
1562
+ function payload(result) {
1563
+ if (result?.isError || result?.success === false || result?.error)
1564
+ throw new Error("GUI tool rejected request");
1565
+ if (Array.isArray(result?.content)) {
1566
+ const text = result.content.find((c) => c.type === "text")?.text;
1567
+ if (!text)
1568
+ throw new Error("GUI tool returned no receipt");
1569
+ if (typeof text !== "string" || text.length > 1048576)
1570
+ throw new Error("GUI receipt exceeds size limit");
1571
+ const parsed = JSON.parse(text);
1572
+ if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__"))
1573
+ throw new Error("Invalid GUI receipt");
1574
+ return parsed;
1575
+ }
1576
+ return result;
1577
+ }
1578
+ function validTarget(value) {
1579
+ 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
1580
  }
1333
1581
 
1582
+ class GuiChannel {
1583
+ directory;
1584
+ allowedThreads;
1585
+ constructor(directory, allowedThreads) {
1586
+ this.directory = directory;
1587
+ this.allowedThreads = allowedThreads;
1588
+ const existing = lstatSync3(directory, { throwIfNoEntry: false });
1589
+ if (existing && (existing.isSymbolicLink() || !existing.isDirectory()))
1590
+ throw new Error("GUI outbox must be a real directory, not a symlink");
1591
+ assertDirectoryAncestors(directory);
1592
+ mkdirSync2(directory, { recursive: true, mode: 448 });
1593
+ const stat = lstatSync3(directory);
1594
+ if (stat.isSymbolicLink() || !stat.isDirectory())
1595
+ throw new Error("GUI outbox must be a real directory, not a symlink");
1596
+ }
1597
+ path(id) {
1598
+ if (!/^[0-9a-f-]{36}$/.test(id))
1599
+ throw new Error("Invalid delivery ID");
1600
+ return join3(this.directory, `${id}.json`);
1601
+ }
1602
+ save(entry) {
1603
+ const path = this.path(entry.id), temp = `${path}.${randomUUID()}.tmp`;
1604
+ const stat = lstatSync3(path, { throwIfNoEntry: false });
1605
+ if (stat?.isSymbolicLink() || stat && !stat.isFile())
1606
+ throw new Error("GUI receipt must be a regular file, not a symlink");
1607
+ try {
1608
+ writeFileSync(temp, JSON.stringify(entry), { mode: 384, flag: "wx" });
1609
+ atomicReplaceRegularFile(temp, path, () => {
1610
+ const current = lstatSync3(path, { throwIfNoEntry: false });
1611
+ if (current && (current.isSymbolicLink() || !current.isFile()))
1612
+ throw new Error("GUI receipt must be a regular file, not a symlink");
1613
+ });
1614
+ } catch (error) {
1615
+ if (error.code !== "EEXIST")
1616
+ rmSync(temp, { force: true });
1617
+ throw error;
1618
+ }
1619
+ }
1620
+ get(id) {
1621
+ const path = this.path(id), stat = lstatSync3(path);
1622
+ if (stat.isSymbolicLink() || !stat.isFile())
1623
+ throw new Error("GUI receipt must be a regular file, not a symlink");
1624
+ if (stat.size > 1048576)
1625
+ throw new Error("GUI receipt exceeds size limit");
1626
+ const entry = JSON.parse(readFileSync2(path, "utf8"));
1627
+ 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")
1628
+ throw new Error("Invalid GUI receipt");
1629
+ return entry;
1630
+ }
1631
+ list() {
1632
+ const entries = [];
1633
+ for (const file of readdirSync2(this.directory)) {
1634
+ if (!/^[0-9a-f-]{36}\.json$/.test(file))
1635
+ continue;
1636
+ try {
1637
+ entries.push(this.get(file.slice(0, -5)));
1638
+ } catch {}
1639
+ }
1640
+ return entries;
1641
+ }
1642
+ enqueue(threadId, text, hostId) {
1643
+ if (!validTarget(threadId) || hostId !== undefined && !validTarget(hostId))
1644
+ throw new Error("Invalid GUI target");
1645
+ if (!this.allowedThreads.includes(threadId))
1646
+ throw new Error("GUI target is not allowed");
1647
+ if (!text.trim() || text.length > 24000)
1648
+ throw new Error("GUI message must contain 1–24000 characters");
1649
+ const id = randomUUID();
1650
+ const entry = {
1651
+ id,
1652
+ threadId,
1653
+ ...hostId ? { hostId } : {},
1654
+ prompt: `[AgentsChat delivery ${id}]
1655
+ ${text}`,
1656
+ status: "pending",
1657
+ createdAt: new Date().toISOString()
1658
+ };
1659
+ this.save(entry);
1660
+ return entry;
1661
+ }
1662
+ async dispatch(id, call) {
1663
+ const lock = `${this.path(id)}.lock`;
1664
+ try {
1665
+ mkdirSync2(lock, { mode: 448 });
1666
+ } catch (error) {
1667
+ if (error.code !== "EEXIST")
1668
+ throw error;
1669
+ const stat = lstatSync3(lock);
1670
+ if (stat.isSymbolicLink())
1671
+ throw new Error("GUI delivery lock must not be a symlink");
1672
+ const ageMs = Date.now() - stat.mtimeMs;
1673
+ if (!stat.isDirectory() || ageMs >= -5 * 60000 && ageMs <= 5 * 60000)
1674
+ throw error;
1675
+ rmSync(lock, { recursive: true, force: true });
1676
+ mkdirSync2(lock, { mode: 448 });
1677
+ }
1678
+ try {
1679
+ const entry = this.get(id);
1680
+ if (!this.allowedThreads.includes(entry.threadId))
1681
+ throw new Error("GUI target is no longer allowed");
1682
+ if (entry.status === "delivered")
1683
+ return entry;
1684
+ const target = { threadId: entry.threadId, ...entry.hostId ? { hostId: entry.hostId } : {} };
1685
+ if (entry.status === "pending") {
1686
+ entry.status = "sending";
1687
+ this.save(entry);
1688
+ try {
1689
+ payload(await call("send_message_to_thread", { ...target, prompt: entry.prompt }));
1690
+ entry.status = "submitted";
1691
+ this.save(entry);
1692
+ } catch {
1693
+ entry.status = "uncertain";
1694
+ this.save(entry);
1695
+ }
1696
+ }
1697
+ if (entry.status === "sending") {
1698
+ entry.status = "uncertain";
1699
+ this.save(entry);
1700
+ }
1701
+ try {
1702
+ let cursor;
1703
+ const seenCursors = new Set;
1704
+ for (let page = 0;page < 5; page++) {
1705
+ const history = payload(await call("read_thread", {
1706
+ ...target,
1707
+ turnLimit: 10,
1708
+ maxOutputCharsPerItem: 32000,
1709
+ ...cursor ? { cursor } : {}
1710
+ }));
1711
+ if (history?.thread?.id !== entry.threadId)
1712
+ throw new Error("Wrong GUI thread in receipt");
1713
+ const turn = history.turns?.find((t) => t.items?.some((item) => item.type === "userMessage" && item.content?.some((c) => c.type === "text" && c.text === entry.prompt)));
1714
+ if (turn) {
1715
+ entry.status = "delivered";
1716
+ entry.deliveredAt = new Date().toISOString();
1717
+ entry.turnId = turn.id;
1718
+ this.save(entry);
1719
+ break;
1720
+ }
1721
+ const nextCursor = history.page?.nextCursor;
1722
+ if (typeof nextCursor !== "string" || !nextCursor.length || seenCursors.has(nextCursor))
1723
+ break;
1724
+ seenCursors.add(nextCursor);
1725
+ cursor = nextCursor;
1726
+ }
1727
+ } catch {}
1728
+ return entry;
1729
+ } finally {
1730
+ rmSync(lock, { recursive: true, force: true });
1731
+ }
1732
+ }
1733
+ }
1734
+
1735
+ // codex/run.ts
1736
+ import { readFileSync as readFileSync11, lstatSync as lstatSync12 } from "node:fs";
1737
+ import { homedir as homedir6 } from "node:os";
1738
+ import { join as join12, dirname as dirname5 } from "node:path";
1739
+
1334
1740
  // codex/bots-config.ts
1741
+ import { readFileSync as readFileSync3, realpathSync as realpathSync3, mkdirSync as mkdirSync3, lstatSync as lstatSync4 } from "node:fs";
1742
+ import { homedir as homedir3 } from "node:os";
1743
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join4, resolve as resolve3 } from "node:path";
1335
1744
  function defaultRegistry(home = homedir3()) {
1336
1745
  return join4(home, ".agentschat/codex-bots.json");
1337
1746
  }
1338
1747
  function loadBots(file = defaultRegistry(), home = homedir3()) {
1748
+ assertDirectoryAncestors(dirname2(file));
1339
1749
  let doc;
1340
1750
  try {
1751
+ const info = lstatSync4(file);
1752
+ if (info.isSymbolicLink() || !info.isFile() || info.size > 1048576)
1753
+ throw new Error("Invalid registry file");
1341
1754
  doc = JSON.parse(readFileSync3(file, "utf8"));
1342
1755
  } catch {
1343
1756
  throw new Error("Cannot read bot registry JSON");
1344
1757
  }
1345
1758
  const object = (x) => x && typeof x === "object" && !Array.isArray(x);
1346
1759
  const fields = (x, keys) => {
1347
- if (!object(x) || Object.keys(x).some((k) => !keys.includes(k)))
1760
+ if (!object(x) || Object.getOwnPropertyNames(x).some((k) => !keys.includes(k)))
1348
1761
  throw new Error("Unknown or invalid bot registry field");
1349
1762
  };
1350
- const text = (x) => typeof x === "string" && x.trim().length > 0;
1763
+ const text = (x) => typeof x === "string" && x.trim().length > 0 && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(x);
1764
+ const reserved = (s) => ["__proto__", "constructor", "prototype"].includes(s.toLowerCase());
1351
1765
  fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
1352
- if (doc.version !== 1 || !Array.isArray(doc.bots))
1766
+ if (doc.version !== 1 || !Array.isArray(doc.bots) || doc.bots.length > 128)
1353
1767
  throw new Error("Registry requires version 1 and bots array");
1354
1768
  for (const k of ["default_workdir", "codex_bin"])
1355
1769
  if (doc[k] !== undefined && !text(doc[k]))
1356
1770
  throw new Error(`Invalid ${k}`);
1357
- const path = (value) => value.startsWith("~/") ? join4(home, value.slice(2)) : isAbsolute3(value) ? value : resolve3(dirname(file), value);
1771
+ const path = (value) => /^~[\\/]/.test(value) ? join4(home, value.slice(2)) : isAbsolute3(value) ? value : resolve3(dirname2(file), value);
1358
1772
  const defaultDir = doc.default_workdir ? path(doc.default_workdir) : join4(home, ".agentschat/workspace");
1359
1773
  const names = new Set, identities = new Set;
1360
1774
  const bots = [];
1361
1775
  for (const bot of doc.bots) {
1362
1776
  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))
1777
+ 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
1778
  throw new Error("Bot names must be unique simple labels");
1365
1779
  names.add(bot.name);
1366
1780
  if (bot.enabled !== undefined && typeof bot.enabled !== "boolean")
@@ -1369,11 +1783,23 @@ function loadBots(file = defaultRegistry(), home = homedir3()) {
1369
1783
  continue;
1370
1784
  if (!text(bot.profile) || bot.workdir !== undefined && !text(bot.workdir))
1371
1785
  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))
1786
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile) || bot.profile.includes("..") || reservedProfileStem(bot.profile)) {
1373
1787
  throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
1374
- if (!doc.default_workdir && !bot.workdir)
1788
+ }
1789
+ const directoryLeaf = (dir) => {
1790
+ const info = lstatSync4(dir, { throwIfNoEntry: false });
1791
+ if (info && (info.isSymbolicLink() || !info.isDirectory()))
1792
+ throw new Error("Bot workdir must be a directory, not a symlink");
1793
+ assertDirectoryAncestors(dir);
1794
+ };
1795
+ if (!doc.default_workdir && !bot.workdir) {
1796
+ directoryLeaf(join4(home, ".agentschat"));
1797
+ directoryLeaf(defaultDir);
1375
1798
  mkdirSync3(defaultDir, { recursive: true, mode: 448 });
1376
- const cwd = realpathSync3(bot.workdir ? path(bot.workdir) : defaultDir);
1799
+ }
1800
+ const workdir = bot.workdir ? path(bot.workdir) : defaultDir;
1801
+ directoryLeaf(workdir);
1802
+ const cwd = realpathSync3(workdir);
1377
1803
  const settings = {};
1378
1804
  for (const k of ["agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "codex_home_mode"])
1379
1805
  if (bot[k] !== undefined)
@@ -1401,6 +1827,84 @@ import { spawn } from "node:child_process";
1401
1827
  import { fileURLToPath } from "node:url";
1402
1828
  import { createInterface } from "node:readline";
1403
1829
 
1830
+ // src/wake.ts
1831
+ import { existsSync as existsSync2, lstatSync as lstatSync5, readFileSync as readFileSync4, readlinkSync as readlinkSync2 } from "node:fs";
1832
+ import { homedir as homedir4 } from "node:os";
1833
+ import { dirname as dirname3, isAbsolute as isAbsolute4, join as join5, parse as parse2, resolve as resolve4, win32 as pathWin32 } from "node:path";
1834
+ var PROTOTYPE_WAKE_KEYS = new Set([
1835
+ "prototype",
1836
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
1837
+ ]);
1838
+ var GROK_GATEWAY_PATH_CANDIDATES = [
1839
+ join5(process.env.HOME || process.env.USERPROFILE || homedir4(), ".grok", "gateway.json"),
1840
+ "/home/box/sand-data/gateway.json"
1841
+ ];
1842
+ var zcodeSessionQueues = new Map;
1843
+ function resolveWindowsCliSpawn(cmd, args, opts) {
1844
+ const platform = opts?.platform ?? process.platform;
1845
+ const trimmed = (cmd || "").trim();
1846
+ if (!trimmed)
1847
+ return { cmd, args };
1848
+ const execPath = opts?.execPath ?? process.execPath;
1849
+ if (/\.(?:cjs|mjs|js)$/i.test(trimmed)) {
1850
+ return { cmd: execPath, args: [trimmed, ...args] };
1851
+ }
1852
+ if (platform !== "win32") {
1853
+ return { cmd: trimmed, args };
1854
+ }
1855
+ const env = opts?.env ?? process.env;
1856
+ const exists = opts?.existsImpl ?? existsSync2;
1857
+ const readText = opts?.readTextImpl ?? ((p) => readFileSync4(p, "utf8"));
1858
+ const hasSep = /[\\/]/.test(trimmed) || /^[A-Za-z]:/.test(trimmed);
1859
+ const hasWinExt = /\.(?:exe|cmd|bat)$/i.test(trimmed);
1860
+ const candidates = [];
1861
+ if (hasSep) {
1862
+ if (hasWinExt) {
1863
+ candidates.push(trimmed);
1864
+ } else {
1865
+ candidates.push(`${trimmed}.exe`, `${trimmed}.cmd`, trimmed);
1866
+ }
1867
+ } else {
1868
+ const rawPath = env.PATH ?? env.Path ?? env.path ?? "";
1869
+ for (const rawDir of rawPath.split(";")) {
1870
+ const dir = rawDir.trim().replace(/^"+|"+$/g, "");
1871
+ if (!dir)
1872
+ continue;
1873
+ if (hasWinExt) {
1874
+ candidates.push(pathWin32.join(dir, trimmed));
1875
+ } else {
1876
+ candidates.push(pathWin32.join(dir, `${trimmed}.exe`), pathWin32.join(dir, `${trimmed}.cmd`));
1877
+ }
1878
+ }
1879
+ }
1880
+ for (const candidate of candidates) {
1881
+ if (!exists(candidate))
1882
+ continue;
1883
+ if (/\.exe$/i.test(candidate)) {
1884
+ return { cmd: candidate, args };
1885
+ }
1886
+ if (/\.(?:cmd|bat)$/i.test(candidate)) {
1887
+ try {
1888
+ const content = readText(candidate);
1889
+ const m = content.match(/%(?:~)?dp0%?[\\/]([^"\r\n]+?\.(?:cjs|mjs|js))/i);
1890
+ if (m && m[1]) {
1891
+ const cmdDir = pathWin32.dirname(candidate);
1892
+ const scriptPath = pathWin32.resolve(cmdDir, m[1].replace(/\//g, "\\"));
1893
+ if (exists(scriptPath)) {
1894
+ const bundledNode = pathWin32.join(cmdDir, "node.exe");
1895
+ const runner = exists(bundledNode) ? bundledNode : execPath;
1896
+ return { cmd: runner, args: [scriptPath, ...args] };
1897
+ }
1898
+ }
1899
+ } catch {}
1900
+ return { cmd: candidate, args };
1901
+ }
1902
+ return { cmd: candidate, args };
1903
+ }
1904
+ return { cmd: trimmed, args };
1905
+ }
1906
+
1907
+ // codex/app-server.ts
1404
1908
  class ThreadBusyError extends Error {
1405
1909
  constructor() {
1406
1910
  super("This conversation has another active writer; waiting to resume the same task");
@@ -1416,9 +1920,12 @@ class AppServer {
1416
1920
  effort;
1417
1921
  model;
1418
1922
  toolIdentity;
1923
+ requestTimeoutMs;
1419
1924
  onFatal;
1420
1925
  closed = false;
1421
1926
  child;
1927
+ rl;
1928
+ killTimer;
1422
1929
  nextId = 0;
1423
1930
  pending = new Map;
1424
1931
  active;
@@ -1427,7 +1934,7 @@ class AppServer {
1427
1934
  readonlyFilesystemReported = false;
1428
1935
  diagnosticTail = "";
1429
1936
  disabledMcp = {};
1430
- constructor(bin = "codex", args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs, permissions = "full-access", runtime, effort, model, toolIdentity) {
1937
+ constructor(bin = "codex", args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs, permissions = "full-access", runtime, effort, model, toolIdentity, requestTimeoutMs = 30000) {
1431
1938
  this.bin = bin;
1432
1939
  this.args = args;
1433
1940
  this.permissions = permissions;
@@ -1435,11 +1942,14 @@ class AppServer {
1435
1942
  this.effort = effort;
1436
1943
  this.model = model;
1437
1944
  this.toolIdentity = toolIdentity;
1945
+ this.requestTimeoutMs = requestTimeoutMs;
1438
1946
  }
1439
1947
  get namespace() {
1440
1948
  return this.runtime?.home;
1441
1949
  }
1442
1950
  async start() {
1951
+ if (this.model !== undefined && (typeof this.model !== "string" || !this.model.trim() || this.model.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(this.model)))
1952
+ throw new Error("Invalid app-server model");
1443
1953
  const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^AGENTS?CHAT_|^RELAY_/.test(k)));
1444
1954
  env.AGENTSCHAT_LOCK_OWNER_PID = String(process.pid);
1445
1955
  env.AGENTSCHAT_TOOL_ONLY = "1";
@@ -1467,7 +1977,8 @@ class AppServer {
1467
1977
  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
1978
  args.push("-c", `mcp_servers.agentschat=${encode(entry)}`);
1469
1979
  }
1470
- this.child = spawn(this.bin, args, { env, stdio: "pipe" });
1980
+ const resolved = resolveWindowsCliSpawn(this.bin, args, { env });
1981
+ this.child = spawn(resolved.cmd, resolved.args, { env, stdio: "pipe", windowsHide: true });
1471
1982
  this.child.stderr.on("data", (chunk) => {
1472
1983
  if (this.initialized)
1473
1984
  return;
@@ -1477,13 +1988,31 @@ class AppServer {
1477
1988
  });
1478
1989
  this.child.stdin.on("error", () => this.fatal(new Error("Codex input pipe closed")));
1479
1990
  this.child.on("error", () => this.fatal(new Error("Could not start Codex app-server")));
1480
- this.child.on("exit", () => 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")));
1481
- createInterface({ input: this.child.stdout }).on("line", (line) => {
1991
+ this.child.on("exit", () => {
1992
+ if (this.killTimer) {
1993
+ clearTimeout(this.killTimer);
1994
+ this.killTimer = undefined;
1995
+ }
1996
+ 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"));
1997
+ });
1998
+ this.rl = createInterface({ input: this.child.stdout });
1999
+ this.rl.on("line", (line) => {
2000
+ if (line.length > 8 * 1024 * 1024) {
2001
+ this.fatal(new Error("Oversized app-server response"));
2002
+ return;
2003
+ }
2004
+ let parsed;
1482
2005
  try {
1483
- this.receive(JSON.parse(line));
2006
+ parsed = JSON.parse(line);
1484
2007
  } catch {
1485
2008
  this.fatal(new Error("Invalid app-server response"));
2009
+ return;
2010
+ }
2011
+ if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
2012
+ this.fatal(new Error("Invalid app-server response"));
2013
+ return;
1486
2014
  }
2015
+ this.receive(parsed);
1487
2016
  });
1488
2017
  await this.request("initialize", { clientInfo: { name: "agentschat_bridge", version: "0.1.0" } });
1489
2018
  this.write({ method: "initialized" });
@@ -1508,26 +2037,42 @@ class AppServer {
1508
2037
  this.child.stdin.write(JSON.stringify(value) + `
1509
2038
  `);
1510
2039
  }
1511
- request(method, params) {
1512
- return new Promise((resolve4, reject) => {
2040
+ request(method, params, timeoutMs = this.requestTimeoutMs) {
2041
+ return new Promise((resolve5, reject) => {
1513
2042
  const id = ++this.nextId;
1514
- this.pending.set(id, { method, resolve: resolve4, reject });
2043
+ const timer = setTimeout(() => {
2044
+ if (!this.pending.delete(id))
2045
+ return;
2046
+ const err = new Error(`App-server request timed out (${method})`);
2047
+ this.fatal(err);
2048
+ reject(err);
2049
+ }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(Math.max(50, Math.floor(timeoutMs)), 2147483647) : 30000);
2050
+ timer.unref?.();
2051
+ this.pending.set(id, { method, timer, resolve: resolve5, reject });
1515
2052
  try {
1516
2053
  this.write({ id, method, params });
1517
2054
  } catch (e) {
2055
+ clearTimeout(timer);
1518
2056
  this.pending.delete(id);
1519
2057
  reject(e);
1520
2058
  }
1521
2059
  });
1522
2060
  }
1523
2061
  receive(message) {
2062
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
2063
+ this.fatal(new Error("Invalid app-server response"));
2064
+ return;
2065
+ }
1524
2066
  if (message.id !== undefined && message.method) {
1525
- this.write({ id: message.id, error: { code: -32601, message: "Interactive requests unsupported by bridge" } });
2067
+ try {
2068
+ this.write({ id: message.id, error: { code: -32601, message: "Interactive requests unsupported by bridge" } });
2069
+ } catch {}
1526
2070
  return;
1527
2071
  }
1528
2072
  if (message.id !== undefined) {
1529
2073
  const waiter = this.pending.get(message.id);
1530
2074
  if (waiter) {
2075
+ clearTimeout(waiter.timer);
1531
2076
  this.pending.delete(message.id);
1532
2077
  if (message.error) {
1533
2078
  const detail = typeof message.error.message === "string" ? message.error.message : "";
@@ -1542,36 +2087,46 @@ class AppServer {
1542
2087
  if (!a || p?.threadId !== a.thread)
1543
2088
  return;
1544
2089
  if (!a.turn) {
1545
- a.early.push(message);
2090
+ if (a.early.length < 500)
2091
+ a.early.push(message);
1546
2092
  return;
1547
2093
  }
1548
2094
  if ((p.turnId ?? p.turn?.id) !== a.turn)
1549
2095
  return;
1550
- if (message.method === "item/completed" && p.item?.type === "agentMessage" && (!p.item.phase || p.item.phase === "final_answer"))
1551
- a.items.set(p.item.id, p.item.text);
2096
+ const recordItem = (item) => {
2097
+ 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))
2098
+ a.items.set(item.id, item.text);
2099
+ };
2100
+ if (message.method === "item/completed")
2101
+ recordItem(p.item);
1552
2102
  if (message.method === "turn/completed") {
1553
2103
  this.active = undefined;
1554
- if (p.turn.status !== "completed") {
1555
- a.reject(new Error(`Codex turn ${p.turn.status}`));
2104
+ if (p.turn?.status !== "completed") {
2105
+ a.reject(new Error(`Codex turn ${p.turn?.status ?? "unknown"}`));
1556
2106
  return;
1557
2107
  }
1558
- for (const item of p.turn.items ?? [])
1559
- if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer"))
1560
- a.items.set(item.id, item.text);
2108
+ for (const item of Array.isArray(p.turn.items) ? p.turn.items : [])
2109
+ recordItem(item);
1561
2110
  const text = [...a.items.values()].join(`
1562
2111
  `).trim();
1563
2112
  text ? a.resolve(text) : a.reject(new Error("Codex completed without a final reply"));
1564
2113
  }
1565
2114
  }
1566
2115
  async thread(cwd, existing, ephemeral = false, permissions = this.permissions) {
2116
+ if (typeof cwd !== "string" || !cwd.trim() || cwd.length > 4096 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(cwd))
2117
+ throw new Error("Invalid app-server cwd");
2118
+ if (existing !== undefined && (typeof existing !== "string" || !existing.trim() || existing.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(existing)))
2119
+ throw new Error("Invalid app-server thread ID");
1567
2120
  const configured = existing ? this.threadPermissions.get(existing) : undefined;
1568
2121
  if (configured !== undefined && configured !== permissions) {
1569
2122
  throw new Error("Cannot change permissions of a loaded thread; create a new thread");
1570
2123
  }
1571
2124
  const result = await this.request("config/read", { includeLayers: false, cwd });
1572
2125
  this.disabledMcp = {};
1573
- for (const name of Object.keys(result.config?.mcp_servers ?? {}))
1574
- this.disabledMcp[name] = { enabled: false };
2126
+ for (const name of Object.keys(result.config?.mcp_servers ?? {})) {
2127
+ if (!/^(?:__proto__|constructor|prototype)$/i.test(name))
2128
+ this.disabledMcp[name] = { enabled: false };
2129
+ }
1575
2130
  const r = await this.request(existing ? "thread/resume" : "thread/start", {
1576
2131
  ...existing ? { threadId: existing } : { ephemeral },
1577
2132
  cwd,
@@ -1584,6 +2139,8 @@ class AppServer {
1584
2139
  if (typeof r.thread?.id !== "string")
1585
2140
  throw new Error("App-server returned no thread ID");
1586
2141
  this.threadPermissions.set(r.thread.id, permissions);
2142
+ if (this.threadPermissions.size > 1024)
2143
+ this.threadPermissions.delete(this.threadPermissions.keys().next().value);
1587
2144
  return r.thread.id;
1588
2145
  }
1589
2146
  async readThread(thread) {
@@ -1614,8 +2171,8 @@ class AppServer {
1614
2171
  const permissions = this.threadPermissions.get(thread);
1615
2172
  if (!permissions)
1616
2173
  throw new Error("Thread permissions have not been configured");
1617
- const completed = new Promise((resolve4, reject) => {
1618
- this.active = { thread, items: new Map, early: [], resolve: resolve4, reject };
2174
+ const completed = new Promise((resolve5, reject) => {
2175
+ this.active = { thread, items: new Map, early: [], resolve: resolve5, reject };
1619
2176
  });
1620
2177
  completed.catch(() => {});
1621
2178
  try {
@@ -1636,48 +2193,88 @@ class AppServer {
1636
2193
  }
1637
2194
  }
1638
2195
  fail(error) {
1639
- for (const p of this.pending.values())
2196
+ for (const p of this.pending.values()) {
2197
+ clearTimeout(p.timer);
1640
2198
  p.reject(error);
2199
+ }
1641
2200
  this.pending.clear();
1642
2201
  if (this.active) {
1643
2202
  this.active.reject(error);
1644
2203
  this.active = undefined;
1645
2204
  }
1646
2205
  }
2206
+ terminateChild() {
2207
+ try {
2208
+ this.rl?.close();
2209
+ } catch {}
2210
+ this.rl = undefined;
2211
+ const child = this.child;
2212
+ if (!child)
2213
+ return;
2214
+ try {
2215
+ child.stdin.end();
2216
+ } catch {}
2217
+ if (child.exitCode === null && child.signalCode === null) {
2218
+ try {
2219
+ child.kill("SIGTERM");
2220
+ } catch {}
2221
+ if (!this.killTimer) {
2222
+ this.killTimer = setTimeout(() => {
2223
+ this.killTimer = undefined;
2224
+ if (child.exitCode === null && child.signalCode === null) {
2225
+ try {
2226
+ child.kill("SIGKILL");
2227
+ } catch {}
2228
+ }
2229
+ }, 2000);
2230
+ this.killTimer.unref?.();
2231
+ }
2232
+ }
2233
+ }
1647
2234
  fatal(error) {
1648
2235
  if (this.closed)
1649
2236
  return;
1650
2237
  this.closed = true;
1651
2238
  this.fail(error);
1652
2239
  this.onFatal?.();
1653
- this.child?.kill();
2240
+ this.terminateChild();
1654
2241
  }
1655
2242
  close() {
1656
2243
  this.closed = true;
1657
2244
  this.fail(new Error("App-server stopped"));
1658
- this.child?.kill();
2245
+ this.terminateChild();
1659
2246
  }
1660
2247
  }
1661
2248
 
1662
2249
  // src/team-lead-skill.ts
1663
- import { readFileSync as readFileSync4 } from "node:fs";
2250
+ import { readFileSync as readFileSync5 } from "node:fs";
1664
2251
  var TEAM_LEAD_SKILL_ID = "agentschat-team-lead";
1665
- var TEAM_LEAD_SKILL_BODY = readFileSync4(new URL("../skills/agentschat-team-lead/SKILL.md", import.meta.url), "utf8");
2252
+ var TEAM_LEAD_SKILL_BODY = readFileSync5(new URL("../skills/agentschat-team-lead/SKILL.md", import.meta.url), "utf8");
1666
2253
  var TEAM_LEAD_NO_UPDATE = "[[AGENTSCHAT_NO_UPDATE]]";
1667
2254
  function isTeamLeadSkillInvocation(prompt) {
2255
+ if (typeof prompt !== "string" || prompt.length > 256 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/.test(prompt)) {
2256
+ return false;
2257
+ }
1668
2258
  return [TEAM_LEAD_SKILL_ID, `$${TEAM_LEAD_SKILL_ID}`, `执行 $${TEAM_LEAD_SKILL_ID}`].includes(prompt.trim());
1669
2259
  }
1670
2260
 
1671
2261
  // codex/bridge.ts
1672
- import { existsSync as existsSync5, mkdirSync as mkdirSync6, readFileSync as readFileSync8, renameSync as renameSync4, writeFileSync as writeFileSync4, openSync as openSync2, closeSync as closeSync2, unlinkSync as unlinkSync3 } from "node:fs";
1673
- import { join as join8 } from "node:path";
2262
+ 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";
2263
+ import { join as join10 } from "node:path";
2264
+ import { randomBytes as randomBytes2 } from "node:crypto";
1674
2265
 
1675
2266
  // codex/thread-history.ts
1676
- import { createHash as createHash2 } from "node:crypto";
1677
- import { mkdirSync as mkdirSync4, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
1678
- import { join as join5 } from "node:path";
2267
+ import { createHash as createHash2, randomBytes } from "node:crypto";
2268
+ import { chmodSync, lstatSync as lstatSync6, mkdirSync as mkdirSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
2269
+ import { join as join6 } from "node:path";
1679
2270
  function priorChannelThreads(threads, channel) {
1680
- return [...new Set(Object.entries(threads).filter(([key]) => {
2271
+ if (!threads || typeof threads !== "object" || typeof channel !== "string" || !channel)
2272
+ return [];
2273
+ return [...new Set(Object.entries(threads).filter(([key, id]) => {
2274
+ if (["__proto__", "constructor", "prototype"].includes(key.toLowerCase()))
2275
+ return false;
2276
+ if (typeof id !== "string" || !id.trim())
2277
+ return false;
1681
2278
  if (key === channel)
1682
2279
  return true;
1683
2280
  try {
@@ -1689,28 +2286,84 @@ function priorChannelThreads(threads, channel) {
1689
2286
  }).map(([, id]) => id))];
1690
2287
  }
1691
2288
  function preserveChannelHistory(directory, channel, histories, redact) {
1692
- const root = join5(directory, "history");
2289
+ if (typeof channel !== "string" || !channel.trim() || channel.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel)) {
2290
+ throw new Error("Invalid history channel");
2291
+ }
2292
+ const checkDirectory = (path) => {
2293
+ try {
2294
+ const stat = lstatSync6(path);
2295
+ if (stat.isSymbolicLink() || !stat.isDirectory())
2296
+ throw new Error("History directory must be a non-symlink directory");
2297
+ } catch (error) {
2298
+ if (error.code !== "ENOENT")
2299
+ throw error;
2300
+ }
2301
+ };
2302
+ assertDirectoryAncestors(directory);
2303
+ const root = join6(directory, "history");
2304
+ checkDirectory(directory);
2305
+ checkDirectory(root);
1693
2306
  mkdirSync4(root, { recursive: true, mode: 448 });
1694
- const file = join5(root, createHash2("sha256").update(channel).digest("hex").slice(0, 24) + ".json");
1695
- writeFileSync2(file + ".tmp", redact(JSON.stringify({ channel_id: channel, threads: histories })), { mode: 384 });
1696
- renameSync2(file + ".tmp", file);
2307
+ checkDirectory(root);
2308
+ if (process.platform !== "win32")
2309
+ chmodSync(root, 448);
2310
+ const file = join6(root, createHash2("sha256").update(channel).digest("hex").slice(0, 24) + ".json");
2311
+ try {
2312
+ const stat = lstatSync6(file);
2313
+ if (stat.isSymbolicLink() || !stat.isFile())
2314
+ throw new Error("History archive must be a regular file, not a symlink");
2315
+ } catch (e) {
2316
+ if (e.code !== "ENOENT")
2317
+ throw e;
2318
+ }
2319
+ const tmp = `${file}.${process.pid}.${Date.now()}.${randomBytes(4).toString("hex")}.tmp`;
2320
+ try {
2321
+ writeFileSync2(tmp, redact(JSON.stringify({ channel_id: channel, threads: histories })), { flag: "wx", mode: 384 });
2322
+ if (process.platform !== "win32")
2323
+ chmodSync(tmp, 384);
2324
+ atomicReplaceRegularFile(tmp, file, () => {
2325
+ try {
2326
+ const stat = lstatSync6(file);
2327
+ if (stat.isSymbolicLink() || !stat.isFile())
2328
+ throw new Error("History archive must be a regular file, not a symlink");
2329
+ } catch (error) {
2330
+ if (error.code !== "ENOENT")
2331
+ throw error;
2332
+ }
2333
+ });
2334
+ } catch (err) {
2335
+ try {
2336
+ unlinkSync2(tmp);
2337
+ } catch {}
2338
+ throw err;
2339
+ }
1697
2340
  const records = [];
1698
2341
  let sequence = 0;
1699
- for (const history of histories)
1700
- for (const turn of history.turns) {
2342
+ for (const history of Array.isArray(histories) ? histories : []) {
2343
+ if (!history || typeof history !== "object")
2344
+ continue;
2345
+ for (const turn of Array.isArray(history.turns) ? history.turns : []) {
2346
+ if (!turn || typeof turn !== "object")
2347
+ continue;
1701
2348
  const order = String(turn.id ?? history.createdAt ?? history.id);
1702
- for (const item of turn.items ?? []) {
2349
+ for (const item of Array.isArray(turn.items) ? turn.items : []) {
2350
+ if (!item || typeof item !== "object")
2351
+ continue;
1703
2352
  if (item.type === "userMessage") {
1704
- let text = (item.content ?? []).filter((part) => part.type === "text").map((part) => part.text).join(`
2353
+ const contentParts = Array.isArray(item.content) ? item.content : [];
2354
+ let text = contentParts.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
1705
2355
  `);
1706
2356
  const marker = `AgentsChat message:
1707
2357
  `;
1708
2358
  if (text.includes(marker)) {
1709
2359
  try {
1710
- const message = JSON.parse(text.slice(text.lastIndexOf(marker) + marker.length));
1711
- if (message.channel_id === channel)
1712
- records.push({ order, sequence: sequence++, value: { ...message, role: "user" } });
1713
- continue;
2360
+ let message = JSON.parse(text.slice(text.lastIndexOf(marker) + marker.length));
2361
+ if (message && typeof message === "object" && !Array.isArray(message)) {
2362
+ message = Object.fromEntries(Object.entries(message).filter(([key]) => !["__proto__", "constructor", "prototype"].includes(key.toLowerCase())));
2363
+ if (message.channel_id === channel)
2364
+ records.push({ order, sequence: sequence++, value: { ...message, role: "user" } });
2365
+ continue;
2366
+ }
1714
2367
  } catch {}
1715
2368
  }
1716
2369
  if (text.startsWith("Previous conversations for this channel have been consolidated.")) {
@@ -1722,15 +2375,16 @@ function preserveChannelHistory(directory, channel, histories, redact) {
1722
2375
  }
1723
2376
  if (text.trim())
1724
2377
  records.push({ order, sequence: sequence++, value: { role: "user", content: text } });
1725
- } else if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer")) {
2378
+ } else if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer") && typeof item.text === "string") {
1726
2379
  records.push({ order, sequence: sequence++, value: { role: "assistant", content: item.text } });
1727
2380
  }
1728
2381
  }
1729
2382
  }
2383
+ }
1730
2384
  records.sort((a, b) => a.order.localeCompare(b.order) || a.sequence - b.sequence);
1731
2385
  const seen = new Set;
1732
2386
  const lines = records.filter(({ value }) => {
1733
- if (!value.id)
2387
+ if (typeof value.id !== "string" || !value.id)
1734
2388
  return true;
1735
2389
  if (seen.has(value.id))
1736
2390
  return false;
@@ -1758,26 +2412,39 @@ End of historical context.
1758
2412
  }
1759
2413
 
1760
2414
  // codex/loop-grants.ts
1761
- import { lstatSync as lstatSync2, readFileSync as readFileSync5 } from "node:fs";
1762
- import { join as join6 } from "node:path";
1763
- function grants(config) {
2415
+ import { lstatSync as lstatSync7, readFileSync as readFileSync6 } from "node:fs";
2416
+ import { join as join7 } from "node:path";
2417
+ function grants(config, opts) {
1764
2418
  try {
1765
- const file = join6(config.stateDir, "loop-grants.json"), stat = lstatSync2(file);
1766
- if (!stat.isFile() || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())
2419
+ const platform = opts?.platform ?? process.platform;
2420
+ const getuid = opts && "getuid" in opts ? opts.getuid : process.getuid;
2421
+ assertDirectoryAncestors(config.stateDir);
2422
+ const directory = lstatSync7(config.stateDir);
2423
+ if (directory.isSymbolicLink() || !directory.isDirectory())
2424
+ return [];
2425
+ const file = join7(config.stateDir, "loop-grants.json"), stat = lstatSync7(file);
2426
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1048576)
1767
2427
  return [];
1768
- const doc = JSON.parse(readFileSync5(file, "utf8"));
1769
- if (doc?.version !== 1 || !Array.isArray(doc.grants))
2428
+ if (platform !== "win32") {
2429
+ if (typeof getuid !== "function" || (stat.mode & 63) !== 0 || stat.uid !== getuid())
2430
+ return [];
2431
+ }
2432
+ const doc = JSON.parse(readFileSync6(file, "utf8"));
2433
+ const ownProto = (value) => Object.prototype.hasOwnProperty.call(value, "__proto__");
2434
+ if (doc?.version !== 1 || ownProto(doc) || !Array.isArray(doc.grants) || doc.grants.length > 256)
1770
2435
  return [];
1771
- return doc.grants.filter((g) => g && [g.loop_id, g.channel_id, g.agent_id, g.owner_id, g.prompt].every((v) => typeof v === "string" && v.trim()) && g.agent_id === config.agentId && g.prompt.length <= 4000 && Number.isSafeInteger(g.interval_ms) && g.interval_ms >= 60000 && g.interval_ms <= 86400000);
2436
+ const safeId = (value) => typeof value === "string" && value.length > 0 && value.length <= 128 && value.trim() === value && value !== "." && value !== ".." && !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) && !["__proto__", "constructor", "prototype"].includes(value.toLowerCase());
2437
+ 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) && !["__proto__", "constructor", "prototype"].includes(value.toLowerCase());
2438
+ 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
2439
  } catch {
1773
2440
  return [];
1774
2441
  }
1775
2442
  }
1776
- function authorizedLoopTick(raw, config) {
2443
+ function authorizedLoopTick(raw, config, opts) {
1777
2444
  const tick = raw?.meta;
1778
2445
  if (raw?.sender_id !== config.agentId || tick?.kind !== "loop_tick" || !Number.isSafeInteger(tick.next_tick_ms) || tick.next_tick_ms <= 0)
1779
2446
  return null;
1780
- const matches = grants(config).filter((g) => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
2447
+ const matches = grants(config, opts).filter((g) => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
1781
2448
  if (matches.length !== 1)
1782
2449
  return null;
1783
2450
  const grant = matches[0];
@@ -1785,8 +2452,8 @@ function authorizedLoopTick(raw, config) {
1785
2452
  return null;
1786
2453
  return grant;
1787
2454
  }
1788
- async function verifyLoopTick(raw, config, owner, list) {
1789
- const grant = authorizedLoopTick(raw, config);
2455
+ async function verifyLoopTick(raw, config, owner, list, opts) {
2456
+ const grant = authorizedLoopTick(raw, config, opts);
1790
2457
  if (!grant || owner !== grant.owner_id || config.permissions !== "full-access")
1791
2458
  return null;
1792
2459
  let response;
@@ -1795,67 +2462,226 @@ async function verifyLoopTick(raw, config, owner, list) {
1795
2462
  } catch {
1796
2463
  return null;
1797
2464
  }
1798
- const rows = Array.isArray(response?.loops) ? response.loops.filter((r) => r?.loop_id === grant.loop_id) : [];
2465
+ const rows = Array.isArray(response?.loops) && response.loops.length <= 1024 ? response.loops.filter((r) => r?.loop_id === grant.loop_id) : [];
1799
2466
  if (rows.length !== 1)
1800
2467
  return null;
1801
2468
  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)
2469
+ if (!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
2470
  return null;
1804
- const current = authorizedLoopTick(raw, config);
2471
+ const current = authorizedLoopTick(raw, config, opts);
1805
2472
  return current && current.owner_id === owner ? current : null;
1806
2473
  }
1807
2474
 
1808
2475
  // src/session-bind.ts
1809
2476
  import { createHash as createHash3 } from "node:crypto";
1810
- import { closeSync, existsSync as existsSync4, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync7, readSync, readdirSync as readdirSync4, statSync as statSync3, unlinkSync as unlinkSync2 } from "node:fs";
1811
- import { homedir as homedir4, tmpdir } from "node:os";
1812
- import { join as join7 } from "node:path";
2477
+ 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";
2478
+ import { homedir as homedir5, tmpdir } from "node:os";
2479
+ import { isAbsolute as isAbsolute5, join as join9, parse as parse3, resolve as resolve6 } from "node:path";
1813
2480
 
1814
2481
  // src/profile-store.ts
1815
- import { existsSync as existsSync3, writeFileSync as writeFileSync3, renameSync as renameSync3, chmodSync, unlinkSync, statSync as statSync2, readdirSync as readdirSync3, readFileSync as readFileSync6 } from "fs";
2482
+ import {
2483
+ lstatSync as lstatSync8,
2484
+ realpathSync as realpathSync4,
2485
+ writeFileSync as writeFileSync3,
2486
+ renameSync as renameSync2,
2487
+ copyFileSync as copyFileSync2,
2488
+ chmodSync as chmodSync2,
2489
+ unlinkSync as unlinkSync3,
2490
+ readdirSync as readdirSync3,
2491
+ readFileSync as readFileSync7
2492
+ } from "fs";
2493
+ import { dirname as dirname4, join as join8, resolve as resolve5 } from "path";
1816
2494
  var defaultWarn = (m) => process.stderr.write(m);
2495
+ var MAX_PROFILE_JSON_BYTES = 64 * 1024;
2496
+ var CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g;
2497
+ var DARWIN_SYSTEM_SYMLINKS = new Set(["/var", "/tmp", "/etc"]);
2498
+ function sanitizeWarnPart(value) {
2499
+ return redactSecrets(String(value ?? "")).replace(/\b(https?:\/\/?)([^/\s@]*@)/gi, "$1[REDACTED]@").replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]").replace(/\b(?: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, "?");
2500
+ }
2501
+ function safeLstat(target) {
2502
+ try {
2503
+ return lstatSync8(target);
2504
+ } catch (err) {
2505
+ if (err && err.code === "ENOENT")
2506
+ return;
2507
+ throw err;
2508
+ }
2509
+ }
2510
+ function isAllowedDarwinSystemSymlink(dirPath) {
2511
+ if (process.platform !== "darwin" || !DARWIN_SYSTEM_SYMLINKS.has(dirPath))
2512
+ return false;
2513
+ try {
2514
+ const resolved = realpathSync4(dirPath);
2515
+ if (resolved !== `/private${dirPath}`)
2516
+ return false;
2517
+ const privSt = lstatSync8("/private");
2518
+ if (!privSt.isDirectory() || privSt.isSymbolicLink())
2519
+ return false;
2520
+ const realSt = lstatSync8(resolved);
2521
+ return realSt.isDirectory() && !realSt.isSymbolicLink();
2522
+ } catch {
2523
+ return false;
2524
+ }
2525
+ }
2526
+ function hasSafeRawDotDotAncestors(targetPath) {
2527
+ if (!targetPath.includes(".."))
2528
+ return true;
2529
+ const rawParent = dirname4(targetPath);
2530
+ const parts = rawParent.split(/[\\/]+/);
2531
+ let acc = rawParent.startsWith("/") ? "/" : /^[A-Za-z]:/.test(rawParent) ? parts[0] + "\\" : process.cwd();
2532
+ const startIdx = rawParent.startsWith("/") ? 1 : /^[A-Za-z]:/.test(rawParent) ? 1 : 0;
2533
+ for (let i = startIdx;i < parts.length; i++) {
2534
+ const seg = parts[i];
2535
+ if (!seg || seg === ".")
2536
+ continue;
2537
+ acc = seg === ".." ? dirname4(acc) : join8(acc, seg);
2538
+ const st = safeLstat(acc);
2539
+ if (st) {
2540
+ if (st.isSymbolicLink()) {
2541
+ if (!isAllowedDarwinSystemSymlink(acc))
2542
+ return false;
2543
+ } else if (!st.isDirectory()) {
2544
+ return false;
2545
+ }
2546
+ }
2547
+ }
2548
+ return true;
2549
+ }
2550
+ function hasSafeAncestorDirs(targetPath) {
2551
+ if (!hasSafeRawDotDotAncestors(targetPath))
2552
+ return false;
2553
+ let cur = dirname4(resolve5(targetPath));
2554
+ for (let depth = 0;depth < 64; depth += 1) {
2555
+ const st = safeLstat(cur);
2556
+ if (st) {
2557
+ if (st.isSymbolicLink()) {
2558
+ if (!isAllowedDarwinSystemSymlink(cur))
2559
+ return false;
2560
+ } else if (!st.isDirectory()) {
2561
+ return false;
2562
+ }
2563
+ }
2564
+ const parent = dirname4(cur);
2565
+ if (parent === cur)
2566
+ break;
2567
+ cur = parent;
2568
+ }
2569
+ return true;
2570
+ }
1817
2571
  function safeWriteProfile(path, data, warn = defaultWarn) {
2572
+ const parentDir = dirname4(path);
2573
+ const parentStat = safeLstat(parentDir);
2574
+ if (!parentStat || parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(path)) {
2575
+ throw new Error(`Refusing to write profile into invalid or symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
2576
+ }
2577
+ const pathStat = safeLstat(path);
2578
+ if (pathStat?.isSymbolicLink()) {
2579
+ throw new Error(`Refusing to write profile through symlink: ${sanitizeWarnPart(path)}`);
2580
+ }
1818
2581
  const tmp = path + ".tmp";
1819
- try {
1820
- if (existsSync3(tmp))
1821
- unlinkSync(tmp);
1822
- } catch (e) {
1823
- warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
2582
+ const tmpStat = safeLstat(tmp);
2583
+ if (tmpStat) {
2584
+ try {
2585
+ unlinkSync3(tmp);
2586
+ } catch (e) {
2587
+ warn(`[agentchat] WARNING: stale ${sanitizeWarnPart(tmp)} could not be removed: ${sanitizeWarnPart(e)}
1824
2588
  `);
2589
+ }
1825
2590
  }
1826
- writeFileSync3(tmp, JSON.stringify(data, null, 2), { mode: 384 });
1827
- renameSync3(tmp, path);
1828
- try {
1829
- chmodSync(path, 384);
1830
- } catch (e) {
1831
- warn(`[agentchat] WARNING: could not chmod ${path} to 0600: ${e}
1832
- `);
2591
+ writeFileSync3(tmp, JSON.stringify(data, null, 2), { mode: 384, flag: "wx" });
2592
+ const currentParent = safeLstat(parentDir);
2593
+ if (!currentParent || currentParent.isSymbolicLink() || !currentParent.isDirectory() || !hasSafeAncestorDirs(path)) {
2594
+ try {
2595
+ unlinkSync3(tmp);
2596
+ } catch {}
2597
+ throw new Error(`Refusing to write profile into symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
2598
+ }
2599
+ if (safeLstat(path)?.isSymbolicLink()) {
2600
+ try {
2601
+ unlinkSync3(tmp);
2602
+ } catch {}
2603
+ throw new Error(`Refusing to overwrite symlinked profile: ${sanitizeWarnPart(path)}`);
1833
2604
  }
1834
2605
  try {
1835
- const mode = statSync2(path).mode & 511;
1836
- if (mode !== 384) {
1837
- warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
2606
+ renameSync2(tmp, path);
2607
+ } catch (err) {
2608
+ if (process.platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
2609
+ const winTarget = safeLstat(path);
2610
+ if (winTarget?.isSymbolicLink() || winTarget?.isDirectory()) {
2611
+ try {
2612
+ unlinkSync3(tmp);
2613
+ } catch {}
2614
+ throw new Error(`Refusing to overwrite symlinked or directory profile: ${sanitizeWarnPart(path)}`);
2615
+ }
2616
+ copyFileSync2(tmp, path);
2617
+ try {
2618
+ unlinkSync3(tmp);
2619
+ } catch {}
2620
+ } else {
2621
+ throw err;
2622
+ }
2623
+ }
2624
+ if (process.platform !== "win32") {
2625
+ const postStat = safeLstat(path);
2626
+ if (!postStat || postStat.isSymbolicLink() || !postStat.isFile()) {
2627
+ warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target
1838
2628
  `);
2629
+ return;
1839
2630
  }
1840
- } catch (e) {
1841
- warn(`[agentchat] WARNING: could not verify permissions of ${path}: ${e}
2631
+ try {
2632
+ chmodSync2(path, 384);
2633
+ } catch (e) {
2634
+ warn(`[agentchat] WARNING: could not chmod ${sanitizeWarnPart(path)} to 0600: ${sanitizeWarnPart(e)}
2635
+ `);
2636
+ }
2637
+ try {
2638
+ const verified = safeLstat(path);
2639
+ if (!verified || verified.isSymbolicLink() || !verified.isFile()) {
2640
+ warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target
1842
2641
  `);
2642
+ return;
2643
+ }
2644
+ const mode = verified.mode & 511;
2645
+ if (mode !== 384) {
2646
+ warn(`[agentchat] WARNING: ${sanitizeWarnPart(path)} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${sanitizeWarnPart(path)}
2647
+ `);
2648
+ }
2649
+ } catch (e) {
2650
+ warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: ${sanitizeWarnPart(e)}
2651
+ `);
2652
+ }
1843
2653
  }
1844
2654
  }
1845
2655
  var NON_PROFILE_JSON_FILES = new Set([
1846
2656
  "session-binds.json",
2657
+ "session-binds.meta.json",
2658
+ "session-binds-meta.json",
2659
+ "session-binds_meta.json",
2660
+ "agy-session-binds.json",
2661
+ "agy-session-binds.meta.json",
2662
+ "agy-session-binds_meta.json",
1847
2663
  "agy-binds.json",
2664
+ "agy-binds.meta.json",
2665
+ "agy-binds-meta.json",
2666
+ "agy-binds_meta.json",
1848
2667
  "grok-binds.json",
1849
2668
  "grok-binds-meta.json",
1850
2669
  "grok-binds.meta.json",
2670
+ "grok-binds_meta.json",
1851
2671
  "identity-guard.json",
2672
+ "cursor.json",
2673
+ "read-cursors.json",
2674
+ "mention-timestamps.json",
2675
+ "wake-pids.json",
2676
+ "codex-bots.json",
1852
2677
  "dsh.json",
1853
- "config.json"
2678
+ "config.json",
2679
+ "muse.json"
1854
2680
  ]);
1855
2681
 
1856
2682
  // src/session-bind.ts
1857
2683
  function isPidAlive(pid) {
1858
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
2684
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
1859
2685
  return false;
1860
2686
  try {
1861
2687
  process.kill(pid, 0);
@@ -1868,35 +2694,195 @@ function isPidAlive(pid) {
1868
2694
  }
1869
2695
  function resolveLockDir(homeDir, env = process.env) {
1870
2696
  const explicit = env.AGENTSCHAT_LOCK_DIR?.trim();
1871
- if (explicit)
2697
+ if (explicit && explicit.length <= 4096 && !explicit.startsWith("-") && !CONTROL_CHAR_RE2.test(explicit) && isAbsolute5(explicit) && isSafeDirOrMissing(explicit)) {
1872
2698
  return explicit;
2699
+ }
1873
2700
  const hash = createHash3("sha256").update(homeDir || ".").digest("hex").slice(0, 12);
1874
2701
  const baseTmp = process.platform === "win32" ? tmpdir() : "/tmp";
1875
- return join7(baseTmp, `agentschat-locks-${hash}`);
2702
+ return join9(baseTmp, `agentschat-locks-${hash}`);
2703
+ }
2704
+ var LOCK_FILE_MAX_BYTES = 64 * 1024;
2705
+ var LOCK_KEY_MAX_CHARS = 128;
2706
+ var SESSION_BINDS_MAX_BYTES = 1024 * 1024;
2707
+ var CONTROL_CHAR_RE2 = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
2708
+ var RESERVED_BIND_SIDECARS = new Set([
2709
+ "session-binds",
2710
+ "session-binds.meta",
2711
+ "session-binds_meta",
2712
+ "agy-binds",
2713
+ "agy-binds.meta",
2714
+ "agy-binds_meta",
2715
+ "grok-binds",
2716
+ "grok-binds.meta",
2717
+ "grok-binds_meta",
2718
+ "agy-session-binds",
2719
+ "identity-guard",
2720
+ "cursor",
2721
+ "read-cursors",
2722
+ "mention-timestamps",
2723
+ "wake-pids",
2724
+ "config",
2725
+ "codex-bots",
2726
+ "dsh",
2727
+ "muse"
2728
+ ]);
2729
+ function readBoundedRegularJson(path, maxBytes) {
2730
+ try {
2731
+ const st = lstatSync9(path);
2732
+ if (st.isSymbolicLink() || !st.isFile() || st.size > maxBytes)
2733
+ return null;
2734
+ const parsed = JSON.parse(readFileSync8(path, "utf8"));
2735
+ if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
2736
+ return null;
2737
+ }
2738
+ return parsed;
2739
+ } catch {
2740
+ return null;
2741
+ }
2742
+ }
2743
+ function isSafeTargetFileOrMissing(path) {
2744
+ try {
2745
+ const st = lstatSync9(path);
2746
+ return !st.isSymbolicLink() && st.isFile();
2747
+ } catch (e) {
2748
+ return Boolean(e && typeof e === "object" && e.code === "ENOENT");
2749
+ }
2750
+ }
2751
+ function isAllowedDarwinSystemLink(dirPath) {
2752
+ if (process.platform !== "darwin")
2753
+ return false;
2754
+ if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc")
2755
+ return false;
2756
+ try {
2757
+ const expected = `/private${dirPath}`;
2758
+ return readlinkSync3(dirPath) === `private${dirPath}` && realpathSync5(dirPath) === expected && !lstatSync9("/private").isSymbolicLink() && lstatSync9("/private").isDirectory() && !lstatSync9(expected).isSymbolicLink() && statSync(expected).isDirectory();
2759
+ } catch {
2760
+ return false;
2761
+ }
2762
+ }
2763
+ function hasSafeRawDotDotSegments(rawPath) {
2764
+ if (!rawPath.includes(".."))
2765
+ return true;
2766
+ const baseAbs = isAbsolute5(rawPath) ? rawPath : `${process.cwd()}/${rawPath}`;
2767
+ const root = parse3(baseAbs).root;
2768
+ const rawParts = baseAbs.slice(root.length).split(/[\\/]+/).filter(Boolean);
2769
+ let cur = root;
2770
+ for (const part of rawParts) {
2771
+ if (part === ".")
2772
+ continue;
2773
+ if (part === "..") {
2774
+ cur = resolve6(cur, "..");
2775
+ continue;
2776
+ }
2777
+ cur = join9(cur, part);
2778
+ try {
2779
+ const st = lstatSync9(cur);
2780
+ if (st.isSymbolicLink()) {
2781
+ if (isAllowedDarwinSystemLink(cur))
2782
+ continue;
2783
+ return false;
2784
+ }
2785
+ if (!st.isDirectory())
2786
+ return false;
2787
+ } catch (e) {
2788
+ if (e && typeof e === "object" && e.code === "ENOENT")
2789
+ continue;
2790
+ return false;
2791
+ }
2792
+ }
2793
+ return true;
2794
+ }
2795
+ function isSafeDirOrMissing(dirPath) {
2796
+ if (!dirPath || CONTROL_CHAR_RE2.test(dirPath))
2797
+ return false;
2798
+ if (!hasSafeRawDotDotSegments(dirPath))
2799
+ return false;
2800
+ const abs = resolve6(dirPath);
2801
+ const root = parse3(abs).root;
2802
+ const segments = abs.slice(root.length).split(/[\\/]+/).filter(Boolean);
2803
+ let cur = root;
2804
+ for (let i = 0;i < segments.length; i++) {
2805
+ cur = join9(cur, segments[i]);
2806
+ try {
2807
+ const st = lstatSync9(cur);
2808
+ if (st.isSymbolicLink()) {
2809
+ if (isAllowedDarwinSystemLink(cur))
2810
+ continue;
2811
+ return false;
2812
+ }
2813
+ if (!st.isDirectory())
2814
+ return false;
2815
+ } catch (e) {
2816
+ if (e && typeof e === "object" && e.code === "ENOENT")
2817
+ return true;
2818
+ return false;
2819
+ }
2820
+ }
2821
+ return true;
1876
2822
  }
1877
2823
  function lockFilePath(lockDir, agentId) {
1878
- const safe = String(agentId || "").trim().replace(/[^a-zA-Z0-9_-]/g, "_");
1879
- return join7(lockDir, `${safe}.lock`);
2824
+ const trimmed = String(agentId || "").trim();
2825
+ let safe = trimmed.replace(/[^a-zA-Z0-9_-]/g, "_");
2826
+ if (safe.length > LOCK_KEY_MAX_CHARS) {
2827
+ const digest = createHash3("sha256").update(trimmed).digest("hex").slice(0, 12);
2828
+ safe = `${safe.slice(0, LOCK_KEY_MAX_CHARS - 13)}_${digest}`;
2829
+ }
2830
+ if (!safe || isUnsafeBindKey(safe)) {
2831
+ safe = `_${safe}`;
2832
+ }
2833
+ return join9(lockDir, `${safe}.lock`);
1880
2834
  }
1881
2835
  function readAgentLock(lockDir, agentId) {
1882
- if (!agentId)
2836
+ if (!agentId || !isSafeDirOrMissing(lockDir))
1883
2837
  return null;
1884
2838
  const file = lockFilePath(lockDir, agentId);
1885
- if (!existsSync4(file))
2839
+ const raw = readBoundedRegularJson(file, LOCK_FILE_MAX_BYTES);
2840
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.prototype.hasOwnProperty.call(raw, "__proto__") || typeof raw.pid !== "number" || typeof raw.agentId !== "string") {
1886
2841
  return null;
1887
- try {
1888
- const raw = JSON.parse(readFileSync7(file, "utf8"));
1889
- if (!raw || typeof raw !== "object" || typeof raw.pid !== "number" || typeof raw.agentId !== "string") {
1890
- return null;
2842
+ }
2843
+ return raw;
2844
+ }
2845
+ function checkAgentLock(opts) {
2846
+ const { lockDir, agentId } = opts;
2847
+ const currentPid = opts.currentPid ?? process.pid;
2848
+ if (!agentId || !isSafeDirOrMissing(lockDir))
2849
+ return { locked: false };
2850
+ const file = lockFilePath(lockDir, agentId);
2851
+ const record = readAgentLock(lockDir, agentId);
2852
+ if (!record) {
2853
+ try {
2854
+ const st = lstatSync9(file);
2855
+ const ageMs = Date.now() - st.mtimeMs;
2856
+ if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1000 || ageMs < -1000))
2857
+ unlinkSync4(file);
2858
+ } catch {}
2859
+ return { locked: false };
2860
+ }
2861
+ if (!isPidAlive(record.pid)) {
2862
+ try {
2863
+ unlinkSync4(file);
2864
+ } catch {}
2865
+ return { locked: false, stale: true };
2866
+ }
2867
+ if (record.pid === currentPid) {
2868
+ if (opts.currentSessionId && record.sessionId && opts.currentSessionId !== record.sessionId) {
2869
+ return { locked: true, holder: record };
1891
2870
  }
1892
- return raw;
1893
- } catch {
1894
- return null;
2871
+ return { locked: false, holder: record };
2872
+ }
2873
+ if (opts.lockOwnerPid && record.pid === opts.lockOwnerPid)
2874
+ return { locked: false, holder: record };
2875
+ if (opts.currentSessionId && record.sessionId && opts.currentSessionId === record.sessionId) {
2876
+ return { locked: false, holder: record };
1895
2877
  }
2878
+ return { locked: true, holder: record };
1896
2879
  }
1897
2880
  function acquireAgentLock(opts) {
1898
2881
  if (!opts.agentId)
1899
2882
  return null;
2883
+ const file = lockFilePath(opts.lockDir, opts.agentId);
2884
+ if (!isSafeDirOrMissing(opts.lockDir) || !isSafeTargetFileOrMissing(file))
2885
+ return null;
1900
2886
  const record = {
1901
2887
  pid: opts.currentPid ?? process.pid,
1902
2888
  agentId: opts.agentId,
@@ -1907,40 +2893,80 @@ function acquireAgentLock(opts) {
1907
2893
  };
1908
2894
  try {
1909
2895
  mkdirSync5(opts.lockDir, { recursive: true, mode: 448 });
1910
- safeWriteProfile(lockFilePath(opts.lockDir, opts.agentId), record);
2896
+ safeWriteProfile(file, record);
1911
2897
  return record;
1912
2898
  } catch {
1913
2899
  return null;
1914
2900
  }
1915
2901
  }
1916
2902
  function releaseAgentLock(opts) {
1917
- if (!opts.agentId)
2903
+ if (!opts.agentId || !isSafeDirOrMissing(opts.lockDir))
1918
2904
  return false;
1919
2905
  const currentPid = opts.currentPid ?? process.pid;
2906
+ const file = lockFilePath(opts.lockDir, opts.agentId);
1920
2907
  const existing = readAgentLock(opts.lockDir, opts.agentId);
1921
- if (!existing)
2908
+ if (!existing) {
2909
+ try {
2910
+ const st = lstatSync9(file);
2911
+ const ageMs = Date.now() - st.mtimeMs;
2912
+ if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1000 || ageMs < -1000)) {
2913
+ unlinkSync4(file);
2914
+ return true;
2915
+ }
2916
+ } catch {}
1922
2917
  return false;
2918
+ }
1923
2919
  const samePid = existing.pid === currentPid;
1924
2920
  const sameSession = Boolean(opts.currentSessionId && existing.sessionId && opts.currentSessionId === existing.sessionId);
1925
2921
  const dead = !isPidAlive(existing.pid);
1926
2922
  if (!samePid && !sameSession && !dead)
1927
2923
  return false;
1928
2924
  try {
1929
- unlinkSync2(lockFilePath(opts.lockDir, opts.agentId));
2925
+ unlinkSync4(file);
1930
2926
  return true;
1931
2927
  } catch {
1932
2928
  return false;
1933
2929
  }
1934
2930
  }
2931
+ function isUnsafeBindKey(key) {
2932
+ const lower = key.toLowerCase();
2933
+ return lower === "__proto__" || lower === "constructor" || lower === "prototype";
2934
+ }
2935
+ var DSH_HEALTH_MAX_BYTES = 256 * 1024;
1935
2936
 
1936
2937
  // codex/bridge.ts
2938
+ var MAX_BRIDGE_TERMINAL_ENTRIES = 500;
1937
2939
  function permitted(m, c) {
1938
2940
  if (m.meta?.kind === "loop_tick")
1939
2941
  return authorizedLoopTick(m, c) !== null;
1940
2942
  return (!c.channels.length || c.channels.includes(m.channel_id)) && (!c.senders.length || c.senders.includes(m.sender_id));
1941
2943
  }
2944
+ var isPrototypeKey = (key) => /^(?:__proto__|constructor|prototype)$/i.test(key);
2945
+ function isPlainObject(value) {
2946
+ return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
2947
+ }
2948
+ function safeMessageId(value) {
2949
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value && value !== "." && value !== ".." && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) && !isPrototypeKey(value);
2950
+ }
2951
+ function validMentions(value) {
2952
+ return value === undefined || Array.isArray(value) && value.length <= 128 && [...value].every((id) => typeof id === "string");
2953
+ }
2954
+ function checkStateDir(dir, allowMissing = false) {
2955
+ try {
2956
+ const stat = lstatSync10(dir);
2957
+ if (stat.isSymbolicLink() || !stat.isDirectory())
2958
+ throw new Error("Unsafe bridge state directory");
2959
+ } catch (error) {
2960
+ if (!allowMissing || error.code !== "ENOENT")
2961
+ throw error;
2962
+ }
2963
+ assertDirectoryAncestors(dir);
2964
+ }
2965
+ var entryStatuses = new Set(["pending", "running", "ready", "sending", "sent", "failed", "uncertain", "blocked", "skipped"]);
1942
2966
  function addressed(m, c) {
1943
- if (!m || ["id", "channel_id", "sender_id", "content"].some((k) => typeof m[k] !== "string" || !m[k].trim()))
2967
+ if (!isPlainObject(m) || Object.prototype.hasOwnProperty.call(m, "__proto__") || ["id", "channel_id", "sender_id", "content"].some((k) => typeof m[k] !== "string" || !m[k].trim()))
2968
+ return false;
2969
+ if (![m.id, m.channel_id, m.sender_id].every(safeMessageId) || !validMentions(m.mentions) || !validMentions(m.mentioned_ids))
1944
2970
  return false;
1945
2971
  if (m.content === "__typing__" || m.content.length > 32000)
1946
2972
  return false;
@@ -1953,7 +2979,7 @@ function addressed(m, c) {
1953
2979
  if (!permitted(m, c))
1954
2980
  return false;
1955
2981
  const escaped = c.agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1956
- return m.channel_id.startsWith("dm-") || [m.mentions, m.mentioned_ids].some((a) => Array.isArray(a) && a.includes(c.agentId)) || new RegExp(`@${escaped}(?![\\w-])|@[^\\n(]+\\(${escaped}\\)`).test(m.content);
2982
+ 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
2983
  }
1958
2984
 
1959
2985
  class Bridge {
@@ -1979,16 +3005,20 @@ class Bridge {
1979
3005
  this.activity = activity;
1980
3006
  this.owner = owner;
1981
3007
  this.loops = loops;
3008
+ checkStateDir(config.stateDir, true);
1982
3009
  mkdirSync6(config.stateDir, { recursive: true, mode: 448 });
1983
- this.file = join8(config.stateDir, "state.json");
1984
- this.lock = join8(config.stateDir, "bridge.lock");
1985
- if (existsSync5(this.lock)) {
1986
- try {
1987
- const holderPid = Number(readFileSync8(this.lock, "utf8").trim());
1988
- if (holderPid > 0 && !isPidAlive(holderPid))
1989
- unlinkSync3(this.lock);
1990
- } catch {}
1991
- }
3010
+ checkStateDir(config.stateDir);
3011
+ this.file = join10(config.stateDir, "state.json");
3012
+ this.lock = join10(config.stateDir, "bridge.lock");
3013
+ try {
3014
+ const stat = lstatSync10(this.lock);
3015
+ if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024) {
3016
+ const content = readFileSync9(this.lock, "utf8");
3017
+ const holderPid = /^\d+$/.test(content) && content.trim() === content ? Number(content) : NaN;
3018
+ if (!Number.isSafeInteger(holderPid) || holderPid <= 0 || !isPidAlive(holderPid))
3019
+ unlinkSync5(this.lock);
3020
+ }
3021
+ } catch {}
1992
3022
  try {
1993
3023
  const fd = openSync2(this.lock, "wx", 384);
1994
3024
  writeFileSync4(fd, String(process.pid));
@@ -1997,16 +3027,24 @@ class Bridge {
1997
3027
  throw new Error(`Bridge already locked: ${this.lock}. If its process has exited, remove that lock manually.`);
1998
3028
  }
1999
3029
  const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
2000
- acquireAgentLock({
2001
- lockDir: resolveLockDir(homeDir, process.env),
2002
- agentId: config.agentId,
2003
- runtime: "codex-bridge"
2004
- });
3030
+ const lockDir = resolveLockDir(homeDir, process.env);
2005
3031
  try {
2006
- this.state = existsSync5(this.file) ? JSON.parse(readFileSync8(this.file, "utf8")) : { version: 1, threads: {}, entries: [] };
2007
- if (this.state.version !== 1 || !this.state.threads || !Array.isArray(this.state.entries))
3032
+ let hasState = false;
3033
+ try {
3034
+ const stat = lstatSync10(this.file);
3035
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024)
3036
+ throw new Error("Unsafe bridge state");
3037
+ hasState = true;
3038
+ } catch (error) {
3039
+ if (error.code !== "ENOENT")
3040
+ throw error;
3041
+ }
3042
+ this.state = hasState ? JSON.parse(readFileSync9(this.file, "utf8")) : { version: 1, threads: {}, entries: [] };
3043
+ if (this.state?.version !== 1 || Object.prototype.hasOwnProperty.call(this.state, "__proto__") || !isPlainObject(this.state.threads) || !Array.isArray(this.state.entries) || Object.prototype.hasOwnProperty.call(this.state, "channels") && !isPlainObject(this.state.channels))
2008
3044
  throw new Error("Invalid bridge state");
2009
3045
  for (const e of this.state.entries) {
3046
+ 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))
3047
+ throw new Error("Invalid bridge entry");
2010
3048
  if (e.status === "sending")
2011
3049
  e.status = "uncertain";
2012
3050
  if (e.status === "running")
@@ -2014,14 +3052,69 @@ class Bridge {
2014
3052
  }
2015
3053
  this.save();
2016
3054
  } catch {
2017
- unlinkSync3(this.lock);
3055
+ try {
3056
+ unlinkSync5(this.lock);
3057
+ } catch {}
2018
3058
  throw new Error("Cannot load bridge state; refusing to discard history");
2019
3059
  }
3060
+ try {
3061
+ const existingLock = checkAgentLock({ lockDir, agentId: config.agentId });
3062
+ if (existingLock.locked) {
3063
+ throw new Error(`Agent identity ${config.agentId} is already locked by live process ${existingLock.holder?.pid ?? "unknown"} (${existingLock.holder?.runtime ?? "unknown"})`);
3064
+ }
3065
+ if (!acquireAgentLock({
3066
+ lockDir,
3067
+ agentId: config.agentId,
3068
+ runtime: "codex-bridge"
3069
+ })) {
3070
+ throw new Error(`Cannot acquire agent lock for ${config.agentId}`);
3071
+ }
3072
+ } catch (err) {
3073
+ try {
3074
+ unlinkSync5(this.lock);
3075
+ } catch {}
3076
+ throw err;
3077
+ }
2020
3078
  }
2021
3079
  save() {
2022
- const tmp = this.file + ".tmp";
2023
- writeFileSync4(tmp, JSON.stringify(this.state), { mode: 384 });
2024
- renameSync4(tmp, this.file);
3080
+ const isTerminal = (status) => status === "sent" || status === "skipped" || status === "blocked";
3081
+ let terminalCount = 0;
3082
+ for (const entry of this.state.entries) {
3083
+ if (isTerminal(entry.status))
3084
+ terminalCount++;
3085
+ }
3086
+ if (terminalCount > MAX_BRIDGE_TERMINAL_ENTRIES) {
3087
+ let dropRemaining = terminalCount - MAX_BRIDGE_TERMINAL_ENTRIES;
3088
+ this.state.entries = this.state.entries.filter((entry) => {
3089
+ if (dropRemaining > 0 && isTerminal(entry.status)) {
3090
+ dropRemaining--;
3091
+ return false;
3092
+ }
3093
+ return true;
3094
+ });
3095
+ }
3096
+ const tmp = `${this.file}.tmp.${process.pid}.${Date.now()}.${randomBytes2(16).toString("hex")}`;
3097
+ try {
3098
+ const serialized = JSON.stringify(this.state);
3099
+ checkStateDir(this.config.stateDir);
3100
+ writeFileSync4(tmp, serialized, { mode: 384, flag: "wx" });
3101
+ atomicReplaceRegularFile(tmp, this.file, () => {
3102
+ try {
3103
+ const stat = lstatSync10(this.file);
3104
+ if (stat.isSymbolicLink() || !stat.isFile())
3105
+ throw new Error("Bridge state must not be a symlink");
3106
+ } catch (error) {
3107
+ if (error.code !== "ENOENT")
3108
+ throw error;
3109
+ }
3110
+ checkStateDir(this.config.stateDir);
3111
+ });
3112
+ } catch (err) {
3113
+ try {
3114
+ unlinkSync5(tmp);
3115
+ } catch {}
3116
+ throw err;
3117
+ }
2025
3118
  }
2026
3119
  accept(raw) {
2027
3120
  if (this.stopped || !addressed(raw, this.config))
@@ -2041,6 +3134,8 @@ class Bridge {
2041
3134
  sender_id: raw.sender_id,
2042
3135
  ...Array.isArray(raw.mentioned_ids) ? { mentioned_ids: raw.mentioned_ids.filter((id) => typeof id === "string") } : {},
2043
3136
  ...Array.isArray(raw.mentions) ? { mentions: raw.mentions.filter((id) => typeof id === "string") } : {},
3137
+ ...!tick && typeof raw.parent_id === "string" && safeMessageId(raw.parent_id.trim()) ? { parent_id: raw.parent_id.trim() } : {},
3138
+ ...!tick && typeof raw.reply_to === "string" && safeMessageId(raw.reply_to.trim()) ? { reply_to: raw.reply_to.trim() } : {},
2044
3139
  content: tick ? "Authorized scheduled loop" : this.redact(raw.content),
2045
3140
  ...tick ? { meta: {
2046
3141
  kind: "loop_tick",
@@ -2056,7 +3151,7 @@ class Bridge {
2056
3151
  return true;
2057
3152
  }
2058
3153
  redact(text) {
2059
- return redactSecrets(text.split(this.config.token).join("[REDACTED]"));
3154
+ return redactSecrets(this.config.token ? text.split(this.config.token).join("[REDACTED]") : text);
2060
3155
  }
2061
3156
  recover(raw) {
2062
3157
  if (this.stopped)
@@ -2080,8 +3175,10 @@ class Bridge {
2080
3175
  return this.draining;
2081
3176
  }
2082
3177
  async prepareChannel(chat) {
3178
+ if (!safeMessageId(chat))
3179
+ throw new Error("Invalid channel ID");
2083
3180
  this.state.channels ??= {};
2084
- let channel = this.state.channels[chat];
3181
+ let channel = Object.prototype.hasOwnProperty.call(this.state.channels, chat) ? this.state.channels[chat] : undefined;
2085
3182
  if (!this.loaded.has(chat)) {
2086
3183
  const namespace = this.codex.namespace;
2087
3184
  if (channel?.namespace && channel.namespace !== namespace)
@@ -2142,7 +3239,7 @@ This scheduled skill run supports ${TEAM_LEAD_NO_UPDATE}; return it alone only w
2142
3239
  Authorized task:
2143
3240
  ${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
3241
  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 ${join8(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.
3242
+ 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
3243
  AgentsChat message:
2147
3244
  ` + JSON.stringify(e.message);
2148
3245
  e.answer = this.redact(await this.codex.generate(channel.thread, (channel.bootstrap ?? "") + prompt));
@@ -2176,11 +3273,13 @@ AgentsChat message:
2176
3273
  e.error = error.message;
2177
3274
  this.save();
2178
3275
  this.log("Conversation in use; queued message will resume in the same task");
2179
- if (!this.stopped)
3276
+ if (!this.stopped) {
2180
3277
  this.retry = setTimeout(() => {
2181
3278
  this.retry = undefined;
2182
3279
  this.drain();
2183
3280
  }, 5000);
3281
+ this.retry.unref?.();
3282
+ }
2184
3283
  return;
2185
3284
  }
2186
3285
  e.error = this.redact(error instanceof Error ? error.message : "Bridge operation failed").slice(0, 240);
@@ -2200,8 +3299,14 @@ AgentsChat message:
2200
3299
  async stop() {
2201
3300
  this.pause();
2202
3301
  await this.draining;
2203
- if (existsSync5(this.lock))
2204
- unlinkSync3(this.lock);
3302
+ try {
3303
+ const stat = lstatSync10(this.lock);
3304
+ if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 && readFileSync9(this.lock, "utf8") === String(process.pid))
3305
+ unlinkSync5(this.lock);
3306
+ } catch (error) {
3307
+ if (error.code !== "ENOENT")
3308
+ throw error;
3309
+ }
2205
3310
  const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
2206
3311
  releaseAgentLock({ lockDir: resolveLockDir(homeDir, process.env), agentId: this.config.agentId });
2207
3312
  }
@@ -2217,18 +3322,18 @@ var WS_OPEN = 1;
2217
3322
  var WS_CLOSING = 2;
2218
3323
  class HeartbeatMonitor {
2219
3324
  deps;
2220
- pingInterval;
2221
- pongTimeout;
2222
- connectTimeout;
2223
3325
  lastPong;
2224
3326
  timer = null;
2225
3327
  connectingSince = null;
2226
3328
  reconnecting = false;
3329
+ pingInterval;
3330
+ pongTimeout;
3331
+ connectTimeout;
2227
3332
  constructor(deps, pingInterval = 30000, pongTimeout = 90000, connectTimeout = 30000) {
2228
3333
  this.deps = deps;
2229
- this.pingInterval = pingInterval;
2230
- this.pongTimeout = pongTimeout;
2231
- this.connectTimeout = connectTimeout;
3334
+ this.pingInterval = Number.isFinite(pingInterval) && pingInterval > 0 ? Math.max(1, Math.min(Math.floor(pingInterval), 2147483647)) : 30000;
3335
+ this.pongTimeout = Number.isFinite(pongTimeout) && pongTimeout > 0 ? Math.max(1, Math.min(Math.floor(pongTimeout), 2147483647)) : 90000;
3336
+ this.connectTimeout = Number.isFinite(connectTimeout) && connectTimeout > 0 ? Math.max(1, Math.min(Math.floor(connectTimeout), 2147483647)) : 30000;
2232
3337
  this.lastPong = Date.now();
2233
3338
  }
2234
3339
  receivedPong() {
@@ -2242,6 +3347,7 @@ class HeartbeatMonitor {
2242
3347
  this.connectingSince = null;
2243
3348
  this.reconnecting = false;
2244
3349
  this.timer = setInterval(() => this.tick(), this.pingInterval);
3350
+ this.timer?.unref?.();
2245
3351
  }
2246
3352
  stop() {
2247
3353
  if (this.timer) {
@@ -2253,20 +3359,35 @@ class HeartbeatMonitor {
2253
3359
  this.reconnecting = false;
2254
3360
  }
2255
3361
  tick() {
2256
- const state = this.deps.getReadyState();
3362
+ let state;
3363
+ try {
3364
+ state = this.deps.getReadyState();
3365
+ } catch {
3366
+ this.connectingSince = null;
3367
+ this.safeReconnect("readyState failed");
3368
+ return;
3369
+ }
3370
+ const now = Date.now();
2257
3371
  if (state === WS_OPEN) {
2258
3372
  this.connectingSince = null;
2259
- if (Date.now() - this.lastPong > this.pongTimeout) {
3373
+ if (this.lastPong > now) {
3374
+ this.lastPong = now;
3375
+ }
3376
+ if (now - this.lastPong > this.pongTimeout) {
2260
3377
  this.safeReconnect("pong timeout");
2261
3378
  return;
2262
3379
  }
2263
- this.deps.sendPing();
3380
+ try {
3381
+ this.deps.sendPing();
3382
+ } catch {
3383
+ this.safeReconnect("ping send failed");
3384
+ }
2264
3385
  return;
2265
3386
  }
2266
3387
  if (state === WS_CONNECTING) {
2267
- if (!this.connectingSince) {
2268
- this.connectingSince = Date.now();
2269
- } else if (Date.now() - this.connectingSince > this.connectTimeout) {
3388
+ if (this.connectingSince === null || this.connectingSince > now) {
3389
+ this.connectingSince = now;
3390
+ } else if (now - this.connectingSince > this.connectTimeout) {
2270
3391
  this.connectingSince = null;
2271
3392
  this.safeReconnect("connect timeout");
2272
3393
  }
@@ -2279,38 +3400,110 @@ class HeartbeatMonitor {
2279
3400
  if (this.reconnecting)
2280
3401
  return;
2281
3402
  this.reconnecting = true;
2282
- this.deps.reconnect();
3403
+ try {
3404
+ this.deps.reconnect();
3405
+ } catch {
3406
+ this.reconnecting = false;
3407
+ }
3408
+ }
3409
+ }
3410
+
3411
+ // src/reconnect.ts
3412
+ function safeUnitRand(rand) {
3413
+ let r;
3414
+ try {
3415
+ r = rand();
3416
+ } catch {
3417
+ return 0;
2283
3418
  }
3419
+ if (!Number.isFinite(r) || r <= 0)
3420
+ return 0;
3421
+ return r >= 1 ? 0.999999 : r;
3422
+ }
3423
+ function computePleaseReconnectDelay(jitterMs, rand = Math.random) {
3424
+ const maxJitter = typeof jitterMs === "number" && Number.isFinite(jitterMs) && jitterMs > 0 ? Math.min(Math.floor(jitterMs), 1e4) : 2000;
3425
+ return 200 + Math.floor(safeUnitRand(rand) * maxJitter);
3426
+ }
3427
+ function resolveDrainReconnectDelay(frame, rand = Math.random) {
3428
+ const safeFrame = frame && typeof frame === "object" && !Array.isArray(frame) && !Object.prototype.hasOwnProperty.call(frame, "__proto__") ? frame : null;
3429
+ return computePleaseReconnectDelay(safeFrame?.jitter_ms ?? safeFrame?.within_ms, rand);
2284
3430
  }
2285
3431
 
2286
3432
  // codex/inbox-sync.ts
2287
- import { existsSync as existsSync6, mkdirSync as mkdirSync7, readFileSync as readFileSync9, renameSync as renameSync5, writeFileSync as writeFileSync5 } from "node:fs";
2288
- import { join as join9 } from "node:path";
3433
+ import { chmodSync as chmodSync3, lstatSync as lstatSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync10, unlinkSync as unlinkSync6, writeFileSync as writeFileSync5 } from "node:fs";
3434
+ import { randomBytes as randomBytes3 } from "node:crypto";
3435
+ import { join as join11 } from "node:path";
2289
3436
 
2290
3437
  // src/timestamps.ts
3438
+ var ISO_OFFSET_RE = /^(\d{4}-\d{2}-\d{2})[Tt ](\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|z|[+-]\d{2}:\d{2})$/;
3439
+ function isValidCalendarDateTime(datePart, timePart, tzPart) {
3440
+ const year = Number(datePart.slice(0, 4));
3441
+ const month = Number(datePart.slice(5, 7));
3442
+ const day = Number(datePart.slice(8, 10));
3443
+ const hour = Number(timePart.slice(0, 2));
3444
+ const minute = Number(timePart.slice(3, 5));
3445
+ const second = Number(timePart.slice(6, 8));
3446
+ if (month < 1 || month > 12 || hour > 23 || minute > 59 || second > 59)
3447
+ return false;
3448
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
3449
+ const maxDay = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
3450
+ if (day < 1 || day > maxDay)
3451
+ return false;
3452
+ if (tzPart !== "Z" && tzPart !== "z") {
3453
+ const offHour = Number(tzPart.slice(1, 3));
3454
+ const offMin = Number(tzPart.slice(4, 6));
3455
+ if (offHour > 23 || offMin > 59)
3456
+ return false;
3457
+ }
3458
+ return true;
3459
+ }
2291
3460
  function normalizeTimestampForCursor(ts, mode) {
2292
- if (!ts || typeof ts !== "string")
3461
+ if (!ts || typeof ts !== "string" || ts.length > 128)
3462
+ return ts;
3463
+ if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(ts))
3464
+ return;
3465
+ if (mode !== "before" && mode !== "after")
2293
3466
  return ts;
2294
3467
  const padChar = mode === "before" ? "9" : "0";
2295
- const withFrac = ts.match(/^(.*\.)(\d+)(Z)$/);
2296
- if (withFrac) {
2297
- const frac = withFrac[2];
2298
- if (frac.length >= 9)
3468
+ const trimmed = ts.trim();
3469
+ const m = trimmed.match(ISO_OFFSET_RE);
3470
+ if (m) {
3471
+ const datePart = m[1];
3472
+ const timePart = m[2];
3473
+ const rawFrac = m[3] ?? "";
3474
+ const tzPart = m[4];
3475
+ if (!isValidCalendarDateTime(datePart, timePart, tzPart))
2299
3476
  return ts;
2300
- return withFrac[1] + frac + padChar.repeat(9 - frac.length) + withFrac[3];
2301
- }
2302
- const noFrac = ts.match(/^(.*\d)(Z)$/);
2303
- if (noFrac) {
2304
- return noFrac[1] + "." + padChar.repeat(9) + noFrac[2];
3477
+ const frac9 = rawFrac.length === 9 ? rawFrac : rawFrac.length > 9 ? rawFrac.slice(0, 9) : rawFrac + padChar.repeat(9 - rawFrac.length);
3478
+ if (tzPart === "Z" || tzPart === "z") {
3479
+ return `${datePart}T${timePart}.${frac9}Z`;
3480
+ }
3481
+ const wholeUtcMs = Date.parse(`${datePart}T${timePart}${tzPart}`);
3482
+ if (Number.isFinite(wholeUtcMs)) {
3483
+ const iso = new Date(wholeUtcMs).toISOString();
3484
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(iso)) {
3485
+ return `${iso.slice(0, 19)}.${frac9}Z`;
3486
+ }
3487
+ }
2305
3488
  }
2306
3489
  return ts;
2307
3490
  }
2308
3491
 
2309
3492
  // codex/inbox-sync.ts
2310
3493
  function timestamp(value) {
2311
- if (typeof value !== "string" || !Number.isFinite(Date.parse(value)))
3494
+ 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)))
2312
3495
  throw new Error("Invalid history timestamp");
2313
- return normalizeTimestampForCursor(value, "after");
3496
+ const normalized = normalizeTimestampForCursor(value, "after");
3497
+ if (!normalized || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/.test(normalized))
3498
+ throw new Error("Invalid history timestamp");
3499
+ return normalized;
3500
+ }
3501
+ function validChannel(channel) {
3502
+ 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) && !["__proto__", "constructor", "prototype"].includes(channel.trim().toLowerCase());
3503
+ }
3504
+ function validateChannel(channel) {
3505
+ if (!validChannel(channel))
3506
+ throw new Error("Invalid inbound channel");
2314
3507
  }
2315
3508
 
2316
3509
  class InboxSync {
@@ -2327,20 +3520,64 @@ class InboxSync {
2327
3520
  this.receive = receive;
2328
3521
  this.active = active;
2329
3522
  this.log = log;
3523
+ const existing = lstatSync11(stateDir, { throwIfNoEntry: false });
3524
+ if (existing && (existing.isSymbolicLink() || !existing.isDirectory()))
3525
+ throw new Error("Invalid inbound state directory");
3526
+ assertDirectoryAncestors(stateDir);
2330
3527
  mkdirSync7(stateDir, { recursive: true, mode: 448 });
2331
- this.file = join9(stateDir, "inbound-cursors.json");
2332
- this.state = existsSync6(this.file) ? JSON.parse(readFileSync9(this.file, "utf8")) : { version: 1, channels: {} };
2333
- if (this.state.version !== 1 || !this.state.channels || typeof this.state.channels !== "object" || Array.isArray(this.state.channels))
3528
+ const dirStat = lstatSync11(stateDir);
3529
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory())
3530
+ throw new Error("Invalid inbound state directory");
3531
+ if (process.platform !== "win32")
3532
+ chmodSync3(stateDir, 448);
3533
+ this.file = join11(stateDir, "inbound-cursors.json");
3534
+ let fileStat;
3535
+ try {
3536
+ fileStat = lstatSync11(this.file);
3537
+ } catch (err) {
3538
+ if (err.code !== "ENOENT")
3539
+ throw err;
3540
+ }
3541
+ if (fileStat && (fileStat.isSymbolicLink() || !fileStat.isFile()))
3542
+ throw new Error("Invalid inbound cursors file");
3543
+ if (fileStat && fileStat.size > 1048576)
3544
+ throw new Error("Inbound cursors exceed size limit");
3545
+ this.state = fileStat ? JSON.parse(readFileSync10(this.file, "utf8")) : { version: 1, channels: {} };
3546
+ 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
3547
  throw new Error("Invalid inbound cursors; refusing to discard checkpoint");
2335
- for (const value of Object.values(this.state.channels))
3548
+ const channels = Object.create(null);
3549
+ for (const [channel, value] of Object.entries(this.state.channels)) {
3550
+ if (!validChannel(channel))
3551
+ continue;
2336
3552
  timestamp(value);
2337
- this.state.channels = Object.assign(Object.create(null), this.state.channels);
3553
+ channels[channel] = value;
3554
+ }
3555
+ this.state.channels = channels;
2338
3556
  }
2339
3557
  save() {
2340
- writeFileSync5(this.file + ".tmp", JSON.stringify(this.state), { mode: 384 });
2341
- renameSync5(this.file + ".tmp", this.file);
3558
+ const tmp = `${this.file}.${process.pid}.${Date.now()}.${randomBytes3(4).toString("hex")}.tmp`;
3559
+ let created = false;
3560
+ try {
3561
+ writeFileSync5(tmp, JSON.stringify(this.state), { mode: 384, flag: "wx" });
3562
+ created = true;
3563
+ atomicReplaceRegularFile(tmp, this.file, () => {
3564
+ const current = lstatSync11(this.file, { throwIfNoEntry: false });
3565
+ if (current && (current.isSymbolicLink() || !current.isFile()))
3566
+ throw new Error("Invalid inbound cursors file");
3567
+ });
3568
+ } catch (err) {
3569
+ if (created) {
3570
+ try {
3571
+ unlinkSync6(tmp);
3572
+ } catch {}
3573
+ }
3574
+ throw err;
3575
+ }
2342
3576
  }
2343
3577
  watch(channel) {
3578
+ validateChannel(channel);
3579
+ if (!Object.hasOwn(this.state.channels, channel) && Object.keys(this.state.channels).length >= 1024)
3580
+ throw new Error("Inbound channel limit exceeded");
2344
3581
  this.channels.add(channel);
2345
3582
  if (!Object.hasOwn(this.state.channels, channel)) {
2346
3583
  this.state.channels[channel] = timestamp(new Date().toISOString());
@@ -2348,9 +3585,20 @@ class InboxSync {
2348
3585
  }
2349
3586
  }
2350
3587
  memberships(channels) {
2351
- this.channels.clear();
2352
3588
  for (const channel of channels)
2353
- this.watch(channel);
3589
+ validateChannel(channel);
3590
+ if (new Set([...Object.keys(this.state.channels), ...channels]).size > 1024)
3591
+ throw new Error("Inbound channel limit exceeded");
3592
+ this.channels = new Set(channels);
3593
+ let changed = false;
3594
+ for (const channel of this.channels) {
3595
+ if (!Object.hasOwn(this.state.channels, channel)) {
3596
+ this.state.channels[channel] = timestamp(new Date().toISOString());
3597
+ changed = true;
3598
+ }
3599
+ }
3600
+ if (changed)
3601
+ this.save();
2354
3602
  }
2355
3603
  sync() {
2356
3604
  if (!this.running)
@@ -2377,7 +3625,7 @@ class InboxSync {
2377
3625
  if (!Array.isArray(messages))
2378
3626
  throw new Error("Invalid history response");
2379
3627
  const rows = messages.map((m) => {
2380
- if (!m || m.channel_id !== channel || typeof m.id !== "string")
3628
+ if (!m || m.channel_id !== channel || typeof m.id !== "string" || m.id.trim().length === 0 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(m.id))
2381
3629
  throw new Error("Invalid history message");
2382
3630
  return { message: m, time: timestamp(m.timestamp) };
2383
3631
  }).sort((a, b) => a.time.localeCompare(b.time));
@@ -2414,6 +3662,46 @@ class InboxSync {
2414
3662
  }
2415
3663
 
2416
3664
  // codex/transport.ts
3665
+ function safeChannel(channel) {
3666
+ 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) && !/^(?:__proto__|constructor|prototype)$/i.test(channel);
3667
+ }
3668
+ function requireChannel(channel) {
3669
+ if (!safeChannel(channel))
3670
+ throw new Error("Invalid AgentsChat channel");
3671
+ }
3672
+ function apiUrl(path, base) {
3673
+ const invalid = () => new Error("Invalid AgentsChat API path");
3674
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//") || /[\x00-\x1f\x7f-\x9f\u2028\u2029\\]/.test(path))
3675
+ throw invalid();
3676
+ try {
3677
+ const pathname = path.split(/[?#]/, 1)[0];
3678
+ if (/%25(?:2e|2f|5c|00)/i.test(pathname))
3679
+ throw invalid();
3680
+ const decoded = decodeURIComponent(pathname);
3681
+ if ([pathname, decoded].some((value) => value.split("/").includes("..")) || /[\x00-\x1f\x7f-\x9f\u2028\u2029\\]/.test(decoded))
3682
+ throw invalid();
3683
+ const origin = new URL(base).origin, resolved = new URL(path, base);
3684
+ if (resolved.origin !== origin)
3685
+ throw invalid();
3686
+ return resolved;
3687
+ } catch {
3688
+ throw invalid();
3689
+ }
3690
+ }
3691
+ function rawWsFrameBytes(raw) {
3692
+ if (Buffer.isBuffer(raw))
3693
+ return raw.byteLength;
3694
+ if (raw instanceof ArrayBuffer)
3695
+ return raw.byteLength;
3696
+ if (Array.isArray(raw)) {
3697
+ let total = 0;
3698
+ for (const chunk of raw)
3699
+ total += chunk.byteLength;
3700
+ return total;
3701
+ }
3702
+ return Buffer.byteLength(String(raw), "utf8");
3703
+ }
3704
+
2417
3705
  class AgentsChatTransport {
2418
3706
  config;
2419
3707
  receive;
@@ -2434,13 +3722,15 @@ class AgentsChatTransport {
2434
3722
  this.receive = receive;
2435
3723
  this.log = log;
2436
3724
  this.syncIntervalMs = syncIntervalMs;
3725
+ this.syncIntervalMs = Number.isFinite(syncIntervalMs) && syncIntervalMs > 0 ? Math.min(Math.floor(syncIntervalMs), 2147483647) : 60000;
2437
3726
  if (recover)
2438
3727
  this.inboxSync = new InboxSync(config.stateDir, (path) => this.api(path), recover, () => !this.closed && this.authenticated, log);
2439
3728
  }
2440
3729
  async api(path, body) {
3730
+ const resolved = apiUrl(path, this.config.apiUrl);
2441
3731
  let response;
2442
3732
  try {
2443
- response = await fetch(this.config.apiUrl + path, {
3733
+ response = await fetch(resolved, {
2444
3734
  method: body ? "POST" : "GET",
2445
3735
  redirect: "error",
2446
3736
  headers: { Authorization: `Bearer ${this.config.token}`, "Content-Type": "application/json" },
@@ -2450,25 +3740,66 @@ class AgentsChatTransport {
2450
3740
  } catch {
2451
3741
  throw new Error("AgentsChat request failed or timed out");
2452
3742
  }
2453
- if (!response.ok)
3743
+ if (!response.ok) {
3744
+ try {
3745
+ await response.body?.cancel?.();
3746
+ } catch {}
2454
3747
  throw new Error(`AgentsChat HTTP ${response.status}`);
3748
+ }
3749
+ let reader;
2455
3750
  try {
2456
- return await response.json();
3751
+ reader = response.body?.getReader();
3752
+ if (!reader)
3753
+ throw new Error("Missing response body");
3754
+ const decoder = new TextDecoder("utf-8", { fatal: true });
3755
+ let bytes = 0, text = "";
3756
+ while (true) {
3757
+ const { done, value: value2 } = await reader.read();
3758
+ if (done)
3759
+ break;
3760
+ bytes += value2.byteLength;
3761
+ if (bytes > 4 * 1024 * 1024) {
3762
+ try {
3763
+ await reader.cancel();
3764
+ } catch {}
3765
+ throw new Error("Response too large");
3766
+ }
3767
+ text += decoder.decode(value2, { stream: true });
3768
+ }
3769
+ const value = JSON.parse(text + decoder.decode());
3770
+ if (value && typeof value === "object" && Object.hasOwn(value, "__proto__"))
3771
+ throw new Error("Invalid JSON prototype key");
3772
+ return value;
2457
3773
  } catch {
2458
3774
  throw new Error("Invalid AgentsChat response");
3775
+ } finally {
3776
+ reader?.releaseLock();
2459
3777
  }
2460
3778
  }
2461
3779
  setTyping(channel, active) {
3780
+ requireChannel(channel);
2462
3781
  clearInterval(this.typing.get(channel));
2463
3782
  this.typing.delete(channel);
2464
3783
  if (!active || this.closed)
2465
3784
  return;
3785
+ if (this.typing.size >= 64)
3786
+ throw new Error("AgentsChat typing limit reached");
2466
3787
  const pulse = () => {
2467
- if (this.authenticated && this.socket?.readyState === WebSocket.OPEN)
2468
- this.socket.send(JSON.stringify({ type: "typing", channel_id: channel, sender_id: this.config.agentId, cross_pod: true }));
3788
+ if (this.authenticated && this.socket?.readyState === WebSocket.OPEN) {
3789
+ try {
3790
+ this.socket.send(JSON.stringify({ type: "typing", channel_id: channel, sender_id: this.config.agentId, cross_pod: true }));
3791
+ } catch {}
3792
+ }
2469
3793
  };
2470
3794
  pulse();
2471
- this.typing.set(channel, setInterval(pulse, 2000));
3795
+ const typingTimer = setInterval(pulse, 2000);
3796
+ typingTimer.unref?.();
3797
+ this.typing.set(channel, typingTimer);
3798
+ }
3799
+ clearTyping() {
3800
+ for (const timer of this.typing.values())
3801
+ clearInterval(timer);
3802
+ this.typing.clear();
2472
3803
  }
2473
3804
  rejectPending() {
2474
3805
  for (const p of this.pending.values()) {
@@ -2478,29 +3809,39 @@ class AgentsChatTransport {
2478
3809
  this.pending.clear();
2479
3810
  }
2480
3811
  async send(channel, text) {
3812
+ requireChannel(channel);
2481
3813
  if (this.authenticated && this.socket?.readyState === WebSocket.OPEN) {
3814
+ if (this.pending.size >= 256)
3815
+ throw new Error("AgentsChat pending message limit reached");
2482
3816
  const id = randomUUID2();
2483
- await new Promise((resolve4, reject) => {
3817
+ await new Promise((resolve7, reject) => {
2484
3818
  const timer = setTimeout(() => {
2485
3819
  this.pending.delete(id);
2486
3820
  reject(new Error("AgentsChat acknowledgement timed out"));
2487
3821
  }, 15000);
2488
- this.pending.set(id, { resolve: resolve4, reject, timer });
2489
- this.socket.send(JSON.stringify({
2490
- type: "message",
2491
- id,
2492
- channel_id: channel,
2493
- sender_id: this.config.agentId,
2494
- sender_type: "agent",
2495
- content_type: "text",
2496
- content: text
2497
- }), (error) => {
2498
- if (error) {
2499
- clearTimeout(timer);
2500
- this.pending.delete(id);
2501
- reject(new Error("AgentsChat socket send failed"));
2502
- }
2503
- });
3822
+ timer.unref?.();
3823
+ this.pending.set(id, { resolve: resolve7, reject, timer });
3824
+ try {
3825
+ this.socket.send(JSON.stringify({
3826
+ type: "message",
3827
+ id,
3828
+ channel_id: channel,
3829
+ sender_id: this.config.agentId,
3830
+ sender_type: "agent",
3831
+ content_type: "text",
3832
+ content: text
3833
+ }), (error) => {
3834
+ if (error) {
3835
+ clearTimeout(timer);
3836
+ this.pending.delete(id);
3837
+ reject(new Error("AgentsChat socket send failed"));
3838
+ }
3839
+ });
3840
+ } catch {
3841
+ clearTimeout(timer);
3842
+ this.pending.delete(id);
3843
+ reject(new Error("AgentsChat socket send failed"));
3844
+ }
2504
3845
  });
2505
3846
  return;
2506
3847
  }
@@ -2513,15 +3854,30 @@ class AgentsChatTransport {
2513
3854
  start() {
2514
3855
  if (this.closed)
2515
3856
  return;
3857
+ clearTimeout(this.retry);
3858
+ this.retry = undefined;
3859
+ clearInterval(this.syncTimer);
3860
+ this.syncTimer = undefined;
3861
+ this.heartbeat?.stop();
3862
+ this.heartbeat = undefined;
3863
+ this.authenticated = false;
3864
+ this.clearTyping();
3865
+ this.rejectPending();
3866
+ const previous = this.socket;
3867
+ this.socket = undefined;
3868
+ previous?.terminate();
2516
3869
  const socket = new WebSocket(this.config.wsUrl, { maxPayload: 1048576, handshakeTimeout: 15000 });
2517
3870
  this.socket = socket;
2518
3871
  const current = () => !this.closed && this.socket === socket;
2519
3872
  const send = (value) => {
2520
- if (current() && socket.readyState === WebSocket.OPEN)
2521
- socket.send(JSON.stringify(value));
3873
+ if (current() && socket.readyState === WebSocket.OPEN) {
3874
+ try {
3875
+ socket.send(JSON.stringify(value));
3876
+ } catch {}
3877
+ }
2522
3878
  };
2523
- const join10 = (channel) => {
2524
- if (!this.config.channels.length || this.config.channels.includes(channel)) {
3879
+ const join12 = (channel) => {
3880
+ if (safeChannel(channel) && (!this.config.channels.length || this.config.channels.includes(channel))) {
2525
3881
  this.inboxSync?.watch(channel);
2526
3882
  send({ type: "join_channel", channel_id: channel, agent_id: this.config.agentId });
2527
3883
  }
@@ -2534,7 +3890,7 @@ class AgentsChatTransport {
2534
3890
  this.heartbeat.start();
2535
3891
  socket.on("open", () => send({ type: "auth", agent_id: this.config.agentId, token: this.config.token, capabilities: ["chat", "codex"] }));
2536
3892
  socket.on("message", (raw) => {
2537
- if (!current())
3893
+ if (!current() || rawWsFrameBytes(raw) > 1048576)
2538
3894
  return;
2539
3895
  let data;
2540
3896
  try {
@@ -2542,25 +3898,30 @@ class AgentsChatTransport {
2542
3898
  } catch {
2543
3899
  return;
2544
3900
  }
2545
- this.heartbeat?.receivedPong();
3901
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.hasOwn(data, "__proto__"))
3902
+ return;
3903
+ if (data.type !== "auth_error")
3904
+ this.heartbeat?.receivedPong();
2546
3905
  if (data.type === "auth_ok") {
2547
3906
  this.authenticated = true;
2548
3907
  this.delay = 1000;
2549
3908
  this.log(`AgentsChat connected as ${this.config.agentId}`);
2550
- if (this.inboxSync && !this.syncTimer)
3909
+ if (this.inboxSync && !this.syncTimer) {
2551
3910
  this.syncTimer = setInterval(() => {
2552
3911
  this.inboxSync.sync();
2553
3912
  }, this.syncIntervalMs);
3913
+ this.syncTimer.unref?.();
3914
+ }
2554
3915
  this.api("/api/channels/mine").then((body) => {
2555
3916
  if (!current())
2556
3917
  return;
2557
3918
  const channels = Array.isArray(body) ? body : body.channels;
2558
3919
  if (!Array.isArray(channels))
2559
3920
  throw new Error("Invalid membership response");
2560
- const ids = channels.map((c) => c.id ?? c.channel_id).filter((id) => typeof id === "string" && (!this.config.channels.length || this.config.channels.includes(id)));
3921
+ const ids = channels.map((c) => c?.id ?? c?.channel_id).filter((id) => safeChannel(id) && (!this.config.channels.length || this.config.channels.includes(id)));
2561
3922
  this.inboxSync?.memberships(ids);
2562
3923
  for (const id of ids)
2563
- join10(id);
3924
+ join12(id);
2564
3925
  this.inboxSync?.sync();
2565
3926
  }).catch(() => {
2566
3927
  if (current()) {
@@ -2576,37 +3937,49 @@ class AgentsChatTransport {
2576
3937
  pending.resolve();
2577
3938
  }
2578
3939
  } else if (data.type === "channel_created" && typeof data.channel_id === "string")
2579
- join10(data.channel_id);
3940
+ join12(data.channel_id);
2580
3941
  else if (["message", "thread_reply"].includes(data.type))
2581
3942
  this.receive(data);
2582
- else if (data.type === "shard_moved" || data.type === "please_reconnect")
3943
+ else if (data.type === "shard_moved" || data.type === "please_reconnect") {
3944
+ this.delay = resolveDrainReconnectDelay(data);
2583
3945
  socket.terminate();
2584
- else if (data.type === "auth_error" || data.type === "error")
3946
+ } else if (data.type === "auth_error") {
3947
+ this.log("AgentsChat authentication rejected; check profile token (backing off 30s)");
3948
+ this.delay = 30000;
3949
+ socket.close();
3950
+ } else if (data.type === "error")
2585
3951
  this.log("AgentsChat returned an error; check account and channel permissions");
2586
3952
  });
2587
3953
  socket.on("error", () => this.log("AgentsChat socket error"));
2588
3954
  socket.on("close", () => {
2589
3955
  if (!current())
2590
3956
  return;
3957
+ clearInterval(this.syncTimer);
3958
+ this.syncTimer = undefined;
2591
3959
  this.authenticated = false;
3960
+ this.clearTyping();
2592
3961
  this.rejectPending();
2593
3962
  this.heartbeat?.stop();
2594
3963
  this.log("AgentsChat disconnected; reconnecting with history reconciliation");
2595
3964
  this.retry = setTimeout(() => this.start(), this.delay);
3965
+ this.retry.unref?.();
2596
3966
  this.delay = Math.min(this.delay * 2, 30000);
2597
3967
  });
2598
3968
  }
2599
3969
  stop() {
2600
- for (const timer of this.typing.values())
2601
- clearInterval(timer);
2602
- this.typing.clear();
2603
3970
  this.closed = true;
2604
3971
  this.authenticated = false;
3972
+ this.clearTyping();
2605
3973
  this.rejectPending();
2606
3974
  clearTimeout(this.retry);
3975
+ this.retry = undefined;
2607
3976
  clearInterval(this.syncTimer);
3977
+ this.syncTimer = undefined;
2608
3978
  this.heartbeat?.stop();
2609
- this.socket?.terminate();
3979
+ this.heartbeat = undefined;
3980
+ const socket = this.socket;
3981
+ this.socket = undefined;
3982
+ socket?.terminate();
2610
3983
  }
2611
3984
  }
2612
3985
 
@@ -2640,6 +4013,13 @@ See codex/README.md for setup, verification, limitations and recovery.
2640
4013
  var codex;
2641
4014
  var bridge;
2642
4015
  var transport;
4016
+ function isPlainObject2(value) {
4017
+ return value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
4018
+ }
4019
+ var IPC_CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
4020
+ function isCleanIpcString(value, allowEmpty = false) {
4021
+ return typeof value === "string" && (allowEmpty || value.length > 0) && !IPC_CONTROL_CHAR_RE.test(value);
4022
+ }
2643
4023
  async function main() {
2644
4024
  const { values } = parseArgs({ options: {
2645
4025
  "codex-bridge": { type: "boolean" },
@@ -2665,28 +4045,42 @@ async function main() {
2665
4045
  return;
2666
4046
  }
2667
4047
  if (values["gui-thread"] || values["gui-message-file"] || values["gui-status"]) {
2668
- const channel = new GuiChannel(join10(homedir5(), ".agentschat/codex-gui-outbox"), values["gui-thread"] ? [values["gui-thread"]] : []);
4048
+ const parent = lstatSync12(join12(homedir6(), ".agentschat"), { throwIfNoEntry: false });
4049
+ if (parent && (parent.isSymbolicLink() || !parent.isDirectory()))
4050
+ throw new Error("GUI parent must be a real directory, not a symlink");
4051
+ const channel = new GuiChannel(join12(homedir6(), ".agentschat/codex-gui-outbox"), values["gui-thread"] ? [values["gui-thread"]] : []);
2669
4052
  if (values["gui-status"]) {
2670
4053
  console.log(JSON.stringify(channel.list().map(({ prompt: prompt2, ...receipt2 }) => receipt2)));
2671
4054
  return;
2672
4055
  }
2673
4056
  if (!values["gui-thread"] || !values["gui-message-file"])
2674
4057
  throw new Error("GUI submission requires --gui-thread and --gui-message-file");
2675
- const { prompt, ...receipt } = channel.enqueue(values["gui-thread"], readFileSync10(values["gui-message-file"], "utf8"));
4058
+ assertDirectoryAncestors(dirname5(values["gui-message-file"]));
4059
+ const stat = lstatSync12(values["gui-message-file"]);
4060
+ if (stat.isSymbolicLink() || !stat.isFile())
4061
+ throw new Error("GUI message must be a regular file, not a symlink");
4062
+ if (stat.size > 256 * 1024)
4063
+ throw new Error("GUI message file exceeds 256 KiB");
4064
+ const { prompt, ...receipt } = channel.enqueue(values["gui-thread"], readFileSync11(values["gui-message-file"], "utf8"));
2676
4065
  console.log(JSON.stringify(receipt));
2677
4066
  return;
2678
4067
  }
2679
4068
  if ((values.bot || values["managed-worker"]) && (values["state-root"] || values["codex-home-mode"]))
2680
4069
  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((resolve4, reject) => {
4070
+ const snapshot = values["managed-worker"] ? await new Promise((resolve7, reject) => {
2682
4071
  if (!process.connected) {
2683
4072
  reject(new Error("Managed worker needs parent IPC"));
2684
4073
  return;
2685
4074
  }
2686
4075
  const timer = setTimeout(() => reject(new Error("Parent configuration missing")), 1e4);
4076
+ timer.unref?.();
2687
4077
  process.once("message", (config) => {
2688
4078
  clearTimeout(timer);
2689
- resolve4(config);
4079
+ 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)))) {
4080
+ reject(new Error("Invalid parent configuration"));
4081
+ return;
4082
+ }
4083
+ resolve7(config);
2690
4084
  });
2691
4085
  }) : undefined;
2692
4086
  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 +4102,42 @@ async function main() {
2708
4102
  const runtime = prepareRuntimeHome(c.stateDir, undefined, c.codexHomeMode, c.codexBin);
2709
4103
  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
4104
  if (values.conversations || values["read-conversation"]) {
2711
- const state = JSON.parse(readFileSync10(join10(c.stateDir, "state.json"), "utf8"));
2712
- const channels = state.channels ?? {};
4105
+ const dir = lstatSync12(c.stateDir), stateFile = join12(c.stateDir, "state.json");
4106
+ if (dir.isSymbolicLink() || !dir.isDirectory())
4107
+ throw new Error("Conversation state must use a real directory");
4108
+ assertDirectoryAncestors(c.stateDir);
4109
+ const stat = lstatSync12(stateFile);
4110
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024)
4111
+ throw new Error("Unsafe conversation state file");
4112
+ const state = JSON.parse(readFileSync11(stateFile, "utf8"));
4113
+ if (!isPlainObject2(state) || Object.prototype.hasOwnProperty.call(state, "__proto__"))
4114
+ throw new Error("Invalid conversation state");
4115
+ const channels = state?.channels === undefined ? {} : state.channels;
4116
+ if (!isPlainObject2(channels) || Object.prototype.hasOwnProperty.call(channels, "__proto__"))
4117
+ throw new Error("Invalid conversation channels");
4118
+ const safeOutput = (value) => {
4119
+ const text = JSON.stringify(value);
4120
+ return redactSecrets(typeof c.token === "string" && c.token.length > 0 ? text.split(c.token).join("[REDACTED]") : text);
4121
+ };
2713
4122
  if (values.conversations) {
2714
- console.log(JSON.stringify(Object.entries(channels).map(([channel2, data]) => ({ channel: channel2, thread: data.thread, isolated: data.namespace === runtime.home }))));
4123
+ console.log(safeOutput(Object.entries(channels).map(([channel2, data]) => ({ channel: channel2, thread: data.thread, isolated: data.namespace === runtime.home }))));
2715
4124
  return;
2716
4125
  }
2717
- const channel = channels[values["read-conversation"]];
2718
- if (!channel)
4126
+ const key = values["read-conversation"];
4127
+ if (!Object.prototype.hasOwnProperty.call(channels, key))
2719
4128
  throw new Error("Unknown conversation channel");
4129
+ const channel = channels[key];
4130
+ if (!isPlainObject2(channel) || typeof channel.thread !== "string" || !channel.thread)
4131
+ throw new Error("Invalid conversation channel");
2720
4132
  if (channel.namespace && channel.namespace !== runtime.home)
2721
4133
  throw new Error("Conversation belongs to a different runtime home");
2722
4134
  await codex.start();
2723
- const history = channel.namespace ? await codex.readThread(channel.thread) : await codex.readLegacyThread(channel.thread);
2724
- console.log(redactSecrets(JSON.stringify(history).split(c.token).join("[REDACTED]")));
2725
- codex.close();
4135
+ try {
4136
+ const history = channel.namespace ? await codex.readThread(channel.thread) : await codex.readLegacyThread(channel.thread);
4137
+ console.log(safeOutput(history));
4138
+ } finally {
4139
+ codex.close();
4140
+ }
2726
4141
  return;
2727
4142
  }
2728
4143
  if (c.permissions === "full-access") {
@@ -2733,9 +4148,12 @@ async function main() {
2733
4148
  }
2734
4149
  if (values.check) {
2735
4150
  await codex.start();
2736
- console.log("Official app-server initialization: OK (no chat connection or generation)");
2737
- console.log(JSON.stringify({ authentication: await codex.authenticationStatus(), generation_verified: false, reply_verified: false, codex_home_mode: c.codexHomeMode ?? "linked" }));
2738
- codex.close();
4151
+ try {
4152
+ console.log("Official app-server initialization: OK (no chat connection or generation)");
4153
+ console.log(JSON.stringify({ authentication: await codex.authenticationStatus(), generation_verified: false, reply_verified: false, codex_home_mode: c.codexHomeMode ?? "linked" }));
4154
+ } finally {
4155
+ codex.close();
4156
+ }
2739
4157
  return;
2740
4158
  }
2741
4159
  transport = new AgentsChatTransport(c, (m) => {
@@ -2779,7 +4197,9 @@ async function main() {
2779
4197
  transport.start();
2780
4198
  }
2781
4199
  main().catch(async (e) => {
2782
- console.error(`Bridge startup failed: ${e instanceof Error && !/token|secret/i.test(e.message) ? e.message : "invalid configuration"}`);
4200
+ const rawMessage = e instanceof Error ? e.message.replace(/\x1b\[[0-9;]*[A-Za-z]|[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ").trim() : "";
4201
+ const diagnostic = rawMessage ? redactSecrets(rawMessage) : "invalid configuration";
4202
+ console.error(`Bridge startup failed: ${/token|secret|bearer|password|key|cookie|authorization|credential/i.test(diagnostic) ? "invalid configuration" : diagnostic}`);
2783
4203
  transport?.stop();
2784
4204
  codex?.close();
2785
4205
  await bridge?.stop();