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.
- package/CHANGELOG.md +7 -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 +4277 -929
- 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 +1 -1
- 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 +9 -9
- package/src/argcheck.ts +113 -33
- 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 +285 -93
- 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 +10 -1
- package/src/wake.ts +510 -91
|
@@ -33,7 +33,9 @@
|
|
|
33
33
|
*/
|
|
34
34
|
import { spawn, spawnSync } from "node:child_process";
|
|
35
35
|
import {
|
|
36
|
+
constants as fsConstants,
|
|
36
37
|
existsSync,
|
|
38
|
+
lstatSync,
|
|
37
39
|
openSync,
|
|
38
40
|
readFileSync,
|
|
39
41
|
readdirSync,
|
|
@@ -63,7 +65,7 @@ export function defaultLockPath() {
|
|
|
63
65
|
/** @param {string | undefined} raw */
|
|
64
66
|
export function resolveRunTimeoutMs(raw) {
|
|
65
67
|
const n = Number(raw);
|
|
66
|
-
return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_RUN_TIMEOUT_MS;
|
|
68
|
+
return Number.isFinite(n) && n > 0 ? Math.min(Math.floor(n), 2_147_483_647) : DEFAULT_RUN_TIMEOUT_MS;
|
|
67
69
|
}
|
|
68
70
|
|
|
69
71
|
/**
|
|
@@ -74,7 +76,7 @@ export function resolveRunTimeoutMs(raw) {
|
|
|
74
76
|
* @param {{ kill?: (pid: number, sig: number) => void, readCmdline?: (pid: number) => string | null }} [deps]
|
|
75
77
|
*/
|
|
76
78
|
export function isLockOwnerAlive(pid, deps = {}) {
|
|
77
|
-
if (!Number.
|
|
79
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
78
80
|
const kill = deps.kill ?? ((p, sig) => process.kill(p, sig));
|
|
79
81
|
try {
|
|
80
82
|
kill(pid, 0);
|
|
@@ -96,6 +98,48 @@ export function isLockOwnerAlive(pid, deps = {}) {
|
|
|
96
98
|
return cmd.includes(LOCK_OWNER_MARKER) || cmd.includes("agentschat-ensure-grok-wakes");
|
|
97
99
|
}
|
|
98
100
|
|
|
101
|
+
const RESERVED_BIND_KEYS = new Set([
|
|
102
|
+
"__proto__",
|
|
103
|
+
"constructor",
|
|
104
|
+
"prototype",
|
|
105
|
+
"profile",
|
|
106
|
+
"grok-binds",
|
|
107
|
+
"grok-binds.meta",
|
|
108
|
+
"session-binds",
|
|
109
|
+
"agy-session-binds",
|
|
110
|
+
]);
|
|
111
|
+
|
|
112
|
+
function isSystemDarwinRootSymlink(p) {
|
|
113
|
+
return process.platform === "darwin" && (p === "/var" || p === "/tmp" || p === "/etc");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Returns false if `dirPath` or any existing ancestor directory is a symlink
|
|
118
|
+
* (except macOS system root symlinks `/var`, `/tmp`, `/etc`).
|
|
119
|
+
* @param {string} dirPath
|
|
120
|
+
*/
|
|
121
|
+
export function hasSafeAncestorDirs(dirPath) {
|
|
122
|
+
let cur = resolve(dirPath);
|
|
123
|
+
const visited = new Set();
|
|
124
|
+
while (cur && !visited.has(cur)) {
|
|
125
|
+
visited.add(cur);
|
|
126
|
+
try {
|
|
127
|
+
const st = lstatSync(cur);
|
|
128
|
+
if (st.isSymbolicLink()) {
|
|
129
|
+
if (!isSystemDarwinRootSymlink(cur)) return false;
|
|
130
|
+
} else if (!st.isDirectory()) {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
} catch (e) {
|
|
134
|
+
if (/** @type {any} */ (e)?.code !== "ENOENT") return false;
|
|
135
|
+
}
|
|
136
|
+
const parent = dirname(cur);
|
|
137
|
+
if (parent === cur) break;
|
|
138
|
+
cur = parent;
|
|
139
|
+
}
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
|
|
99
143
|
/**
|
|
100
144
|
* Non-blocking run lock. Returns a release() on success, or null when another
|
|
101
145
|
* live run holds it. Stale locks (dead/recycled pid, unreadable content) are
|
|
@@ -107,6 +151,7 @@ export function isLockOwnerAlive(pid, deps = {}) {
|
|
|
107
151
|
export function acquireRunLock(lockPath, opts = {}) {
|
|
108
152
|
const pid = opts.pid ?? process.pid;
|
|
109
153
|
const isAlive = opts.isAlive ?? ((p) => isLockOwnerAlive(p));
|
|
154
|
+
if (!hasSafeAncestorDirs(dirname(resolve(lockPath)))) return null;
|
|
110
155
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
111
156
|
try {
|
|
112
157
|
const fd = openSync(lockPath, "wx", 0o600);
|
|
@@ -117,7 +162,10 @@ export function acquireRunLock(lockPath, opts = {}) {
|
|
|
117
162
|
if (released) return;
|
|
118
163
|
released = true;
|
|
119
164
|
try {
|
|
120
|
-
|
|
165
|
+
const st = lstatSync(lockPath);
|
|
166
|
+
if (!st.isSymbolicLink() && st.isFile() && st.size <= 65_536) {
|
|
167
|
+
if (readFileSync(lockPath, "utf8").trim() === String(pid)) unlinkSync(lockPath);
|
|
168
|
+
}
|
|
121
169
|
} catch {
|
|
122
170
|
/* already gone */
|
|
123
171
|
}
|
|
@@ -126,7 +174,11 @@ export function acquireRunLock(lockPath, opts = {}) {
|
|
|
126
174
|
if (!(e && /** @type {any} */ (e).code === "EEXIST")) throw e;
|
|
127
175
|
let holder = NaN;
|
|
128
176
|
try {
|
|
129
|
-
|
|
177
|
+
const st = lstatSync(lockPath);
|
|
178
|
+
if (st.isSymbolicLink() || !st.isFile()) return null;
|
|
179
|
+
if (st.size <= 65_536) {
|
|
180
|
+
holder = Number(readFileSync(lockPath, "utf8").trim());
|
|
181
|
+
}
|
|
130
182
|
} catch {
|
|
131
183
|
/* unreadable → stale */
|
|
132
184
|
}
|
|
@@ -135,7 +187,7 @@ export function acquireRunLock(lockPath, opts = {}) {
|
|
|
135
187
|
try {
|
|
136
188
|
unlinkSync(lockPath);
|
|
137
189
|
} catch {
|
|
138
|
-
|
|
190
|
+
return null;
|
|
139
191
|
}
|
|
140
192
|
}
|
|
141
193
|
}
|
|
@@ -151,7 +203,17 @@ export function parseBinds(raw) {
|
|
|
151
203
|
if (typeof v !== "string") continue;
|
|
152
204
|
const name = v.trim();
|
|
153
205
|
const key = k.trim();
|
|
154
|
-
if (
|
|
206
|
+
if (
|
|
207
|
+
!name ||
|
|
208
|
+
!key ||
|
|
209
|
+
key.length > 128 ||
|
|
210
|
+
name.length > 128 ||
|
|
211
|
+
RESERVED_BIND_KEYS.has(key.toLowerCase()) ||
|
|
212
|
+
RESERVED_BIND_KEYS.has(name.toLowerCase())
|
|
213
|
+
) {
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (!/^[A-Za-z0-9_-]+$/.test(key) || !/^[A-Za-z0-9_-]+$/.test(name)) continue;
|
|
155
217
|
out[key] = name;
|
|
156
218
|
}
|
|
157
219
|
return out;
|
|
@@ -200,7 +262,12 @@ export function mayPruneWakes(bindsFileExists) {
|
|
|
200
262
|
/** @param {string} text */
|
|
201
263
|
export function parseBindsText(text) {
|
|
202
264
|
try {
|
|
203
|
-
|
|
265
|
+
const raw = JSON.parse(text);
|
|
266
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { binds: {}, malformed: true };
|
|
267
|
+
const binds = parseBinds(raw);
|
|
268
|
+
// Invalid rows must never turn an authoritative file into prune-all.
|
|
269
|
+
if (Object.keys(binds).length !== Object.keys(raw).length) return { binds: {}, malformed: true };
|
|
270
|
+
return { binds, malformed: false };
|
|
204
271
|
} catch {
|
|
205
272
|
return { binds: {}, malformed: true };
|
|
206
273
|
}
|
|
@@ -412,15 +479,28 @@ export function stopWakePid(pid) {
|
|
|
412
479
|
*/
|
|
413
480
|
export function startWakeDaemon(opts) {
|
|
414
481
|
const logDir = opts.logDir;
|
|
482
|
+
if (!logDir || !hasSafeAncestorDirs(logDir)) return false;
|
|
415
483
|
try {
|
|
416
484
|
spawnSync("mkdir", ["-p", logDir], { stdio: "ignore" });
|
|
417
485
|
} catch {
|
|
418
486
|
/* best-effort */
|
|
419
487
|
}
|
|
488
|
+
if (!hasSafeAncestorDirs(logDir)) return false;
|
|
420
489
|
const logPath = join(logDir, `agentschat-wake-${safeLogName(opts.profileName)}.log`);
|
|
490
|
+
try {
|
|
491
|
+
const st = lstatSync(logPath);
|
|
492
|
+
if (st.isSymbolicLink() || !st.isFile()) return false;
|
|
493
|
+
} catch (e) {
|
|
494
|
+
if (/** @type {any} */ (e)?.code !== "ENOENT") return false;
|
|
495
|
+
}
|
|
421
496
|
let logFd;
|
|
422
497
|
try {
|
|
423
|
-
|
|
498
|
+
const flags =
|
|
499
|
+
fsConstants.O_WRONLY |
|
|
500
|
+
fsConstants.O_CREAT |
|
|
501
|
+
fsConstants.O_APPEND |
|
|
502
|
+
(typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0);
|
|
503
|
+
logFd = openSync(logPath, flags, 0o600);
|
|
424
504
|
} catch {
|
|
425
505
|
return false;
|
|
426
506
|
}
|
|
@@ -497,6 +577,11 @@ async function main() {
|
|
|
497
577
|
if (existsSync(bindsPath)) {
|
|
498
578
|
let text;
|
|
499
579
|
try {
|
|
580
|
+
const st = lstatSync(bindsPath);
|
|
581
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > 1_048_576) {
|
|
582
|
+
console.error(`failed binds-unsafe path=${bindsPath}`);
|
|
583
|
+
process.exit(1);
|
|
584
|
+
}
|
|
500
585
|
text = readFileSync(bindsPath, "utf8");
|
|
501
586
|
} catch {
|
|
502
587
|
console.error(`failed binds-read path=${bindsPath}`);
|
|
@@ -28,6 +28,8 @@
|
|
|
28
28
|
* scripts/example-agy-mcp-wrapper.sh as the host's MCP command (fails closed).
|
|
29
29
|
*
|
|
30
30
|
* Signature header: x-agentschat-signature (same as mcp-plugin/src/wake.ts).
|
|
31
|
+
* Limits: 64 KiB raw body, timestamp within ±5 minutes, 15s HTTP receive timeout.
|
|
32
|
+
* Host commands have a 180s deadline; stdout/stderr are suppressed to protect credentials.
|
|
31
33
|
* Payload fields: type, channel_id, message_id, sender_id, content (≤500),
|
|
32
34
|
* mentioned_ids, timestamp. Never expect an ac_ token in the body.
|
|
33
35
|
*
|
|
@@ -59,7 +61,7 @@ export function signWakeBody(body, secret) {
|
|
|
59
61
|
|
|
60
62
|
/** Constant-time verify that `sigHex` signs `body` under `secret`. */
|
|
61
63
|
export function verifyWakeSignature(body, sigHex, secret) {
|
|
62
|
-
if (
|
|
64
|
+
if (typeof sigHex !== "string" || !/^[a-f0-9]{64}$/i.test(sigHex) || !secret) return false;
|
|
63
65
|
let sigBuf;
|
|
64
66
|
try {
|
|
65
67
|
sigBuf = Buffer.from(sigHex, "hex");
|
|
@@ -81,16 +83,144 @@ function envOr(name, fallback) {
|
|
|
81
83
|
return v && v.trim() ? v.trim() : fallback;
|
|
82
84
|
}
|
|
83
85
|
|
|
86
|
+
export const WAKE_BODY_MAX_BYTES = 64 * 1024;
|
|
87
|
+
export const WAKE_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
|
88
|
+
|
|
89
|
+
export function isFreshWakeTimestamp(value, now = Date.now()) {
|
|
90
|
+
if (typeof value !== "string" || !/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(value)) return false;
|
|
91
|
+
const time = Date.parse(value);
|
|
92
|
+
return Number.isFinite(time) && Math.abs(now - time) <= WAKE_REPLAY_WINDOW_MS;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function redactWakeLog(value) {
|
|
96
|
+
let text = String(value);
|
|
97
|
+
for (const secret of [process.env.AGENTCHAT_WAKE_SECRET, process.env.AGENTCHAT_TOKEN]) {
|
|
98
|
+
if (secret) text = text.split(secret).join("[redacted]");
|
|
99
|
+
}
|
|
100
|
+
return text
|
|
101
|
+
.replace(
|
|
102
|
+
/(?:mcp_(?:at|rt|code)_|ac_|agent_key_|whsec_|sk-|sk_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|AIza|AKIA|ASIA)[A-Za-z0-9+/=_-]+/gi,
|
|
103
|
+
"[redacted]",
|
|
104
|
+
)
|
|
105
|
+
.replace(/(?:Bearer|Basic)\s+[^\s]+/gi, "[redacted]")
|
|
106
|
+
.replace(/[\r\n\x00-\x1f\x7f]/g, " ");
|
|
107
|
+
}
|
|
108
|
+
|
|
84
109
|
function log(msg) {
|
|
85
|
-
process.stderr.write(`${new Date().toISOString()} ${msg}\n`);
|
|
110
|
+
process.stderr.write(`${new Date().toISOString()} ${redactWakeLog(msg)}\n`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isSystemDarwinRootSymlink(p) {
|
|
114
|
+
return process.platform === "darwin" && (p === "/var" || p === "/tmp" || p === "/etc");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function hasSafeParentDirs(dirPath) {
|
|
118
|
+
let cur = path.resolve(dirPath);
|
|
119
|
+
const visited = new Set();
|
|
120
|
+
while (cur && !visited.has(cur)) {
|
|
121
|
+
visited.add(cur);
|
|
122
|
+
try {
|
|
123
|
+
const st = fs.lstatSync(cur);
|
|
124
|
+
if (st.isSymbolicLink()) {
|
|
125
|
+
if (!isSystemDarwinRootSymlink(cur)) return false;
|
|
126
|
+
} else if (!st.isDirectory()) {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
} catch (e) {
|
|
130
|
+
if (e?.code !== "ENOENT") return false;
|
|
131
|
+
}
|
|
132
|
+
const parent = path.dirname(cur);
|
|
133
|
+
if (parent === cur) break;
|
|
134
|
+
cur = parent;
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function atomicWriteJson(filename, value) {
|
|
140
|
+
if (!hasSafeParentDirs(path.dirname(path.resolve(filename)))) {
|
|
141
|
+
throw new Error("Refusing to write inside symlinked or non-directory parent");
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const existing = fs.lstatSync(filename);
|
|
145
|
+
if (existing.isSymbolicLink() || !existing.isFile()) {
|
|
146
|
+
throw new Error("Refusing to overwrite symlink or non-regular file");
|
|
147
|
+
}
|
|
148
|
+
} catch (e) {
|
|
149
|
+
if (e?.code !== "ENOENT") throw e;
|
|
150
|
+
}
|
|
151
|
+
const tmp = `${filename}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`;
|
|
152
|
+
try {
|
|
153
|
+
fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600, flag: "wx" });
|
|
154
|
+
try {
|
|
155
|
+
const targetStat = fs.lstatSync(filename);
|
|
156
|
+
if (targetStat.isSymbolicLink() || !targetStat.isFile()) {
|
|
157
|
+
throw new Error("Refusing to overwrite symlink or non-regular file");
|
|
158
|
+
}
|
|
159
|
+
} catch (e) {
|
|
160
|
+
if (e?.code !== "ENOENT") throw e;
|
|
161
|
+
}
|
|
162
|
+
fs.renameSync(tmp, filename);
|
|
163
|
+
} finally {
|
|
164
|
+
try { fs.unlinkSync(tmp); } catch { /* renamed or failed */ }
|
|
165
|
+
}
|
|
86
166
|
}
|
|
87
167
|
|
|
88
|
-
function readBody(req) {
|
|
168
|
+
export function readBody(req, maxBytes = WAKE_BODY_MAX_BYTES) {
|
|
89
169
|
return new Promise((resolve, reject) => {
|
|
90
170
|
const chunks = [];
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
171
|
+
let size = 0;
|
|
172
|
+
let done = false;
|
|
173
|
+
const fail = (error) => {
|
|
174
|
+
if (done) return;
|
|
175
|
+
done = true;
|
|
176
|
+
chunks.length = 0;
|
|
177
|
+
reject(error);
|
|
178
|
+
};
|
|
179
|
+
req.on("data", (chunk) => {
|
|
180
|
+
if (done) return;
|
|
181
|
+
const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
182
|
+
size += c.length;
|
|
183
|
+
if (size > maxBytes) {
|
|
184
|
+
fail(Object.assign(new Error("body too large"), { statusCode: 413 }));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
chunks.push(c);
|
|
188
|
+
});
|
|
189
|
+
req.on("end", () => {
|
|
190
|
+
if (done) return;
|
|
191
|
+
done = true;
|
|
192
|
+
resolve(Buffer.concat(chunks));
|
|
193
|
+
});
|
|
194
|
+
req.on("error", fail);
|
|
195
|
+
req.on("aborted", () => fail(new Error("request aborted")));
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Kill the whole shell group on timeout; never inherit credential-bearing output. */
|
|
200
|
+
export function runWakeCommand(cmd, input, env, timeoutMs = 180_000) {
|
|
201
|
+
const boundedTimeoutMs =
|
|
202
|
+
typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
|
|
203
|
+
? Math.min(Math.floor(timeoutMs), 2_147_483_647)
|
|
204
|
+
: 180_000;
|
|
205
|
+
return new Promise((resolve, reject) => {
|
|
206
|
+
const child = spawn(cmd, { shell: true, detached: process.platform !== "win32",
|
|
207
|
+
env, stdio: ["pipe", "ignore", "ignore"] });
|
|
208
|
+
const timer = setTimeout(() => {
|
|
209
|
+
try {
|
|
210
|
+
if (process.platform !== "win32" && child.pid) process.kill(-child.pid, "SIGKILL");
|
|
211
|
+
else child.kill("SIGKILL");
|
|
212
|
+
} catch { /* already exited */ }
|
|
213
|
+
reject(new Error("wake command timed out"));
|
|
214
|
+
}, boundedTimeoutMs);
|
|
215
|
+
timer.unref?.();
|
|
216
|
+
child.stdin.on("error", () => { /* early child exit / EPIPE */ });
|
|
217
|
+
child.once("error", () => { clearTimeout(timer); reject(new Error("wake command spawn failed")); });
|
|
218
|
+
child.once("close", (code) => {
|
|
219
|
+
clearTimeout(timer);
|
|
220
|
+
if (code === 0) resolve();
|
|
221
|
+
else reject(new Error("wake command failed"));
|
|
222
|
+
});
|
|
223
|
+
child.stdin.end(input);
|
|
94
224
|
});
|
|
95
225
|
}
|
|
96
226
|
|
|
@@ -130,7 +260,20 @@ export function withoutCursorSessionEnv(base) {
|
|
|
130
260
|
/** Env that could override or contradict the pinned identity in the host's MCP. */
|
|
131
261
|
export const IDENTITY_OVERRIDE_ENV = ["AGENTCHAT_PROFILE", "AGENTCHAT_TOKEN", "AGENTCHAT_AGENT_ID"];
|
|
132
262
|
|
|
133
|
-
const PROFILE_NAME_RE = /^[A-Za-z0-9_-]
|
|
263
|
+
const PROFILE_NAME_RE = /^[A-Za-z0-9_-]{1,128}$/;
|
|
264
|
+
const AGENT_ID_PIN_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
265
|
+
const RESERVED_PROTO_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
266
|
+
const RESERVED_PROFILE_NAMES = new Set([
|
|
267
|
+
"__proto__",
|
|
268
|
+
"constructor",
|
|
269
|
+
"prototype",
|
|
270
|
+
"profile",
|
|
271
|
+
"grok-binds",
|
|
272
|
+
"grok-binds.meta",
|
|
273
|
+
"session-binds",
|
|
274
|
+
"agy-session-binds",
|
|
275
|
+
]);
|
|
276
|
+
export const MAX_QUEUE_JOBS = 1000;
|
|
134
277
|
|
|
135
278
|
/**
|
|
136
279
|
* Read the required identity pin from env. Throws (receiver must not start)
|
|
@@ -146,12 +289,52 @@ export function requireIdentityPin(env) {
|
|
|
146
289
|
"AGENTCHAT_URL_WAKE_PROFILE and AGENTCHAT_URL_WAKE_AGENT_ID are required (identity pin) — refusing to start",
|
|
147
290
|
);
|
|
148
291
|
}
|
|
149
|
-
if (!PROFILE_NAME_RE.test(profile)) {
|
|
292
|
+
if (!PROFILE_NAME_RE.test(profile) || RESERVED_PROFILE_NAMES.has(profile.toLowerCase())) {
|
|
150
293
|
throw new Error("AGENTCHAT_URL_WAKE_PROFILE must be a plain profile name");
|
|
151
294
|
}
|
|
295
|
+
if (
|
|
296
|
+
!AGENT_ID_PIN_RE.test(agentId) ||
|
|
297
|
+
agentId === "." ||
|
|
298
|
+
agentId.includes("..") ||
|
|
299
|
+
RESERVED_PROTO_KEYS.has(agentId.toLowerCase())
|
|
300
|
+
) {
|
|
301
|
+
throw new Error("AGENTCHAT_URL_WAKE_AGENT_ID must be a safe agent identifier");
|
|
302
|
+
}
|
|
152
303
|
return { profile, agentId };
|
|
153
304
|
}
|
|
154
305
|
|
|
306
|
+
/**
|
|
307
|
+
* Bounded single-flight lock acquisition (at most 2 attempts) — never recurses
|
|
308
|
+
* infinitely if a stale lock path cannot be unlinked (e.g. directory or EACCES).
|
|
309
|
+
*/
|
|
310
|
+
export function tryAcquireSingleFlightLock(lockPath, isBusyFn, pid = process.pid) {
|
|
311
|
+
if (!hasSafeParentDirs(path.dirname(path.resolve(lockPath)))) return false;
|
|
312
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
313
|
+
try {
|
|
314
|
+
const fd = fs.openSync(lockPath, "wx", 0o600);
|
|
315
|
+
fs.writeFileSync(fd, String(pid));
|
|
316
|
+
fs.closeSync(fd);
|
|
317
|
+
return true;
|
|
318
|
+
} catch (e) {
|
|
319
|
+
if (e && e.code === "EEXIST") {
|
|
320
|
+
if (attempt === 0 && !isBusyFn()) {
|
|
321
|
+
try {
|
|
322
|
+
const st = fs.lstatSync(lockPath);
|
|
323
|
+
if (!st.isSymbolicLink() && st.isFile()) fs.unlinkSync(lockPath);
|
|
324
|
+
else return false;
|
|
325
|
+
} catch {
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
throw e;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
|
|
155
338
|
/**
|
|
156
339
|
* Env for the host turn: Cursor session keys and identity overrides stripped,
|
|
157
340
|
* AGENTSCHAT_PROFILE + AGENTCHAT_EXPECT_AGENT_ID pinned to this bot.
|
|
@@ -175,19 +358,30 @@ export function identityCheckLines(pin) {
|
|
|
175
358
|
];
|
|
176
359
|
}
|
|
177
360
|
|
|
361
|
+
function sanitizePromptHeaderField(value, maxLen = 128) {
|
|
362
|
+
return String(value ?? "")
|
|
363
|
+
.replace(/[\x00-\x1f\x7f]+/g, " ")
|
|
364
|
+
.trim()
|
|
365
|
+
.slice(0, maxLen);
|
|
366
|
+
}
|
|
367
|
+
|
|
178
368
|
/** Build a prompt string hosts can inject into one dedicated session. */
|
|
179
369
|
export function buildHostPrompt(job, pin) {
|
|
180
370
|
const mentioned = Array.isArray(job.mentioned_ids)
|
|
181
|
-
? job.mentioned_ids
|
|
182
|
-
|
|
371
|
+
? job.mentioned_ids
|
|
372
|
+
.slice(0, 32)
|
|
373
|
+
.map((id) => sanitizePromptHeaderField(id, 128))
|
|
374
|
+
.filter(Boolean)
|
|
375
|
+
.join(",")
|
|
376
|
+
: sanitizePromptHeaderField(job.mentioned_ids, 512);
|
|
183
377
|
return [
|
|
184
378
|
"[AgentsChat inbound]",
|
|
185
379
|
...(pin ? identityCheckLines(pin) : []),
|
|
186
|
-
`channel_id=${job.channel_id
|
|
187
|
-
`message_id=${job.message_id
|
|
188
|
-
`sender_id=${job.sender_id
|
|
380
|
+
`channel_id=${sanitizePromptHeaderField(job.channel_id, 128)}`,
|
|
381
|
+
`message_id=${sanitizePromptHeaderField(job.message_id, 128)}`,
|
|
382
|
+
`sender_id=${sanitizePromptHeaderField(job.sender_id, 128)}`,
|
|
189
383
|
`mentioned_ids=${mentioned}`,
|
|
190
|
-
`timestamp=${job.timestamp
|
|
384
|
+
`timestamp=${sanitizePromptHeaderField(job.timestamp, 64)}`,
|
|
191
385
|
"content:",
|
|
192
386
|
String(job.content ?? ""),
|
|
193
387
|
"",
|
|
@@ -210,6 +404,10 @@ function startServer() {
|
|
|
210
404
|
process.exit(1);
|
|
211
405
|
}
|
|
212
406
|
const port = Number(envOr("AGENTCHAT_URL_WAKE_PORT", "18765"));
|
|
407
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
408
|
+
console.error("AGENTCHAT_URL_WAKE_PORT must be an integer port between 1 and 65535");
|
|
409
|
+
process.exit(1);
|
|
410
|
+
}
|
|
213
411
|
const wakePath = envOr("AGENTCHAT_URL_WAKE_PATH", "/wake");
|
|
214
412
|
const cmd = process.env.AGENTCHAT_URL_WAKE_CMD || "";
|
|
215
413
|
const stateDir = path.resolve(envOr("AGENTCHAT_URL_WAKE_DIR", "./url-wake-state"));
|
|
@@ -220,6 +418,8 @@ function startServer() {
|
|
|
220
418
|
|
|
221
419
|
function loadSeen() {
|
|
222
420
|
try {
|
|
421
|
+
const st = fs.lstatSync(dedupePath);
|
|
422
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > 1_048_576) return [];
|
|
223
423
|
const arr = JSON.parse(fs.readFileSync(dedupePath, "utf8"));
|
|
224
424
|
return Array.isArray(arr) ? arr : [];
|
|
225
425
|
} catch {
|
|
@@ -238,7 +438,7 @@ function startServer() {
|
|
|
238
438
|
if (seen.includes(messageId)) return;
|
|
239
439
|
seen.push(messageId);
|
|
240
440
|
if (seen.length > 200) seen = seen.slice(seen.length - 200);
|
|
241
|
-
|
|
441
|
+
atomicWriteJson(dedupePath, seen);
|
|
242
442
|
}
|
|
243
443
|
|
|
244
444
|
function queueLen() {
|
|
@@ -251,13 +451,15 @@ function startServer() {
|
|
|
251
451
|
|
|
252
452
|
function isBusy() {
|
|
253
453
|
try {
|
|
454
|
+
const st = fs.lstatSync(lockPath);
|
|
455
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > 65_536) return false;
|
|
254
456
|
const pid = Number(fs.readFileSync(lockPath, "utf8").trim());
|
|
255
|
-
if (!pid) return false;
|
|
457
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
256
458
|
try {
|
|
257
459
|
process.kill(pid, 0);
|
|
258
460
|
return true;
|
|
259
|
-
} catch {
|
|
260
|
-
return
|
|
461
|
+
} catch (e) {
|
|
462
|
+
return e?.code === "EPERM";
|
|
261
463
|
}
|
|
262
464
|
} catch {
|
|
263
465
|
return false;
|
|
@@ -265,30 +467,17 @@ function startServer() {
|
|
|
265
467
|
}
|
|
266
468
|
|
|
267
469
|
function tryAcquireLock() {
|
|
268
|
-
|
|
269
|
-
const fd = fs.openSync(lockPath, "wx");
|
|
270
|
-
fs.writeFileSync(fd, String(process.pid));
|
|
271
|
-
fs.closeSync(fd);
|
|
272
|
-
return true;
|
|
273
|
-
} catch (e) {
|
|
274
|
-
if (e && e.code === "EEXIST") {
|
|
275
|
-
if (!isBusy()) {
|
|
276
|
-
try {
|
|
277
|
-
fs.unlinkSync(lockPath);
|
|
278
|
-
} catch {
|
|
279
|
-
/* ignore */
|
|
280
|
-
}
|
|
281
|
-
return tryAcquireLock();
|
|
282
|
-
}
|
|
283
|
-
return false;
|
|
284
|
-
}
|
|
285
|
-
throw e;
|
|
286
|
-
}
|
|
470
|
+
return tryAcquireSingleFlightLock(lockPath, isBusy, process.pid);
|
|
287
471
|
}
|
|
288
472
|
|
|
289
473
|
function releaseLock() {
|
|
290
474
|
try {
|
|
291
|
-
fs.
|
|
475
|
+
const st = fs.lstatSync(lockPath);
|
|
476
|
+
if (!st.isSymbolicLink() && st.isFile() && st.size <= 65_536) {
|
|
477
|
+
if (fs.readFileSync(lockPath, "utf8").trim() === String(process.pid)) {
|
|
478
|
+
fs.unlinkSync(lockPath);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
292
481
|
} catch {
|
|
293
482
|
/* ignore */
|
|
294
483
|
}
|
|
@@ -309,25 +498,11 @@ function startServer() {
|
|
|
309
498
|
log(`EXAMPLE no AGENTCHAT_URL_WAKE_CMD; would inject:\n${prompt.slice(0, 200)}…`);
|
|
310
499
|
return;
|
|
311
500
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
...buildHostChildEnv(process.env, pin),
|
|
318
|
-
AGENTCHAT_URL_WAKE_PROMPT: prompt,
|
|
319
|
-
AGENTCHAT_URL_WAKE_CHANNEL_ID: String(job.channel_id || ""),
|
|
320
|
-
AGENTCHAT_URL_WAKE_MESSAGE_ID: String(job.message_id || ""),
|
|
321
|
-
},
|
|
322
|
-
stdio: ["pipe", "inherit", "inherit"],
|
|
323
|
-
});
|
|
324
|
-
child.stdin.write(JSON.stringify({ ...job, prompt }));
|
|
325
|
-
child.stdin.end();
|
|
326
|
-
child.on("close", () => resolve());
|
|
327
|
-
child.on("error", (err) => {
|
|
328
|
-
log(`spawn error: ${err}`);
|
|
329
|
-
resolve();
|
|
330
|
-
});
|
|
501
|
+
await runWakeCommand(cmd, JSON.stringify({ ...job, prompt }), {
|
|
502
|
+
...buildHostChildEnv(process.env, pin),
|
|
503
|
+
AGENTCHAT_URL_WAKE_PROMPT: prompt,
|
|
504
|
+
AGENTCHAT_URL_WAKE_CHANNEL_ID: String(job.channel_id || ""),
|
|
505
|
+
AGENTCHAT_URL_WAKE_MESSAGE_ID: String(job.message_id || ""),
|
|
331
506
|
});
|
|
332
507
|
}
|
|
333
508
|
|
|
@@ -379,8 +554,9 @@ function startServer() {
|
|
|
379
554
|
let raw;
|
|
380
555
|
try {
|
|
381
556
|
raw = await readBody(req);
|
|
382
|
-
} catch {
|
|
383
|
-
|
|
557
|
+
} catch (e) {
|
|
558
|
+
res.setHeader("Connection", "close");
|
|
559
|
+
sendJson(res, e?.statusCode === 413 ? 413 : 400, { ok: false, error: "bad body" });
|
|
384
560
|
return;
|
|
385
561
|
}
|
|
386
562
|
const sig = req.headers[WAKE_SIG_HEADER];
|
|
@@ -400,13 +576,20 @@ function startServer() {
|
|
|
400
576
|
sendJson(res, 400, { ok: false, error: "channel_id required" });
|
|
401
577
|
return;
|
|
402
578
|
}
|
|
579
|
+
if (!isFreshWakeTimestamp(payload.timestamp)) {
|
|
580
|
+
sendJson(res, 400, { ok: false, error: "stale or missing timestamp" });
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
403
583
|
const messageId = typeof payload.message_id === "string" ? payload.message_id : undefined;
|
|
404
584
|
if (messageId && wasSeen(messageId)) {
|
|
405
585
|
log(`dedupe skip message_id=${messageId}`);
|
|
406
586
|
sendJson(res, 202, { ok: true, deduped: true });
|
|
407
587
|
return;
|
|
408
588
|
}
|
|
409
|
-
if (
|
|
589
|
+
if (queueLen() >= MAX_QUEUE_JOBS) {
|
|
590
|
+
sendJson(res, 503, { ok: false, error: "queue full" });
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
410
593
|
const qid = `${Date.now()}-${crypto.randomBytes(4).toString("hex")}`;
|
|
411
594
|
const job = {
|
|
412
595
|
type: payload.type || "message",
|
|
@@ -422,7 +605,14 @@ function startServer() {
|
|
|
422
605
|
_qid: qid,
|
|
423
606
|
_enqueued_at: new Date().toISOString(),
|
|
424
607
|
};
|
|
425
|
-
|
|
608
|
+
try {
|
|
609
|
+
atomicWriteJson(path.join(queueDir, `${qid}.json`), job);
|
|
610
|
+
if (messageId) rememberSeen(messageId);
|
|
611
|
+
} catch {
|
|
612
|
+
log("queue persistence failed");
|
|
613
|
+
sendJson(res, 503, { ok: false, error: "queue unavailable" });
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
426
616
|
log(`enqueued qid=${qid} channel_id=${job.channel_id}`);
|
|
427
617
|
sendJson(res, 202, { ok: true, queued: true, qid });
|
|
428
618
|
setImmediate(() => {
|
|
@@ -433,6 +623,9 @@ function startServer() {
|
|
|
433
623
|
sendJson(res, 404, { ok: false, error: "not found" });
|
|
434
624
|
});
|
|
435
625
|
|
|
626
|
+
server.requestTimeout = 15_000;
|
|
627
|
+
server.headersTimeout = 10_000;
|
|
628
|
+
server.setTimeout(15_000, (socket) => socket.destroy());
|
|
436
629
|
server.listen(port, "127.0.0.1", () => {
|
|
437
630
|
log(`EXAMPLE listening 127.0.0.1:${port}${wakePath} (not a production daemon)`);
|
|
438
631
|
pump().catch((e) => log(`boot pump error: ${e}`));
|