agentschat-mcp 0.36.25 → 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/CHANGELOG.md +7 -0
- package/README.md +10 -10
- package/codex/README.md +4 -4
- package/codex/app-server.ts +101 -22
- package/codex/bots-config.ts +32 -11
- package/codex/bridge.ts +127 -28
- package/codex/config.ts +137 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +77 -12
- package/codex/loop-grants.ts +49 -11
- package/codex/manager.ts +108 -27
- package/codex/owner.ts +106 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +51 -11
- package/codex/thread-history.ts +87 -30
- package/codex/transport.ts +135 -22
- package/connector/README.md +1 -1
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/cordis.patch.yml +4 -2
- package/dist/codex-bots.js +437 -75
- package/dist/codex-bridge.js +2111 -582
- package/dist/connector.js +1300 -493
- package/dist/dsh.js +1789 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +4410 -919
- package/dsh/README.md +1 -1
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +677 -154
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +1174 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +3 -3
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/onboarding.md +15 -15
- package/src/argcheck.ts +113 -33
- package/src/cli.mjs +100 -16
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +182 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +299 -18
- package/src/profile-store.ts +248 -30
- package/src/read-cursor.ts +280 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +286 -94
- package/src/session-bind.ts +777 -134
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +10 -1
- package/src/wake.ts +510 -91
package/src/wake.ts
CHANGED
|
@@ -23,6 +23,9 @@
|
|
|
23
23
|
* timeout, then drop with a stderr note.
|
|
24
24
|
*/
|
|
25
25
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
26
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, type Stats } from "node:fs";
|
|
27
|
+
import { homedir } from "node:os";
|
|
28
|
+
import { dirname, isAbsolute, join, parse, resolve, win32 as pathWin32 } from "node:path";
|
|
26
29
|
import { redactSecrets } from "./redact.ts";
|
|
27
30
|
|
|
28
31
|
/** Signature header the receiver reads to verify a wake POST. */
|
|
@@ -30,7 +33,165 @@ export const WAKE_SIG_HEADER = "x-agentschat-signature";
|
|
|
30
33
|
/** Header forwarded on authenticated REST calls when AGENTSCHAT_WAKE_ID is present. */
|
|
31
34
|
export const WAKE_ID_HEADER = "X-AgentsChat-Wake-Id";
|
|
32
35
|
const SAFE_WAKE_ID_RE = /^[a-zA-Z0-9_-]{1,128}$/;
|
|
33
|
-
const CREDENTIAL_PREFIX_RE =
|
|
36
|
+
const CREDENTIAL_PREFIX_RE =
|
|
37
|
+
/^(ac_|mcp_(?:at|rt|code)_|agent_key_|whsec_|mr_|sk-|sk_|rk_live_|rk_test_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|AIza|AKIA|ASIA)/i;
|
|
38
|
+
const MAX_WAKE_TIMER_MS = 2_147_483_647;
|
|
39
|
+
const GROK_GATEWAY_MAX_BYTES = 1_048_576;
|
|
40
|
+
const DIRECT_CHANNEL_RE = /^dm[-:]/i;
|
|
41
|
+
const SAFE_ZCODE_SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
42
|
+
const PROTOTYPE_WAKE_KEYS = new Set([
|
|
43
|
+
"prototype",
|
|
44
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
function isAllowedDarwinSystemLink(dirPath: string): boolean {
|
|
48
|
+
if (process.platform !== "darwin") return false;
|
|
49
|
+
if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc") return false;
|
|
50
|
+
try {
|
|
51
|
+
const privStat = lstatSync("/private");
|
|
52
|
+
if (privStat.isSymbolicLink() || !privStat.isDirectory()) return false;
|
|
53
|
+
const targetStat = lstatSync(`/private${dirPath}`);
|
|
54
|
+
if (targetStat.isSymbolicLink() || !targetStat.isDirectory()) return false;
|
|
55
|
+
return readlinkSync(dirPath) === `private${dirPath}`;
|
|
56
|
+
} catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function hasSafeWakeDirChain(dirPath: string): boolean {
|
|
62
|
+
if (typeof dirPath !== "string" || !dirPath.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(dirPath)) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(dirPath)) {
|
|
66
|
+
const rawBase = isAbsolute(dirPath) ? parse(dirPath).root : resolve(".");
|
|
67
|
+
const rawRel = isAbsolute(dirPath) ? dirPath.slice(rawBase.length) : dirPath;
|
|
68
|
+
let rawCur = rawBase.replace(/[\\/]+$/, "") || "/";
|
|
69
|
+
for (const seg of rawRel.split(/[\\/]+/).filter(Boolean)) {
|
|
70
|
+
if (seg === ".") continue;
|
|
71
|
+
if (seg === "..") {
|
|
72
|
+
rawCur = dirname(rawCur);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
rawCur = rawCur === "/" ? `/${seg}` : `${rawCur}/${seg}`;
|
|
76
|
+
try {
|
|
77
|
+
const st = lstatSync(rawCur);
|
|
78
|
+
if (st.isSymbolicLink() && !isAllowedDarwinSystemLink(rawCur)) return false;
|
|
79
|
+
if (!st.isSymbolicLink() && !st.isDirectory()) return false;
|
|
80
|
+
} catch (err: any) {
|
|
81
|
+
if (err && err.code === "ENOENT") break;
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const abs = resolve(dirPath);
|
|
87
|
+
const root = parse(abs).root;
|
|
88
|
+
const rel = abs.slice(root.length);
|
|
89
|
+
const segments = rel.split(/[\\/]+/).filter(Boolean);
|
|
90
|
+
let cur = root;
|
|
91
|
+
for (let i = 0; i < segments.length; i++) {
|
|
92
|
+
cur = join(cur, segments[i]!);
|
|
93
|
+
let st: Stats;
|
|
94
|
+
try {
|
|
95
|
+
st = lstatSync(cur);
|
|
96
|
+
} catch (err: any) {
|
|
97
|
+
if (err && err.code === "ENOENT") return true;
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
if (st.isSymbolicLink()) {
|
|
101
|
+
if (isAllowedDarwinSystemLink(cur)) continue;
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
if (!st.isDirectory()) return false;
|
|
105
|
+
}
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function isUnsafeMetadataOrLinkLocalHost(hostname: string): boolean {
|
|
110
|
+
const lower = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
111
|
+
if (
|
|
112
|
+
!lower ||
|
|
113
|
+
lower === "0" ||
|
|
114
|
+
lower === "0.0.0.0" ||
|
|
115
|
+
/^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(lower) ||
|
|
116
|
+
lower === "::" ||
|
|
117
|
+
lower === "100.100.100.200" ||
|
|
118
|
+
lower === "fd00:ec2::254" ||
|
|
119
|
+
lower === "metadata.google.internal" ||
|
|
120
|
+
lower.endsWith(".metadata.google.internal") ||
|
|
121
|
+
lower === "metadata" ||
|
|
122
|
+
lower === "metadata.goog" ||
|
|
123
|
+
lower.endsWith(".metadata.goog") ||
|
|
124
|
+
lower === "instance-data"
|
|
125
|
+
) {
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
if (/^169\.254\.\d{1,3}\.\d{1,3}$/.test(lower)) return true;
|
|
129
|
+
if (/^fe[89ab][0-9a-f]:/.test(lower)) return true;
|
|
130
|
+
if (lower.startsWith("::ffff:")) {
|
|
131
|
+
const tail = lower.slice("::ffff:".length);
|
|
132
|
+
const tailParts = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(tail) ? tail.slice(2) : tail;
|
|
133
|
+
if (
|
|
134
|
+
/^169\.254\.\d{1,3}\.\d{1,3}$/.test(tailParts) ||
|
|
135
|
+
/^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(tailParts) ||
|
|
136
|
+
tailParts === "100.100.100.200" ||
|
|
137
|
+
tailParts === "0.0.0.0"
|
|
138
|
+
) {
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
const hexMatch = tailParts.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
142
|
+
if (hexMatch) {
|
|
143
|
+
const hi = parseInt(hexMatch[1]!, 16);
|
|
144
|
+
const lo = parseInt(hexMatch[2]!, 16);
|
|
145
|
+
if (
|
|
146
|
+
(((hi >> 8) & 0xff) === 169 && (hi & 0xff) === 254) ||
|
|
147
|
+
(hi === 0x6464 && lo === 0x64c8) ||
|
|
148
|
+
((hi >> 8) & 0xff) === 0
|
|
149
|
+
) {
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Clamp timeout/grace durations to safe positive 32-bit signed integers so setTimeout never overflows to 1ms. */
|
|
158
|
+
export function clampWakeTimerMs(raw: unknown, fallback: number, minMs = 1): number {
|
|
159
|
+
return typeof raw === "number" && Number.isFinite(raw) && raw > 0
|
|
160
|
+
? Math.min(MAX_WAKE_TIMER_MS, Math.max(minMs, Math.floor(raw)))
|
|
161
|
+
: fallback;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Validate explicit Antigravity language_server address strictly as loopback host:port (1..65535). */
|
|
165
|
+
export function normalizeLoopbackLsAddress(raw: unknown): string | null {
|
|
166
|
+
if (typeof raw !== "string") return null;
|
|
167
|
+
const m = /^(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})$/i.exec(raw.trim());
|
|
168
|
+
if (!m) return null;
|
|
169
|
+
const port = Number(m[2]);
|
|
170
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
|
|
171
|
+
return `${m[1]!.toLowerCase()}:${port}`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function sanitizeWakeAttachmentUrl(raw: unknown): string | null {
|
|
175
|
+
if (typeof raw !== "string") return null;
|
|
176
|
+
const cleaned = raw.trim().replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029\r\n]+/g, "");
|
|
177
|
+
if (!cleaned || cleaned.length > 2048 || /\s/.test(cleaned) || !/^https?:\/\//i.test(cleaned) || /:0(?:\/|$)/.test(cleaned)) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
let parsed: URL;
|
|
181
|
+
try {
|
|
182
|
+
parsed = new URL(cleaned);
|
|
183
|
+
} catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
|
187
|
+
if (parsed.username || parsed.password) return null;
|
|
188
|
+
if (parsed.port) {
|
|
189
|
+
const port = Number(parsed.port);
|
|
190
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
|
|
191
|
+
}
|
|
192
|
+
if (isUnsafeMetadataOrLinkLocalHost(parsed.hostname)) return null;
|
|
193
|
+
return cleaned;
|
|
194
|
+
}
|
|
34
195
|
|
|
35
196
|
/**
|
|
36
197
|
* Validate `AGENTSCHAT_WAKE_ID` injected by Cloud Sandbox per wake turn so
|
|
@@ -98,20 +259,65 @@ export function formatWakeAttachments(attachments: unknown): string {
|
|
|
98
259
|
for (const raw of attachments) {
|
|
99
260
|
if (!raw || typeof raw !== "object") continue;
|
|
100
261
|
const a = raw as WakeAttachment;
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
const
|
|
104
|
-
|
|
262
|
+
const safeUrl = sanitizeWakeAttachmentUrl(a.url);
|
|
263
|
+
if (!safeUrl) continue;
|
|
264
|
+
const cleanedType =
|
|
265
|
+
typeof a.type === "string" ? a.type.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, "").trim().slice(0, 32) : "";
|
|
266
|
+
const t = cleanedType || "file";
|
|
267
|
+
const dim =
|
|
268
|
+
typeof a.width === "number" &&
|
|
269
|
+
Number.isFinite(a.width) &&
|
|
270
|
+
a.width >= 0 &&
|
|
271
|
+
typeof a.height === "number" &&
|
|
272
|
+
Number.isFinite(a.height) &&
|
|
273
|
+
a.height >= 0
|
|
274
|
+
? ` ${a.width}×${a.height}`
|
|
275
|
+
: "";
|
|
276
|
+
const dur =
|
|
277
|
+
typeof a.duration_ms === "number" && Number.isFinite(a.duration_ms) && a.duration_ms >= 0
|
|
278
|
+
? ` ${(a.duration_ms / 1000).toFixed(1)}s`
|
|
279
|
+
: "";
|
|
105
280
|
const icon = t === "image" ? "🖼" : t === "video" ? "🎬" : t === "audio" ? "🔊" : "📎";
|
|
106
|
-
let desc = `${icon} ${t}${dim}${dur}: ${
|
|
107
|
-
if (typeof a.transcript === "string"
|
|
108
|
-
|
|
281
|
+
let desc = `${icon} ${t}${dim}${dur}: ${safeUrl}`;
|
|
282
|
+
if (typeof a.transcript === "string") {
|
|
283
|
+
const safeTranscript = a.transcript
|
|
284
|
+
.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029"]+/g, " ")
|
|
285
|
+
.trim()
|
|
286
|
+
.slice(0, 300);
|
|
287
|
+
if (safeTranscript) {
|
|
288
|
+
desc += ` (transcript: "${redactSecrets(safeTranscript)}")`;
|
|
289
|
+
}
|
|
109
290
|
}
|
|
110
291
|
lines.push(desc);
|
|
111
292
|
}
|
|
112
293
|
return lines.length > 0 ? ` [附件: ${lines.join("; ")}]` : "";
|
|
113
294
|
}
|
|
114
295
|
|
|
296
|
+
function sanitizeWakeHeaderToken(raw: unknown, maxLen = 128): string | undefined {
|
|
297
|
+
if (typeof raw !== "string") return undefined;
|
|
298
|
+
const cleaned = raw.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, "").trim().slice(0, maxLen);
|
|
299
|
+
return cleaned.length > 0 ? cleaned : undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function isAllowedWakeHttpUrl(rawUrl: string): boolean {
|
|
303
|
+
if (!rawUrl || rawUrl.length > 4096 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(rawUrl) || /:0(?:\/|$)/.test(rawUrl)) {
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
let parsed: URL;
|
|
307
|
+
try {
|
|
308
|
+
parsed = new URL(rawUrl);
|
|
309
|
+
} catch {
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
|
|
313
|
+
if (isUnsafeMetadataOrLinkLocalHost(parsed.hostname)) return false;
|
|
314
|
+
if (parsed.port) {
|
|
315
|
+
const port = Number(parsed.port);
|
|
316
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return false;
|
|
317
|
+
}
|
|
318
|
+
return true;
|
|
319
|
+
}
|
|
320
|
+
|
|
115
321
|
/**
|
|
116
322
|
* Build the wake body: the fields the receiver needs to wake + decide + optionally
|
|
117
323
|
* skip a history fetch. Credential-shaped fields are never carried across.
|
|
@@ -125,29 +331,43 @@ export function buildWakePayload(msg: WakeMessage, opts: { targetSessionId?: str
|
|
|
125
331
|
const content = typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX), redactOpts) : undefined;
|
|
126
332
|
const attachments = Array.isArray(msg.attachments) && msg.attachments.length > 0
|
|
127
333
|
? msg.attachments
|
|
128
|
-
.
|
|
129
|
-
.map((a) =>
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
334
|
+
.slice(0, 16)
|
|
335
|
+
.map((a) => {
|
|
336
|
+
if (!a || typeof a !== "object") return null;
|
|
337
|
+
const safeUrl = sanitizeWakeAttachmentUrl(a.url);
|
|
338
|
+
if (!safeUrl) return null;
|
|
339
|
+
return {
|
|
340
|
+
type: sanitizeWakeHeaderToken(a.type, 32),
|
|
341
|
+
url: safeUrl,
|
|
342
|
+
mime: sanitizeWakeHeaderToken(a.mime, 128),
|
|
343
|
+
size: typeof a.size === "number" && Number.isFinite(a.size) && a.size >= 0 ? a.size : undefined,
|
|
344
|
+
width: typeof a.width === "number" && Number.isFinite(a.width) && a.width >= 0 ? a.width : undefined,
|
|
345
|
+
height: typeof a.height === "number" && Number.isFinite(a.height) && a.height >= 0 ? a.height : undefined,
|
|
346
|
+
duration_ms: typeof a.duration_ms === "number" && Number.isFinite(a.duration_ms) && a.duration_ms >= 0 ? a.duration_ms : undefined,
|
|
347
|
+
transcript: typeof a.transcript === "string" ? redactSecrets(a.transcript.slice(0, 300), redactOpts) : undefined,
|
|
348
|
+
};
|
|
349
|
+
})
|
|
350
|
+
.filter((x): x is NonNullable<typeof x> => x !== null)
|
|
351
|
+
: undefined;
|
|
352
|
+
const targetSessionId = sanitizeWakeHeaderToken(opts.targetSessionId, 256);
|
|
353
|
+
const channelId = sanitizeWakeHeaderToken(msg.channel_id, 128);
|
|
354
|
+
const messageId = sanitizeWakeHeaderToken(msg.id, 128);
|
|
355
|
+
const senderId = sanitizeWakeHeaderToken(msg.sender_id, 128);
|
|
356
|
+
const mentionedIds = Array.isArray(msg.mentioned_ids)
|
|
357
|
+
? msg.mentioned_ids
|
|
358
|
+
.slice(0, 64)
|
|
359
|
+
.map((x) => sanitizeWakeHeaderToken(x, 128))
|
|
360
|
+
.filter((x): x is string => Boolean(x))
|
|
139
361
|
: undefined;
|
|
140
|
-
const targetSessionId =
|
|
141
|
-
typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
|
|
142
362
|
return {
|
|
143
|
-
type:
|
|
144
|
-
channel_id:
|
|
145
|
-
message_id:
|
|
146
|
-
sender_id:
|
|
363
|
+
type: sanitizeWakeHeaderToken(msg.type, 64) ?? "message",
|
|
364
|
+
channel_id: channelId,
|
|
365
|
+
message_id: messageId,
|
|
366
|
+
sender_id: senderId,
|
|
147
367
|
content,
|
|
148
368
|
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
|
149
|
-
mentioned_ids:
|
|
150
|
-
timestamp:
|
|
369
|
+
mentioned_ids: mentionedIds,
|
|
370
|
+
timestamp: sanitizeWakeHeaderToken(msg.timestamp, 64),
|
|
151
371
|
...(targetSessionId ? { target_session_id: targetSessionId } : {}),
|
|
152
372
|
};
|
|
153
373
|
}
|
|
@@ -159,15 +379,19 @@ export function signWakeBody(body: string, secret: string): string {
|
|
|
159
379
|
|
|
160
380
|
/** Constant-time check that `sigHex` signs `body` under ANY of `secrets` (rotation). */
|
|
161
381
|
export function verifyWakeSignature(body: string, sigHex: string, secrets: readonly string[]): boolean {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
return false;
|
|
167
|
-
}
|
|
168
|
-
if (sigBuf.length === 0) return false;
|
|
382
|
+
if (typeof body !== "string" || typeof sigHex !== "string" || !/^[0-9a-f]{64}$/i.test(sigHex)) return false;
|
|
383
|
+
if (!Array.isArray(secrets) || secrets.length === 0) return false;
|
|
384
|
+
const sigBuf = Buffer.from(sigHex, "hex");
|
|
385
|
+
if (sigBuf.length !== 32) return false;
|
|
169
386
|
for (const secret of secrets) {
|
|
170
|
-
if (
|
|
387
|
+
if (
|
|
388
|
+
typeof secret !== "string" ||
|
|
389
|
+
!secret ||
|
|
390
|
+
secret.length > 8192 ||
|
|
391
|
+
/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(secret)
|
|
392
|
+
) {
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
171
395
|
const expected = Buffer.from(signWakeBody(body, secret), "hex");
|
|
172
396
|
if (expected.length !== sigBuf.length) continue;
|
|
173
397
|
if (timingSafeEqual(sigBuf, expected)) return true;
|
|
@@ -175,6 +399,20 @@ export function verifyWakeSignature(body: string, sigHex: string, secrets: reado
|
|
|
175
399
|
return false;
|
|
176
400
|
}
|
|
177
401
|
|
|
402
|
+
/** Strip URL userinfo, query params, and secret-shaped path tokens before logging wake URLs. */
|
|
403
|
+
export function sanitizeWakeLogUrl(rawUrl: string): string {
|
|
404
|
+
try {
|
|
405
|
+
const parsed = new URL(rawUrl);
|
|
406
|
+
parsed.username = "";
|
|
407
|
+
parsed.password = "";
|
|
408
|
+
if (parsed.search) parsed.search = "?[REDACTED]";
|
|
409
|
+
parsed.hash = "";
|
|
410
|
+
return redactSecrets(parsed.toString());
|
|
411
|
+
} catch {
|
|
412
|
+
return redactSecrets(String(rawUrl || "")).slice(0, 120);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
178
416
|
export interface WakeConfig {
|
|
179
417
|
/** Where to POST. Empty/absent disables the wake webhook entirely. */
|
|
180
418
|
url?: string;
|
|
@@ -197,19 +435,35 @@ export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void>
|
|
|
197
435
|
const log = cfg.logger ?? (() => {});
|
|
198
436
|
const url = (cfg.url ?? "").trim();
|
|
199
437
|
if (!url) return; // not configured — the wake path is opt-in
|
|
438
|
+
const safeLogUrl = sanitizeWakeLogUrl(url);
|
|
439
|
+
if (!isAllowedWakeHttpUrl(url)) {
|
|
440
|
+
log(`[agentchat] wake POST rejected invalid or non-HTTP(S) URL: ${safeLogUrl}`);
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
200
443
|
|
|
201
444
|
const payload = buildWakePayload(msg, { targetSessionId: cfg.targetSessionId });
|
|
445
|
+
if (!payload.timestamp) payload.timestamp = new Date().toISOString();
|
|
202
446
|
const body = JSON.stringify(payload);
|
|
203
447
|
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
204
|
-
if (
|
|
448
|
+
if (
|
|
449
|
+
typeof cfg.secret === "string" &&
|
|
450
|
+
cfg.secret.length > 0 &&
|
|
451
|
+
cfg.secret.length <= 8192 &&
|
|
452
|
+
!/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(cfg.secret)
|
|
453
|
+
) {
|
|
454
|
+
headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
|
|
455
|
+
}
|
|
205
456
|
|
|
457
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 5000);
|
|
206
458
|
const doPost = async (): Promise<void> => {
|
|
207
459
|
const f = cfg.fetchImpl ?? fetch;
|
|
208
460
|
const ctrl = new AbortController();
|
|
209
|
-
const t = setTimeout(() => ctrl.abort(),
|
|
461
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
462
|
+
t.unref?.();
|
|
210
463
|
try {
|
|
211
|
-
const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
|
|
212
|
-
if (!res.ok) log(`[agentchat] wake POST ${
|
|
464
|
+
const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal, redirect: "error" });
|
|
465
|
+
if (!res.ok) log(`[agentchat] wake POST ${safeLogUrl} → HTTP ${res.status}`);
|
|
466
|
+
await res.body?.cancel().catch(() => {});
|
|
213
467
|
} finally {
|
|
214
468
|
clearTimeout(t);
|
|
215
469
|
}
|
|
@@ -222,7 +476,7 @@ export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void>
|
|
|
222
476
|
try {
|
|
223
477
|
await doPost();
|
|
224
478
|
} catch (e2) {
|
|
225
|
-
log(`[agentchat] wake POST ${
|
|
479
|
+
log(`[agentchat] wake POST ${safeLogUrl} failed: ${redactSecrets(String(e2)).slice(0, 200)}`);
|
|
226
480
|
}
|
|
227
481
|
}
|
|
228
482
|
}
|
|
@@ -252,10 +506,10 @@ export function buildGrokPrompt(msg: WakeMessage, agentId: string, contextPrefix
|
|
|
252
506
|
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
253
507
|
const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
|
|
254
508
|
const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim(), redactOpts) : "";
|
|
255
|
-
const channel = msg.channel_id ?? "?";
|
|
256
|
-
const sender = msg.sender_id ?? "someone";
|
|
257
|
-
const msgId = (msg.id ?? (msg as any).message_id ?? ""
|
|
258
|
-
const isDm =
|
|
509
|
+
const channel = sanitizeWakeHeaderToken(msg.channel_id, 128) ?? "?";
|
|
510
|
+
const sender = sanitizeWakeHeaderToken(msg.sender_id, 128) ?? "someone";
|
|
511
|
+
const msgId = sanitizeWakeHeaderToken(msg.id ?? (msg as any).message_id, 128) ?? "";
|
|
512
|
+
const isDm = DIRECT_CHANNEL_RE.test(channel);
|
|
259
513
|
const where = isDm ? "私聊 (DM)" : `频道 ${channel}`;
|
|
260
514
|
const actionHint = isTruncated
|
|
261
515
|
? `——消息已截断,可调 get_history 查看全文,再用 reply 回复`
|
|
@@ -277,16 +531,28 @@ export function buildGrokPrompt(msg: WakeMessage, agentId: string, contextPrefix
|
|
|
277
531
|
* rotate it are picked up automatically, and it never touches argv/env/channel.
|
|
278
532
|
*/
|
|
279
533
|
export function grokBearerFromGatewayConfig(cfg: any): string | null {
|
|
280
|
-
if (!cfg || typeof cfg !== "object")
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
534
|
+
if (!cfg || typeof cfg !== "object" || Array.isArray(cfg) || Object.prototype.hasOwnProperty.call(cfg, "__proto__")) {
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
537
|
+
const candidate =
|
|
538
|
+
typeof cfg.token === "string" && cfg.token
|
|
539
|
+
? cfg.token.trim()
|
|
540
|
+
: cfg.auth &&
|
|
541
|
+
typeof cfg.auth === "object" &&
|
|
542
|
+
!Array.isArray(cfg.auth) &&
|
|
543
|
+
!Object.prototype.hasOwnProperty.call(cfg.auth, "__proto__") &&
|
|
544
|
+
typeof cfg.auth.bearer === "string" &&
|
|
545
|
+
cfg.auth.bearer
|
|
546
|
+
? cfg.auth.bearer.trim()
|
|
547
|
+
: "";
|
|
548
|
+
if (!candidate || candidate.length > 4096 || /[\x00-\x20\x7f-\x9f\u2028\u2029]/.test(candidate)) return null;
|
|
549
|
+
return candidate;
|
|
284
550
|
}
|
|
285
551
|
|
|
286
552
|
/** Extract the gateway port (for the loopback URL) from a parsed gateway.json. */
|
|
287
553
|
export function grokPortFromGatewayConfig(cfg: any, fallback = 1340): number {
|
|
288
554
|
const p = cfg?.port;
|
|
289
|
-
return typeof p === "number" && p
|
|
555
|
+
return typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535 ? p : fallback;
|
|
290
556
|
}
|
|
291
557
|
|
|
292
558
|
/**
|
|
@@ -299,7 +565,7 @@ export function grokPortFromGatewayConfig(cfg: any, fallback = 1340): number {
|
|
|
299
565
|
* error — fail closed, no wake.
|
|
300
566
|
*/
|
|
301
567
|
export const GROK_GATEWAY_PATH_CANDIDATES = [
|
|
302
|
-
|
|
568
|
+
join(process.env.HOME || process.env.USERPROFILE || homedir(), ".grok", "gateway.json"),
|
|
303
569
|
"/home/box/sand-data/gateway.json",
|
|
304
570
|
] as const;
|
|
305
571
|
|
|
@@ -355,7 +621,7 @@ export async function resolveGrokAgentId(opts: {
|
|
|
355
621
|
return hit.id;
|
|
356
622
|
}
|
|
357
623
|
} catch (e) {
|
|
358
|
-
log(`[agentchat] grok wake: listAgents fallback failed: ${e}`);
|
|
624
|
+
log(`[agentchat] grok wake: listAgents fallback failed: ${redactSecrets(String(e)).slice(0, 200)}`);
|
|
359
625
|
}
|
|
360
626
|
}
|
|
361
627
|
log(`[agentchat] grok wake: no Grok agentId bound. Set AGENTCHAT_GROK_AGENT_ID=<gateway agent uuid> (1:1 mapping).`);
|
|
@@ -374,10 +640,24 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
374
640
|
}
|
|
375
641
|
let gwcfg: any;
|
|
376
642
|
try {
|
|
377
|
-
const
|
|
378
|
-
|
|
643
|
+
const rawGatewayDir = dirname(cfg.gatewayConfigPath);
|
|
644
|
+
const resolvedGatewayPath = resolve(cfg.gatewayConfigPath);
|
|
645
|
+
if (!hasSafeWakeDirChain(rawGatewayDir) || !hasSafeWakeDirChain(dirname(resolvedGatewayPath))) {
|
|
646
|
+
log(`[agentchat] grok wake: rejected symlinked ancestor directory for ${cfg.gatewayConfigPath}`);
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
const stat = lstatSync(resolvedGatewayPath);
|
|
650
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > GROK_GATEWAY_MAX_BYTES) {
|
|
651
|
+
log(`[agentchat] grok wake: rejected unsafe or oversized gateway config ${cfg.gatewayConfigPath}`);
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
gwcfg = JSON.parse(readFileSync(resolvedGatewayPath, "utf8"));
|
|
655
|
+
if (!gwcfg || typeof gwcfg !== "object" || Object.prototype.hasOwnProperty.call(gwcfg, "__proto__")) {
|
|
656
|
+
log(`[agentchat] grok wake: rejected malformed gateway config ${cfg.gatewayConfigPath}`);
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
379
659
|
} catch (e) {
|
|
380
|
-
log(`[agentchat] grok wake: cannot read ${cfg.gatewayConfigPath}: ${e}`);
|
|
660
|
+
log(`[agentchat] grok wake: cannot read ${cfg.gatewayConfigPath}: ${redactSecrets(String(e)).slice(0, 200)}`);
|
|
381
661
|
return;
|
|
382
662
|
}
|
|
383
663
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
@@ -388,11 +668,13 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
388
668
|
const port = grokPortFromGatewayConfig(gwcfg);
|
|
389
669
|
const url = `http://127.0.0.1:${port}/api/sendPrompt`;
|
|
390
670
|
const body = JSON.stringify(buildGrokPrompt(msg, cfg.agentId, cfg.contextPrefix));
|
|
671
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 5000);
|
|
391
672
|
|
|
392
673
|
const doPost = async (): Promise<void> => {
|
|
393
674
|
const f = cfg.fetchImpl ?? fetch;
|
|
394
675
|
const ctrl = new AbortController();
|
|
395
|
-
const t = setTimeout(() => ctrl.abort(),
|
|
676
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
677
|
+
t.unref?.();
|
|
396
678
|
try {
|
|
397
679
|
const res = await f(url, {
|
|
398
680
|
method: "POST",
|
|
@@ -401,6 +683,7 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
401
683
|
signal: ctrl.signal,
|
|
402
684
|
});
|
|
403
685
|
if (!res.ok) log(`[agentchat] grok wake POST ${url} → HTTP ${res.status}`);
|
|
686
|
+
await res.body?.cancel().catch(() => {});
|
|
404
687
|
} finally {
|
|
405
688
|
clearTimeout(t);
|
|
406
689
|
}
|
|
@@ -412,7 +695,7 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
412
695
|
try {
|
|
413
696
|
await doPost();
|
|
414
697
|
} catch (e2) {
|
|
415
|
-
log(`[agentchat] grok wake POST ${url} failed: ${e2}`);
|
|
698
|
+
log(`[agentchat] grok wake POST ${url} failed: ${redactSecrets(String(e2)).slice(0, 200)}`);
|
|
416
699
|
}
|
|
417
700
|
}
|
|
418
701
|
}
|
|
@@ -431,10 +714,10 @@ export function buildWakePrompt(msg: WakeMessage, contextPrefix = ""): string {
|
|
|
431
714
|
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
432
715
|
const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
|
|
433
716
|
const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim(), redactOpts) : "";
|
|
434
|
-
const channel = msg.channel_id ?? "?";
|
|
435
|
-
const sender = msg.sender_id ?? "someone";
|
|
436
|
-
const msgId = (msg.id ?? (msg as any).message_id ?? ""
|
|
437
|
-
const isDm =
|
|
717
|
+
const channel = sanitizeWakeHeaderToken(msg.channel_id, 128) ?? "?";
|
|
718
|
+
const sender = sanitizeWakeHeaderToken(msg.sender_id, 128) ?? "someone";
|
|
719
|
+
const msgId = sanitizeWakeHeaderToken(msg.id ?? (msg as any).message_id, 128) ?? "";
|
|
720
|
+
const isDm = DIRECT_CHANNEL_RE.test(channel);
|
|
438
721
|
const where = isDm ? `私聊 (${channel})` : `频道 ${channel}`;
|
|
439
722
|
const actionHint = isTruncated
|
|
440
723
|
? ` —— 消息过长已截断,可调用 get_history(chat_id, message_id) 查看全文,再用 reply 回复并 mark_read 标记已读`
|
|
@@ -477,17 +760,29 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
477
760
|
const log = cfg.logger ?? (() => {});
|
|
478
761
|
const conversationId = (cfg.conversationId ?? "").trim();
|
|
479
762
|
const csrfToken = (cfg.csrfToken ?? "").trim();
|
|
480
|
-
if (
|
|
481
|
-
|
|
763
|
+
if (
|
|
764
|
+
!conversationId ||
|
|
765
|
+
conversationId.length > 128 ||
|
|
766
|
+
/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(conversationId) ||
|
|
767
|
+
!csrfToken ||
|
|
768
|
+
csrfToken.length > 1024 ||
|
|
769
|
+
/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(csrfToken)
|
|
770
|
+
) {
|
|
771
|
+
log(`[agentchat] antigravity wake: missing or unsafe conversationId or csrfToken, skipping`);
|
|
482
772
|
return false;
|
|
483
773
|
}
|
|
484
774
|
|
|
485
775
|
const addresses: string[] = [];
|
|
486
776
|
if (cfg.lsAddress && cfg.lsAddress.trim()) {
|
|
487
|
-
|
|
777
|
+
const safeAddr = normalizeLoopbackLsAddress(cfg.lsAddress);
|
|
778
|
+
if (safeAddr) {
|
|
779
|
+
addresses.push(safeAddr);
|
|
780
|
+
} else {
|
|
781
|
+
log(`[agentchat] antigravity wake: rejected non-loopback or invalid lsAddress`);
|
|
782
|
+
}
|
|
488
783
|
}
|
|
489
784
|
for (const p of cfg.ports ?? []) {
|
|
490
|
-
if (typeof p === "number" && p
|
|
785
|
+
if (typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535) {
|
|
491
786
|
const addr = `127.0.0.1:${p}`;
|
|
492
787
|
if (!addresses.includes(addr)) addresses.push(addr);
|
|
493
788
|
}
|
|
@@ -498,8 +793,8 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
498
793
|
}
|
|
499
794
|
|
|
500
795
|
const prompt = cfg.promptOverride ?? buildWakePrompt(msg, cfg.contextPrefix);
|
|
501
|
-
const channel = msg.channel_id ?? "chat";
|
|
502
|
-
const sender = msg.sender_id ?? "channel";
|
|
796
|
+
const channel = sanitizeWakeHeaderToken(redactSecrets(String(msg.channel_id ?? "")), 128) ?? "chat";
|
|
797
|
+
const sender = sanitizeWakeHeaderToken(redactSecrets(String(msg.sender_id ?? "")), 128) ?? "channel";
|
|
503
798
|
const body = JSON.stringify({
|
|
504
799
|
recipient: conversationId,
|
|
505
800
|
senderId: `agentschat:${sender}`,
|
|
@@ -508,10 +803,12 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
508
803
|
});
|
|
509
804
|
|
|
510
805
|
const f = cfg.fetchImpl ?? fetch;
|
|
806
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 5000);
|
|
511
807
|
for (const addr of addresses) {
|
|
512
808
|
const url = `http://${addr}/exa.language_server_pb.LanguageServerService/SendAgentMessage`;
|
|
513
809
|
const ctrl = new AbortController();
|
|
514
|
-
const t = setTimeout(() => ctrl.abort(),
|
|
810
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
811
|
+
t.unref?.();
|
|
515
812
|
try {
|
|
516
813
|
const res = await f(url, {
|
|
517
814
|
method: "POST",
|
|
@@ -523,6 +820,7 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
523
820
|
body,
|
|
524
821
|
signal: ctrl.signal,
|
|
525
822
|
});
|
|
823
|
+
await res.body?.cancel().catch(() => {});
|
|
526
824
|
if (res.ok) {
|
|
527
825
|
return true;
|
|
528
826
|
}
|
|
@@ -554,6 +852,8 @@ export interface ZcodeWakeConfig {
|
|
|
554
852
|
promptOverride?: string;
|
|
555
853
|
/** Timeout per turn in ms (default 180s). */
|
|
556
854
|
timeoutMs?: number;
|
|
855
|
+
/** Grace period in ms after SIGTERM before escalating to SIGKILL (default 2000ms). */
|
|
856
|
+
killGraceMs?: number;
|
|
557
857
|
/** Injectable runner for unit tests. */
|
|
558
858
|
runCommandImpl?: (cmd: string, args: string[], opts: { cwd?: string; env: Record<string, string | undefined>; timeoutMs: number }) => Promise<{ code: number; stderr?: string }>;
|
|
559
859
|
logger?: (msg: string) => void;
|
|
@@ -561,6 +861,94 @@ export interface ZcodeWakeConfig {
|
|
|
561
861
|
|
|
562
862
|
const zcodeSessionQueues = new Map<string, Promise<void>>();
|
|
563
863
|
|
|
864
|
+
export interface ResolveWindowsCliOptions {
|
|
865
|
+
platform?: NodeJS.Platform;
|
|
866
|
+
env?: Record<string, string | undefined>;
|
|
867
|
+
execPath?: string;
|
|
868
|
+
existsImpl?: (path: string) => boolean;
|
|
869
|
+
readTextImpl?: (path: string) => string;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Safely resolve a CLI command on Windows (`win32`) without `shell: true`
|
|
874
|
+
* (preventing Node CVE-2024-27980 `EINVAL` / `ENOENT` on npm `.cmd` shims AND
|
|
875
|
+
* preventing `cmd.exe` `%VAR%` / `&` metacharacter injection on user prompts).
|
|
876
|
+
*
|
|
877
|
+
* Resolution order on `win32`:
|
|
878
|
+
* 1. `.js` / `.cjs` / `.mjs` script -> `{ cmd: execPath, args: [script, ...args] }`
|
|
879
|
+
* 2. `<cmd>.exe` (explicit path or on `PATH`) -> `{ cmd: exePath, args }`
|
|
880
|
+
* 3. npm `<cmd>.cmd` shim wrapping a JS/CJS/MJS script (`"%~dp0\...\cli.js" %*`
|
|
881
|
+
* or `"%dp0%\...\cli.cjs" %*`) -> `{ cmd: execPath, args: [resolvedJsPath, ...args] }`
|
|
882
|
+
*/
|
|
883
|
+
export function resolveWindowsCliSpawn(
|
|
884
|
+
cmd: string,
|
|
885
|
+
args: string[],
|
|
886
|
+
opts?: ResolveWindowsCliOptions,
|
|
887
|
+
): { cmd: string; args: string[] } {
|
|
888
|
+
const platform = opts?.platform ?? process.platform;
|
|
889
|
+
const trimmed = (cmd || "").trim();
|
|
890
|
+
if (!trimmed) return { cmd, args };
|
|
891
|
+
const execPath = opts?.execPath ?? process.execPath;
|
|
892
|
+
if (/\.(?:cjs|mjs|js)$/i.test(trimmed)) {
|
|
893
|
+
return { cmd: execPath, args: [trimmed, ...args] };
|
|
894
|
+
}
|
|
895
|
+
if (platform !== "win32") {
|
|
896
|
+
return { cmd: trimmed, args };
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
const env = opts?.env ?? process.env;
|
|
900
|
+
const exists = opts?.existsImpl ?? existsSync;
|
|
901
|
+
const readText = opts?.readTextImpl ?? ((p: string) => readFileSync(p, "utf8"));
|
|
902
|
+
const hasSep = /[\\/]/.test(trimmed) || /^[A-Za-z]:/.test(trimmed);
|
|
903
|
+
const hasWinExt = /\.(?:exe|cmd|bat)$/i.test(trimmed);
|
|
904
|
+
|
|
905
|
+
const candidates: string[] = [];
|
|
906
|
+
if (hasSep) {
|
|
907
|
+
if (hasWinExt) {
|
|
908
|
+
candidates.push(trimmed);
|
|
909
|
+
} else {
|
|
910
|
+
candidates.push(`${trimmed}.exe`, `${trimmed}.cmd`, trimmed);
|
|
911
|
+
}
|
|
912
|
+
} else {
|
|
913
|
+
const rawPath = env.PATH ?? env.Path ?? env.path ?? "";
|
|
914
|
+
for (const rawDir of rawPath.split(";")) {
|
|
915
|
+
const dir = rawDir.trim().replace(/^"+|"+$/g, "");
|
|
916
|
+
if (!dir) continue;
|
|
917
|
+
if (hasWinExt) {
|
|
918
|
+
candidates.push(pathWin32.join(dir, trimmed));
|
|
919
|
+
} else {
|
|
920
|
+
candidates.push(pathWin32.join(dir, `${trimmed}.exe`), pathWin32.join(dir, `${trimmed}.cmd`));
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
for (const candidate of candidates) {
|
|
926
|
+
if (!exists(candidate)) continue;
|
|
927
|
+
if (/\.exe$/i.test(candidate)) {
|
|
928
|
+
return { cmd: candidate, args };
|
|
929
|
+
}
|
|
930
|
+
if (/\.(?:cmd|bat)$/i.test(candidate)) {
|
|
931
|
+
try {
|
|
932
|
+
const content = readText(candidate);
|
|
933
|
+
const m = content.match(/%(?:~)?dp0%?[\\/]([^"\r\n]+?\.(?:cjs|mjs|js))/i);
|
|
934
|
+
if (m && m[1]) {
|
|
935
|
+
const cmdDir = pathWin32.dirname(candidate);
|
|
936
|
+
const scriptPath = pathWin32.resolve(cmdDir, m[1].replace(/\//g, "\\"));
|
|
937
|
+
if (exists(scriptPath)) {
|
|
938
|
+
const bundledNode = pathWin32.join(cmdDir, "node.exe");
|
|
939
|
+
const runner = exists(bundledNode) ? bundledNode : execPath;
|
|
940
|
+
return { cmd: runner, args: [scriptPath, ...args] };
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
} catch {}
|
|
944
|
+
return { cmd: candidate, args };
|
|
945
|
+
}
|
|
946
|
+
return { cmd: candidate, args };
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
return { cmd: trimmed, args };
|
|
950
|
+
}
|
|
951
|
+
|
|
564
952
|
/**
|
|
565
953
|
* Resolve the executable command + prefix args for `zcode` CLI.
|
|
566
954
|
* Supports `zcode` on PATH or macOS `/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs`.
|
|
@@ -568,18 +956,19 @@ const zcodeSessionQueues = new Map<string, Promise<void>>();
|
|
|
568
956
|
export async function resolveZcodeCommand(explicitBin?: string): Promise<{ cmd: string; prefixArgs: string[] }> {
|
|
569
957
|
const fromArg = (explicitBin ?? process.env.ZCODE_BIN ?? "").trim();
|
|
570
958
|
if (fromArg) {
|
|
571
|
-
if (
|
|
572
|
-
return { cmd:
|
|
959
|
+
if (/\.(?:cjs|mjs|js)$/i.test(fromArg)) {
|
|
960
|
+
return { cmd: process.execPath, prefixArgs: [fromArg] };
|
|
573
961
|
}
|
|
574
962
|
return { cmd: fromArg, prefixArgs: [] };
|
|
575
963
|
}
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
964
|
+
if (process.platform === "darwin") {
|
|
965
|
+
const macAppBundleCjs = "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs";
|
|
966
|
+
try {
|
|
967
|
+
if (existsSync(macAppBundleCjs)) {
|
|
968
|
+
return { cmd: process.execPath, prefixArgs: [macAppBundleCjs] };
|
|
969
|
+
}
|
|
970
|
+
} catch {}
|
|
971
|
+
}
|
|
583
972
|
return { cmd: "zcode", prefixArgs: [] };
|
|
584
973
|
}
|
|
585
974
|
|
|
@@ -591,8 +980,8 @@ export async function resolveZcodeCommand(explicitBin?: string): Promise<{ cmd:
|
|
|
591
980
|
export function fireZcodeWake(msg: WakeMessage, cfg: ZcodeWakeConfig): Promise<boolean> {
|
|
592
981
|
const log = cfg.logger ?? (() => {});
|
|
593
982
|
const sessionId = (cfg.sessionId ?? "").trim();
|
|
594
|
-
if (!sessionId) {
|
|
595
|
-
log(`[agentchat] zcode wake: missing sessionId, skipping`);
|
|
983
|
+
if (!sessionId || !SAFE_ZCODE_SESSION_ID_RE.test(sessionId)) {
|
|
984
|
+
log(`[agentchat] zcode wake: missing or unsafe sessionId, skipping`);
|
|
596
985
|
return Promise.resolve(false);
|
|
597
986
|
}
|
|
598
987
|
|
|
@@ -603,60 +992,90 @@ export function fireZcodeWake(msg: WakeMessage, cfg: ZcodeWakeConfig): Promise<b
|
|
|
603
992
|
const runTurn = async (): Promise<void> => {
|
|
604
993
|
try {
|
|
605
994
|
const { cmd, prefixArgs } = await resolveZcodeCommand(cfg.zcodeBin);
|
|
606
|
-
const
|
|
995
|
+
const rawArgs = [...prefixArgs, "-p", prompt, "--resume", sessionId];
|
|
607
996
|
if (cfg.workspacePath && cfg.workspacePath.trim()) {
|
|
608
|
-
|
|
997
|
+
const wsPath = cfg.workspacePath.trim();
|
|
998
|
+
if (!wsPath.startsWith("-") && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(wsPath)) {
|
|
999
|
+
rawArgs.push("--cwd", wsPath);
|
|
1000
|
+
}
|
|
609
1001
|
}
|
|
1002
|
+
const safeProfileName =
|
|
1003
|
+
typeof cfg.profileName === "string" &&
|
|
1004
|
+
cfg.profileName.trim().length > 0 &&
|
|
1005
|
+
cfg.profileName.trim().length <= 128 &&
|
|
1006
|
+
!cfg.profileName.includes("..") &&
|
|
1007
|
+
!/[\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(cfg.profileName.trim()) &&
|
|
1008
|
+
!PROTOTYPE_WAKE_KEYS.has(cfg.profileName.trim().toLowerCase())
|
|
1009
|
+
? cfg.profileName.trim()
|
|
1010
|
+
: undefined;
|
|
610
1011
|
const env: Record<string, string | undefined> = {
|
|
611
1012
|
...process.env,
|
|
612
1013
|
AGENTSCHAT_TOOL_ONLY: "1",
|
|
613
1014
|
AGENTSCHAT_LOCK_OWNER_PID: String(cfg.lockOwnerPid ?? process.pid),
|
|
614
1015
|
ZCODE_SESSION_ID: sessionId,
|
|
615
|
-
...(
|
|
1016
|
+
...(safeProfileName ? { AGENTSCHAT_PROFILE: safeProfileName } : {}),
|
|
616
1017
|
};
|
|
617
|
-
const
|
|
1018
|
+
const resolved = resolveWindowsCliSpawn(cmd, rawArgs, { env });
|
|
1019
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 180_000);
|
|
1020
|
+
const killGraceMs = clampWakeTimerMs(cfg.killGraceMs, 2000);
|
|
618
1021
|
|
|
619
1022
|
if (cfg.runCommandImpl) {
|
|
620
|
-
const res = await cfg.runCommandImpl(cmd, args, { cwd: cfg.workspacePath, env, timeoutMs });
|
|
1023
|
+
const res = await cfg.runCommandImpl(resolved.cmd, resolved.args, { cwd: cfg.workspacePath, env, timeoutMs });
|
|
621
1024
|
succeeded = res.code === 0;
|
|
622
1025
|
if (!succeeded) {
|
|
623
|
-
log(`[agentchat] zcode wake (${sessionId}) exited with code ${res.code}${res.stderr ? `: ${res.stderr.slice(0, 200)}` : ""}`);
|
|
1026
|
+
log(`[agentchat] zcode wake (${sessionId}) exited with code ${res.code}${res.stderr ? `: ${redactSecrets(res.stderr).slice(0, 200)}` : ""}`);
|
|
624
1027
|
}
|
|
625
1028
|
return;
|
|
626
1029
|
}
|
|
627
1030
|
|
|
628
1031
|
const { spawn } = await import("node:child_process");
|
|
629
1032
|
await new Promise<void>((resolve) => {
|
|
630
|
-
const child = spawn(cmd, args, {
|
|
1033
|
+
const child = spawn(resolved.cmd, resolved.args, {
|
|
631
1034
|
cwd: cfg.workspacePath || process.cwd(),
|
|
632
1035
|
env: env as NodeJS.ProcessEnv,
|
|
633
1036
|
stdio: ["ignore", "ignore", "pipe"],
|
|
1037
|
+
windowsHide: true,
|
|
634
1038
|
});
|
|
635
1039
|
let stderr = "";
|
|
636
1040
|
child.stderr?.on("data", (chunk) => {
|
|
637
|
-
if (stderr.length < 500) stderr += String(chunk);
|
|
1041
|
+
if (stderr.length < 500) stderr += String(chunk).slice(0, 500 - stderr.length);
|
|
638
1042
|
});
|
|
1043
|
+
let killGraceTimer: ReturnType<typeof setTimeout> | null = null;
|
|
1044
|
+
const clearTimers = () => {
|
|
1045
|
+
clearTimeout(timer);
|
|
1046
|
+
if (killGraceTimer) {
|
|
1047
|
+
clearTimeout(killGraceTimer);
|
|
1048
|
+
killGraceTimer = null;
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
639
1051
|
const timer = setTimeout(() => {
|
|
640
1052
|
try {
|
|
641
1053
|
child.kill("SIGTERM");
|
|
642
1054
|
} catch {}
|
|
1055
|
+
killGraceTimer = setTimeout(() => {
|
|
1056
|
+
try {
|
|
1057
|
+
child.kill("SIGKILL");
|
|
1058
|
+
} catch {}
|
|
1059
|
+
}, killGraceMs);
|
|
1060
|
+
killGraceTimer.unref?.();
|
|
643
1061
|
}, timeoutMs);
|
|
1062
|
+
timer.unref?.();
|
|
644
1063
|
child.on("error", (err) => {
|
|
645
|
-
|
|
646
|
-
log(`[agentchat] zcode wake spawn error (${sessionId}): ${err}`);
|
|
1064
|
+
clearTimers();
|
|
1065
|
+
log(`[agentchat] zcode wake spawn error (${sessionId}): ${redactSecrets(String(err)).slice(0, 200)}`);
|
|
647
1066
|
resolve();
|
|
648
1067
|
});
|
|
649
1068
|
child.on("close", (code) => {
|
|
650
|
-
|
|
1069
|
+
clearTimers();
|
|
651
1070
|
succeeded = code === 0;
|
|
652
1071
|
if (!succeeded) {
|
|
653
|
-
log(`[agentchat] zcode wake (${sessionId}) exited code=${code}${stderr ? `: ${stderr.trim().slice(0, 200)}` : ""}`);
|
|
1072
|
+
log(`[agentchat] zcode wake (${sessionId}) exited code=${code}${stderr ? `: ${redactSecrets(stderr.trim()).slice(0, 200)}` : ""}`);
|
|
654
1073
|
}
|
|
655
1074
|
resolve();
|
|
656
1075
|
});
|
|
657
1076
|
});
|
|
658
1077
|
} catch (e) {
|
|
659
|
-
log(`[agentchat] zcode wake failed (${sessionId}): ${e}`);
|
|
1078
|
+
log(`[agentchat] zcode wake failed (${sessionId}): ${redactSecrets(String(e)).slice(0, 200)}`);
|
|
660
1079
|
}
|
|
661
1080
|
};
|
|
662
1081
|
|