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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Release notes
2
2
 
3
+ ## 0.36.26 — OKR/loop/docs/memory CAS tools, cross-platform Windows/POSIX hardening & bridge security
4
+
5
+ - Preserve human participant email handles (e.g. `swswordholy@gmail.com`) across `list_members`, `channel_brief`, `get_history`, `search_messages`, `list_proposals`, and group wake context so bots can identify human teammates directly instead of collapsing them into `user:xx***` (phone numbers remain masked as `user:phone_***NN`).
6
+ - Add verified `create_loop`, `set_loop_interval`, and `stop_loop` lifecycle tools, `list_pins` and `list_proposals` (with REST-first `propose`/`vote`), `delete_memory` and `load_memory` `include_revisions`, `archive_channel_doc` CAS, personal skill load/revisions/CAS save, and full OKR authoring/CAS tools (`okr_update_objective`, `okr_update_kr`, `append_evidence`, `if_match_updated_at`, `linked_channel_docs`, validated `depends_on`, and `channel_brief` 1-RTT `okr_summary` / `loop_summary` / `wake_health_summary`).
7
+ - Harden cross-platform Windows & POSIX reliability across MCP server, REST+SSE CLI, Codex bridge/bots, Hermes relay connector, DeepSeek Harness (`--dsh`), and Muse (`--muse`): NTFS `EPERM`/`EACCES` atomic replace fallbacks with symlink/TOCTOU re-checks, Windows process-tree cleanup & Antigravity wake support, `shard_moved` / `please_reconnect` jittered drains, `auth_error` loop halts, per-request HTTP deadlines, and backward-NTP clock recovery.
8
+ - Strengthen SSRF (including IPv4-mapped IPv6 `0.0.0.0/8`, loopback, link-local, and metadata hosts), prototype-key/own-`__proto__`, ancestor-symlink, bounded timer/queue, and C0/C1/U+2028/U+2029 + credential redaction guards across all CLI entrypoints and prebuilt Node bundles.
9
+
3
10
  ## 0.36.25 — verified loop lifecycle & room cloud wake health
4
11
 
5
12
  - Add `pause_loop` and `resume_loop` MCP tools backed by the existing authenticated REST lifecycle endpoints. Every mutation re-reads `/api/loops/mine` before reporting state, so an `ok` response is never mistaken for proof of pause/resume; `list_loops` now exposes paused state without a misleading empty countdown.
package/codex/README.md CHANGED
@@ -71,7 +71,7 @@ fallback to a lower-priority identity and no automatic registration.
71
71
  ```toml
72
72
  [mcp_servers.agentschat]
73
73
  command = "npx"
74
- args = ["-y", "agentschat-mcp", "--profile", "my-project-agent"]
74
+ args = ["-y", "agentschat-mcp@latest", "--profile", "my-project-agent"]
75
75
  ```
76
76
 
77
77
  For a bridge-specific selector and scope, use `.agentschat/config.json`:
@@ -1,6 +1,7 @@
1
1
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { createInterface } from "node:readline";
4
+ import { resolveWindowsCliSpawn } from "../src/wake.ts";
4
5
  import type { ThreadHistory } from "./thread-history.ts";
5
6
  import type { PermissionMode, ReasoningEffort } from "./config.ts";
6
7
 
@@ -13,8 +14,10 @@ export class AppServer {
13
14
  onFatal?: () => void;
14
15
  private closed = false;
15
16
  private child?: ChildProcessWithoutNullStreams;
17
+ private rl?: ReturnType<typeof createInterface>;
18
+ private killTimer?: ReturnType<typeof setTimeout>;
16
19
  private nextId = 0;
17
- private pending = new Map<number, { method: string; resolve: (v: any) => void; reject: (e: Error) => void }>();
20
+ private pending = new Map<number, { method: string; timer: ReturnType<typeof setTimeout>; resolve: (v: any) => void; reject: (e: Error) => void }>();
18
21
  private active?: { thread: string; turn?: string; items: Map<string, string>; early: any[];
19
22
  resolve: (s: string) => void; reject: (e: Error) => void };
20
23
  private threadPermissions = new Map<string, PermissionMode>();
@@ -23,9 +26,11 @@ export class AppServer {
23
26
  private diagnosticTail = "";
24
27
  private disabledMcp: Record<string, { enabled: boolean }> = {};
25
28
  // Keep the legacy positional argument for callers; turns have no time limit.
26
- constructor(private bin = "codex", private args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs?: number, private permissions: PermissionMode = "full-access", private runtime?: {home: string; legacyHome?: string}, private effort?: ReasoningEffort, private model?: string, private toolIdentity?: { profileFile: string; agentId: string; apiUrl: string; wsUrl: string }) {}
29
+ constructor(private bin = "codex", private args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs?: number, private permissions: PermissionMode = "full-access", private runtime?: {home: string; legacyHome?: string}, private effort?: ReasoningEffort, private model?: string, private toolIdentity?: { profileFile: string; agentId: string; apiUrl: string; wsUrl: string }, private requestTimeoutMs = 30_000) {}
27
30
  get namespace() { return this.runtime?.home; }
28
31
  async start() {
32
+ if (this.model !== undefined && (typeof this.model !== "string" || !this.model.trim() ||
33
+ this.model.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(this.model))) throw new Error("Invalid app-server model");
29
34
  const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^AGENTS?CHAT_|^RELAY_/.test(k)));
30
35
  env.AGENTSCHAT_LOCK_OWNER_PID = String(process.pid);
31
36
  env.AGENTSCHAT_TOOL_ONLY = "1";
@@ -57,7 +62,8 @@ export class AppServer {
57
62
  : JSON.stringify(value);
58
63
  args.push("-c", `mcp_servers.agentschat=${encode(entry)}`);
59
64
  }
60
- this.child = spawn(this.bin, args, { env, stdio: "pipe" });
65
+ const resolved = resolveWindowsCliSpawn(this.bin, args, { env });
66
+ this.child = spawn(resolved.cmd, resolved.args, { env, stdio: "pipe", windowsHide: true });
61
67
  // Child diagnostics may contain account or MCP credentials; never relay raw stderr.
62
68
  this.child.stderr.on("data", (chunk: Buffer) => {
63
69
  if (this.initialized) return;
@@ -67,11 +73,21 @@ export class AppServer {
67
73
  });
68
74
  this.child.stdin.on("error", () => this.fatal(new Error("Codex input pipe closed")));
69
75
  this.child.on("error", () => this.fatal(new Error("Could not start Codex app-server")));
70
- this.child.on("exit", () => this.fatal(new Error(!this.initialized && this.readonlyFilesystemReported
71
- ? "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."
72
- : "Codex app-server exited")));
73
- createInterface({ input: this.child.stdout }).on("line", line => {
74
- try { this.receive(JSON.parse(line)); } catch { this.fatal(new Error("Invalid app-server response")); }
76
+ this.child.on("exit", () => {
77
+ if (this.killTimer) { clearTimeout(this.killTimer); this.killTimer = undefined; }
78
+ this.fatal(new Error(!this.initialized && this.readonlyFilesystemReported
79
+ ? "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."
80
+ : "Codex app-server exited"));
81
+ });
82
+ this.rl = createInterface({ input: this.child.stdout });
83
+ this.rl.on("line", line => {
84
+ if (line.length > 8 * 1024 * 1024) { this.fatal(new Error("Oversized app-server response")); return; }
85
+ let parsed: any;
86
+ try { parsed = JSON.parse(line); } catch { this.fatal(new Error("Invalid app-server response")); return; }
87
+ if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
88
+ this.fatal(new Error("Invalid app-server response")); return;
89
+ }
90
+ this.receive(parsed);
75
91
  });
76
92
  await this.request("initialize", { clientInfo: { name: "agentschat_bridge", version: "0.1.0" } });
77
93
  this.write({ method: "initialized" });
@@ -91,23 +107,33 @@ export class AppServer {
91
107
  if (this.closed || !this.child || this.child.exitCode !== null || this.child.stdin.destroyed) throw new Error("App-server unavailable");
92
108
  this.child.stdin.write(JSON.stringify(value) + "\n");
93
109
  }
94
- request(method: string, params: unknown): Promise<any> {
110
+ request(method: string, params: unknown, timeoutMs = this.requestTimeoutMs): Promise<any> {
95
111
  return new Promise((resolve, reject) => {
96
112
  const id = ++this.nextId;
97
- this.pending.set(id, { method, resolve, reject });
113
+ const timer = setTimeout(() => {
114
+ if (!this.pending.delete(id)) return;
115
+ const err = new Error(`App-server request timed out (${method})`);
116
+ this.fatal(err);
117
+ reject(err);
118
+ }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(Math.max(50, Math.floor(timeoutMs)), 2_147_483_647) : 30_000);
119
+ timer.unref?.();
120
+ this.pending.set(id, { method, timer, resolve, reject });
98
121
  try { this.write({ id, method, params }); }
99
- catch (e) { this.pending.delete(id); reject(e); }
122
+ catch (e) { clearTimeout(timer); this.pending.delete(id); reject(e); }
100
123
  });
101
124
  }
102
125
  private receive(message: any) {
126
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
127
+ this.fatal(new Error("Invalid app-server response")); return;
128
+ }
103
129
  if (message.id !== undefined && message.method) {
104
130
  // Headless bridge never approves commands or answers interactive prompts.
105
- this.write({ id: message.id, error: { code: -32601, message: "Interactive requests unsupported by bridge" } });
131
+ try { this.write({ id: message.id, error: { code: -32601, message: "Interactive requests unsupported by bridge" } }); } catch {}
106
132
  return;
107
133
  }
108
134
  if (message.id !== undefined) {
109
135
  const waiter = this.pending.get(message.id);
110
- if (waiter) { this.pending.delete(message.id);
136
+ if (waiter) { clearTimeout(waiter.timer); this.pending.delete(message.id);
111
137
  if (message.error) {
112
138
  const detail = typeof message.error.message === "string" ? message.error.message : "";
113
139
  const error = waiter.method === "thread/resume" && /already has an active writer/i.test(detail)
@@ -123,19 +149,27 @@ export class AppServer {
123
149
  }
124
150
  const a = this.active, p = message.params;
125
151
  if (!a || p?.threadId !== a.thread) return;
126
- if (!a.turn) { a.early.push(message); return; }
152
+ if (!a.turn) { if (a.early.length < 500) a.early.push(message); return; }
127
153
  if ((p.turnId ?? p.turn?.id) !== a.turn) return;
128
- if (message.method === "item/completed" && p.item?.type === "agentMessage" &&
129
- (!p.item.phase || p.item.phase === "final_answer")) a.items.set(p.item.id, p.item.text);
154
+ const recordItem = (item: any) => {
155
+ if (item?.type === "agentMessage" && (!item.phase || item.phase === "final_answer") &&
156
+ typeof item.id === "string" && item.id.length > 0 && typeof item.text === "string" &&
157
+ (a.items.has(item.id) || a.items.size < 512)) a.items.set(item.id, item.text);
158
+ };
159
+ if (message.method === "item/completed") recordItem(p.item);
130
160
  if (message.method === "turn/completed") {
131
161
  this.active = undefined;
132
- if (p.turn.status !== "completed") { a.reject(new Error(`Codex turn ${p.turn.status}`)); return; }
133
- for (const item of p.turn.items ?? []) if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer")) a.items.set(item.id, item.text);
162
+ if (p.turn?.status !== "completed") { a.reject(new Error(`Codex turn ${p.turn?.status ?? "unknown"}`)); return; }
163
+ for (const item of Array.isArray(p.turn.items) ? p.turn.items : []) recordItem(item);
134
164
  const text = [...a.items.values()].join("\n").trim();
135
165
  text ? a.resolve(text) : a.reject(new Error("Codex completed without a final reply"));
136
166
  }
137
167
  }
138
168
  async thread(cwd: string, existing?: string, ephemeral = false, permissions: PermissionMode = this.permissions): Promise<string> {
169
+ if (typeof cwd !== "string" || !cwd.trim() || cwd.length > 4096 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(cwd))
170
+ throw new Error("Invalid app-server cwd");
171
+ if (existing !== undefined && (typeof existing !== "string" || !existing.trim() || existing.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(existing)))
172
+ throw new Error("Invalid app-server thread ID");
139
173
  // Loaded-thread resume ignores MCP and developer-instruction overrides.
140
174
  // Keep the original runtime policy; a different permission needs a new thread.
141
175
  const configured = existing ? this.threadPermissions.get(existing) : undefined;
@@ -144,7 +178,9 @@ export class AppServer {
144
178
  }
145
179
  const result = await this.request("config/read", { includeLayers: false, cwd });
146
180
  this.disabledMcp = {};
147
- for (const name of Object.keys(result.config?.mcp_servers ?? {})) this.disabledMcp[name] = { enabled: false };
181
+ for (const name of Object.keys(result.config?.mcp_servers ?? {})) {
182
+ if (!/^(?:__proto__|constructor|prototype)$/i.test(name)) this.disabledMcp[name] = { enabled: false };
183
+ }
148
184
  const r = await this.request(existing ? "thread/resume" : "thread/start", {
149
185
  ...(existing ? { threadId: existing } : { ephemeral }), cwd, ...(this.model ? { model: this.model } : {}),
150
186
  approvalPolicy: "never", sandbox: permissions === "full-access" ? "danger-full-access" : "read-only",
@@ -157,6 +193,7 @@ export class AppServer {
157
193
  });
158
194
  if (typeof r.thread?.id !== "string") throw new Error("App-server returned no thread ID");
159
195
  this.threadPermissions.set(r.thread.id, permissions);
196
+ if (this.threadPermissions.size > 1024) this.threadPermissions.delete(this.threadPermissions.keys().next().value!);
160
197
  return r.thread.id;
161
198
  }
162
199
  async readThread(thread: string): Promise<ThreadHistory> {
@@ -195,12 +232,32 @@ export class AppServer {
195
232
  } catch (e) { this.fail(e instanceof Error ? e : new Error("Generation failed")); throw e; }
196
233
  }
197
234
  private fail(error: Error) {
198
- for (const p of this.pending.values()) p.reject(error); this.pending.clear();
235
+ for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(error); }
236
+ this.pending.clear();
199
237
  if (this.active) { this.active.reject(error); this.active = undefined; }
200
238
  }
239
+ private terminateChild() {
240
+ try { this.rl?.close(); } catch {}
241
+ this.rl = undefined;
242
+ const child = this.child;
243
+ if (!child) return;
244
+ try { child.stdin.end(); } catch {}
245
+ if (child.exitCode === null && child.signalCode === null) {
246
+ try { child.kill("SIGTERM"); } catch {}
247
+ if (!this.killTimer) {
248
+ this.killTimer = setTimeout(() => {
249
+ this.killTimer = undefined;
250
+ if (child.exitCode === null && child.signalCode === null) {
251
+ try { child.kill("SIGKILL"); } catch {}
252
+ }
253
+ }, 2_000);
254
+ this.killTimer.unref?.();
255
+ }
256
+ }
257
+ }
201
258
  private fatal(error: Error) {
202
259
  if (this.closed) return;
203
- this.closed = true; this.fail(error); this.onFatal?.(); this.child?.kill();
260
+ this.closed = true; this.fail(error); this.onFatal?.(); this.terminateChild();
204
261
  }
205
- close() { this.closed = true; this.fail(new Error("App-server stopped")); this.child?.kill(); }
262
+ close() { this.closed = true; this.fail(new Error("App-server stopped")); this.terminateChild(); }
206
263
  }
@@ -1,36 +1,56 @@
1
- import { readFileSync, realpathSync, mkdirSync } from "node:fs";
1
+ import { readFileSync, realpathSync, mkdirSync, lstatSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, isAbsolute, join, resolve } from "node:path";
4
- import { resolveConfig, type BridgeConfig, type IdentitySettings } from "./config.ts";
4
+ import { assertDirectoryAncestors, reservedProfileStem, resolveConfig, type BridgeConfig, type IdentitySettings } from "./config.ts";
5
5
 
6
6
  export interface BotConfig extends BridgeConfig { name: string }
7
7
  export function defaultRegistry(home = homedir()) { return join(home, ".agentschat/codex-bots.json"); }
8
8
  export function loadBots(file = defaultRegistry(), home = homedir()): BotConfig[] {
9
+ assertDirectoryAncestors(dirname(file));
9
10
  let doc: any;
10
- try { doc = JSON.parse(readFileSync(file, "utf8")); } catch { throw new Error("Cannot read bot registry JSON"); }
11
+ try {
12
+ const info = lstatSync(file);
13
+ if (info.isSymbolicLink() || !info.isFile() || info.size > 1_048_576) throw new Error("Invalid registry file");
14
+ doc = JSON.parse(readFileSync(file, "utf8"));
15
+ } catch { throw new Error("Cannot read bot registry JSON"); }
11
16
  const object = (x: any) => x && typeof x === "object" && !Array.isArray(x);
12
17
  const fields = (x: any, keys: string[]) => {
13
- if (!object(x) || Object.keys(x).some(k => !keys.includes(k))) throw new Error("Unknown or invalid bot registry field");
18
+ if (!object(x) || Object.getOwnPropertyNames(x).some(k => !keys.includes(k))) throw new Error("Unknown or invalid bot registry field");
14
19
  };
15
- const text = (x: unknown): x is string => typeof x === "string" && x.trim().length > 0;
20
+ const text = (x: unknown): x is string => typeof x === "string" && x.trim().length > 0 && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(x);
21
+ const reserved = (s: string) => ["__proto__", "constructor", "prototype"].includes(s.toLowerCase());
16
22
  fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
17
- if (doc.version !== 1 || !Array.isArray(doc.bots)) throw new Error("Registry requires version 1 and bots array");
23
+ if (doc.version !== 1 || !Array.isArray(doc.bots) || doc.bots.length > 128) throw new Error("Registry requires version 1 and bots array");
18
24
  for (const k of ["default_workdir", "codex_bin"]) if (doc[k] !== undefined && !text(doc[k])) throw new Error(`Invalid ${k}`);
19
- const path = (value: string) => value.startsWith("~/") ? join(home, value.slice(2)) : isAbsolute(value) ? value : resolve(dirname(file), value);
25
+ const path = (value: string) => /^~[\\/]/.test(value) ? join(home, value.slice(2)) : isAbsolute(value) ? value : resolve(dirname(file), value);
20
26
  const defaultDir = doc.default_workdir ? path(doc.default_workdir) : join(home, ".agentschat/workspace");
21
27
  const names = new Set<string>(), identities = new Set<string>();
22
28
  const bots: BotConfig[] = [];
23
29
  for (const bot of doc.bots) {
24
30
  fields(bot, ["name", "profile", "workdir", "enabled", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
25
- if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || names.has(bot.name)) throw new Error("Bot names must be unique simple labels");
31
+ if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || reserved(bot.name) || names.has(bot.name)) throw new Error("Bot names must be unique simple labels");
26
32
  names.add(bot.name);
27
33
  if (bot.enabled !== undefined && typeof bot.enabled !== "boolean") throw new Error("Invalid bot enabled flag");
28
34
  if (bot.enabled === false) continue;
29
35
  if (!text(bot.profile) || (bot.workdir !== undefined && !text(bot.workdir))) throw new Error(`Bot ${bot.name} needs a profile and valid optional workdir`);
30
36
  // Registry profiles are named, centrally stored identities, not project-relative files.
31
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile)) throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
32
- if (!doc.default_workdir && !bot.workdir) mkdirSync(defaultDir, { recursive: true, mode: 0o700 });
33
- const cwd = realpathSync(bot.workdir ? path(bot.workdir) : defaultDir);
37
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile) || bot.profile.includes("..") ||
38
+ reservedProfileStem(bot.profile)) {
39
+ throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
40
+ }
41
+ const directoryLeaf = (dir: string) => {
42
+ const info = lstatSync(dir, { throwIfNoEntry: false });
43
+ if (info && (info.isSymbolicLink() || !info.isDirectory())) throw new Error("Bot workdir must be a directory, not a symlink");
44
+ assertDirectoryAncestors(dir);
45
+ };
46
+ if (!doc.default_workdir && !bot.workdir) {
47
+ directoryLeaf(join(home, ".agentschat"));
48
+ directoryLeaf(defaultDir);
49
+ mkdirSync(defaultDir, { recursive: true, mode: 0o700 });
50
+ }
51
+ const workdir = bot.workdir ? path(bot.workdir) : defaultDir;
52
+ directoryLeaf(workdir);
53
+ const cwd = realpathSync(workdir);
34
54
  const settings: IdentitySettings = {};
35
55
  for (const k of ["agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "codex_home_mode"] as const) if (bot[k] !== undefined) (settings as any)[k] = bot[k];
36
56
  if (bot.state_root !== undefined) { if (!text(bot.state_root)) throw new Error("Invalid state_root"); settings.state_root = path(bot.state_root); }
package/codex/bridge.ts CHANGED
@@ -1,14 +1,17 @@
1
1
  import { ThreadBusyError } from "./app-server.ts";
2
2
  import { TEAM_LEAD_SKILL_ID, TEAM_LEAD_SKILL_BODY, TEAM_LEAD_NO_UPDATE, isTeamLeadSkillInvocation } from "../src/team-lead-skill.ts";
3
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, openSync, closeSync, unlinkSync } from "node:fs";
3
+ import { lstatSync, mkdirSync, readFileSync, writeFileSync, openSync, closeSync, unlinkSync } from "node:fs";
4
4
  import { join } from "node:path";
5
+ import { randomBytes } from "node:crypto";
5
6
  import { priorChannelThreads, preserveChannelHistory, type ThreadHistory } from "./thread-history.ts";
7
+ import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
6
8
  import type { BridgeConfig, PermissionMode } from "./config.ts";
7
9
  import { redactSecrets } from "../src/redact.ts";
8
10
  import { authorizedLoopTick, verifyLoopTick, type LoopTick } from "./loop-grants.ts";
9
- import { acquireAgentLock, isPidAlive, releaseAgentLock, resolveLockDir } from "../src/session-bind.ts";
11
+ import { acquireAgentLock, checkAgentLock, isPidAlive, releaseAgentLock, resolveLockDir } from "../src/session-bind.ts";
10
12
 
11
- export interface ChatMessage { id: string; channel_id: string; sender_id: string; content: string; mentions?: string[]; mentioned_ids?: string[]; meta?: LoopTick }
13
+ export const MAX_BRIDGE_TERMINAL_ENTRIES = 500;
14
+ export interface ChatMessage { id: string; channel_id: string; sender_id: string; content: string; mentions?: string[]; mentioned_ids?: string[]; parent_id?: string; reply_to?: string; meta?: LoopTick }
12
15
  interface Entry { message: ChatMessage; status: "pending" | "running" | "ready" | "sending" | "sent" | "failed" | "uncertain" | "blocked" | "skipped"; answer?: string; error?: string }
13
16
  interface ChannelThread { thread: string; namespace?: string; bootstrap?: string; importedThreads?: string[] }
14
17
  interface State { version: 1; threads: Record<string, string>; channels?: Record<string, ChannelThread>; entries: Entry[] }
@@ -17,15 +20,37 @@ function permitted(m: ChatMessage, c: BridgeConfig) {
17
20
  if (m.meta?.kind === "loop_tick") return authorizedLoopTick(m, c) !== null;
18
21
  return (!c.channels.length || c.channels.includes(m.channel_id)) && (!c.senders.length || c.senders.includes(m.sender_id));
19
22
  }
23
+ const isPrototypeKey = (key: string) => /^(?:__proto__|constructor|prototype)$/i.test(key);
24
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
25
+ return value !== null && typeof value === "object" &&
26
+ (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
27
+ }
28
+ function safeMessageId(value: unknown): value is string {
29
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value &&
30
+ value !== "." && value !== ".." && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) &&
31
+ !/%(?:2e%2e|2f|5c|00)/i.test(value) && !isPrototypeKey(value);
32
+ }
33
+ function validMentions(value: unknown): boolean {
34
+ return value === undefined || (Array.isArray(value) && value.length <= 128 && [...value].every(id => typeof id === "string"));
35
+ }
36
+ function checkStateDir(dir: string, allowMissing = false) {
37
+ try {
38
+ const stat = lstatSync(dir);
39
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("Unsafe bridge state directory");
40
+ } catch (error: any) { if (!allowMissing || error.code !== "ENOENT") throw error; }
41
+ assertDirectoryAncestors(dir);
42
+ }
43
+ const entryStatuses = new Set<Entry["status"]>(["pending", "running", "ready", "sending", "sent", "failed", "uncertain", "blocked", "skipped"]);
20
44
  export function addressed(m: any, c: BridgeConfig): m is ChatMessage {
21
- if (!m || ["id", "channel_id", "sender_id", "content"].some(k => typeof m[k] !== "string" || !m[k].trim())) return false;
45
+ if (!isPlainObject(m as unknown) || Object.prototype.hasOwnProperty.call(m, "__proto__") || ["id", "channel_id", "sender_id", "content"].some(k => typeof m[k] !== "string" || !m[k].trim())) return false;
46
+ if (![m.id, m.channel_id, m.sender_id].every(safeMessageId) || !validMentions(m.mentions) || !validMentions(m.mentioned_ids)) return false;
22
47
  if (m.content === "__typing__" || m.content.length > 32_000) return false;
23
48
  if (["slash_input", "loop_status", "slash_response"].includes(m.meta?.kind)) return false;
24
49
  if (m.meta?.kind === "loop_tick") return authorizedLoopTick(m, c) !== null;
25
50
  if (m.sender_id === c.agentId) return false;
26
51
  if (!permitted(m, c)) return false;
27
52
  const escaped = c.agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
- return m.channel_id.startsWith("dm-") || [m.mentions, m.mentioned_ids].some(a => Array.isArray(a) && a.includes(c.agentId)) ||
53
+ return /^dm[-:]/i.test(m.channel_id) || [m.mentions, m.mentioned_ids].some(a => Array.isArray(a) && a.includes(c.agentId)) ||
29
54
  new RegExp(`@${escaped}(?![\\w-])|@[^\\n(]+\\(${escaped}\\)`).test(m.content);
30
55
  }
31
56
  export class Bridge {
@@ -41,35 +66,98 @@ export class Bridge {
41
66
  private activity: (channel: string, active: boolean) => void = () => {},
42
67
  private owner: () => Promise<string | null> = async () => null,
43
68
  private loops: () => Promise<unknown> = async () => null) {
69
+ checkStateDir(config.stateDir, true);
44
70
  mkdirSync(config.stateDir, { recursive: true, mode: 0o700 });
71
+ checkStateDir(config.stateDir);
45
72
  this.file = join(config.stateDir, "state.json"); this.lock = join(config.stateDir, "bridge.lock");
46
- if (existsSync(this.lock)) {
47
- try {
48
- const holderPid = Number(readFileSync(this.lock, "utf8").trim());
49
- if (holderPid > 0 && !isPidAlive(holderPid)) unlinkSync(this.lock);
50
- } catch {}
51
- }
73
+ try {
74
+ const stat = lstatSync(this.lock);
75
+ if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024) {
76
+ const content = readFileSync(this.lock, "utf8");
77
+ const holderPid = /^\d+$/.test(content) && content.trim() === content ? Number(content) : NaN;
78
+ if (!Number.isSafeInteger(holderPid) || holderPid <= 0 || !isPidAlive(holderPid)) unlinkSync(this.lock);
79
+ }
80
+ } catch {}
52
81
  try { const fd = openSync(this.lock, "wx", 0o600); writeFileSync(fd, String(process.pid)); closeSync(fd); }
53
82
  catch { throw new Error(`Bridge already locked: ${this.lock}. If its process has exited, remove that lock manually.`); }
54
83
  const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
55
- acquireAgentLock({
56
- lockDir: resolveLockDir(homeDir, process.env),
57
- agentId: config.agentId,
58
- runtime: "codex-bridge",
59
- });
84
+ const lockDir = resolveLockDir(homeDir, process.env);
60
85
  try {
61
- this.state = existsSync(this.file) ? JSON.parse(readFileSync(this.file, "utf8")) : { version: 1, threads: {}, entries: [] };
62
- if (this.state.version !== 1 || !this.state.threads || !Array.isArray(this.state.entries)) throw new Error("Invalid bridge state");
86
+ let hasState = false;
87
+ try {
88
+ const stat = lstatSync(this.file);
89
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024) throw new Error("Unsafe bridge state");
90
+ hasState = true;
91
+ } catch (error: any) { if (error.code !== "ENOENT") throw error; }
92
+ this.state = hasState ? JSON.parse(readFileSync(this.file, "utf8")) : { version: 1, threads: {}, entries: [] };
93
+ if (this.state?.version !== 1 || Object.prototype.hasOwnProperty.call(this.state, "__proto__") || !isPlainObject(this.state.threads) || !Array.isArray(this.state.entries) ||
94
+ (Object.prototype.hasOwnProperty.call(this.state, "channels") && !isPlainObject(this.state.channels))) throw new Error("Invalid bridge state");
63
95
  for (const e of this.state.entries) {
96
+ if (!isPlainObject(e) || Object.prototype.hasOwnProperty.call(e, "__proto__") || !entryStatuses.has(e.status as Entry["status"]) || !isPlainObject(e.message) || Object.prototype.hasOwnProperty.call(e.message, "__proto__") ||
97
+ ![e.message.id, e.message.channel_id, e.message.sender_id].every(safeMessageId) || typeof e.message.content !== "string" ||
98
+ !validMentions(e.message.mentions) || !validMentions(e.message.mentioned_ids)) throw new Error("Invalid bridge entry");
64
99
  if (e.status === "sending") e.status = "uncertain";
65
100
  if (e.status === "running") e.status = "failed";
66
101
  }
67
102
  this.save();
68
- } catch { unlinkSync(this.lock); throw new Error("Cannot load bridge state; refusing to discard history"); }
103
+ } catch {
104
+ try { unlinkSync(this.lock); } catch {}
105
+ throw new Error("Cannot load bridge state; refusing to discard history");
106
+ }
107
+ try {
108
+ const existingLock = checkAgentLock({ lockDir, agentId: config.agentId });
109
+ if (existingLock.locked) {
110
+ throw new Error(
111
+ `Agent identity ${config.agentId} is already locked by live process ${existingLock.holder?.pid ?? "unknown"} (${existingLock.holder?.runtime ?? "unknown"})`,
112
+ );
113
+ }
114
+ if (
115
+ !acquireAgentLock({
116
+ lockDir,
117
+ agentId: config.agentId,
118
+ runtime: "codex-bridge",
119
+ })
120
+ ) {
121
+ throw new Error(`Cannot acquire agent lock for ${config.agentId}`);
122
+ }
123
+ } catch (err) {
124
+ try { unlinkSync(this.lock); } catch {}
125
+ throw err;
126
+ }
69
127
  }
70
128
  private save() {
71
- const tmp = this.file + ".tmp";
72
- writeFileSync(tmp, JSON.stringify(this.state), { mode: 0o600 }); renameSync(tmp, this.file);
129
+ const isTerminal = (status: Entry["status"]) =>
130
+ status === "sent" || status === "skipped" || status === "blocked";
131
+ let terminalCount = 0;
132
+ for (const entry of this.state.entries) {
133
+ if (isTerminal(entry.status)) terminalCount++;
134
+ }
135
+ if (terminalCount > MAX_BRIDGE_TERMINAL_ENTRIES) {
136
+ let dropRemaining = terminalCount - MAX_BRIDGE_TERMINAL_ENTRIES;
137
+ this.state.entries = this.state.entries.filter((entry) => {
138
+ if (dropRemaining > 0 && isTerminal(entry.status)) {
139
+ dropRemaining--;
140
+ return false;
141
+ }
142
+ return true;
143
+ });
144
+ }
145
+ const tmp = `${this.file}.tmp.${process.pid}.${Date.now()}.${randomBytes(16).toString("hex")}`;
146
+ try {
147
+ const serialized = JSON.stringify(this.state);
148
+ checkStateDir(this.config.stateDir);
149
+ writeFileSync(tmp, serialized, { mode: 0o600, flag: "wx" });
150
+ atomicReplaceRegularFile(tmp, this.file, () => {
151
+ try {
152
+ const stat = lstatSync(this.file);
153
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("Bridge state must not be a symlink");
154
+ } catch (error: any) { if (error.code !== "ENOENT") throw error; }
155
+ checkStateDir(this.config.stateDir);
156
+ });
157
+ } catch (err) {
158
+ try { unlinkSync(tmp); } catch {}
159
+ throw err;
160
+ }
73
161
  }
74
162
  accept(raw: unknown): boolean {
75
163
  if (this.stopped || !addressed(raw, this.config)) return false;
@@ -84,13 +172,15 @@ export class Bridge {
84
172
  const message: ChatMessage = { id: raw.id, channel_id: raw.channel_id, sender_id: raw.sender_id,
85
173
  ...(Array.isArray(raw.mentioned_ids) ? { mentioned_ids: raw.mentioned_ids.filter((id: unknown) => typeof id === "string") } : {}),
86
174
  ...(Array.isArray(raw.mentions) ? { mentions: raw.mentions.filter((id: unknown) => typeof id === "string") } : {}),
175
+ ...(!tick && typeof raw.parent_id === "string" && safeMessageId(raw.parent_id.trim()) ? { parent_id: raw.parent_id.trim() } : {}),
176
+ ...(!tick && typeof raw.reply_to === "string" && safeMessageId(raw.reply_to.trim()) ? { reply_to: raw.reply_to.trim() } : {}),
87
177
  content: tick ? "Authorized scheduled loop" : this.redact(raw.content),
88
178
  ...(tick ? { meta: { kind: "loop_tick", loop_id: tick.loop_id, interval_ms: tick.interval_ms,
89
179
  next_tick_ms: tick.next_tick_ms, prompt: tick.prompt } as LoopTick } : {}) };
90
180
  this.state.entries.push({ message, status: "pending" }); this.save();
91
181
  void this.drain(); return true;
92
182
  }
93
- redact(text: string) { return redactSecrets(text.split(this.config.token).join("[REDACTED]")); }
183
+ redact(text: string) { return redactSecrets(this.config.token ? text.split(this.config.token).join("[REDACTED]") : text); }
94
184
  /** History cursors may advance past ignored/known messages, never a full inbox. */
95
185
  recover(raw: unknown): boolean {
96
186
  if (this.stopped) return false;
@@ -108,8 +198,9 @@ export class Bridge {
108
198
  }
109
199
  /** Can be called while idle to migrate existing channels without sending messages. */
110
200
  async prepareChannel(chat: string): Promise<ChannelThread> {
201
+ if (!safeMessageId(chat)) throw new Error("Invalid channel ID");
111
202
  this.state.channels ??= {};
112
- let channel = this.state.channels[chat];
203
+ let channel = Object.prototype.hasOwnProperty.call(this.state.channels, chat) ? this.state.channels[chat] : undefined;
113
204
  if (!this.loaded.has(chat)) {
114
205
  const namespace = this.codex.namespace;
115
206
  if (channel?.namespace && channel.namespace !== namespace)
@@ -181,7 +272,10 @@ export class Bridge {
181
272
  if (error instanceof ThreadBusyError) {
182
273
  e.status = "pending"; e.error = error.message; this.save();
183
274
  this.log("Conversation in use; queued message will resume in the same task");
184
- if (!this.stopped) this.retry = setTimeout(() => { this.retry = undefined; void this.drain(); }, 5000);
275
+ if (!this.stopped) {
276
+ this.retry = setTimeout(() => { this.retry = undefined; void this.drain(); }, 5000);
277
+ this.retry.unref?.();
278
+ }
185
279
  return;
186
280
  }
187
281
  e.error = this.redact(error instanceof Error ? error.message : "Bridge operation failed").slice(0, 240);
@@ -194,7 +288,11 @@ export class Bridge {
194
288
  async stop() {
195
289
  this.pause();
196
290
  await this.draining;
197
- if (existsSync(this.lock)) unlinkSync(this.lock);
291
+ try {
292
+ const stat = lstatSync(this.lock);
293
+ if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 &&
294
+ readFileSync(this.lock, "utf8") === String(process.pid)) unlinkSync(this.lock);
295
+ } catch (error: any) { if (error.code !== "ENOENT") throw error; }
198
296
  const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
199
297
  releaseAgentLock({ lockDir: resolveLockDir(homeDir, process.env), agentId: this.config.agentId });
200
298
  }