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.
@@ -35,7 +35,16 @@ export type Warn = (message: string) => void;
35
35
 
36
36
  const defaultWarn: Warn = (m) => process.stderr.write(m);
37
37
  const MAX_PROFILE_JSON_BYTES = 64 * 1024;
38
+ const MAX_PROFILE_PATH_LEN = 4096;
39
+ const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
38
40
  const CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g;
41
+ const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
42
+ const RESERVED_PROTO_STEMS = new Set([
43
+ "__proto__",
44
+ "constructor",
45
+ "prototype",
46
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
47
+ ]);
39
48
  const DARWIN_SYSTEM_SYMLINKS = new Set(["/var", "/tmp", "/etc"]);
40
49
 
41
50
  function sanitizeWarnPart(value: unknown): string {
@@ -43,7 +52,7 @@ function sanitizeWarnPart(value: unknown): string {
43
52
  .replace(/\b(https?:\/\/?)([^/\s@]*@)/gi, "$1[REDACTED]@")
44
53
  .replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]")
45
54
  .replace(
46
- /\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,
55
+ /(?:ac_|mcp_at_|mcp_rt_|mcp_|agent_key_|sk-|whsec_|rk_(?:live|test)_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|mr_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g,
47
56
  "[REDACTED]",
48
57
  )
49
58
  .replace(CONTROL_CHAR_GLOBAL_RE, "?");
@@ -114,6 +123,9 @@ function hasSafeAncestorDirs(targetPath: string): boolean {
114
123
  }
115
124
 
116
125
  export function safeWriteProfile(path: string, data: unknown, warn: Warn = defaultWarn): void {
126
+ if (typeof path !== "string" || !path || path.length > MAX_PROFILE_PATH_LEN || path.includes("\x00")) {
127
+ throw new Error(`Refusing to write profile into invalid path: ${sanitizeWarnPart(path)}`);
128
+ }
117
129
  const parentDir = dirname(path);
118
130
  const parentStat = safeLstat(parentDir);
119
131
  if (!parentStat || parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(path)) {
@@ -124,6 +136,9 @@ export function safeWriteProfile(path: string, data: unknown, warn: Warn = defau
124
136
  if (pathStat?.isSymbolicLink()) {
125
137
  throw new Error(`Refusing to write profile through symlink: ${sanitizeWarnPart(path)}`);
126
138
  }
139
+ if (pathStat && !pathStat.isFile() && !pathStat.isDirectory()) {
140
+ throw new Error(`Refusing to write profile into non-regular target: ${sanitizeWarnPart(path)}`);
141
+ }
127
142
 
128
143
  const tmp = path + ".tmp";
129
144
 
@@ -292,7 +307,14 @@ export function findDefaultProfileCollision(
292
307
  const candidatePath = join(dir, file);
293
308
  if (resolve(candidatePath) === resolvedDefault) continue;
294
309
  const baseName = file.replace(/\.json$/i, "");
295
- if (baseName.toLowerCase() === "profile") continue;
310
+ const baseLower = baseName.toLowerCase();
311
+ if (
312
+ baseLower === "profile" ||
313
+ RESERVED_PROTO_STEMS.has(baseLower) ||
314
+ WINDOWS_DEVICE_STEM_RE.test(baseName)
315
+ ) {
316
+ continue;
317
+ }
296
318
 
297
319
  const candStat = safeLstat(candidatePath);
298
320
  if (!candStat || candStat.isSymbolicLink() || !candStat.isFile() || candStat.size > MAX_PROFILE_JSON_BYTES) {
@@ -314,7 +336,9 @@ export function findDefaultProfileCollision(
314
336
  }
315
337
  const candAgentId = typeof candidate.agent_id === "string" ? candidate.agent_id.trim() : "";
316
338
  const candToken = typeof candidate.token === "string" ? candidate.token.trim() : "";
317
- if (!candAgentId || !candToken) continue;
339
+ if (!candAgentId || !candToken || CONTROL_CHAR_RE.test(candAgentId) || RESERVED_PROTO_STEMS.has(candAgentId.toLowerCase())) {
340
+ continue;
341
+ }
318
342
 
319
343
  if (defAgentId && candAgentId === defAgentId) {
320
344
  return { collidingName: baseName, collidingPath: candidatePath, reason: "agent_id" };
@@ -38,9 +38,20 @@ export interface PersistCursorFsOps {
38
38
 
39
39
  const MAX_CURSOR_BYTES = 4 * 1024 * 1024;
40
40
  const MAX_CURSOR_ENTRIES = 50_000;
41
- const RESERVED_PROTO_KEY = /^(?:__proto__|constructor|prototype)$/i;
41
+ const MAX_CURSOR_PATH_LEN = 4096;
42
+ const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
43
+ const RESERVED_PROTO_KEYS = new Set([
44
+ "__proto__",
45
+ "constructor",
46
+ "prototype",
47
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
48
+ ]);
42
49
  let tmpCounter = 0;
43
50
 
51
+ function isReservedCursorKey(key: string): boolean {
52
+ return RESERVED_PROTO_KEYS.has(key.toLowerCase());
53
+ }
54
+
44
55
  function scrubDiag(value: unknown): string {
45
56
  return redactSecrets(String(value ?? ""))
46
57
  .replace(/\b(https?:\/\/)([^/\s@]*@)/gi, "$1[REDACTED]@")
@@ -135,8 +146,17 @@ export function safeAgentCursorSlug(agentId: string): string {
135
146
  const cleaned = String(agentId || "")
136
147
  .trim()
137
148
  .replace(/[^A-Za-z0-9._-]/g, "_")
149
+ .replace(/\.+$/g, "")
138
150
  .slice(0, 128);
139
- if (!cleaned || cleaned === "." || cleaned === ".." || RESERVED_PROTO_KEY.test(cleaned)) return "_";
151
+ if (
152
+ !cleaned ||
153
+ cleaned === "." ||
154
+ cleaned.includes("..") ||
155
+ WINDOWS_DEVICE_STEM_RE.test(cleaned) ||
156
+ isReservedCursorKey(cleaned)
157
+ ) {
158
+ return "_";
159
+ }
140
160
  return cleaned;
141
161
  }
142
162
 
@@ -177,7 +197,7 @@ export function loadCursor(file: string, warn: Warn): Map<string, string> {
177
197
  }
178
198
  const entries: Array<[string, string]> = [];
179
199
  for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
180
- if (RESERVED_PROTO_KEY.test(k)) continue;
200
+ if (isReservedCursorKey(k)) continue;
181
201
  if (typeof v !== "string") {
182
202
  throw new Error(`cursor value for ${scrubDiag(k)} must be a string`);
183
203
  }
@@ -205,6 +225,10 @@ export function persistCursor(
205
225
  warn: Warn,
206
226
  fsOps?: PersistCursorFsOps,
207
227
  ): boolean {
228
+ if (typeof file !== "string" || !file || file.length > MAX_CURSOR_PATH_LEN || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(file)) {
229
+ warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: invalid cursor file path\n`);
230
+ return false;
231
+ }
208
232
  try {
209
233
  const parentStat = lstatSync(dirname(file));
210
234
  if (parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(file)) {
@@ -229,7 +253,7 @@ export function persistCursor(
229
253
  }
230
254
  const validEntries: Array<[string, string]> = [];
231
255
  for (const [k, v] of cursor) {
232
- if (!k || k.length > 256 || RESERVED_PROTO_KEY.test(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || typeof v !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
256
+ if (!k || k.length > 256 || isReservedCursorKey(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || typeof v !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
233
257
  continue;
234
258
  }
235
259
  validEntries.push([k, v]);
package/src/server.ts CHANGED
@@ -292,7 +292,7 @@ project/runtime binding or default profile is loaded; only when none exists and
292
292
  credentials are supplied does the server run ANONYMOUS (lists tools, no account).
293
293
 
294
294
  Profiles stored in: ~/.agentschat/ (legacy fallback: ~/.agentchat/)
295
- Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
295
+ Docs: https://github.com/swswordholy-tech/AgentsChat`);
296
296
  process.exit(0);
297
297
  }
298
298
 
@@ -81,6 +81,13 @@ const LOCK_KEY_MAX_CHARS = 128;
81
81
  const SESSION_BINDS_MAX_BYTES = 1024 * 1024;
82
82
  const MAX_SESSION_BINDS_ENTRIES = 1024;
83
83
  const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
84
+ const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
85
+ const UNSAFE_BIND_KEYS = new Set([
86
+ "__proto__",
87
+ "constructor",
88
+ "prototype",
89
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
90
+ ]);
84
91
  // NOTE: "profile" MUST NEVER be added here — `profile.json` is the default boot identity slot.
85
92
  const RESERVED_BIND_SIDECARS = new Set([
86
93
  "session-binds",
@@ -210,13 +217,21 @@ function isValidBindToken(value: string): boolean {
210
217
  }
211
218
 
212
219
  function isValidBoundProfileName(value: string): boolean {
213
- if (!isValidBindToken(value) || value === "." || value === ".." || value.includes("/") || value.includes("\\")) {
220
+ if (
221
+ !isValidBindToken(value) ||
222
+ value === "." ||
223
+ value.includes("..") ||
224
+ value.includes("/") ||
225
+ value.includes("\\")
226
+ ) {
214
227
  return false;
215
228
  }
216
- const stem = value.replace(/\.json$/i, "").toLowerCase();
229
+ const rawStem = value.replace(/\.json$/i, "");
230
+ const stem = rawStem.toLowerCase();
217
231
  const normalizedStem = stem.replace(/[^a-z0-9_-]/g, "_");
218
232
  return (
219
233
  Boolean(stem) &&
234
+ !WINDOWS_DEVICE_STEM_RE.test(rawStem) &&
220
235
  !isUnsafeBindKey(value) &&
221
236
  !isUnsafeBindKey(stem) &&
222
237
  !RESERVED_BIND_SIDECARS.has(stem) &&
@@ -361,8 +376,7 @@ export function releaseAgentLock(opts: {
361
376
  }
362
377
 
363
378
  function isUnsafeBindKey(key: string): boolean {
364
- const lower = key.toLowerCase();
365
- return lower === "__proto__" || lower === "constructor" || lower === "prototype";
379
+ return UNSAFE_BIND_KEYS.has(key.toLowerCase());
366
380
  }
367
381
 
368
382
  /** Parse a `session-binds.json` (or `agy-binds.json`) payload into `sessionId -> profileName`. */
@@ -405,13 +419,16 @@ export function loadSessionBinds(configDir: string): Record<string, string> {
405
419
  }
406
420
 
407
421
  function resolveAgentIdForProfileName(configDir: string, name: string): string | null {
408
- if (!name || name === "." || name === ".." || name.includes("/") || name.includes("\\") || CONTROL_CHAR_RE.test(name)) return null;
422
+ if (!name || name === "." || name.includes("..") || name.includes("/") || name.includes("\\") || CONTROL_CHAR_RE.test(name)) return null;
409
423
  if (!isSafeDirOrMissing(configDir)) return null;
410
- const stem = name.replace(/\.json$/i, "").toLowerCase();
411
- const base = name.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
424
+ const rawStem = name.replace(/\.json$/i, "");
425
+ const stem = rawStem.toLowerCase();
426
+ const base = rawStem.replace(/[^a-zA-Z0-9_-]/g, "_");
412
427
  if (
413
428
  !base ||
414
429
  base.length > LOCK_KEY_MAX_CHARS ||
430
+ WINDOWS_DEVICE_STEM_RE.test(rawStem) ||
431
+ WINDOWS_DEVICE_STEM_RE.test(base) ||
415
432
  isUnsafeBindKey(base) ||
416
433
  RESERVED_BIND_SIDECARS.has(stem) ||
417
434
  RESERVED_BIND_SIDECARS.has(base.toLowerCase())
@@ -523,7 +540,7 @@ export function findBoundSessionForProfile(
523
540
  }
524
541
 
525
542
  function isSafeDetectedSessionId(sid: string): boolean {
526
- return isValidBindToken(sid) && sid !== "." && sid !== ".." && !sid.includes("/") && !sid.includes("\\") && !isUnsafeBindKey(sid);
543
+ return isValidBindToken(sid) && sid !== "." && !sid.includes("..") && !sid.includes("/") && !sid.includes("\\") && !isUnsafeBindKey(sid);
527
544
  }
528
545
 
529
546
  function cleanDetectedWorkspacePath(raw: unknown): string | undefined {
@@ -538,6 +555,10 @@ export function detectRuntimeSession(
538
555
  env: Record<string, string | undefined> = process.env,
539
556
  meta?: Record<string, any> | null,
540
557
  ): DetectedSession | null {
558
+ if (env.AGENTSCHAT_DSH_HEALTH_URL?.trim() || env.AGENTSCHAT_DSH_HOME?.trim()) {
559
+ return null;
560
+ }
561
+
541
562
  // 1. ZCode MCP request `_meta` (injected on every tools/call by ZCode's NodeMcpAdapter)
542
563
  const zcodeCtx = meta?.["com.zcode/request-context"];
543
564
  const metaSessionId =
@@ -869,6 +890,13 @@ export function discoverAntigravityHost(opts?: {
869
890
  cacheMs?: number;
870
891
  }): AntigravityHostInfo | null {
871
892
  if (!opts?.currentPid) {
893
+ if (
894
+ process.env.AGENTSCHAT_DSH_HEALTH_URL?.trim() ||
895
+ process.env.AGENTSCHAT_DSH_HOME?.trim() ||
896
+ process.env.DSH_HOME?.trim()
897
+ ) {
898
+ return null;
899
+ }
872
900
  const envAddr = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
873
901
  const envCsrf = process.env.ANTIGRAVITY_CSRF_TOKEN?.trim() || "";
874
902
  if (envAddr && envCsrf) {
@@ -893,8 +921,12 @@ export function discoverAntigravityHost(opts?: {
893
921
  }
894
922
 
895
923
  const now = Date.now();
896
- const cacheMs = opts?.cacheMs ?? 5_000;
897
- if (cachedAgyHost && now >= cachedAgyHost.at && now - cachedAgyHost.at < cacheMs) return cachedAgyHost.info;
924
+ const cacheMs =
925
+ typeof opts?.cacheMs === "number" && Number.isFinite(opts.cacheMs) && opts.cacheMs >= 0
926
+ ? opts.cacheMs
927
+ : 5_000;
928
+ if (cachedAgyHost && now < cachedAgyHost.at) cachedAgyHost = null;
929
+ if (cachedAgyHost && now - cachedAgyHost.at < cacheMs) return cachedAgyHost.info;
898
930
 
899
931
  try {
900
932
  const startPid = opts?.currentPid ?? process.pid;
@@ -918,7 +950,7 @@ export function discoverAntigravityHost(opts?: {
918
950
  if (!m) break;
919
951
  const ppid = Number(m[1]);
920
952
  const cmd = m[2]!;
921
- if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test"))) break;
953
+ if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test") || matchesDshCommandLine(cmd))) break;
922
954
  if (cmd.includes("language_server") && cmd.includes("--csrf_token")) {
923
955
  lsPid = pid;
924
956
  lsCmd = cmd;
@@ -1088,6 +1120,7 @@ function matchesDshCommandLine(cmd: string): boolean {
1088
1120
  cmd.includes("@deepseek-ai") ||
1089
1121
  cmd.includes("/.dsh/") ||
1090
1122
  cmd.toLowerCase().includes("\\.dsh\\") ||
1123
+ /deepseek[- ]harness/i.test(cmd) ||
1091
1124
  /\bdsh(?:\.cmd|\.exe)?\b/i.test(cmd)
1092
1125
  );
1093
1126
  }
@@ -1107,8 +1140,12 @@ export function isDshHostProcess(opts?: {
1107
1140
  return true;
1108
1141
  }
1109
1142
  const now = Date.now();
1110
- const cacheMs = opts?.cacheMs ?? 15_000;
1111
- if (cachedIsDshHost && now >= cachedIsDshHost.at && now - cachedIsDshHost.at < cacheMs) return cachedIsDshHost.value;
1143
+ const cacheMs =
1144
+ typeof opts?.cacheMs === "number" && Number.isFinite(opts.cacheMs) && opts.cacheMs >= 0
1145
+ ? opts.cacheMs
1146
+ : 15_000;
1147
+ if (cachedIsDshHost && now < cachedIsDshHost.at) cachedIsDshHost = null;
1148
+ if (cachedIsDshHost && now - cachedIsDshHost.at < cacheMs) return cachedIsDshHost.value;
1112
1149
  try {
1113
1150
  let pid = opts?.currentPid ?? process.pid;
1114
1151
  if (process.platform === "win32") {
@@ -1262,7 +1299,14 @@ function sessionDirMtime(dir: string): number {
1262
1299
  const dirStat = safeLstat(dir);
1263
1300
  if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) return 0;
1264
1301
  let newest = 0;
1265
- for (const file of ["session.v4.jsonl.zstd", "session.v4.jsonl"]) {
1302
+ let entries: string[] = [];
1303
+ try {
1304
+ entries = readdirSync(dir);
1305
+ } catch {
1306
+ entries = ["session.v4.jsonl.zstd", "session.v4.jsonl"];
1307
+ }
1308
+ for (const file of entries) {
1309
+ if (!/^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(file)) continue;
1266
1310
  const st = safeLstat(join(dir, file));
1267
1311
  if (st && !st.isSymbolicLink() && st.isFile() && st.mtimeMs > newest) {
1268
1312
  newest = st.mtimeMs;