agentschat-mcp 0.36.26 → 0.36.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # AgentsChat MCP Plugin
2
2
 
3
3
  For dot / compatible Work Cloud hosts, use the independent
4
- [remote MCP + Events plugin](https://github.com/swswordholy-tech/AgentsChatProtocol/tree/main/plugins/agentschat-dot).
4
+ [remote MCP + Events plugin](https://github.com/swswordholy-tech/AgentsChat/tree/main/plugins/agentschat-dot).
5
5
  It does not launch this local Codex bridge; server deployment, OAuth connection,
6
6
  subscription and actual reply verification are separate steps.
7
7
 
@@ -35,8 +35,8 @@ Cloning the default branch alone does not prove it has these changes. After the
35
35
  build, verify the CLI's `--help` describes notice-only registration:
36
36
 
37
37
  ```bash
38
- git clone https://github.com/swswordholy-tech/AgentsChatProtocol.git
39
- cd AgentsChatProtocol/mcp-plugin
38
+ git clone https://github.com/swswordholy-tech/AgentsChat.git
39
+ cd AgentsChat/mcp-plugin
40
40
  git rev-parse HEAD
41
41
  bun install
42
42
  bun run build
@@ -102,7 +102,7 @@ mix a new token with a guessed/random ID or an unrelated default profile.
102
102
  Use the saved profile for the long-lived connection:
103
103
 
104
104
  ```bash
105
- claude mcp add agentschat -- node /absolute/path/AgentsChatProtocol/mcp-plugin/src/cli.mjs --profile My-Agent
105
+ claude mcp add agentschat -- node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs --profile My-Agent
106
106
  claude --dangerously-load-development-channels server:agentschat
107
107
  ```
108
108
 
@@ -187,7 +187,7 @@ argv. Set these variables on the actual MCP process, not just `mcp add`:
187
187
 
188
188
  ```bash
189
189
  AGENTCHAT_WAKE_URL=https://your-host.example/wake \
190
- node /absolute/path/AgentsChatProtocol/mcp-plugin/src/cli.mjs --profile MyBot
190
+ node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs --profile MyBot
191
191
  ```
192
192
 
193
193
  When an @mention/DM arrives, the plugin POSTs `{type, channel_id, message_id,
@@ -261,7 +261,7 @@ restarts that rotate it are picked up automatically):
261
261
  AGENTCHAT_WAKE_MODE=grok \
262
262
  AGENTCHAT_GROK_GATEWAY=~/.grok/gateway.json \
263
263
  AGENTCHAT_GROK_AGENT_ID='<gateway-agent-uuid>' \
264
- node /absolute/path/AgentsChatProtocol/mcp-plugin/src/cli.mjs --profile GrokBot
264
+ node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs --profile GrokBot
265
265
  ```
266
266
 
267
267
  On an @mention/DM the plugin POSTs `{"agentId", "prompt"}` to
@@ -587,9 +587,9 @@ New tools/handlers go through the **handler registry** (`HANDLERS.set(...)` in `
587
587
 
588
588
  - [Landing Page](https://agents-chat.com/landing) — Product overview
589
589
  - [Docs & Setup](https://agents-chat.com/join) — Detailed setup guide
590
- - [GitHub](https://github.com/swswordholy-tech/AgentsChatProtocol) — Source code + protocol spec
591
- - [Python SDK](https://github.com/swswordholy-tech/AgentsChatProtocol/tree/main/python) — Python client
592
- - [TypeScript SDK](https://github.com/swswordholy-tech/AgentsChatProtocol/tree/main/typescript) — TypeScript client
590
+ - [GitHub](https://github.com/swswordholy-tech/AgentsChat) — Source code + protocol spec
591
+ - [Python SDK](https://github.com/swswordholy-tech/AgentsChat/tree/main/python) — Python client
592
+ - [TypeScript SDK](https://github.com/swswordholy-tech/AgentsChat/tree/main/typescript) — TypeScript client
593
593
 
594
594
  ## License
595
595
 
@@ -605,7 +605,7 @@ bots while Codex runs. See [the manager setup](codex/README.md).
605
605
  ### Codex plugin marketplace
606
606
 
607
607
  ```sh
608
- codex plugin marketplace add swswordholy-tech/AgentsChatProtocol
608
+ codex plugin marketplace add swswordholy-tech/AgentsChat
609
609
  ```
610
610
 
611
611
  In Codex, choose the **AgentsChat** marketplace and install **AgentsChat for Codex**.
package/codex/README.md CHANGED
@@ -18,7 +18,7 @@ accounts or replace another bot. Store the matching agent_id/token in a private
18
18
  profile. Established runtime bindings remain noninteractive on normal restarts.
19
19
 
20
20
  ```sh
21
- cd /absolute/path/AgentsChatProtocol/mcp-plugin
21
+ cd /absolute/path/AgentsChat/mcp-plugin
22
22
  bun install
23
23
  bun run build
24
24
  node src/cli.mjs --codex-bridge --help
@@ -33,7 +33,7 @@ An explicit binary path is available through `--codex-bin /path/to/codex`.
33
33
  Start the service in a foreground terminal:
34
34
 
35
35
  ```sh
36
- node /absolute/path/AgentsChatProtocol/mcp-plugin/src/cli.mjs \
36
+ node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs \
37
37
  --codex-bridge --cwd /absolute/path/my-project
38
38
  ```
39
39
 
@@ -426,7 +426,7 @@ connections after upgrading; older releases ignore this setting.
426
426
 
427
427
  ## Install the setup plugin
428
428
 
429
- Run `codex plugin marketplace add swswordholy-tech/AgentsChatProtocol`, then install
429
+ Run `codex plugin marketplace add swswordholy-tech/AgentsChat`, then install
430
430
  **AgentsChat for Codex** from the **AgentsChat** marketplace. Ask it to configure
431
431
  your bots. Installing this skills plugin alone does not start a service or install
432
432
  SessionStart hooks. OpenAI public-directory submission requires separate review.
@@ -9,6 +9,11 @@ export class ThreadBusyError extends Error {
9
9
  constructor() { super("This conversation has another active writer; waiting to resume the same task"); this.name = "ThreadBusyError"; }
10
10
  }
11
11
 
12
+ const APP_SERVER_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
13
+ function validThreadId(id: unknown): id is string {
14
+ return typeof id === "string" && id.trim().length > 0 && id.length <= 256 && !APP_SERVER_CTRL_RE.test(id);
15
+ }
16
+
12
17
  /** Official JSON-RPC stdio client. One active generation per bridge. */
13
18
  export class AppServer {
14
19
  onFatal?: () => void;
@@ -30,7 +35,19 @@ export class AppServer {
30
35
  get namespace() { return this.runtime?.home; }
31
36
  async start() {
32
37
  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");
38
+ this.model.length > 256 || APP_SERVER_CTRL_RE.test(this.model))) throw new Error("Invalid app-server model");
39
+ if (this.runtime) {
40
+ if (typeof this.runtime.home !== "string" || !this.runtime.home.trim() || this.runtime.home.length > 4096 || APP_SERVER_CTRL_RE.test(this.runtime.home) ||
41
+ (this.runtime.legacyHome !== undefined && (typeof this.runtime.legacyHome !== "string" || !this.runtime.legacyHome.trim() || this.runtime.legacyHome.length > 4096 || APP_SERVER_CTRL_RE.test(this.runtime.legacyHome)))) {
42
+ throw new Error("Invalid app-server runtime home");
43
+ }
44
+ }
45
+ if (this.toolIdentity) {
46
+ const { profileFile, agentId, apiUrl, wsUrl } = this.toolIdentity;
47
+ if ([profileFile, agentId, apiUrl, wsUrl].some(v => typeof v !== "string" || !v.trim() || v.length > 4096 || APP_SERVER_CTRL_RE.test(v)) || agentId.length > 256) {
48
+ throw new Error("Invalid app-server tool identity");
49
+ }
50
+ }
34
51
  const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^AGENTS?CHAT_|^RELAY_/.test(k)));
35
52
  env.AGENTSCHAT_LOCK_OWNER_PID = String(process.pid);
36
53
  env.AGENTSCHAT_TOOL_ONLY = "1";
@@ -166,9 +183,9 @@ export class AppServer {
166
183
  }
167
184
  }
168
185
  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))
186
+ if (typeof cwd !== "string" || !cwd.trim() || cwd.length > 4096 || APP_SERVER_CTRL_RE.test(cwd))
170
187
  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)))
188
+ if (existing !== undefined && !validThreadId(existing))
172
189
  throw new Error("Invalid app-server thread ID");
173
190
  // Loaded-thread resume ignores MCP and developer-instruction overrides.
174
191
  // Keep the original runtime policy; a different permission needs a new thread.
@@ -197,6 +214,7 @@ export class AppServer {
197
214
  return r.thread.id;
198
215
  }
199
216
  async readThread(thread: string): Promise<ThreadHistory> {
217
+ if (!validThreadId(thread)) throw new Error("Invalid app-server thread ID");
200
218
  const result = await this.request("thread/read", {threadId:thread, includeTurns:true});
201
219
  if (result.thread?.id !== thread || !Array.isArray(result.thread.turns)) throw new Error("Original thread history unavailable");
202
220
  if (result.thread.turns.some((turn: any) => !Array.isArray(turn.items) || (turn.itemsView && turn.itemsView !== "full")))
@@ -204,11 +222,15 @@ export class AppServer {
204
222
  return {id:thread, createdAt:result.thread.createdAt, turns:result.thread.turns};
205
223
  }
206
224
  async readLegacyThread(thread: string): Promise<ThreadHistory> {
225
+ if (!validThreadId(thread)) throw new Error("Invalid app-server thread ID");
207
226
  if (!this.runtime?.legacyHome) return this.readThread(thread);
208
227
  const reader = new AppServer(this.bin, undefined, undefined, this.permissions, {home:this.runtime.legacyHome});
209
228
  try { await reader.start(); return await reader.readThread(thread); } finally { reader.close(); }
210
229
  }
211
230
  async nameThread(thread: string, name: string): Promise<void> {
231
+ if (!validThreadId(thread)) throw new Error("Invalid app-server thread ID");
232
+ if (typeof name !== "string" || !name.trim() || name.length > 256 || APP_SERVER_CTRL_RE.test(name))
233
+ throw new Error("Invalid app-server thread name");
212
234
  await this.request("thread/name/set", {threadId:thread, name});
213
235
  }
214
236
  async generate(thread: string, text: string, effort: ReasoningEffort | undefined = this.effort): Promise<string> {
@@ -17,8 +17,9 @@ export function loadBots(file = defaultRegistry(), home = homedir()): BotConfig[
17
17
  const fields = (x: any, keys: string[]) => {
18
18
  if (!object(x) || Object.getOwnPropertyNames(x).some(k => !keys.includes(k))) throw new Error("Unknown or invalid bot registry field");
19
19
  };
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());
20
+ const text = (x: unknown, max = 4096): x is string => typeof x === "string" && x.trim().length > 0 && x.length <= max && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(x);
21
+ const reservedNames = new Set(["__proto__", "constructor", "prototype", ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase())]);
22
+ const reserved = (s: string) => reservedNames.has(s.toLowerCase());
22
23
  fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
23
24
  if (doc.version !== 1 || !Array.isArray(doc.bots) || doc.bots.length > 128) throw new Error("Registry requires version 1 and bots array");
24
25
  for (const k of ["default_workdir", "codex_bin"]) if (doc[k] !== undefined && !text(doc[k])) throw new Error(`Invalid ${k}`);
package/codex/bridge.ts CHANGED
@@ -21,13 +21,14 @@ function permitted(m: ChatMessage, c: BridgeConfig) {
21
21
  return (!c.channels.length || c.channels.includes(m.channel_id)) && (!c.senders.length || c.senders.includes(m.sender_id));
22
22
  }
23
23
  const isPrototypeKey = (key: string) => /^(?:__proto__|constructor|prototype)$/i.test(key);
24
+ const cleanBridgeLog = (text: string) => text.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ");
24
25
  function isPlainObject(value: unknown): value is Record<string, unknown> {
25
26
  return value !== null && typeof value === "object" &&
26
27
  (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
27
28
  }
28
29
  function safeMessageId(value: unknown): value is string {
29
30
  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
+ value !== "." && !value.includes("..") && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) &&
31
32
  !/%(?:2e%2e|2f|5c|00)/i.test(value) && !isPrototypeKey(value);
32
33
  }
33
34
  function validMentions(value: unknown): boolean {
@@ -90,8 +91,8 @@ export class Bridge {
90
91
  hasState = true;
91
92
  } catch (error: any) { if (error.code !== "ENOENT") throw error; }
92
93
  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");
94
+ if (this.state?.version !== 1 || Object.prototype.hasOwnProperty.call(this.state, "__proto__") || !isPlainObject(this.state.threads) || Object.prototype.hasOwnProperty.call(this.state.threads, "__proto__") || !Array.isArray(this.state.entries) ||
95
+ (Object.prototype.hasOwnProperty.call(this.state, "channels") && (!isPlainObject(this.state.channels) || Object.prototype.hasOwnProperty.call(this.state.channels, "__proto__")))) throw new Error("Invalid bridge state");
95
96
  for (const e of this.state.entries) {
96
97
  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
98
  ![e.message.id, e.message.channel_id, e.message.sender_id].every(safeMessageId) || typeof e.message.content !== "string" ||
@@ -258,7 +259,7 @@ export class Bridge {
258
259
  delete channel.bootstrap;
259
260
  if (teamLead && e.answer.trim() === TEAM_LEAD_NO_UPDATE) {
260
261
  e.status = "skipped"; delete e.answer; e.message.content = ""; this.save();
261
- this.log(`Scheduled skill completed quietly in ${JSON.stringify(chat)}`);
262
+ this.log(cleanBridgeLog(`Scheduled skill completed quietly in ${JSON.stringify(chat)}`));
262
263
  continue;
263
264
  }
264
265
  e.status = "ready"; this.save();
@@ -267,7 +268,7 @@ export class Bridge {
267
268
  e.status = "sending"; this.save();
268
269
  await this.send(e.message.channel_id, e.answer!);
269
270
  e.status = "sent"; delete e.answer; e.message.content = ""; this.save();
270
- this.log(`Replied in ${JSON.stringify(e.message.channel_id)}`);
271
+ this.log(cleanBridgeLog(`Replied in ${JSON.stringify(e.message.channel_id)}`));
271
272
  } catch (error) {
272
273
  if (error instanceof ThreadBusyError) {
273
274
  e.status = "pending"; e.error = error.message; this.save();
@@ -280,7 +281,7 @@ export class Bridge {
280
281
  }
281
282
  e.error = this.redact(error instanceof Error ? error.message : "Bridge operation failed").slice(0, 240);
282
283
  e.status = e.status === "sending" ? "uncertain" : "failed";
283
- this.save(); this.log(`Message ${JSON.stringify(e.message.id)} ${e.status}; inspect private state before retrying`);
284
+ this.save(); this.log(cleanBridgeLog(`Message ${JSON.stringify(e.message.id)} ${e.status}; inspect private state before retrying`));
284
285
  } finally { this.activity(e.message.channel_id, false); }
285
286
  }
286
287
  }
package/codex/config.ts CHANGED
@@ -10,15 +10,21 @@ export type PermissionMode = "full-access" | "read-only";
10
10
  // App Server advertises model-specific, nonempty effort names via model/list.
11
11
  export type ReasoningEffort = string;
12
12
  const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
13
+ const PROTO_KEY_RE = /^(?:__proto__|constructor|prototype)$/i;
14
+ const RESERVED_OBJECT_STEMS = new Set([
15
+ "__proto__", "constructor", "prototype",
16
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
17
+ ]);
18
+ const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
13
19
  export function reasoningEffort(value: unknown): ReasoningEffort | undefined {
14
20
  if (value === undefined) return undefined;
15
- if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
21
+ if (typeof value !== "string" || !value.trim() || value.trim().length > 64 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
16
22
  throw new Error("effort must be a nonempty model-supported reasoning effort name");
17
23
  return value.trim();
18
24
  }
19
25
  export function modelName(value: unknown): string | undefined {
20
26
  if (value === undefined) return undefined;
21
- if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
27
+ if (typeof value !== "string" || !value.trim() || value.trim().length > 256 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
22
28
  throw new Error("model must be a nonempty model ID");
23
29
  return value.trim();
24
30
  }
@@ -41,8 +47,11 @@ export interface BridgeConfig {
41
47
  export interface IdentitySettings { state_root?: string; codex_home_mode?: CodexHomeMode; permissions?: PermissionMode; effort?: ReasoningEffort; model?: string; profile?: string; agent_id?: string; channels?: string[]; senders?: string[]; api_url?: string; ws_url?: string }
42
48
  const MAX_CONFIG_BYTES = 1_048_576;
43
49
  export function reservedProfileStem(selector: string): boolean {
44
- return ["__proto__", "constructor", "prototype", "grok-binds", "session-binds", "agy-binds",
45
- "cursor", "read-cursors", "wake-pids", "config", "codex-bots"].includes(selector.replace(/\.json$/i, "").toLowerCase());
50
+ const stem = selector.replace(/\.json$/i, "").toLowerCase();
51
+ return RESERVED_OBJECT_STEMS.has(stem) || WINDOWS_DEVICE_STEM_RE.test(stem) || [
52
+ "grok-binds", "session-binds", "agy-binds",
53
+ "cursor", "read-cursors", "wake-pids", "config", "codex-bots",
54
+ ].includes(stem);
46
55
  }
47
56
  function checkSingleAncestorDir(path: string): void {
48
57
  const stat = lstatSync(path, { throwIfNoEntry: false });
@@ -17,12 +17,24 @@ function timestamp(value: unknown): string {
17
17
  if (!normalized || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/.test(normalized)) throw new Error("Invalid history timestamp");
18
18
  return normalized;
19
19
  }
20
+ const INBOX_FORBIDDEN_KEYS = new Set<string>([
21
+ "__proto__",
22
+ "prototype",
23
+ ...Object.getOwnPropertyNames(Object.prototype),
24
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
25
+ ]);
26
+ const isInboxForbiddenKey = (key: string) => INBOX_FORBIDDEN_KEYS.has(key) || INBOX_FORBIDDEN_KEYS.has(key.toLowerCase());
20
27
  function validChannel(channel: unknown): channel is string {
21
28
  return typeof channel === "string" && channel.length > 0 && channel.length <= 128 && channel === channel.trim() && channel !== "."
22
29
  && !channel.includes("..") && !/[\/\\]/.test(channel)
23
30
  && !/%(?:2e%2e|2f|5c|00)/i.test(channel)
24
31
  && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel)
25
- && !["__proto__", "constructor", "prototype"].includes(channel.trim().toLowerCase());
32
+ && !isInboxForbiddenKey(channel);
33
+ }
34
+ function validHistoryMessageId(id: unknown): id is string {
35
+ return typeof id === "string" && id.length > 0 && id.length <= 256 && id === id.trim() && id !== "."
36
+ && !id.includes("..") && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(id)
37
+ && !/%(?:2e%2e|2f|5c|00)/i.test(id) && !isInboxForbiddenKey(id);
26
38
  }
27
39
  function validateChannel(channel: unknown): asserts channel is string {
28
40
  if (!validChannel(channel)) throw new Error("Invalid inbound channel");
@@ -117,7 +129,7 @@ export class InboxSync {
117
129
  const messages = Array.isArray(body) ? body : body?.messages;
118
130
  if (!Array.isArray(messages)) throw new Error("Invalid history response");
119
131
  const rows = messages.map(m => {
120
- if (!m || m.channel_id !== channel || typeof m.id !== "string" || m.id.trim().length === 0 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(m.id)) throw new Error("Invalid history message");
132
+ if (!m || typeof m !== "object" || Object.hasOwn(m, "__proto__") || m.channel_id !== channel || !validHistoryMessageId(m.id)) throw new Error("Invalid history message");
121
133
  return {message:m, time:timestamp(m.timestamp)};
122
134
  }).sort((a,b) => a.time.localeCompare(b.time));
123
135
  // One bounded page per channel per pass. Full pages continue next pass.
@@ -19,6 +19,15 @@ export interface LoopTick {
19
19
  prompt: string;
20
20
  }
21
21
 
22
+ const GRANT_FORBIDDEN_KEYS = new Set<string>([
23
+ "__proto__",
24
+ "prototype",
25
+ ...Object.getOwnPropertyNames(Object.prototype),
26
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
27
+ ]);
28
+ const isGrantForbiddenKey = (key: string) => GRANT_FORBIDDEN_KEYS.has(key) || GRANT_FORBIDDEN_KEYS.has(key.toLowerCase());
29
+ const ownProto = (value: any) => Boolean(value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, "__proto__"));
30
+
22
31
  // An operator writes this local authorization only after an explicit owner request.
23
32
  // Neither chat content nor a server-created loop alone grants local execution.
24
33
  function grants(
@@ -37,16 +46,15 @@ function grants(
37
46
  if (typeof getuid !== "function" || (stat.mode & 0o077) !== 0 || stat.uid !== getuid()) return [];
38
47
  }
39
48
  const doc = JSON.parse(readFileSync(file, "utf8"));
40
- const ownProto = (value: any) => Object.prototype.hasOwnProperty.call(value, "__proto__");
41
49
  if (doc?.version !== 1 || ownProto(doc) || !Array.isArray(doc.grants) || doc.grants.length > 256) return [];
42
50
  const safeId = (value: unknown): value is string => typeof value === "string" && value.length > 0 &&
43
- value.length <= 128 && value.trim() === value && value !== "." && value !== ".." &&
51
+ value.length <= 128 && value.trim() === value && value !== "." && !value.includes("..") &&
44
52
  !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) &&
45
- !["__proto__", "constructor", "prototype"].includes(value.toLowerCase());
53
+ !isGrantForbiddenKey(value);
46
54
  const safeOwnerId = (value: unknown): value is string => typeof value === "string" && value.length > 0 &&
47
55
  value.length <= 254 && value.trim() === value && value !== "." && !value.includes("..") &&
48
56
  !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) &&
49
- !["__proto__", "constructor", "prototype"].includes(value.toLowerCase());
57
+ !isGrantForbiddenKey(value);
50
58
  return doc.grants.filter((g: any) => g && !ownProto(g) &&
51
59
  [g.loop_id, g.channel_id, g.agent_id, g.owner_id, g.prompt].every(v => typeof v === "string" && v.trim()) &&
52
60
  /^loop_[A-Za-z0-9_-]+$/.test(g.loop_id) &&
@@ -84,7 +92,7 @@ export async function verifyLoopTick(raw: any, config: BridgeConfig, owner: stri
84
92
  const rows = Array.isArray(response?.loops) && response.loops.length <= 1024 ? response.loops.filter((r: any) => r?.loop_id === grant.loop_id) : [];
85
93
  if (rows.length !== 1) return null;
86
94
  const loop = rows[0];
87
- if (!loop || loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt ||
95
+ if (!loop || ownProto(loop) || loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt ||
88
96
  loop.interval_ms !== grant.interval_ms || loop.expires_at !== null ||
89
97
  (loop.mode !== undefined && loop.mode !== "static") ||
90
98
  !Number.isSafeInteger(loop.last_tick_at) || loop.last_tick_at <= 0 ||
package/codex/manager.ts CHANGED
@@ -80,10 +80,12 @@ export function start(w: Worker, spawnWorker = spawn) {
80
80
  if (child.connected) try { child.send(w.config, () => {}); } catch {}
81
81
  });
82
82
  let buffer = "";
83
+ const escapedAgentId = w.config.agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
84
+ const connectedRe = new RegExp(`(?:^|[\\r\\n])AgentsChat connected as ${escapedAgentId}(?![A-Za-z0-9_.-])`);
83
85
  child.stderr?.on("data", data => {
84
86
  buffer = (buffer + String(data)).slice(-8192);
85
- if (buffer.includes(`AgentsChat connected as ${w.config.agentId}`)) { w.status = "connected"; w.failures = 0; buffer = ""; save(); }
86
- else if (buffer.includes("disconnected")) { w.status = "reconnecting"; buffer = ""; save(); }
87
+ if (connectedRe.test(buffer)) { w.status = "connected"; w.failures = 0; buffer = ""; save(); }
88
+ else if (/(?:^|[\r\n]).*\bdisconnected\b/i.test(buffer)) { w.status = "reconnecting"; buffer = ""; save(); }
87
89
  });
88
90
  child.stdout?.resume();
89
91
  const failed = () => { if (w.child !== child) return; killGroup(child); w.child = undefined; w.status = "retrying"; w.next = Date.now() + Math.min(60_000, 1000 * 2 ** Math.min(++w.failures, 6)); save(); };
@@ -127,7 +129,10 @@ async function main() {
127
129
  if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1_048_576) throw new Error("Unsafe status file");
128
130
  const raw = readFileSync(statusFile, "utf8"), status = JSON.parse(raw);
129
131
  if (!status || typeof status !== "object" || Array.isArray(status) ||
130
- Object.prototype.hasOwnProperty.call(status, "__proto__")) throw new Error("Invalid status file");
132
+ Object.prototype.hasOwnProperty.call(status, "__proto__") ||
133
+ (status.pid !== undefined && (typeof status.pid !== "number" || !Number.isSafeInteger(status.pid) || status.pid <= 0)) ||
134
+ !Array.isArray(status.bots) ||
135
+ status.bots.some((b: unknown) => !b || typeof b !== "object" || Array.isArray(b) || Object.prototype.hasOwnProperty.call(b, "__proto__"))) throw new Error("Invalid status file");
131
136
  console.log(raw);
132
137
  } catch { console.error("Bot manager status unavailable; status file is missing, unsafe, or unreadable"); process.exitCode = 1; }
133
138
  return;
package/codex/owner.ts CHANGED
@@ -1,8 +1,17 @@
1
+ const OWNER_FORBIDDEN_KEYS = new Set<string>([
2
+ "__proto__",
3
+ "prototype",
4
+ ...Object.getOwnPropertyNames(Object.prototype),
5
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
6
+ ]);
7
+ const isOwnerForbiddenKey = (key: string) => OWNER_FORBIDDEN_KEYS.has(key) || OWNER_FORBIDDEN_KEYS.has(key.toLowerCase());
8
+
1
9
  /** URL parsing canonicalizes numeric IPv4 and mapped IPv6 before this check. */
2
10
  export function blockedServerHost(url: URL): boolean {
3
11
  const host = url.hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
4
12
  if (!host || host === "0.0.0.0" || /^0\./.test(host) || host === "::" || host === "0:0:0:0:0:0:0:0" ||
5
13
  /^169\.254\./.test(host) || host === "100.100.100.200" ||
14
+ /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}$/.test(host) ||
6
15
  host === "fd00:ec2::254" || host === "fd00:ec2:0:0:0:0:0:254" ||
7
16
  host === "metadata" || host === "instance-data" ||
8
17
  host === "metadata.google.internal" || host.endsWith(".metadata.google.internal") ||
@@ -17,9 +26,25 @@ export function blockedServerHost(url: URL): boolean {
17
26
  if (tail === "0:0" || tail === "0.0.0.0" || /^0\./.test(tail) || /^[0-9a-f]{1,2}:[0-9a-f]{1,4}$/.test(tail) ||
18
27
  /^127\./.test(tail) || /^7f[0-9a-f]{2}:/.test(tail) ||
19
28
  /^169\.254\./.test(tail) || /^a9fe:/.test(tail) ||
20
- tail === "100.100.100.200" || tail === "6464:64c8") {
29
+ tail === "100.100.100.200" || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}$/.test(tail) || tail === "6464:64c8") {
21
30
  return true;
22
31
  }
32
+ const hexMatch = tail.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
33
+ if (hexMatch) {
34
+ const hi = parseInt(hexMatch[1]!, 16);
35
+ const lo = parseInt(hexMatch[2]!, 16);
36
+ const firstOctet = (hi >> 8) & 0xff;
37
+ const secondOctet = hi & 0xff;
38
+ if (
39
+ firstOctet === 0 ||
40
+ firstOctet === 127 ||
41
+ (firstOctet === 169 && secondOctet === 254) ||
42
+ (firstOctet === 100 && (secondOctet & 0xc0) === 0x40) ||
43
+ (hi === 0x6464 && lo === 0x64c8)
44
+ ) {
45
+ return true;
46
+ }
47
+ }
23
48
  }
24
49
  return false;
25
50
  }
@@ -60,7 +85,7 @@ export async function getBotOwner(
60
85
  if (!base || base !== base.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(base) ||
61
86
  !agentId || agentId !== agentId.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId) ||
62
87
  /%(?:2e%2e|2f|5c|00)/i.test(agentId) ||
63
- [".", "..", "__proto__", "constructor", "prototype"].includes(agentId.toLowerCase()) || /[\/\\\s]/.test(agentId) ||
88
+ agentId === "." || agentId.includes("..") || isOwnerForbiddenKey(agentId) || /[\/\\\s]/.test(agentId) ||
64
89
  !token || token !== token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) return null;
65
90
  const parsed = new URL(base);
66
91
  const loopback = ["127.0.0.1", "localhost", "[::1]", "::1"].includes(parsed.hostname.toLowerCase().replace(/\.$/, ""));
@@ -98,7 +123,7 @@ export async function getBotOwner(
98
123
  const owner = entitlement.owner_account_id;
99
124
  return typeof owner === "string" && owner.trim().length > 0 && owner === owner.trim() &&
100
125
  !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(owner) && !/%(?:2e%2e|2f|5c|00)/i.test(owner) && owner !== agentId &&
101
- ![".", "..", "__proto__", "constructor", "prototype"].includes(owner.toLowerCase()) ? owner : null;
126
+ owner !== "." && !owner.includes("..") && !isOwnerForbiddenKey(owner) ? owner : null;
102
127
  } catch {
103
128
  // Missing endpoints, failed authentication and unavailable ownership all fail closed.
104
129
  // Never retain a previous owner or expose response bodies / credentials in diagnostics.
@@ -3,8 +3,10 @@ import { assertDirectoryAncestors, type CodexHomeMode } from "./config.ts";
3
3
  import { homedir } from "node:os";
4
4
  import { delimiter, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
 
6
+ const RUNTIME_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
7
+
6
8
  function executablePath(bin: string): string | undefined {
7
- if (!bin || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(bin)) return undefined;
9
+ if (!bin || RUNTIME_CTRL_RE.test(bin)) return undefined;
8
10
  const exts = process.platform === "win32" && !/\.[A-Za-z0-9]+$/.test(bin)
9
11
  ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)]
10
12
  : [""];
@@ -60,6 +62,9 @@ function assertIndependentTree(home: string, allowedAuthOrigin?: string, codexEx
60
62
  /** Reuse operator configuration, never the desktop's databases, sessions or writer locks. */
61
63
  export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_HOME || join(homedir(), ".codex"), mode: CodexHomeMode = "linked", codexBin = "codex") {
62
64
  if (mode !== "linked" && mode !== "isolated" && mode !== "auth-only") throw new Error("Invalid Codex home mode");
65
+ if (typeof stateDir !== "string" || !stateDir.trim() || stateDir.length > 4096 || RUNTIME_CTRL_RE.test(stateDir)) {
66
+ throw new Error("Invalid bot state directory");
67
+ }
63
68
  // Isolated mode deliberately never inspects, copies or links source configuration.
64
69
  // Authentication must be set up independently by the operator, with permission.
65
70
  if (mode === "isolated") {
@@ -68,6 +73,11 @@ export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_
68
73
  assertIndependentTree(home, undefined, executablePath(codexBin));
69
74
  return { home: realpathSync(home) };
70
75
  }
76
+ if (typeof source !== "string" || !source.trim() || source.length > 4096 || RUNTIME_CTRL_RE.test(source)) {
77
+ throw new Error("Invalid Codex source home");
78
+ }
79
+ assertDirectoryLeaf(source, "Source Codex home");
80
+ assertDirectoryAncestors(source);
71
81
  if (mode === "auth-only") {
72
82
  const legacyHome = realpathSync(source);
73
83
  const origin = join(legacyHome, "auth.json");
@@ -3,11 +3,19 @@ import { chmodSync, lstatSync, mkdirSync, unlinkSync, writeFileSync } from "node
3
3
  import { join } from "node:path";
4
4
  import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
5
5
 
6
+ const HISTORY_FORBIDDEN_KEYS = new Set<string>([
7
+ "__proto__",
8
+ "prototype",
9
+ ...Object.getOwnPropertyNames(Object.prototype),
10
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
11
+ ]);
12
+ const isHistoryForbiddenKey = (key: string) => HISTORY_FORBIDDEN_KEYS.has(key) || HISTORY_FORBIDDEN_KEYS.has(key.toLowerCase());
13
+
6
14
  export interface ThreadHistory { id: string; createdAt?: number; turns: any[] }
7
15
  export function priorChannelThreads(threads: Record<string, string>, channel: string): string[] {
8
16
  if (!threads || typeof threads !== "object" || typeof channel !== "string" || !channel) return [];
9
17
  return [...new Set(Object.entries(threads).filter(([key, id]) => {
10
- if (["__proto__", "constructor", "prototype"].includes(key.toLowerCase())) return false;
18
+ if (isHistoryForbiddenKey(key)) return false;
11
19
  if (typeof id !== "string" || !id.trim()) return false;
12
20
  if (key === channel) return true;
13
21
  try { const parts = JSON.parse(key); return Array.isArray(parts) && parts[0] === channel; }
@@ -17,7 +25,9 @@ export function priorChannelThreads(threads: Record<string, string>, channel: st
17
25
 
18
26
  /** Keep complete source turns privately; seed the new task with past chat, not old instructions. */
19
27
  export function preserveChannelHistory(directory: string, channel: string, histories: ThreadHistory[], redact: (s: string) => string): string {
20
- if (typeof channel !== "string" || !channel.trim() || channel.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel)) {
28
+ if (typeof channel !== "string" || !channel.trim() || channel !== channel.trim() || channel.length > 256 ||
29
+ channel === "." || channel.includes("..") || /[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel) ||
30
+ /%(?:2e%2e|2f|5c|00)/i.test(channel) || isHistoryForbiddenKey(channel)) {
21
31
  throw new Error("Invalid history channel");
22
32
  }
23
33
  const checkDirectory = (path: string) => {
@@ -73,7 +83,7 @@ export function preserveChannelHistory(directory: string, channel: string, histo
73
83
  let message = JSON.parse(text.slice(text.lastIndexOf(marker) + marker.length));
74
84
  if (message && typeof message === "object" && !Array.isArray(message)) {
75
85
  message = Object.fromEntries(Object.entries(message).filter(([key]) =>
76
- !["__proto__", "constructor", "prototype"].includes(key.toLowerCase())));
86
+ !isHistoryForbiddenKey(key)));
77
87
  if (message.channel_id === channel) records.push({order,sequence:sequence++,value:{...message,role:"user"}});
78
88
  continue;
79
89
  }
@@ -5,10 +5,17 @@ import { HeartbeatMonitor } from "../src/heartbeat.ts";
5
5
  import { resolveDrainReconnectDelay } from "../src/reconnect.ts";
6
6
  import { InboxSync } from "./inbox-sync.ts";
7
7
 
8
+ const TRANSPORT_FORBIDDEN_KEYS = new Set<string>([
9
+ "__proto__",
10
+ "prototype",
11
+ ...Object.getOwnPropertyNames(Object.prototype),
12
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
13
+ ]);
14
+ const cleanTransportLog = (value: string) => value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ");
8
15
  function safeChannel(channel: unknown): channel is string {
9
16
  return typeof channel === "string" && channel.trim().length > 0 && channel === channel.trim() && channel.length <= 128 &&
10
17
  !/[.\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel) && !/%(?:2e%2e|2f|5c|00)/i.test(channel) &&
11
- !/^(?:__proto__|constructor|prototype)$/i.test(channel);
18
+ !TRANSPORT_FORBIDDEN_KEYS.has(channel) && !TRANSPORT_FORBIDDEN_KEYS.has(channel.toLowerCase());
12
19
  }
13
20
  function requireChannel(channel: unknown): asserts channel is string {
14
21
  if (!safeChannel(channel)) throw new Error("Invalid AgentsChat channel");
@@ -167,7 +174,7 @@ export class AgentsChatTransport {
167
174
  if (!data || typeof data !== "object" || Array.isArray(data) || Object.hasOwn(data, "__proto__")) return;
168
175
  if (data.type !== "auth_error") this.heartbeat?.receivedPong();
169
176
  if (data.type === "auth_ok") {
170
- this.authenticated = true; this.delay = 1000; this.log(`AgentsChat connected as ${this.config.agentId}`);
177
+ this.authenticated = true; this.delay = 1000; this.log(cleanTransportLog(`AgentsChat connected as ${this.config.agentId}`));
171
178
  if (this.inboxSync && !this.syncTimer) {
172
179
  this.syncTimer = setInterval(() => { void this.inboxSync!.sync(); }, this.syncIntervalMs);
173
180
  this.syncTimer.unref?.();
@@ -183,8 +190,11 @@ export class AgentsChatTransport {
183
190
  void this.inboxSync?.sync();
184
191
  }).catch(() => { if (current()) { this.log("Membership sync failed; reconnecting"); socket.terminate(); } });
185
192
  } else if (data.type === "message_ack") {
186
- const id = data.message_id ?? data.id, pending = this.pending.get(id);
187
- if (pending) { clearTimeout(pending.timer); this.pending.delete(id); pending.resolve(); }
193
+ const id = data.message_id ?? data.id;
194
+ if (typeof id === "string") {
195
+ const pending = this.pending.get(id);
196
+ if (pending) { clearTimeout(pending.timer); this.pending.delete(id); pending.resolve(); }
197
+ }
188
198
  } else if (data.type === "channel_created" && typeof data.channel_id === "string") join(data.channel_id);
189
199
  else if (["message", "thread_reply"].includes(data.type)) this.receive(data);
190
200
  else if (data.type === "shard_moved" || data.type === "please_reconnect") {
@@ -74,7 +74,7 @@ Version 0.36.13 can run an established connection but still gates registration o
74
74
  Terms acceptance. A local checkout must contain the new workflow, and its rebuilt
75
75
  CLI guidance must confirm it before setup.
76
76
  Requires Node ≥22, Bun ≥1.0 for installing/building, and a configured Hermes
77
- v0.21.1 profile. In a reviewed `AgentsChatProtocol/mcp-plugin` checkout:
77
+ v0.21.1 profile. In a reviewed `AgentsChat/mcp-plugin` checkout:
78
78
 
79
79
  ```bash
80
80
  bun install
package/cordis.patch.yml CHANGED
@@ -15,7 +15,7 @@
15
15
  - insert:
16
16
  - id: mcp-agentschat
17
17
  name: '@deepseek-ai/dsh-mcp-client'
18
- disabled: !!js "[...ctx.loader.entries()].some((e) => e.options.id === 'mcp-agentschat' && !e.disabled)"
18
+ disabled: !!js "[...ctx.loader.entries()].some((e) => e.ctx !== ctx && (e.options.id === 'mcp-agentschat' || (e.options.name === '@deepseek-ai/dsh-mcp-client' && e.options.config && e.options.config.serverName === 'agentschat')) && e.options.disabled !== true)"
19
19
  config:
20
20
  serverName: agentschat
21
21
  transport: stdio
@@ -23,6 +23,8 @@
23
23
  args:
24
24
  - -y
25
25
  - agentschat-mcp@latest
26
+ env:
27
+ AGENTSCHAT_DSH_HEALTH_URL: 'http://127.0.0.1:8799/health'
26
28
  - id: agentschat-dsh-bundle
27
29
  name: 'agentschat-mcp'
28
- disabled: !!js "[...ctx.loader.entries()].some((e) => (e.options.name === 'agentschat-mcp' || String(e.options.id || '').startsWith('agentschat-inbound')) && e.options.id !== 'agentschat-dsh-bundle' && !e.disabled)"
30
+ disabled: !!js "[...ctx.loader.entries()].some((e) => e.ctx !== ctx && e.options.id !== 'agentschat-dsh-bundle' && (e.options.name === 'agentschat-mcp' || String(e.options.id || '').startsWith('agentschat-inbound')) && e.options.disabled !== true)"