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/cli.mjs
CHANGED
|
@@ -34,6 +34,16 @@ if ([connectorMode, codexMode, botsMode, museMode, dshMode].filter(Boolean).leng
|
|
|
34
34
|
throw new Error("Choose only one bridge mode");
|
|
35
35
|
}
|
|
36
36
|
const helpRequested = args.includes("--help") || args.includes("-h");
|
|
37
|
+
const oneShotRequested =
|
|
38
|
+
helpRequested ||
|
|
39
|
+
args.includes("--register-only") ||
|
|
40
|
+
args.includes("--version") ||
|
|
41
|
+
args.includes("-v") ||
|
|
42
|
+
args.includes("--check") ||
|
|
43
|
+
args.includes("--status") ||
|
|
44
|
+
args.includes("--join") ||
|
|
45
|
+
args.includes("--send") ||
|
|
46
|
+
args.some((a) => a.startsWith("--join=") || a.startsWith("--send="));
|
|
37
47
|
const superviseRequested =
|
|
38
48
|
args.includes("--supervise") || process.env.AGENTCHAT_WAKE_SUPERVISE === "1";
|
|
39
49
|
|
|
@@ -119,40 +129,100 @@ Source: https://github.com/swswordholy-tech/AgentsChatProtocol/tree/main/mcp-plu
|
|
|
119
129
|
|
|
120
130
|
const filteredArgs = args.filter((a) => a !== "--supervise");
|
|
121
131
|
|
|
122
|
-
function sleep(ms) {
|
|
123
|
-
return new Promise((r) => setTimeout(r, ms));
|
|
124
|
-
}
|
|
125
|
-
|
|
126
132
|
/**
|
|
127
133
|
* Parent strips --supervise / AGENTCHAT_WAKE_SUPERVISE and respawns the same
|
|
128
134
|
* runtime entry on crash until SIGTERM/SIGINT.
|
|
135
|
+
*
|
|
136
|
+
* Hardening invariants:
|
|
137
|
+
* 1. Backoff sleep is immediately interrupted on SIGTERM/SIGINT so service
|
|
138
|
+
* managers (systemd/launchd/Docker) never wait up to 30s to SIGKILL.
|
|
139
|
+
* 2. When a child ran healthily (>= 60s default) before exiting, exponential
|
|
140
|
+
* backoff resets to initialDelayMs so multi-day daemons don't stay pinned
|
|
141
|
+
* at 30s restart latency forever.
|
|
129
142
|
*/
|
|
130
143
|
async function runSupervised(childArgs) {
|
|
131
144
|
let stopping = false;
|
|
132
145
|
/** @type {import("node:child_process").ChildProcess | null} */
|
|
133
146
|
let child = null;
|
|
147
|
+
/** @type {(() => void) | null} */
|
|
148
|
+
let cancelSleep = null;
|
|
149
|
+
|
|
150
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
151
|
+
const clampTimerMs = (raw, minMs, fallbackMs) => {
|
|
152
|
+
const num = Number(raw);
|
|
153
|
+
if (!Number.isFinite(num) || num <= 0) return fallbackMs;
|
|
154
|
+
return Math.min(Math.max(minMs, Math.floor(num)), MAX_TIMER_MS);
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const stopGraceMs = clampTimerMs(process.env.AGENTCHAT_SUPERVISE_STOP_GRACE_MS, 25, 5_000);
|
|
158
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
159
|
+
let killTimer = null;
|
|
134
160
|
|
|
135
161
|
const requestStop = () => {
|
|
136
162
|
stopping = true;
|
|
137
|
-
if (
|
|
163
|
+
if (cancelSleep) {
|
|
164
|
+
cancelSleep();
|
|
165
|
+
cancelSleep = null;
|
|
166
|
+
}
|
|
167
|
+
if (child && child.pid && child.exitCode === null && child.signalCode === null) {
|
|
138
168
|
try {
|
|
139
169
|
child.kill("SIGTERM");
|
|
140
170
|
} catch {
|
|
141
171
|
/* ignore */
|
|
142
172
|
}
|
|
173
|
+
if (!killTimer) {
|
|
174
|
+
const target = child;
|
|
175
|
+
killTimer = setTimeout(() => {
|
|
176
|
+
killTimer = null;
|
|
177
|
+
if (target.exitCode === null && target.signalCode === null) {
|
|
178
|
+
try {
|
|
179
|
+
target.kill("SIGKILL");
|
|
180
|
+
} catch {
|
|
181
|
+
/* ignore */
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}, stopGraceMs);
|
|
185
|
+
killTimer.unref?.();
|
|
186
|
+
}
|
|
143
187
|
}
|
|
144
188
|
};
|
|
145
189
|
process.on("SIGTERM", requestStop);
|
|
146
190
|
process.on("SIGINT", requestStop);
|
|
191
|
+
if (process.platform !== "win32") {
|
|
192
|
+
process.on("SIGHUP", requestStop);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const interruptibleSleep = (ms) =>
|
|
196
|
+
new Promise((resolve) => {
|
|
197
|
+
if (stopping) {
|
|
198
|
+
resolve();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const safeMs = Math.min(Math.max(0, Math.floor(ms)), MAX_TIMER_MS);
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
cancelSleep = null;
|
|
204
|
+
resolve();
|
|
205
|
+
}, safeMs);
|
|
206
|
+
cancelSleep = () => {
|
|
207
|
+
clearTimeout(timer);
|
|
208
|
+
resolve();
|
|
209
|
+
};
|
|
210
|
+
});
|
|
147
211
|
|
|
148
212
|
const selfPath = fileURLToPath(import.meta.url);
|
|
149
213
|
const childEnv = { ...process.env };
|
|
150
214
|
delete childEnv.AGENTCHAT_WAKE_SUPERVISE;
|
|
151
215
|
|
|
152
|
-
|
|
153
|
-
const maxDelayMs =
|
|
216
|
+
const initialDelayMs = clampTimerMs(process.env.AGENTCHAT_SUPERVISE_INITIAL_DELAY_MS, 10, 1000);
|
|
217
|
+
const maxDelayMs = Math.max(
|
|
218
|
+
initialDelayMs,
|
|
219
|
+
clampTimerMs(process.env.AGENTCHAT_SUPERVISE_MAX_DELAY_MS, initialDelayMs, Math.max(initialDelayMs, 30_000)),
|
|
220
|
+
);
|
|
221
|
+
const healthyResetMs = clampTimerMs(process.env.AGENTCHAT_SUPERVISE_RESET_MS, 50, 60_000);
|
|
222
|
+
let delayMs = initialDelayMs;
|
|
154
223
|
|
|
155
224
|
while (!stopping) {
|
|
225
|
+
const startedAt = Date.now();
|
|
156
226
|
child = spawn(process.execPath, [selfPath, ...childArgs], {
|
|
157
227
|
env: childEnv,
|
|
158
228
|
stdio: "inherit",
|
|
@@ -164,16 +234,26 @@ async function runSupervised(childArgs) {
|
|
|
164
234
|
});
|
|
165
235
|
child.on("error", () => resolve(1));
|
|
166
236
|
});
|
|
237
|
+
const now = Date.now();
|
|
238
|
+
const ranMs = now >= startedAt ? now - startedAt : 0;
|
|
239
|
+
if (killTimer) {
|
|
240
|
+
clearTimeout(killTimer);
|
|
241
|
+
killTimer = null;
|
|
242
|
+
}
|
|
167
243
|
child = null;
|
|
168
244
|
if (stopping) process.exit(exitCode);
|
|
245
|
+
if (ranMs >= healthyResetMs) {
|
|
246
|
+
delayMs = initialDelayMs;
|
|
247
|
+
}
|
|
169
248
|
process.stderr.write(`[agentchat] supervise: restarting after exit ${exitCode}\n`);
|
|
170
|
-
await
|
|
249
|
+
await interruptibleSleep(delayMs);
|
|
250
|
+
if (stopping) process.exit(exitCode);
|
|
171
251
|
delayMs = Math.min(delayMs * 2, maxDelayMs);
|
|
172
252
|
}
|
|
173
253
|
process.exit(0);
|
|
174
254
|
}
|
|
175
255
|
|
|
176
|
-
if (superviseRequested && !
|
|
256
|
+
if (superviseRequested && !oneShotRequested) {
|
|
177
257
|
process.argv = [process.argv[0], process.argv[1], ...filteredArgs];
|
|
178
258
|
await runSupervised(filteredArgs);
|
|
179
259
|
process.exit(0);
|
|
@@ -215,7 +295,7 @@ if (typeof globalThis.Bun !== "undefined") {
|
|
|
215
295
|
const selfPath = fileURLToPath(import.meta.url);
|
|
216
296
|
const childEnv = { ...process.env, NODE_USE_ENV_PROXY: "1" };
|
|
217
297
|
for (const key of ["NO_PROXY", "no_proxy"]) {
|
|
218
|
-
const cur = childEnv[key]
|
|
298
|
+
const cur = (childEnv[key] || "").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, "").trim();
|
|
219
299
|
const items = cur ? cur.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
220
300
|
for (const host of ["localhost", "127.0.0.1", "::1", "[::1]"]) {
|
|
221
301
|
if (!items.includes(host)) items.push(host);
|
|
@@ -226,11 +306,15 @@ if (typeof globalThis.Bun !== "undefined") {
|
|
|
226
306
|
env: childEnv,
|
|
227
307
|
stdio: "inherit",
|
|
228
308
|
});
|
|
229
|
-
|
|
309
|
+
const proxySignals =
|
|
310
|
+
process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
311
|
+
for (const sig of proxySignals) {
|
|
230
312
|
process.on(sig, () => {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
313
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
314
|
+
try {
|
|
315
|
+
child.kill(sig);
|
|
316
|
+
} catch {}
|
|
317
|
+
}
|
|
234
318
|
});
|
|
235
319
|
}
|
|
236
320
|
const exitCode = await new Promise((resolve) => {
|
package/src/dedup.ts
CHANGED
|
@@ -7,30 +7,79 @@
|
|
|
7
7
|
* key derivation and the bounded eviction can be unit-tested directly.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
const MAX_DEDUP_ID_CHARS = 256;
|
|
11
|
+
const MAX_DEDUP_KEY_CHARS = 1024;
|
|
12
|
+
const MAX_DEDUP_CAPACITY = 1_000_000;
|
|
13
|
+
const RESERVED_DEDUP_KEY = /^(?:__proto__|constructor|prototype)$/i;
|
|
14
|
+
|
|
10
15
|
/** Stable identity for a message frame, or null if it lacks string id/channel. */
|
|
11
16
|
export function messageDedupKey(data: any): string | null {
|
|
12
|
-
if (
|
|
13
|
-
|
|
17
|
+
if (
|
|
18
|
+
!data ||
|
|
19
|
+
typeof data !== "object" ||
|
|
20
|
+
Array.isArray(data) ||
|
|
21
|
+
Object.prototype.hasOwnProperty.call(data, "__proto__") ||
|
|
22
|
+
typeof data.id !== "string" ||
|
|
23
|
+
typeof data.channel_id !== "string"
|
|
24
|
+
) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
const channelTrim = data.channel_id.trim();
|
|
28
|
+
const idTrim = data.id.trim();
|
|
29
|
+
if (
|
|
30
|
+
!idTrim ||
|
|
31
|
+
!channelTrim ||
|
|
32
|
+
channelTrim === "." ||
|
|
33
|
+
channelTrim === ".." ||
|
|
34
|
+
idTrim === "." ||
|
|
35
|
+
idTrim === ".." ||
|
|
36
|
+
RESERVED_DEDUP_KEY.test(channelTrim) ||
|
|
37
|
+
RESERVED_DEDUP_KEY.test(idTrim) ||
|
|
38
|
+
data.id.length > MAX_DEDUP_ID_CHARS ||
|
|
39
|
+
data.channel_id.length > MAX_DEDUP_ID_CHARS ||
|
|
40
|
+
/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(data.id) ||
|
|
41
|
+
/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(data.channel_id)
|
|
42
|
+
) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
const safeChannel = data.channel_id.replace(/\\/g, "\\\\").replace(/:/g, "\\:");
|
|
46
|
+
return `${safeChannel}:${data.id}`;
|
|
14
47
|
}
|
|
15
48
|
|
|
16
49
|
export class MessageDedup {
|
|
17
50
|
private seen = new Set<string>();
|
|
51
|
+
private readonly max: number;
|
|
52
|
+
private readonly dropOnEvict: number;
|
|
18
53
|
|
|
19
54
|
constructor(
|
|
20
55
|
/** Evict once the set grows past this many keys. */
|
|
21
|
-
|
|
56
|
+
max: number = 5000,
|
|
22
57
|
/** How many oldest keys to drop on eviction (Set preserves insertion order). */
|
|
23
|
-
|
|
24
|
-
) {
|
|
58
|
+
dropOnEvict: number = 1000,
|
|
59
|
+
) {
|
|
60
|
+
const safeMax = Number.isFinite(max) ? Math.min(MAX_DEDUP_CAPACITY, Math.max(1, Math.floor(max))) : 5000;
|
|
61
|
+
const safeDrop = Number.isFinite(dropOnEvict)
|
|
62
|
+
? Math.min(safeMax, Math.max(1, Math.floor(dropOnEvict)))
|
|
63
|
+
: Math.min(safeMax, 1000);
|
|
64
|
+
this.max = safeMax;
|
|
65
|
+
this.dropOnEvict = safeDrop;
|
|
66
|
+
}
|
|
25
67
|
|
|
26
68
|
/** Returns true if `key` was already delivered (skip), false if newly recorded. */
|
|
27
69
|
recordOrSkip(key: string): boolean {
|
|
70
|
+
if (typeof key !== "string" || key.length === 0 || key.length > MAX_DEDUP_KEY_CHARS || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(key)) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
28
73
|
if (this.seen.has(key)) return true;
|
|
29
74
|
this.seen.add(key);
|
|
30
75
|
if (this.seen.size > this.max) {
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
for (const
|
|
76
|
+
const toDrop = Math.max(this.dropOnEvict, this.seen.size - this.max);
|
|
77
|
+
let dropped = 0;
|
|
78
|
+
for (const oldest of this.seen) {
|
|
79
|
+
this.seen.delete(oldest);
|
|
80
|
+
dropped += 1;
|
|
81
|
+
if (dropped >= toDrop) break;
|
|
82
|
+
}
|
|
34
83
|
}
|
|
35
84
|
return false;
|
|
36
85
|
}
|
package/src/grok-bind.ts
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
import { join } from "node:path";
|
|
28
|
+
import { redactSecrets } from "./redact.ts";
|
|
28
29
|
|
|
29
30
|
export const DEFAULT_GROK_BINDS_FILENAME = "grok-binds.json";
|
|
30
31
|
/** Sidecar written by grok-bind-register.sh ({profile, registered_by, ts} per uuid). Not a profile. */
|
|
@@ -44,22 +45,79 @@ export type GrokBindDecision =
|
|
|
44
45
|
/** Bind hit — caller resolves `<profileName>` the same way `--profile` does. */
|
|
45
46
|
| { kind: "hit"; conversationId: string; profileName: string };
|
|
46
47
|
|
|
47
|
-
|
|
48
|
+
function isUnsafeObjectKey(key: string): boolean {
|
|
49
|
+
const lower = key.toLowerCase();
|
|
50
|
+
return lower === "__proto__" || lower === "constructor" || lower === "prototype";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const GROK_CONTROL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
54
|
+
const GROK_CONTROL_STRIP_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g;
|
|
55
|
+
|
|
56
|
+
function hasControlChars(s: string): boolean {
|
|
57
|
+
return GROK_CONTROL_RE.test(s);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function normalizeProfileSlug(s: string): string {
|
|
61
|
+
const base = profileNameFromPath(s) ?? s;
|
|
62
|
+
return base.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const MAX_GROK_BIND_ENTRIES = 1024;
|
|
66
|
+
const MAX_GROK_BINDS_PATH_LEN = 4096;
|
|
67
|
+
const RESERVED_BIND_BASENAMES = new Set([
|
|
68
|
+
"profile",
|
|
69
|
+
"grok-binds",
|
|
70
|
+
"grok-binds-meta",
|
|
71
|
+
"grok-binds.meta",
|
|
72
|
+
"session-binds",
|
|
73
|
+
"session-binds.meta",
|
|
74
|
+
"agy-session-binds",
|
|
75
|
+
"agy-binds",
|
|
76
|
+
"agy-binds.meta",
|
|
77
|
+
"identity-guard",
|
|
78
|
+
"cursor",
|
|
79
|
+
"read-cursors",
|
|
80
|
+
"mention-timestamps",
|
|
81
|
+
"wake-pids",
|
|
82
|
+
"dsh",
|
|
83
|
+
"config",
|
|
84
|
+
"muse",
|
|
85
|
+
]);
|
|
86
|
+
|
|
87
|
+
function hasPathOrTraversalSyntax(s: string): boolean {
|
|
88
|
+
return /[\/\\]/.test(s) || s === "." || s.includes("..");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isSafeProfileBindName(name: string): boolean {
|
|
92
|
+
if (!name || name.length > 256 || hasControlChars(name)) return false;
|
|
93
|
+
if (isUnsafeObjectKey(name) || hasPathOrTraversalSyntax(name)) return false;
|
|
94
|
+
const base = name.replace(/\.json$/i, "").trim().toLowerCase();
|
|
95
|
+
if (!base || isUnsafeObjectKey(base) || RESERVED_BIND_BASENAMES.has(base)) return false;
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** uuid → profile name. Non-string (and empty / prototype / path-traversal / control-char) values are ignored. */
|
|
48
100
|
export function parseGrokBinds(raw: unknown): Record<string, string> {
|
|
49
101
|
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
50
102
|
const out: Record<string, string> = {};
|
|
103
|
+
let count = 0;
|
|
51
104
|
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
105
|
+
if (count >= MAX_GROK_BIND_ENTRIES) break;
|
|
52
106
|
if (typeof v !== "string") continue;
|
|
53
107
|
const name = v.trim();
|
|
54
|
-
if (!name) continue;
|
|
108
|
+
if (!isSafeProfileBindName(name)) continue;
|
|
55
109
|
const key = k.trim();
|
|
56
|
-
if (!key) continue;
|
|
110
|
+
if (!key || key.length > 256 || isUnsafeObjectKey(key) || hasControlChars(key)) continue;
|
|
111
|
+
if (!Object.hasOwn(out, key)) count++;
|
|
57
112
|
out[key] = name;
|
|
58
113
|
}
|
|
59
114
|
return out;
|
|
60
115
|
}
|
|
61
116
|
|
|
62
117
|
export function parseGrokBindsText(text: string): { binds: Record<string, string>; malformed: boolean } {
|
|
118
|
+
if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > 1_048_576) {
|
|
119
|
+
return { binds: {}, malformed: true };
|
|
120
|
+
}
|
|
63
121
|
try {
|
|
64
122
|
return { binds: parseGrokBinds(JSON.parse(text)), malformed: false };
|
|
65
123
|
} catch {
|
|
@@ -68,7 +126,10 @@ export function parseGrokBindsText(text: string): { binds: Record<string, string
|
|
|
68
126
|
}
|
|
69
127
|
|
|
70
128
|
export function resolveGrokBindsPath(configDir: string, envOverride?: string): string {
|
|
71
|
-
|
|
129
|
+
const trimmed = typeof envOverride === "string" ? envOverride.trim() : "";
|
|
130
|
+
if (trimmed.length > 0 && trimmed.length <= MAX_GROK_BINDS_PATH_LEN && !trimmed.startsWith("-") && !hasControlChars(trimmed)) {
|
|
131
|
+
return trimmed;
|
|
132
|
+
}
|
|
72
133
|
return join(configDir, DEFAULT_GROK_BINDS_FILENAME);
|
|
73
134
|
}
|
|
74
135
|
|
|
@@ -84,11 +145,12 @@ export function decideGrokBind(input: {
|
|
|
84
145
|
binds: Record<string, string>;
|
|
85
146
|
}): GrokBindDecision {
|
|
86
147
|
if (input.explicitIdentity || input.hasToken) return { kind: "skip" };
|
|
87
|
-
const id = input.conversationId
|
|
88
|
-
if (!id) return { kind: "skip" };
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
148
|
+
const id = typeof input.conversationId === "string" ? input.conversationId.trim() : "";
|
|
149
|
+
if (!id || isUnsafeObjectKey(id) || hasControlChars(id)) return { kind: "skip" };
|
|
150
|
+
const binds = input.binds && typeof input.binds === "object" ? input.binds : {};
|
|
151
|
+
const profileName = Object.hasOwn(binds, id) ? binds[id] : undefined;
|
|
152
|
+
if (typeof profileName === "string" && isSafeProfileBindName(profileName.trim())) {
|
|
153
|
+
return { kind: "hit", conversationId: id, profileName: profileName.trim() };
|
|
92
154
|
}
|
|
93
155
|
return { kind: "miss", conversationId: id };
|
|
94
156
|
}
|
|
@@ -101,17 +163,18 @@ export function boundProfileForConversation(
|
|
|
101
163
|
conversationId: string | undefined,
|
|
102
164
|
binds: Record<string, string>,
|
|
103
165
|
): string | null {
|
|
104
|
-
const id = conversationId
|
|
105
|
-
if (!id) return null;
|
|
106
|
-
|
|
107
|
-
|
|
166
|
+
const id = typeof conversationId === "string" ? conversationId.trim() : "";
|
|
167
|
+
if (!id || isUnsafeObjectKey(id) || hasControlChars(id)) return null;
|
|
168
|
+
if (!binds || typeof binds !== "object") return null;
|
|
169
|
+
const name = Object.hasOwn(binds, id) ? binds[id] : undefined;
|
|
170
|
+
return typeof name === "string" && isSafeProfileBindName(name.trim()) ? name.trim() : null;
|
|
108
171
|
}
|
|
109
172
|
|
|
110
173
|
/** Basename without `.json` — compare `activeProfileFile` to a bind name. */
|
|
111
174
|
export function profileNameFromPath(profilePath: string | null | undefined): string | null {
|
|
112
|
-
if (!profilePath) return null;
|
|
175
|
+
if (!profilePath || typeof profilePath !== "string") return null;
|
|
113
176
|
const base = profilePath.replace(/\\/g, "/").split("/").pop() || "";
|
|
114
|
-
const name = base.replace(/\.json$/i, "");
|
|
177
|
+
const name = base.replace(/\.json$/i, "").trim();
|
|
115
178
|
return name || null;
|
|
116
179
|
}
|
|
117
180
|
|
|
@@ -142,36 +205,96 @@ export function gateSwitchProfile(input: {
|
|
|
142
205
|
/** Basename of activeProfileFile — used when conversation id is unset. */
|
|
143
206
|
currentProfileName?: string | null;
|
|
144
207
|
}): SwitchProfileGate {
|
|
145
|
-
const
|
|
208
|
+
const reqRaw =
|
|
146
209
|
typeof input.requestedProfileName === "string" ? input.requestedProfileName.trim() : "";
|
|
147
|
-
if (!
|
|
210
|
+
if (!reqRaw) return { kind: "allow" };
|
|
211
|
+
const reqHasPath = hasPathOrTraversalSyntax(reqRaw);
|
|
212
|
+
const reqSlug = normalizeProfileSlug(reqRaw);
|
|
213
|
+
|
|
214
|
+
const binds = input.binds && typeof input.binds === "object" ? input.binds : {};
|
|
215
|
+
const bindValues = Object.values(binds).filter((v) => typeof v === "string" && isSafeProfileBindName(v.trim()));
|
|
216
|
+
if (bindValues.length === 0) return { kind: "allow" };
|
|
148
217
|
|
|
149
|
-
const
|
|
218
|
+
const lockedMessage = (lockedName: string) => {
|
|
219
|
+
const clean = lockedName.replace(GROK_CONTROL_STRIP_RE, "").slice(0, 128);
|
|
220
|
+
return (
|
|
221
|
+
`Outbound identity is locked to grok-bind profile "${clean}" on this shared MCP; ` +
|
|
222
|
+
`use a separate MCP process / wake daemon, do not switch_profile.`
|
|
223
|
+
);
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const bound = boundProfileForConversation(input.conversationId, binds);
|
|
227
|
+
if (bound) {
|
|
228
|
+
if (!reqHasPath && reqSlug === normalizeProfileSlug(bound)) return { kind: "allow" };
|
|
229
|
+
return {
|
|
230
|
+
kind: "locked",
|
|
231
|
+
boundProfileName: bound,
|
|
232
|
+
requestedProfileName: reqRaw.replace(GROK_CONTROL_STRIP_RE, "").slice(0, 128),
|
|
233
|
+
message: lockedMessage(bound),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const current =
|
|
238
|
+
typeof input.currentProfileName === "string" ? input.currentProfileName.trim() : "";
|
|
239
|
+
const currentSlug = current ? normalizeProfileSlug(current) : "";
|
|
240
|
+
if (current && bindValues.some((v) => normalizeProfileSlug(v) === currentSlug)) {
|
|
241
|
+
if (!reqHasPath && reqSlug === currentSlug) return { kind: "allow" };
|
|
242
|
+
return {
|
|
243
|
+
kind: "locked",
|
|
244
|
+
boundProfileName: current.replace(GROK_CONTROL_STRIP_RE, "").slice(0, 128),
|
|
245
|
+
requestedProfileName: reqRaw.replace(GROK_CONTROL_STRIP_RE, "").slice(0, 128),
|
|
246
|
+
message: lockedMessage(current),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
return { kind: "allow" };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Gate `disconnect` / `disconnect_profile` and `register_name` mutations when
|
|
255
|
+
* a grok outbound bind owns this shared MCP identity.
|
|
256
|
+
*/
|
|
257
|
+
export function gateGrokProfileMutation(input: {
|
|
258
|
+
conversationId: string | undefined;
|
|
259
|
+
binds: Record<string, string>;
|
|
260
|
+
currentProfileName?: string | null;
|
|
261
|
+
action: "disconnect" | "register";
|
|
262
|
+
requestedName?: string | null;
|
|
263
|
+
}): SwitchProfileGate {
|
|
264
|
+
const binds = input.binds && typeof input.binds === "object" ? input.binds : {};
|
|
265
|
+
const bindValues = Object.values(binds).filter((v) => typeof v === "string" && isSafeProfileBindName(v.trim()));
|
|
150
266
|
if (bindValues.length === 0) return { kind: "allow" };
|
|
151
267
|
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
268
|
+
const reqLabel =
|
|
269
|
+
typeof input.requestedName === "string" && input.requestedName.trim()
|
|
270
|
+
? input.requestedName.trim().replace(GROK_CONTROL_STRIP_RE, "").slice(0, 128)
|
|
271
|
+
: `(${input.action})`;
|
|
272
|
+
const lockedMessage = (lockedName: string) => {
|
|
273
|
+
const clean = lockedName.replace(GROK_CONTROL_STRIP_RE, "").slice(0, 128);
|
|
274
|
+
return (
|
|
275
|
+
`Outbound identity is locked to grok-bind profile "${clean}" on this shared MCP; ` +
|
|
276
|
+
`use a separate MCP process / wake daemon, do not switch_profile or disconnect_profile.`
|
|
277
|
+
);
|
|
278
|
+
};
|
|
155
279
|
|
|
156
|
-
const bound = boundProfileForConversation(input.conversationId,
|
|
280
|
+
const bound = boundProfileForConversation(input.conversationId, binds);
|
|
157
281
|
if (bound) {
|
|
158
|
-
if (req === bound) return { kind: "allow" };
|
|
159
282
|
return {
|
|
160
283
|
kind: "locked",
|
|
161
284
|
boundProfileName: bound,
|
|
162
|
-
requestedProfileName:
|
|
285
|
+
requestedProfileName: reqLabel,
|
|
163
286
|
message: lockedMessage(bound),
|
|
164
287
|
};
|
|
165
288
|
}
|
|
166
289
|
|
|
167
290
|
const current =
|
|
168
291
|
typeof input.currentProfileName === "string" ? input.currentProfileName.trim() : "";
|
|
169
|
-
|
|
170
|
-
|
|
292
|
+
const currentSlug = current ? normalizeProfileSlug(current) : "";
|
|
293
|
+
if (current && bindValues.some((v) => normalizeProfileSlug(v) === currentSlug)) {
|
|
171
294
|
return {
|
|
172
295
|
kind: "locked",
|
|
173
|
-
boundProfileName: current,
|
|
174
|
-
requestedProfileName:
|
|
296
|
+
boundProfileName: current.replace(GROK_CONTROL_STRIP_RE, "").slice(0, 128),
|
|
297
|
+
requestedProfileName: reqLabel,
|
|
175
298
|
message: lockedMessage(current),
|
|
176
299
|
};
|
|
177
300
|
}
|
|
@@ -189,8 +312,10 @@ export function shouldHealBoundIdentity(input: {
|
|
|
189
312
|
liveAgentId: string | null | undefined;
|
|
190
313
|
boundAgentId: string | null | undefined;
|
|
191
314
|
}): boolean {
|
|
192
|
-
|
|
193
|
-
if (
|
|
315
|
+
const boundNorm = typeof input.boundProfileName === "string" ? input.boundProfileName.trim() : "";
|
|
316
|
+
if (!boundNorm) return false;
|
|
317
|
+
const liveNorm = typeof input.liveProfileName === "string" ? input.liveProfileName.trim() : "";
|
|
318
|
+
if (!liveNorm || normalizeProfileSlug(liveNorm) !== normalizeProfileSlug(boundNorm)) return true;
|
|
194
319
|
if (
|
|
195
320
|
typeof input.boundAgentId === "string" &&
|
|
196
321
|
input.boundAgentId.length > 0 &&
|
|
@@ -217,11 +342,13 @@ export const WAKE_MODE_ENV = "AGENTCHAT_WAKE_MODE";
|
|
|
217
342
|
* - AGENTCHAT_WAKE_MODE set to something other than "grok" → that mode
|
|
218
343
|
*/
|
|
219
344
|
export function nonGrokWakeReason(env: Record<string, string | undefined>): string | null {
|
|
220
|
-
|
|
345
|
+
if (!env || typeof env !== "object") return null;
|
|
346
|
+
const clean = (v: string) => redactSecrets(v.replace(GROK_CONTROL_STRIP_RE, "")).slice(0, 64);
|
|
347
|
+
const anti = clean((env[ANTIGRAVITY_WAKE_ENV] ?? "").trim());
|
|
221
348
|
if (anti) return `${ANTIGRAVITY_WAKE_ENV}=${anti}`;
|
|
222
|
-
const kind = (env[WAKE_KIND_ENV] ?? "").trim();
|
|
349
|
+
const kind = clean((env[WAKE_KIND_ENV] ?? "").trim());
|
|
223
350
|
if (kind && kind.toLowerCase() !== "grok") return `${WAKE_KIND_ENV}=${kind}`;
|
|
224
|
-
const mode = (env[WAKE_MODE_ENV] ?? "").trim();
|
|
351
|
+
const mode = clean((env[WAKE_MODE_ENV] ?? "").trim());
|
|
225
352
|
if (mode && mode.toLowerCase() !== "grok") return `${WAKE_MODE_ENV}=${mode}`;
|
|
226
353
|
return null;
|
|
227
354
|
}
|
package/src/heartbeat.ts
CHANGED
|
@@ -28,15 +28,22 @@ export class HeartbeatMonitor {
|
|
|
28
28
|
/** Guard against overlapping reconnect calls */
|
|
29
29
|
private reconnecting = false;
|
|
30
30
|
|
|
31
|
+
public readonly pingInterval: number;
|
|
32
|
+
public readonly pongTimeout: number;
|
|
33
|
+
public readonly connectTimeout: number;
|
|
34
|
+
|
|
31
35
|
constructor(
|
|
32
36
|
private deps: HeartbeatDeps,
|
|
33
37
|
/** How often to send a ping (ms) */
|
|
34
|
-
|
|
38
|
+
pingInterval: number = 30_000,
|
|
35
39
|
/** Max time without a pong before we consider connection dead (ms) */
|
|
36
|
-
|
|
40
|
+
pongTimeout: number = 90_000,
|
|
37
41
|
/** Max time to stay in CONNECTING before forcing retry (ms) */
|
|
38
|
-
|
|
42
|
+
connectTimeout: number = 30_000,
|
|
39
43
|
) {
|
|
44
|
+
this.pingInterval = Number.isFinite(pingInterval) && pingInterval > 0 ? Math.max(1, Math.min(Math.floor(pingInterval), 2_147_483_647)) : 30_000;
|
|
45
|
+
this.pongTimeout = Number.isFinite(pongTimeout) && pongTimeout > 0 ? Math.max(1, Math.min(Math.floor(pongTimeout), 2_147_483_647)) : 90_000;
|
|
46
|
+
this.connectTimeout = Number.isFinite(connectTimeout) && connectTimeout > 0 ? Math.max(1, Math.min(Math.floor(connectTimeout), 2_147_483_647)) : 30_000;
|
|
40
47
|
this.lastPong = Date.now();
|
|
41
48
|
}
|
|
42
49
|
|
|
@@ -54,6 +61,7 @@ export class HeartbeatMonitor {
|
|
|
54
61
|
this.connectingSince = null;
|
|
55
62
|
this.reconnecting = false;
|
|
56
63
|
this.timer = setInterval(() => this.tick(), this.pingInterval);
|
|
64
|
+
(this.timer as unknown as { unref?: () => void })?.unref?.();
|
|
57
65
|
}
|
|
58
66
|
|
|
59
67
|
/** Stop the heartbeat timer */
|
|
@@ -71,24 +79,39 @@ export class HeartbeatMonitor {
|
|
|
71
79
|
|
|
72
80
|
/** Exposed for testing — runs one heartbeat cycle */
|
|
73
81
|
tick() {
|
|
74
|
-
|
|
82
|
+
let state: number;
|
|
83
|
+
try {
|
|
84
|
+
state = this.deps.getReadyState();
|
|
85
|
+
} catch {
|
|
86
|
+
this.connectingSince = null;
|
|
87
|
+
this.safeReconnect("readyState failed");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
75
90
|
|
|
91
|
+
const now = Date.now();
|
|
76
92
|
if (state === WS_OPEN) {
|
|
77
93
|
this.connectingSince = null;
|
|
78
|
-
if (
|
|
94
|
+
if (this.lastPong > now) {
|
|
95
|
+
this.lastPong = now;
|
|
96
|
+
}
|
|
97
|
+
if (now - this.lastPong > this.pongTimeout) {
|
|
79
98
|
// No pong in too long — force reconnect
|
|
80
99
|
this.safeReconnect("pong timeout");
|
|
81
100
|
return;
|
|
82
101
|
}
|
|
83
|
-
|
|
102
|
+
try {
|
|
103
|
+
this.deps.sendPing();
|
|
104
|
+
} catch {
|
|
105
|
+
this.safeReconnect("ping send failed");
|
|
106
|
+
}
|
|
84
107
|
return;
|
|
85
108
|
}
|
|
86
109
|
|
|
87
110
|
if (state === WS_CONNECTING) {
|
|
88
|
-
// Track how long we've been stuck in CONNECTING
|
|
89
|
-
if (
|
|
90
|
-
this.connectingSince =
|
|
91
|
-
} else if (
|
|
111
|
+
// Track how long we've been stuck in CONNECTING (recovering from backward NTP jumps)
|
|
112
|
+
if (this.connectingSince === null || this.connectingSince > now) {
|
|
113
|
+
this.connectingSince = now;
|
|
114
|
+
} else if (now - this.connectingSince > this.connectTimeout) {
|
|
92
115
|
// Stuck in CONNECTING too long (server probably still down) — force retry
|
|
93
116
|
this.connectingSince = null;
|
|
94
117
|
this.safeReconnect("connect timeout");
|
|
@@ -104,6 +127,11 @@ export class HeartbeatMonitor {
|
|
|
104
127
|
private safeReconnect(reason: string) {
|
|
105
128
|
if (this.reconnecting) return; // already in progress
|
|
106
129
|
this.reconnecting = true;
|
|
107
|
-
|
|
130
|
+
try {
|
|
131
|
+
this.deps.reconnect();
|
|
132
|
+
} catch {
|
|
133
|
+
// Never permanently wedge `reconnecting = true` or crash the interval loop if reconnect throws.
|
|
134
|
+
this.reconnecting = false;
|
|
135
|
+
}
|
|
108
136
|
}
|
|
109
137
|
}
|