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
@@ -13,11 +13,39 @@
13
13
  * `undefined`, which leaves the receiver on its existing fallback. Routing must
14
14
  * never turn a delivery problem into a lost message.
15
15
  */
16
- import { existsSync, readFileSync } from "node:fs";
16
+ import { lstatSync, readFileSync, readlinkSync, realpathSync } from "node:fs";
17
17
  import { homedir } from "node:os";
18
- import { join } from "node:path";
18
+ import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
19
19
  import { loadSessionBinds } from "./session-bind.ts";
20
20
 
21
+ const MAX_PROFILE_BYTES = 64 * 1024;
22
+ const MAX_DIR_PATH_LENGTH = 4096;
23
+ const MAX_SESSION_ID_LENGTH = 256;
24
+ const RESERVED_PROFILE_KEY = /^(?:__proto__|constructor|prototype)$/i;
25
+ const RESERVED_ROUTE_SIDECARS = new Set([
26
+ "profile",
27
+ "session-binds",
28
+ "session-binds_meta",
29
+ "session-binds-meta",
30
+ "agy-binds",
31
+ "agy-binds_meta",
32
+ "agy-binds-meta",
33
+ "agy-session-binds",
34
+ "agy-session-binds_meta",
35
+ "grok-binds",
36
+ "grok-binds_meta",
37
+ "grok-binds-meta",
38
+ "identity-guard",
39
+ "cursor",
40
+ "read-cursors",
41
+ "mention-timestamps",
42
+ "wake-pids",
43
+ "config",
44
+ "codex-bots",
45
+ "dsh",
46
+ "muse",
47
+ ]);
48
+
21
49
  export interface AgentSessionRoute {
22
50
  /** Harness session the wake should be delivered to. */
23
51
  sessionId: string;
@@ -27,9 +55,37 @@ export interface AgentSessionRoute {
27
55
  agentId: string;
28
56
  }
29
57
 
58
+ function isSafeAbsoluteDirEnv(raw: unknown): raw is string {
59
+ if (typeof raw !== "string") return false;
60
+ const s = raw.trim();
61
+ return (
62
+ s.length > 0 &&
63
+ s.length <= MAX_DIR_PATH_LENGTH &&
64
+ !s.startsWith("-") &&
65
+ !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(s) &&
66
+ isAbsolute(s)
67
+ );
68
+ }
69
+
30
70
  /** Same config root the MCP server uses for profiles and `session-binds.json`. */
31
71
  export function agentschatConfigDir(env: Record<string, string | undefined> = process.env): string {
32
- return env.AGENTSCHAT_CONFIG_DIR ?? join(homedir(), ".agentschat");
72
+ if (isSafeAbsoluteDirEnv(env.AGENTSCHAT_CONFIG_DIR)) {
73
+ return env.AGENTSCHAT_CONFIG_DIR.trim();
74
+ }
75
+ const homeCandidate = env.HOME || env.USERPROFILE || "";
76
+ const home = isSafeAbsoluteDirEnv(homeCandidate) ? homeCandidate.trim() : homedir();
77
+ return join(home, ".agentschat");
78
+ }
79
+
80
+ function isSafeAgentId(id: string): boolean {
81
+ return (
82
+ id.length > 0 &&
83
+ id.length <= 128 &&
84
+ id !== "." &&
85
+ id !== ".." &&
86
+ !RESERVED_PROFILE_KEY.test(id) &&
87
+ !/[/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(id)
88
+ );
33
89
  }
34
90
 
35
91
  /**
@@ -40,19 +96,131 @@ export function agentschatConfigDir(env: Record<string, string | undefined> = pr
40
96
  * contains a path separator is skipped rather than guessed, because a wrong path
41
97
  * would silently route a wake into the wrong identity.
42
98
  */
99
+ function isSafeRegularProfileFile(path: string): boolean {
100
+ try {
101
+ const st = lstatSync(path);
102
+ return !st.isSymbolicLink() && st.isFile() && st.size <= MAX_PROFILE_BYTES;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ function isSafeSessionId(sessionId: string): boolean {
109
+ return (
110
+ sessionId.length > 0 &&
111
+ sessionId.length <= MAX_SESSION_ID_LENGTH &&
112
+ sessionId !== "." &&
113
+ sessionId !== ".." &&
114
+ !RESERVED_PROFILE_KEY.test(sessionId) &&
115
+ !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(sessionId)
116
+ );
117
+ }
118
+
119
+ function isAllowedDarwinSystemLink(dirPath: string): boolean {
120
+ if (process.platform !== "darwin") return false;
121
+ if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc") return false;
122
+ try {
123
+ return (
124
+ readlinkSync(dirPath) === `private${dirPath}` &&
125
+ realpathSync(dirPath) === `/private${dirPath}` &&
126
+ !lstatSync("/private").isSymbolicLink() &&
127
+ lstatSync("/private").isDirectory() &&
128
+ !lstatSync(`/private${dirPath}`).isSymbolicLink() &&
129
+ lstatSync(`/private${dirPath}`).isDirectory()
130
+ );
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+
136
+ function hasSafeRawDotDotSegments(rawPath: string): boolean {
137
+ const absRaw = isAbsolute(rawPath) ? rawPath : `${process.cwd()}${sep}${rawPath}`;
138
+ const root = parse(absRaw).root;
139
+ const segments = absRaw.slice(root.length).split(/[\\/]+/).filter(Boolean);
140
+ if (!segments.includes("..")) return true;
141
+ let cur = root;
142
+ for (const seg of segments) {
143
+ if (seg === ".") continue;
144
+ if (seg === "..") {
145
+ cur = dirname(cur);
146
+ continue;
147
+ }
148
+ const next = join(cur, seg);
149
+ try {
150
+ const st = lstatSync(next);
151
+ if (st.isSymbolicLink() && !isAllowedDarwinSystemLink(next)) {
152
+ return false;
153
+ }
154
+ } catch (err) {
155
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") return false;
156
+ }
157
+ cur = next;
158
+ }
159
+ return true;
160
+ }
161
+
162
+ function isSafeRealDir(path: string): boolean {
163
+ try {
164
+ if (!path || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(path) || !hasSafeRawDotDotSegments(path)) {
165
+ return false;
166
+ }
167
+ const st = lstatSync(path);
168
+ if (st.isSymbolicLink() || !st.isDirectory()) return false;
169
+ const abs = resolve(path);
170
+ const root = parse(abs).root;
171
+ const segments = abs.slice(root.length).split(/[\\/]+/).filter(Boolean);
172
+ let cur = root;
173
+ for (let i = 0; i < segments.length; i++) {
174
+ cur = join(cur, segments[i]!);
175
+ const anc = lstatSync(cur);
176
+ if (anc.isSymbolicLink()) {
177
+ if (isAllowedDarwinSystemLink(cur)) continue;
178
+ return false;
179
+ }
180
+ if (!anc.isDirectory()) return false;
181
+ }
182
+ return true;
183
+ } catch {
184
+ return false;
185
+ }
186
+ }
187
+
43
188
  function profilePathForName(configDir: string, name: string): string | undefined {
44
- if (!name || name.includes("/") || name.includes("\\")) return undefined;
45
- const base = name.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
46
- const nested = join(configDir, "profiles", `${base}.json`);
47
- if (existsSync(nested)) return nested;
189
+ if (
190
+ typeof name !== "string" ||
191
+ !name ||
192
+ name.length > 133 ||
193
+ name === "." ||
194
+ name === ".." ||
195
+ name.includes("/") ||
196
+ name.includes("\\") ||
197
+ /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(name) ||
198
+ !isSafeRealDir(configDir)
199
+ ) {
200
+ return undefined;
201
+ }
202
+ const base = name.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
203
+ if (!base || base.length > 128 || RESERVED_PROFILE_KEY.test(base) || RESERVED_ROUTE_SIDECARS.has(base.toLowerCase())) {
204
+ return undefined;
205
+ }
206
+ const profilesDir = join(configDir, "profiles");
207
+ if (isSafeRealDir(profilesDir)) {
208
+ const nested = join(profilesDir, `${base}.json`);
209
+ if (isSafeRegularProfileFile(nested)) return nested;
210
+ }
48
211
  const flat = join(configDir, `${base}.json`);
49
- return existsSync(flat) ? flat : undefined;
212
+ return isSafeRegularProfileFile(flat) ? flat : undefined;
50
213
  }
51
214
 
52
215
  function readAgentId(path: string): string | undefined {
53
216
  try {
217
+ if (!isSafeRegularProfileFile(path)) return undefined;
54
218
  const parsed = JSON.parse(readFileSync(path, "utf8")) as { agent_id?: unknown };
55
- return typeof parsed.agent_id === "string" && parsed.agent_id ? parsed.agent_id : undefined;
219
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
220
+ return undefined;
221
+ }
222
+ const id = typeof parsed.agent_id === "string" ? parsed.agent_id.trim() : "";
223
+ return isSafeAgentId(id) ? id : undefined;
56
224
  } catch {
57
225
  return undefined;
58
226
  }
@@ -73,7 +241,9 @@ export function resolveSessionForAgent(
73
241
  filter?: (sessionId: string) => boolean;
74
242
  } = {},
75
243
  ): AgentSessionRoute | undefined {
76
- if (typeof agentId !== "string" || agentId.length === 0) return undefined;
244
+ if (typeof agentId !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId)) return undefined;
245
+ const targetAgentId = agentId.trim();
246
+ if (!isSafeAgentId(targetAgentId)) return undefined;
77
247
  const configDir = opts.configDir ?? agentschatConfigDir(opts.env);
78
248
  let binds: Record<string, string>;
79
249
  try {
@@ -82,11 +252,12 @@ export function resolveSessionForAgent(
82
252
  return undefined;
83
253
  }
84
254
  for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
255
+ if (!isSafeSessionId(sessionId)) continue;
85
256
  if (opts.filter && !opts.filter(sessionId)) continue;
86
257
  const path = profilePathForName(configDir, profileName);
87
258
  if (path === undefined) continue;
88
- if (readAgentId(path) !== agentId) continue;
89
- return { sessionId, profileName, agentId };
259
+ if (readAgentId(path) !== targetAgentId) continue;
260
+ return { sessionId, profileName, agentId: targetAgentId };
90
261
  }
91
262
  return undefined;
92
263
  }
@@ -10,5 +10,8 @@ export const TEAM_LEAD_NO_UPDATE = "[[AGENTSCHAT_NO_UPDATE]]";
10
10
 
11
11
  /** Only an exact, locally authorized loop reference activates the bundled skill. */
12
12
  export function isTeamLeadSkillInvocation(prompt: string): boolean {
13
+ if (typeof prompt !== "string" || prompt.length > 256 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/.test(prompt)) {
14
+ return false;
15
+ }
13
16
  return [TEAM_LEAD_SKILL_ID, `$${TEAM_LEAD_SKILL_ID}`, `执行 $${TEAM_LEAD_SKILL_ID}`].includes(prompt.trim());
14
17
  }
package/src/timestamps.ts CHANGED
@@ -2,37 +2,70 @@
2
2
  * Normalize an ISO-8601 timestamp for lexical cursor comparison.
3
3
  *
4
4
  * The reconnect backfill compares timestamps as strings (`msgTs > afterTs`).
5
- * For that to match chronological order, fractional seconds must be padded to a
6
- * fixed 9 digits — AND whole-second timestamps (no fractional part) must also
7
- * get a fraction, otherwise "…00.123000000Z" and "…00Z" of the same second sort
8
- * wrong because '.' (0x2E) < 'Z' (0x5A), inverting the boundary comparison.
9
- *
10
- * mode "after" pads with 0 (floor of the second — for the strictly-after cursor);
11
- * mode "before" pads with 9 (ceil of the second).
12
- *
13
- * Extracted from server.ts so it can be unit-tested without loading the
14
- * side-effecting server entrypoint.
5
+ * For that to match chronological order:
6
+ * 1. Non-UTC numeric offsets (`+08:00`, `-05:00`) and lowercase `z` are converted
7
+ * to canonical UTC `YYYY-MM-DDTHH:mm:ss.<9digits>Z` without losing sub-millisecond
8
+ * fractional precision;
9
+ * 2. Fractional seconds are padded (`0` for `"after"`, `9` for `"before"`) OR
10
+ * truncated (`>9` digits → 9 digits) to a fixed 9 digits, including whole-second
11
+ * timestamps, so `'.'` (0x2E) < `'Z'` (0x5A) never inverts ordering.
15
12
  */
13
+ const ISO_OFFSET_RE = /^(\d{4}-\d{2}-\d{2})[Tt ](\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|z|[+-]\d{2}:\d{2})$/;
14
+
15
+ function isValidCalendarDateTime(datePart: string, timePart: string, tzPart: string): boolean {
16
+ const year = Number(datePart.slice(0, 4));
17
+ const month = Number(datePart.slice(5, 7));
18
+ const day = Number(datePart.slice(8, 10));
19
+ const hour = Number(timePart.slice(0, 2));
20
+ const minute = Number(timePart.slice(3, 5));
21
+ const second = Number(timePart.slice(6, 8));
22
+ if (month < 1 || month > 12 || hour > 23 || minute > 59 || second > 59) return false;
23
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
24
+ const maxDay = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]!;
25
+ if (day < 1 || day > maxDay) return false;
26
+ if (tzPart !== "Z" && tzPart !== "z") {
27
+ const offHour = Number(tzPart.slice(1, 3));
28
+ const offMin = Number(tzPart.slice(4, 6));
29
+ if (offHour > 23 || offMin > 59) return false;
30
+ }
31
+ return true;
32
+ }
33
+
16
34
  export function normalizeTimestampForCursor(
17
35
  ts: string | undefined,
18
36
  mode: "before" | "after",
19
37
  ): string | undefined {
20
- if (!ts || typeof ts !== "string") return ts;
38
+ if (!ts || typeof ts !== "string" || ts.length > 128) return ts;
39
+ if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(ts)) return undefined;
40
+ if (mode !== "before" && mode !== "after") return ts;
21
41
  const padChar = mode === "before" ? "9" : "0";
42
+ const trimmed = ts.trim();
22
43
 
23
- // Has a fractional part: pad it to 9 digits.
24
- const withFrac = ts.match(/^(.*\.)(\d+)(Z)$/);
25
- if (withFrac) {
26
- const frac = withFrac[2];
27
- if (frac.length >= 9) return ts;
28
- return withFrac[1] + frac + padChar.repeat(9 - frac.length) + withFrac[3];
29
- }
44
+ const m = trimmed.match(ISO_OFFSET_RE);
45
+ if (m) {
46
+ const datePart = m[1]!;
47
+ const timePart = m[2]!;
48
+ const rawFrac = m[3] ?? "";
49
+ const tzPart = m[4]!;
50
+ if (!isValidCalendarDateTime(datePart, timePart, tzPart)) return ts;
51
+ const frac9 =
52
+ rawFrac.length === 9
53
+ ? rawFrac
54
+ : rawFrac.length > 9
55
+ ? rawFrac.slice(0, 9)
56
+ : rawFrac + padChar.repeat(9 - rawFrac.length);
57
+
58
+ if (tzPart === "Z" || tzPart === "z") {
59
+ return `${datePart}T${timePart}.${frac9}Z`;
60
+ }
30
61
 
31
- // Whole-second timestamp: insert a 9-digit fraction so it sorts consistently
32
- // against fractional timestamps of the same second.
33
- const noFrac = ts.match(/^(.*\d)(Z)$/);
34
- if (noFrac) {
35
- return noFrac[1] + "." + padChar.repeat(9) + noFrac[2];
62
+ const wholeUtcMs = Date.parse(`${datePart}T${timePart}${tzPart}`);
63
+ if (Number.isFinite(wholeUtcMs)) {
64
+ const iso = new Date(wholeUtcMs).toISOString();
65
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(iso)) {
66
+ return `${iso.slice(0, 19)}.${frac9}Z`;
67
+ }
68
+ }
36
69
  }
37
70
 
38
71
  return ts;
@@ -128,5 +128,14 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotation> = {
128
128
 
129
129
  /** Attach annotations to a tools/list payload. Unknown tools fail loudly in tests. */
130
130
  export function annotateTools<T extends { name: string }>(tools: T[]): Array<T & { annotations: ToolAnnotation }> {
131
- return tools.map((t) => ({ ...t, annotations: TOOL_ANNOTATIONS[t.name] ?? W }));
131
+ if (!Array.isArray(tools)) return [];
132
+ return tools.map((t) => {
133
+ const base = Object.prototype.hasOwnProperty.call(TOOL_ANNOTATIONS, t.name)
134
+ ? TOOL_ANNOTATIONS[t.name]!
135
+ : W;
136
+ return {
137
+ ...t,
138
+ annotations: { ...base },
139
+ };
140
+ });
132
141
  }