agentschat-mcp 0.36.24 → 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.
- package/CHANGELOG.md +12 -0
- package/README.md +8 -0
- package/codex/README.md +1 -1
- package/codex/app-server.ts +79 -22
- package/codex/bots-config.ts +31 -11
- package/codex/bridge.ts +123 -25
- package/codex/config.ts +128 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +65 -12
- package/codex/loop-grants.ts +41 -11
- package/codex/manager.ts +101 -25
- package/codex/owner.ts +81 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +41 -11
- package/codex/thread-history.ts +77 -30
- package/codex/transport.ts +122 -19
- 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/dist/codex-bots.js +410 -73
- package/dist/codex-bridge.js +1996 -576
- package/dist/connector.js +1286 -493
- package/dist/dsh.js +1776 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +7645 -1172
- 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 +595 -146
- 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 +990 -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/agentschat-team-lead/SKILL.md +1 -1
- package/skills/onboarding.md +14 -10
- package/src/argcheck.ts +1890 -1
- package/src/cli.mjs +98 -14
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +160 -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 +269 -18
- package/src/profile-store.ts +222 -28
- package/src/read-cursor.ts +256 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +2487 -342
- package/src/session-bind.ts +731 -132
- 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 +22 -1
- package/src/wake.ts +524 -90
package/src/wake.ts
CHANGED
|
@@ -23,10 +23,186 @@
|
|
|
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. */
|
|
29
32
|
export const WAKE_SIG_HEADER = "x-agentschat-signature";
|
|
33
|
+
/** Header forwarded on authenticated REST calls when AGENTSCHAT_WAKE_ID is present. */
|
|
34
|
+
export const WAKE_ID_HEADER = "X-AgentsChat-Wake-Id";
|
|
35
|
+
const SAFE_WAKE_ID_RE = /^[a-zA-Z0-9_-]{1,128}$/;
|
|
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
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Validate `AGENTSCHAT_WAKE_ID` injected by Cloud Sandbox per wake turn so
|
|
198
|
+
* stdio MCP REST calls (`okr_update_task`, `okr_add_task_comment`) carry
|
|
199
|
+
* explicit process-level wake correlation without ever echoing unsafe tokens.
|
|
200
|
+
*/
|
|
201
|
+
export function resolveEnvWakeId(env: Record<string, string | undefined> = process.env): string | undefined {
|
|
202
|
+
const raw = env.AGENTSCHAT_WAKE_ID?.trim();
|
|
203
|
+
if (!raw || !SAFE_WAKE_ID_RE.test(raw) || CREDENTIAL_PREFIX_RE.test(raw)) return undefined;
|
|
204
|
+
return raw;
|
|
205
|
+
}
|
|
30
206
|
|
|
31
207
|
/** Cap the content excerpt for generic HTTP wake webhooks so a long message doesn't balloon the POST body. */
|
|
32
208
|
export const WAKE_CONTENT_MAX = 500;
|
|
@@ -83,20 +259,65 @@ export function formatWakeAttachments(attachments: unknown): string {
|
|
|
83
259
|
for (const raw of attachments) {
|
|
84
260
|
if (!raw || typeof raw !== "object") continue;
|
|
85
261
|
const a = raw as WakeAttachment;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
|
|
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
|
+
: "";
|
|
90
280
|
const icon = t === "image" ? "🖼" : t === "video" ? "🎬" : t === "audio" ? "🔊" : "📎";
|
|
91
|
-
let desc = `${icon} ${t}${dim}${dur}: ${
|
|
92
|
-
if (typeof a.transcript === "string"
|
|
93
|
-
|
|
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
|
+
}
|
|
94
290
|
}
|
|
95
291
|
lines.push(desc);
|
|
96
292
|
}
|
|
97
293
|
return lines.length > 0 ? ` [附件: ${lines.join("; ")}]` : "";
|
|
98
294
|
}
|
|
99
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
|
+
|
|
100
321
|
/**
|
|
101
322
|
* Build the wake body: the fields the receiver needs to wake + decide + optionally
|
|
102
323
|
* skip a history fetch. Credential-shaped fields are never carried across.
|
|
@@ -110,29 +331,43 @@ export function buildWakePayload(msg: WakeMessage, opts: { targetSessionId?: str
|
|
|
110
331
|
const content = typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX), redactOpts) : undefined;
|
|
111
332
|
const attachments = Array.isArray(msg.attachments) && msg.attachments.length > 0
|
|
112
333
|
? msg.attachments
|
|
113
|
-
.
|
|
114
|
-
.map((a) =>
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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))
|
|
124
361
|
: undefined;
|
|
125
|
-
const targetSessionId =
|
|
126
|
-
typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
|
|
127
362
|
return {
|
|
128
|
-
type:
|
|
129
|
-
channel_id:
|
|
130
|
-
message_id:
|
|
131
|
-
sender_id:
|
|
363
|
+
type: sanitizeWakeHeaderToken(msg.type, 64) ?? "message",
|
|
364
|
+
channel_id: channelId,
|
|
365
|
+
message_id: messageId,
|
|
366
|
+
sender_id: senderId,
|
|
132
367
|
content,
|
|
133
368
|
...(attachments && attachments.length > 0 ? { attachments } : {}),
|
|
134
|
-
mentioned_ids:
|
|
135
|
-
timestamp:
|
|
369
|
+
mentioned_ids: mentionedIds,
|
|
370
|
+
timestamp: sanitizeWakeHeaderToken(msg.timestamp, 64),
|
|
136
371
|
...(targetSessionId ? { target_session_id: targetSessionId } : {}),
|
|
137
372
|
};
|
|
138
373
|
}
|
|
@@ -144,15 +379,19 @@ export function signWakeBody(body: string, secret: string): string {
|
|
|
144
379
|
|
|
145
380
|
/** Constant-time check that `sigHex` signs `body` under ANY of `secrets` (rotation). */
|
|
146
381
|
export function verifyWakeSignature(body: string, sigHex: string, secrets: readonly string[]): boolean {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
return false;
|
|
152
|
-
}
|
|
153
|
-
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;
|
|
154
386
|
for (const secret of secrets) {
|
|
155
|
-
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
|
+
}
|
|
156
395
|
const expected = Buffer.from(signWakeBody(body, secret), "hex");
|
|
157
396
|
if (expected.length !== sigBuf.length) continue;
|
|
158
397
|
if (timingSafeEqual(sigBuf, expected)) return true;
|
|
@@ -160,6 +399,20 @@ export function verifyWakeSignature(body: string, sigHex: string, secrets: reado
|
|
|
160
399
|
return false;
|
|
161
400
|
}
|
|
162
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
|
+
|
|
163
416
|
export interface WakeConfig {
|
|
164
417
|
/** Where to POST. Empty/absent disables the wake webhook entirely. */
|
|
165
418
|
url?: string;
|
|
@@ -182,19 +435,35 @@ export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void>
|
|
|
182
435
|
const log = cfg.logger ?? (() => {});
|
|
183
436
|
const url = (cfg.url ?? "").trim();
|
|
184
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
|
+
}
|
|
185
443
|
|
|
186
444
|
const payload = buildWakePayload(msg, { targetSessionId: cfg.targetSessionId });
|
|
445
|
+
if (!payload.timestamp) payload.timestamp = new Date().toISOString();
|
|
187
446
|
const body = JSON.stringify(payload);
|
|
188
447
|
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
189
|
-
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
|
+
}
|
|
190
456
|
|
|
457
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 5000);
|
|
191
458
|
const doPost = async (): Promise<void> => {
|
|
192
459
|
const f = cfg.fetchImpl ?? fetch;
|
|
193
460
|
const ctrl = new AbortController();
|
|
194
|
-
const t = setTimeout(() => ctrl.abort(),
|
|
461
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
462
|
+
t.unref?.();
|
|
195
463
|
try {
|
|
196
|
-
const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
|
|
197
|
-
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(() => {});
|
|
198
467
|
} finally {
|
|
199
468
|
clearTimeout(t);
|
|
200
469
|
}
|
|
@@ -207,7 +476,7 @@ export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void>
|
|
|
207
476
|
try {
|
|
208
477
|
await doPost();
|
|
209
478
|
} catch (e2) {
|
|
210
|
-
log(`[agentchat] wake POST ${
|
|
479
|
+
log(`[agentchat] wake POST ${safeLogUrl} failed: ${redactSecrets(String(e2)).slice(0, 200)}`);
|
|
211
480
|
}
|
|
212
481
|
}
|
|
213
482
|
}
|
|
@@ -237,10 +506,10 @@ export function buildGrokPrompt(msg: WakeMessage, agentId: string, contextPrefix
|
|
|
237
506
|
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
238
507
|
const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
|
|
239
508
|
const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim(), redactOpts) : "";
|
|
240
|
-
const channel = msg.channel_id ?? "?";
|
|
241
|
-
const sender = msg.sender_id ?? "someone";
|
|
242
|
-
const msgId = (msg.id ?? (msg as any).message_id ?? ""
|
|
243
|
-
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);
|
|
244
513
|
const where = isDm ? "私聊 (DM)" : `频道 ${channel}`;
|
|
245
514
|
const actionHint = isTruncated
|
|
246
515
|
? `——消息已截断,可调 get_history 查看全文,再用 reply 回复`
|
|
@@ -262,16 +531,28 @@ export function buildGrokPrompt(msg: WakeMessage, agentId: string, contextPrefix
|
|
|
262
531
|
* rotate it are picked up automatically, and it never touches argv/env/channel.
|
|
263
532
|
*/
|
|
264
533
|
export function grokBearerFromGatewayConfig(cfg: any): string | null {
|
|
265
|
-
if (!cfg || typeof cfg !== "object")
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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;
|
|
269
550
|
}
|
|
270
551
|
|
|
271
552
|
/** Extract the gateway port (for the loopback URL) from a parsed gateway.json. */
|
|
272
553
|
export function grokPortFromGatewayConfig(cfg: any, fallback = 1340): number {
|
|
273
554
|
const p = cfg?.port;
|
|
274
|
-
return typeof p === "number" && p
|
|
555
|
+
return typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535 ? p : fallback;
|
|
275
556
|
}
|
|
276
557
|
|
|
277
558
|
/**
|
|
@@ -284,7 +565,7 @@ export function grokPortFromGatewayConfig(cfg: any, fallback = 1340): number {
|
|
|
284
565
|
* error — fail closed, no wake.
|
|
285
566
|
*/
|
|
286
567
|
export const GROK_GATEWAY_PATH_CANDIDATES = [
|
|
287
|
-
|
|
568
|
+
join(process.env.HOME || process.env.USERPROFILE || homedir(), ".grok", "gateway.json"),
|
|
288
569
|
"/home/box/sand-data/gateway.json",
|
|
289
570
|
] as const;
|
|
290
571
|
|
|
@@ -340,7 +621,7 @@ export async function resolveGrokAgentId(opts: {
|
|
|
340
621
|
return hit.id;
|
|
341
622
|
}
|
|
342
623
|
} catch (e) {
|
|
343
|
-
log(`[agentchat] grok wake: listAgents fallback failed: ${e}`);
|
|
624
|
+
log(`[agentchat] grok wake: listAgents fallback failed: ${redactSecrets(String(e)).slice(0, 200)}`);
|
|
344
625
|
}
|
|
345
626
|
}
|
|
346
627
|
log(`[agentchat] grok wake: no Grok agentId bound. Set AGENTCHAT_GROK_AGENT_ID=<gateway agent uuid> (1:1 mapping).`);
|
|
@@ -359,10 +640,24 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
359
640
|
}
|
|
360
641
|
let gwcfg: any;
|
|
361
642
|
try {
|
|
362
|
-
const
|
|
363
|
-
|
|
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
|
+
}
|
|
364
659
|
} catch (e) {
|
|
365
|
-
log(`[agentchat] grok wake: cannot read ${cfg.gatewayConfigPath}: ${e}`);
|
|
660
|
+
log(`[agentchat] grok wake: cannot read ${cfg.gatewayConfigPath}: ${redactSecrets(String(e)).slice(0, 200)}`);
|
|
366
661
|
return;
|
|
367
662
|
}
|
|
368
663
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
@@ -373,11 +668,13 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
373
668
|
const port = grokPortFromGatewayConfig(gwcfg);
|
|
374
669
|
const url = `http://127.0.0.1:${port}/api/sendPrompt`;
|
|
375
670
|
const body = JSON.stringify(buildGrokPrompt(msg, cfg.agentId, cfg.contextPrefix));
|
|
671
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 5000);
|
|
376
672
|
|
|
377
673
|
const doPost = async (): Promise<void> => {
|
|
378
674
|
const f = cfg.fetchImpl ?? fetch;
|
|
379
675
|
const ctrl = new AbortController();
|
|
380
|
-
const t = setTimeout(() => ctrl.abort(),
|
|
676
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
677
|
+
t.unref?.();
|
|
381
678
|
try {
|
|
382
679
|
const res = await f(url, {
|
|
383
680
|
method: "POST",
|
|
@@ -386,6 +683,7 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
386
683
|
signal: ctrl.signal,
|
|
387
684
|
});
|
|
388
685
|
if (!res.ok) log(`[agentchat] grok wake POST ${url} → HTTP ${res.status}`);
|
|
686
|
+
await res.body?.cancel().catch(() => {});
|
|
389
687
|
} finally {
|
|
390
688
|
clearTimeout(t);
|
|
391
689
|
}
|
|
@@ -397,7 +695,7 @@ export async function fireGrokWake(msg: WakeMessage, cfg: GrokWakeConfig): Promi
|
|
|
397
695
|
try {
|
|
398
696
|
await doPost();
|
|
399
697
|
} catch (e2) {
|
|
400
|
-
log(`[agentchat] grok wake POST ${url} failed: ${e2}`);
|
|
698
|
+
log(`[agentchat] grok wake POST ${url} failed: ${redactSecrets(String(e2)).slice(0, 200)}`);
|
|
401
699
|
}
|
|
402
700
|
}
|
|
403
701
|
}
|
|
@@ -416,10 +714,10 @@ export function buildWakePrompt(msg: WakeMessage, contextPrefix = ""): string {
|
|
|
416
714
|
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
417
715
|
const content = rawContent ? redactSecrets(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
|
|
418
716
|
const cleanPrefix = contextPrefix ? redactSecrets(contextPrefix.trim(), redactOpts) : "";
|
|
419
|
-
const channel = msg.channel_id ?? "?";
|
|
420
|
-
const sender = msg.sender_id ?? "someone";
|
|
421
|
-
const msgId = (msg.id ?? (msg as any).message_id ?? ""
|
|
422
|
-
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);
|
|
423
721
|
const where = isDm ? `私聊 (${channel})` : `频道 ${channel}`;
|
|
424
722
|
const actionHint = isTruncated
|
|
425
723
|
? ` —— 消息过长已截断,可调用 get_history(chat_id, message_id) 查看全文,再用 reply 回复并 mark_read 标记已读`
|
|
@@ -462,17 +760,29 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
462
760
|
const log = cfg.logger ?? (() => {});
|
|
463
761
|
const conversationId = (cfg.conversationId ?? "").trim();
|
|
464
762
|
const csrfToken = (cfg.csrfToken ?? "").trim();
|
|
465
|
-
if (
|
|
466
|
-
|
|
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`);
|
|
467
772
|
return false;
|
|
468
773
|
}
|
|
469
774
|
|
|
470
775
|
const addresses: string[] = [];
|
|
471
776
|
if (cfg.lsAddress && cfg.lsAddress.trim()) {
|
|
472
|
-
|
|
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
|
+
}
|
|
473
783
|
}
|
|
474
784
|
for (const p of cfg.ports ?? []) {
|
|
475
|
-
if (typeof p === "number" && p
|
|
785
|
+
if (typeof p === "number" && Number.isInteger(p) && p >= 1 && p <= 65535) {
|
|
476
786
|
const addr = `127.0.0.1:${p}`;
|
|
477
787
|
if (!addresses.includes(addr)) addresses.push(addr);
|
|
478
788
|
}
|
|
@@ -483,8 +793,8 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
483
793
|
}
|
|
484
794
|
|
|
485
795
|
const prompt = cfg.promptOverride ?? buildWakePrompt(msg, cfg.contextPrefix);
|
|
486
|
-
const channel = msg.channel_id ?? "chat";
|
|
487
|
-
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";
|
|
488
798
|
const body = JSON.stringify({
|
|
489
799
|
recipient: conversationId,
|
|
490
800
|
senderId: `agentschat:${sender}`,
|
|
@@ -493,10 +803,12 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
493
803
|
});
|
|
494
804
|
|
|
495
805
|
const f = cfg.fetchImpl ?? fetch;
|
|
806
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 5000);
|
|
496
807
|
for (const addr of addresses) {
|
|
497
808
|
const url = `http://${addr}/exa.language_server_pb.LanguageServerService/SendAgentMessage`;
|
|
498
809
|
const ctrl = new AbortController();
|
|
499
|
-
const t = setTimeout(() => ctrl.abort(),
|
|
810
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
811
|
+
t.unref?.();
|
|
500
812
|
try {
|
|
501
813
|
const res = await f(url, {
|
|
502
814
|
method: "POST",
|
|
@@ -508,6 +820,7 @@ export async function fireAntigravityWake(msg: WakeMessage, cfg: AntigravityWake
|
|
|
508
820
|
body,
|
|
509
821
|
signal: ctrl.signal,
|
|
510
822
|
});
|
|
823
|
+
await res.body?.cancel().catch(() => {});
|
|
511
824
|
if (res.ok) {
|
|
512
825
|
return true;
|
|
513
826
|
}
|
|
@@ -539,6 +852,8 @@ export interface ZcodeWakeConfig {
|
|
|
539
852
|
promptOverride?: string;
|
|
540
853
|
/** Timeout per turn in ms (default 180s). */
|
|
541
854
|
timeoutMs?: number;
|
|
855
|
+
/** Grace period in ms after SIGTERM before escalating to SIGKILL (default 2000ms). */
|
|
856
|
+
killGraceMs?: number;
|
|
542
857
|
/** Injectable runner for unit tests. */
|
|
543
858
|
runCommandImpl?: (cmd: string, args: string[], opts: { cwd?: string; env: Record<string, string | undefined>; timeoutMs: number }) => Promise<{ code: number; stderr?: string }>;
|
|
544
859
|
logger?: (msg: string) => void;
|
|
@@ -546,6 +861,94 @@ export interface ZcodeWakeConfig {
|
|
|
546
861
|
|
|
547
862
|
const zcodeSessionQueues = new Map<string, Promise<void>>();
|
|
548
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
|
+
|
|
549
952
|
/**
|
|
550
953
|
* Resolve the executable command + prefix args for `zcode` CLI.
|
|
551
954
|
* Supports `zcode` on PATH or macOS `/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs`.
|
|
@@ -553,18 +956,19 @@ const zcodeSessionQueues = new Map<string, Promise<void>>();
|
|
|
553
956
|
export async function resolveZcodeCommand(explicitBin?: string): Promise<{ cmd: string; prefixArgs: string[] }> {
|
|
554
957
|
const fromArg = (explicitBin ?? process.env.ZCODE_BIN ?? "").trim();
|
|
555
958
|
if (fromArg) {
|
|
556
|
-
if (
|
|
557
|
-
return { cmd:
|
|
959
|
+
if (/\.(?:cjs|mjs|js)$/i.test(fromArg)) {
|
|
960
|
+
return { cmd: process.execPath, prefixArgs: [fromArg] };
|
|
558
961
|
}
|
|
559
962
|
return { cmd: fromArg, prefixArgs: [] };
|
|
560
963
|
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
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
|
+
}
|
|
568
972
|
return { cmd: "zcode", prefixArgs: [] };
|
|
569
973
|
}
|
|
570
974
|
|
|
@@ -576,8 +980,8 @@ export async function resolveZcodeCommand(explicitBin?: string): Promise<{ cmd:
|
|
|
576
980
|
export function fireZcodeWake(msg: WakeMessage, cfg: ZcodeWakeConfig): Promise<boolean> {
|
|
577
981
|
const log = cfg.logger ?? (() => {});
|
|
578
982
|
const sessionId = (cfg.sessionId ?? "").trim();
|
|
579
|
-
if (!sessionId) {
|
|
580
|
-
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`);
|
|
581
985
|
return Promise.resolve(false);
|
|
582
986
|
}
|
|
583
987
|
|
|
@@ -588,60 +992,90 @@ export function fireZcodeWake(msg: WakeMessage, cfg: ZcodeWakeConfig): Promise<b
|
|
|
588
992
|
const runTurn = async (): Promise<void> => {
|
|
589
993
|
try {
|
|
590
994
|
const { cmd, prefixArgs } = await resolveZcodeCommand(cfg.zcodeBin);
|
|
591
|
-
const
|
|
995
|
+
const rawArgs = [...prefixArgs, "-p", prompt, "--resume", sessionId];
|
|
592
996
|
if (cfg.workspacePath && cfg.workspacePath.trim()) {
|
|
593
|
-
|
|
997
|
+
const wsPath = cfg.workspacePath.trim();
|
|
998
|
+
if (!wsPath.startsWith("-") && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(wsPath)) {
|
|
999
|
+
rawArgs.push("--cwd", wsPath);
|
|
1000
|
+
}
|
|
594
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;
|
|
595
1011
|
const env: Record<string, string | undefined> = {
|
|
596
1012
|
...process.env,
|
|
597
1013
|
AGENTSCHAT_TOOL_ONLY: "1",
|
|
598
1014
|
AGENTSCHAT_LOCK_OWNER_PID: String(cfg.lockOwnerPid ?? process.pid),
|
|
599
1015
|
ZCODE_SESSION_ID: sessionId,
|
|
600
|
-
...(
|
|
1016
|
+
...(safeProfileName ? { AGENTSCHAT_PROFILE: safeProfileName } : {}),
|
|
601
1017
|
};
|
|
602
|
-
const
|
|
1018
|
+
const resolved = resolveWindowsCliSpawn(cmd, rawArgs, { env });
|
|
1019
|
+
const timeoutMs = clampWakeTimerMs(cfg.timeoutMs, 180_000);
|
|
1020
|
+
const killGraceMs = clampWakeTimerMs(cfg.killGraceMs, 2000);
|
|
603
1021
|
|
|
604
1022
|
if (cfg.runCommandImpl) {
|
|
605
|
-
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 });
|
|
606
1024
|
succeeded = res.code === 0;
|
|
607
1025
|
if (!succeeded) {
|
|
608
|
-
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)}` : ""}`);
|
|
609
1027
|
}
|
|
610
1028
|
return;
|
|
611
1029
|
}
|
|
612
1030
|
|
|
613
1031
|
const { spawn } = await import("node:child_process");
|
|
614
1032
|
await new Promise<void>((resolve) => {
|
|
615
|
-
const child = spawn(cmd, args, {
|
|
1033
|
+
const child = spawn(resolved.cmd, resolved.args, {
|
|
616
1034
|
cwd: cfg.workspacePath || process.cwd(),
|
|
617
1035
|
env: env as NodeJS.ProcessEnv,
|
|
618
1036
|
stdio: ["ignore", "ignore", "pipe"],
|
|
1037
|
+
windowsHide: true,
|
|
619
1038
|
});
|
|
620
1039
|
let stderr = "";
|
|
621
1040
|
child.stderr?.on("data", (chunk) => {
|
|
622
|
-
if (stderr.length < 500) stderr += String(chunk);
|
|
1041
|
+
if (stderr.length < 500) stderr += String(chunk).slice(0, 500 - stderr.length);
|
|
623
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
|
+
};
|
|
624
1051
|
const timer = setTimeout(() => {
|
|
625
1052
|
try {
|
|
626
1053
|
child.kill("SIGTERM");
|
|
627
1054
|
} catch {}
|
|
1055
|
+
killGraceTimer = setTimeout(() => {
|
|
1056
|
+
try {
|
|
1057
|
+
child.kill("SIGKILL");
|
|
1058
|
+
} catch {}
|
|
1059
|
+
}, killGraceMs);
|
|
1060
|
+
killGraceTimer.unref?.();
|
|
628
1061
|
}, timeoutMs);
|
|
1062
|
+
timer.unref?.();
|
|
629
1063
|
child.on("error", (err) => {
|
|
630
|
-
|
|
631
|
-
log(`[agentchat] zcode wake spawn error (${sessionId}): ${err}`);
|
|
1064
|
+
clearTimers();
|
|
1065
|
+
log(`[agentchat] zcode wake spawn error (${sessionId}): ${redactSecrets(String(err)).slice(0, 200)}`);
|
|
632
1066
|
resolve();
|
|
633
1067
|
});
|
|
634
1068
|
child.on("close", (code) => {
|
|
635
|
-
|
|
1069
|
+
clearTimers();
|
|
636
1070
|
succeeded = code === 0;
|
|
637
1071
|
if (!succeeded) {
|
|
638
|
-
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)}` : ""}`);
|
|
639
1073
|
}
|
|
640
1074
|
resolve();
|
|
641
1075
|
});
|
|
642
1076
|
});
|
|
643
1077
|
} catch (e) {
|
|
644
|
-
log(`[agentchat] zcode wake failed (${sessionId}): ${e}`);
|
|
1078
|
+
log(`[agentchat] zcode wake failed (${sessionId}): ${redactSecrets(String(e)).slice(0, 200)}`);
|
|
645
1079
|
}
|
|
646
1080
|
};
|
|
647
1081
|
|