agentschat-mcp 0.36.25 → 0.36.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +10 -10
- package/codex/README.md +4 -4
- package/codex/app-server.ts +101 -22
- package/codex/bots-config.ts +32 -11
- package/codex/bridge.ts +127 -28
- package/codex/config.ts +137 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +77 -12
- package/codex/loop-grants.ts +49 -11
- package/codex/manager.ts +108 -27
- package/codex/owner.ts +106 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +51 -11
- package/codex/thread-history.ts +87 -30
- package/codex/transport.ts +135 -22
- package/connector/README.md +1 -1
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/cordis.patch.yml +4 -2
- package/dist/codex-bots.js +437 -75
- package/dist/codex-bridge.js +2111 -582
- package/dist/connector.js +1300 -493
- package/dist/dsh.js +1789 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +4410 -919
- package/dsh/README.md +1 -1
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +677 -154
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +1174 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +3 -3
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/onboarding.md +15 -15
- package/src/argcheck.ts +113 -33
- package/src/cli.mjs +100 -16
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +182 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +299 -18
- package/src/profile-store.ts +248 -30
- package/src/read-cursor.ts +280 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +286 -94
- package/src/session-bind.ts +777 -134
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +10 -1
- package/src/wake.ts +510 -91
package/src/session-bind.ts
CHANGED
|
@@ -14,9 +14,9 @@
|
|
|
14
14
|
* crashed/closed processes automatically release their lock (never deadlocks).
|
|
15
15
|
*/
|
|
16
16
|
import { createHash } from "node:crypto";
|
|
17
|
-
import { closeSync,
|
|
17
|
+
import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, statSync, unlinkSync, type Stats } from "node:fs";
|
|
18
18
|
import { homedir, tmpdir } from "node:os";
|
|
19
|
-
import { join } from "node:path";
|
|
19
|
+
import { isAbsolute, join, parse, resolve } from "node:path";
|
|
20
20
|
import { spawnSync } from "node:child_process";
|
|
21
21
|
import { safeWriteProfile } from "./profile-store.ts";
|
|
22
22
|
|
|
@@ -48,7 +48,7 @@ export interface AgentLockCheck {
|
|
|
48
48
|
|
|
49
49
|
/** Check whether a local OS process is still alive. Never throws. */
|
|
50
50
|
export function isPidAlive(pid: unknown): boolean {
|
|
51
|
-
if (typeof pid !== "number" || !Number.
|
|
51
|
+
if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
52
52
|
try {
|
|
53
53
|
process.kill(pid, 0);
|
|
54
54
|
return true;
|
|
@@ -61,32 +61,214 @@ export function isPidAlive(pid: unknown): boolean {
|
|
|
61
61
|
/** Deterministic per-HOME lock directory in tmpdir (cleared on OS reboot, isolated in tests). */
|
|
62
62
|
export function resolveLockDir(homeDir: string, env: Record<string, string | undefined> = process.env): string {
|
|
63
63
|
const explicit = env.AGENTSCHAT_LOCK_DIR?.trim();
|
|
64
|
-
if (
|
|
64
|
+
if (
|
|
65
|
+
explicit &&
|
|
66
|
+
explicit.length <= 4096 &&
|
|
67
|
+
!explicit.startsWith("-") &&
|
|
68
|
+
!CONTROL_CHAR_RE.test(explicit) &&
|
|
69
|
+
isAbsolute(explicit) &&
|
|
70
|
+
isSafeDirOrMissing(explicit)
|
|
71
|
+
) {
|
|
72
|
+
return explicit;
|
|
73
|
+
}
|
|
65
74
|
const hash = createHash("sha256").update(homeDir || ".").digest("hex").slice(0, 12);
|
|
66
75
|
const baseTmp = process.platform === "win32" ? tmpdir() : "/tmp";
|
|
67
76
|
return join(baseTmp, `agentschat-locks-${hash}`);
|
|
68
77
|
}
|
|
69
78
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
79
|
+
const LOCK_FILE_MAX_BYTES = 64 * 1024;
|
|
80
|
+
const LOCK_KEY_MAX_CHARS = 128;
|
|
81
|
+
const SESSION_BINDS_MAX_BYTES = 1024 * 1024;
|
|
82
|
+
const MAX_SESSION_BINDS_ENTRIES = 1024;
|
|
83
|
+
const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
84
|
+
const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
|
|
85
|
+
const UNSAFE_BIND_KEYS = new Set([
|
|
86
|
+
"__proto__",
|
|
87
|
+
"constructor",
|
|
88
|
+
"prototype",
|
|
89
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
|
|
90
|
+
]);
|
|
91
|
+
// NOTE: "profile" MUST NEVER be added here — `profile.json` is the default boot identity slot.
|
|
92
|
+
const RESERVED_BIND_SIDECARS = new Set([
|
|
93
|
+
"session-binds",
|
|
94
|
+
"session-binds.meta",
|
|
95
|
+
"session-binds_meta",
|
|
96
|
+
"agy-binds",
|
|
97
|
+
"agy-binds.meta",
|
|
98
|
+
"agy-binds_meta",
|
|
99
|
+
"grok-binds",
|
|
100
|
+
"grok-binds.meta",
|
|
101
|
+
"grok-binds_meta",
|
|
102
|
+
"agy-session-binds",
|
|
103
|
+
"identity-guard",
|
|
104
|
+
"cursor",
|
|
105
|
+
"read-cursors",
|
|
106
|
+
"mention-timestamps",
|
|
107
|
+
"wake-pids",
|
|
108
|
+
"config",
|
|
109
|
+
"codex-bots",
|
|
110
|
+
"dsh",
|
|
111
|
+
"muse",
|
|
112
|
+
]);
|
|
113
|
+
|
|
114
|
+
function safeLstat(path: string): Stats | null {
|
|
115
|
+
try {
|
|
116
|
+
return lstatSync(path);
|
|
117
|
+
} catch {
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
73
120
|
}
|
|
74
121
|
|
|
75
|
-
|
|
76
|
-
if (!agentId) return null;
|
|
77
|
-
const file = lockFilePath(lockDir, agentId);
|
|
78
|
-
if (!existsSync(file)) return null;
|
|
122
|
+
function readBoundedRegularJson(path: string, maxBytes: number): unknown | null {
|
|
79
123
|
try {
|
|
80
|
-
const
|
|
81
|
-
if (
|
|
124
|
+
const st = lstatSync(path);
|
|
125
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > maxBytes) return null;
|
|
126
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
127
|
+
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
82
128
|
return null;
|
|
83
129
|
}
|
|
84
|
-
return
|
|
130
|
+
return parsed;
|
|
85
131
|
} catch {
|
|
86
132
|
return null;
|
|
87
133
|
}
|
|
88
134
|
}
|
|
89
135
|
|
|
136
|
+
function isSafeTargetFileOrMissing(path: string): boolean {
|
|
137
|
+
try {
|
|
138
|
+
const st = lstatSync(path);
|
|
139
|
+
return !st.isSymbolicLink() && st.isFile();
|
|
140
|
+
} catch (e: any) {
|
|
141
|
+
return Boolean(e && typeof e === "object" && e.code === "ENOENT");
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function isAllowedDarwinSystemLink(dirPath: string): boolean {
|
|
146
|
+
if (process.platform !== "darwin") return false;
|
|
147
|
+
if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc") return false;
|
|
148
|
+
try {
|
|
149
|
+
const expected = `/private${dirPath}`;
|
|
150
|
+
return (
|
|
151
|
+
readlinkSync(dirPath) === `private${dirPath}` &&
|
|
152
|
+
realpathSync(dirPath) === expected &&
|
|
153
|
+
!lstatSync("/private").isSymbolicLink() &&
|
|
154
|
+
lstatSync("/private").isDirectory() &&
|
|
155
|
+
!lstatSync(expected).isSymbolicLink() &&
|
|
156
|
+
statSync(expected).isDirectory()
|
|
157
|
+
);
|
|
158
|
+
} catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function hasSafeRawDotDotSegments(rawPath: string): boolean {
|
|
164
|
+
if (!rawPath.includes("..")) return true;
|
|
165
|
+
const baseAbs = isAbsolute(rawPath) ? rawPath : `${process.cwd()}/${rawPath}`;
|
|
166
|
+
const root = parse(baseAbs).root;
|
|
167
|
+
const rawParts = baseAbs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
168
|
+
let cur = root;
|
|
169
|
+
for (const part of rawParts) {
|
|
170
|
+
if (part === ".") continue;
|
|
171
|
+
if (part === "..") {
|
|
172
|
+
cur = resolve(cur, "..");
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
cur = join(cur, part);
|
|
176
|
+
try {
|
|
177
|
+
const st = lstatSync(cur);
|
|
178
|
+
if (st.isSymbolicLink()) {
|
|
179
|
+
if (isAllowedDarwinSystemLink(cur)) continue;
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
if (!st.isDirectory()) return false;
|
|
183
|
+
} catch (e: any) {
|
|
184
|
+
if (e && typeof e === "object" && e.code === "ENOENT") continue;
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function isSafeDirOrMissing(dirPath: string): boolean {
|
|
192
|
+
if (!dirPath || CONTROL_CHAR_RE.test(dirPath)) return false;
|
|
193
|
+
if (!hasSafeRawDotDotSegments(dirPath)) return false;
|
|
194
|
+
const abs = resolve(dirPath);
|
|
195
|
+
const root = parse(abs).root;
|
|
196
|
+
const segments = abs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
197
|
+
let cur = root;
|
|
198
|
+
for (let i = 0; i < segments.length; i++) {
|
|
199
|
+
cur = join(cur, segments[i]!);
|
|
200
|
+
try {
|
|
201
|
+
const st = lstatSync(cur);
|
|
202
|
+
if (st.isSymbolicLink()) {
|
|
203
|
+
if (isAllowedDarwinSystemLink(cur)) continue;
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
if (!st.isDirectory()) return false;
|
|
207
|
+
} catch (e: any) {
|
|
208
|
+
if (e && typeof e === "object" && e.code === "ENOENT") return true;
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function isValidBindToken(value: string): boolean {
|
|
216
|
+
return value.length > 0 && value.length <= 256 && !CONTROL_CHAR_RE.test(value);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function isValidBoundProfileName(value: string): boolean {
|
|
220
|
+
if (
|
|
221
|
+
!isValidBindToken(value) ||
|
|
222
|
+
value === "." ||
|
|
223
|
+
value.includes("..") ||
|
|
224
|
+
value.includes("/") ||
|
|
225
|
+
value.includes("\\")
|
|
226
|
+
) {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
const rawStem = value.replace(/\.json$/i, "");
|
|
230
|
+
const stem = rawStem.toLowerCase();
|
|
231
|
+
const normalizedStem = stem.replace(/[^a-z0-9_-]/g, "_");
|
|
232
|
+
return (
|
|
233
|
+
Boolean(stem) &&
|
|
234
|
+
!WINDOWS_DEVICE_STEM_RE.test(rawStem) &&
|
|
235
|
+
!isUnsafeBindKey(value) &&
|
|
236
|
+
!isUnsafeBindKey(stem) &&
|
|
237
|
+
!RESERVED_BIND_SIDECARS.has(stem) &&
|
|
238
|
+
!RESERVED_BIND_SIDECARS.has(normalizedStem)
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function lockFilePath(lockDir: string, agentId: string): string {
|
|
243
|
+
const trimmed = String(agentId || "").trim();
|
|
244
|
+
let safe = trimmed.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
245
|
+
if (safe.length > LOCK_KEY_MAX_CHARS) {
|
|
246
|
+
const digest = createHash("sha256").update(trimmed).digest("hex").slice(0, 12);
|
|
247
|
+
safe = `${safe.slice(0, LOCK_KEY_MAX_CHARS - 13)}_${digest}`;
|
|
248
|
+
}
|
|
249
|
+
if (!safe || isUnsafeBindKey(safe)) {
|
|
250
|
+
safe = `_${safe}`;
|
|
251
|
+
}
|
|
252
|
+
return join(lockDir, `${safe}.lock`);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function readAgentLock(lockDir: string, agentId: string): AgentLockRecord | null {
|
|
256
|
+
if (!agentId || !isSafeDirOrMissing(lockDir)) return null;
|
|
257
|
+
const file = lockFilePath(lockDir, agentId);
|
|
258
|
+
const raw = readBoundedRegularJson(file, LOCK_FILE_MAX_BYTES) as Record<string, unknown> | null;
|
|
259
|
+
if (
|
|
260
|
+
!raw ||
|
|
261
|
+
typeof raw !== "object" ||
|
|
262
|
+
Array.isArray(raw) ||
|
|
263
|
+
Object.prototype.hasOwnProperty.call(raw, "__proto__") ||
|
|
264
|
+
typeof raw.pid !== "number" ||
|
|
265
|
+
typeof raw.agentId !== "string"
|
|
266
|
+
) {
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
return raw as unknown as AgentLockRecord;
|
|
270
|
+
}
|
|
271
|
+
|
|
90
272
|
/**
|
|
91
273
|
* Check if `agentId` is currently locked by ANOTHER live process.
|
|
92
274
|
* Returns `{ locked: false }` if unlocked, if the lock holder PID exited,
|
|
@@ -102,11 +284,19 @@ export function checkAgentLock(opts: {
|
|
|
102
284
|
}): AgentLockCheck {
|
|
103
285
|
const { lockDir, agentId } = opts;
|
|
104
286
|
const currentPid = opts.currentPid ?? process.pid;
|
|
105
|
-
if (!agentId) return { locked: false };
|
|
287
|
+
if (!agentId || !isSafeDirOrMissing(lockDir)) return { locked: false };
|
|
288
|
+
const file = lockFilePath(lockDir, agentId);
|
|
106
289
|
const record = readAgentLock(lockDir, agentId);
|
|
107
|
-
if (!record)
|
|
290
|
+
if (!record) {
|
|
291
|
+
try {
|
|
292
|
+
const st = lstatSync(file);
|
|
293
|
+
const ageMs = Date.now() - st.mtimeMs;
|
|
294
|
+
if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1_000 || ageMs < -1_000)) unlinkSync(file);
|
|
295
|
+
} catch {}
|
|
296
|
+
return { locked: false };
|
|
297
|
+
}
|
|
108
298
|
if (!isPidAlive(record.pid)) {
|
|
109
|
-
try { unlinkSync(
|
|
299
|
+
try { unlinkSync(file); } catch {}
|
|
110
300
|
return { locked: false, stale: true };
|
|
111
301
|
}
|
|
112
302
|
if (record.pid === currentPid) {
|
|
@@ -132,6 +322,8 @@ export function acquireAgentLock(opts: {
|
|
|
132
322
|
currentPid?: number;
|
|
133
323
|
}): AgentLockRecord | null {
|
|
134
324
|
if (!opts.agentId) return null;
|
|
325
|
+
const file = lockFilePath(opts.lockDir, opts.agentId);
|
|
326
|
+
if (!isSafeDirOrMissing(opts.lockDir) || !isSafeTargetFileOrMissing(file)) return null;
|
|
135
327
|
const record: AgentLockRecord = {
|
|
136
328
|
pid: opts.currentPid ?? process.pid,
|
|
137
329
|
agentId: opts.agentId,
|
|
@@ -142,7 +334,7 @@ export function acquireAgentLock(opts: {
|
|
|
142
334
|
};
|
|
143
335
|
try {
|
|
144
336
|
mkdirSync(opts.lockDir, { recursive: true, mode: 0o700 });
|
|
145
|
-
safeWriteProfile(
|
|
337
|
+
safeWriteProfile(file, record);
|
|
146
338
|
return record;
|
|
147
339
|
} catch {
|
|
148
340
|
return null;
|
|
@@ -156,61 +348,102 @@ export function releaseAgentLock(opts: {
|
|
|
156
348
|
currentPid?: number;
|
|
157
349
|
currentSessionId?: string | null;
|
|
158
350
|
}): boolean {
|
|
159
|
-
if (!opts.agentId) return false;
|
|
351
|
+
if (!opts.agentId || !isSafeDirOrMissing(opts.lockDir)) return false;
|
|
160
352
|
const currentPid = opts.currentPid ?? process.pid;
|
|
353
|
+
const file = lockFilePath(opts.lockDir, opts.agentId);
|
|
161
354
|
const existing = readAgentLock(opts.lockDir, opts.agentId);
|
|
162
|
-
if (!existing)
|
|
355
|
+
if (!existing) {
|
|
356
|
+
try {
|
|
357
|
+
const st = lstatSync(file);
|
|
358
|
+
const ageMs = Date.now() - st.mtimeMs;
|
|
359
|
+
if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1_000 || ageMs < -1_000)) {
|
|
360
|
+
unlinkSync(file);
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
} catch {}
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
163
366
|
const samePid = existing.pid === currentPid;
|
|
164
367
|
const sameSession = Boolean(opts.currentSessionId && existing.sessionId && opts.currentSessionId === existing.sessionId);
|
|
165
368
|
const dead = !isPidAlive(existing.pid);
|
|
166
369
|
if (!samePid && !sameSession && !dead) return false;
|
|
167
370
|
try {
|
|
168
|
-
unlinkSync(
|
|
371
|
+
unlinkSync(file);
|
|
169
372
|
return true;
|
|
170
373
|
} catch {
|
|
171
374
|
return false;
|
|
172
375
|
}
|
|
173
376
|
}
|
|
174
377
|
|
|
378
|
+
function isUnsafeBindKey(key: string): boolean {
|
|
379
|
+
return UNSAFE_BIND_KEYS.has(key.toLowerCase());
|
|
380
|
+
}
|
|
381
|
+
|
|
175
382
|
/** Parse a `session-binds.json` (or `agy-binds.json`) payload into `sessionId -> profileName`. */
|
|
176
383
|
export function parseSessionBinds(raw: unknown): Record<string, string> {
|
|
177
384
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
178
385
|
const out: Record<string, string> = {};
|
|
386
|
+
let count = 0;
|
|
179
387
|
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
388
|
+
if (count >= MAX_SESSION_BINDS_ENTRIES) break;
|
|
180
389
|
const key = k.trim();
|
|
181
|
-
if (!key) continue;
|
|
182
|
-
if (typeof v === "string"
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
390
|
+
if (!isValidBindToken(key) || key === "." || key === ".." || isUnsafeBindKey(key)) continue;
|
|
391
|
+
if (typeof v === "string") {
|
|
392
|
+
const val = v.trim();
|
|
393
|
+
if (isValidBoundProfileName(val)) {
|
|
394
|
+
out[key] = val;
|
|
395
|
+
count += 1;
|
|
396
|
+
}
|
|
397
|
+
} else if (v && typeof v === "object" && typeof (v as any).profile === "string") {
|
|
398
|
+
const val = (v as any).profile.trim();
|
|
399
|
+
if (isValidBoundProfileName(val)) {
|
|
400
|
+
out[key] = val;
|
|
401
|
+
count += 1;
|
|
402
|
+
}
|
|
186
403
|
}
|
|
187
404
|
}
|
|
188
405
|
return out;
|
|
189
406
|
}
|
|
190
407
|
|
|
191
408
|
export function loadSessionBinds(configDir: string): Record<string, string> {
|
|
409
|
+
if (!isSafeDirOrMissing(configDir)) return {};
|
|
192
410
|
const merged: Record<string, string> = {};
|
|
193
411
|
for (const filename of [LEGACY_AGY_BINDS_FILENAME, DEFAULT_SESSION_BINDS_FILENAME]) {
|
|
194
412
|
const path = join(configDir, filename);
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
Object.assign(merged, parseSessionBinds(
|
|
198
|
-
}
|
|
413
|
+
const parsed = readBoundedRegularJson(path, SESSION_BINDS_MAX_BYTES);
|
|
414
|
+
if (parsed !== null) {
|
|
415
|
+
Object.assign(merged, parseSessionBinds(parsed));
|
|
416
|
+
}
|
|
199
417
|
}
|
|
200
418
|
return merged;
|
|
201
419
|
}
|
|
202
420
|
|
|
203
421
|
function resolveAgentIdForProfileName(configDir: string, name: string): string | null {
|
|
204
|
-
if (!name || name.includes("/") || name.includes("\\")) return null;
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
422
|
+
if (!name || name === "." || name.includes("..") || name.includes("/") || name.includes("\\") || CONTROL_CHAR_RE.test(name)) return null;
|
|
423
|
+
if (!isSafeDirOrMissing(configDir)) return null;
|
|
424
|
+
const rawStem = name.replace(/\.json$/i, "");
|
|
425
|
+
const stem = rawStem.toLowerCase();
|
|
426
|
+
const base = rawStem.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
427
|
+
if (
|
|
428
|
+
!base ||
|
|
429
|
+
base.length > LOCK_KEY_MAX_CHARS ||
|
|
430
|
+
WINDOWS_DEVICE_STEM_RE.test(rawStem) ||
|
|
431
|
+
WINDOWS_DEVICE_STEM_RE.test(base) ||
|
|
432
|
+
isUnsafeBindKey(base) ||
|
|
433
|
+
RESERVED_BIND_SIDECARS.has(stem) ||
|
|
434
|
+
RESERVED_BIND_SIDECARS.has(base.toLowerCase())
|
|
435
|
+
) {
|
|
436
|
+
return null;
|
|
437
|
+
}
|
|
438
|
+
const profilesDir = join(configDir, "profiles");
|
|
439
|
+
const candidates = isSafeDirOrMissing(profilesDir)
|
|
440
|
+
? [join(profilesDir, `${base}.json`), join(configDir, `${base}.json`)]
|
|
441
|
+
: [join(configDir, `${base}.json`)];
|
|
442
|
+
for (const candidate of candidates) {
|
|
443
|
+
const parsed = readBoundedRegularJson(candidate, SESSION_BINDS_MAX_BYTES) as { agent_id?: unknown } | null;
|
|
444
|
+
if (typeof parsed?.agent_id === "string" && parsed.agent_id.trim()) {
|
|
445
|
+
return parsed.agent_id.trim();
|
|
446
|
+
}
|
|
214
447
|
}
|
|
215
448
|
return null;
|
|
216
449
|
}
|
|
@@ -218,17 +451,22 @@ function resolveAgentIdForProfileName(configDir: string, name: string): string |
|
|
|
218
451
|
export function saveSessionBind(configDir: string, sessionId: string, profileName: string): void {
|
|
219
452
|
const sid = sessionId.trim();
|
|
220
453
|
const prof = profileName.trim();
|
|
221
|
-
if (!sid || !prof)
|
|
454
|
+
if (!isValidBindToken(sid) || sid === "." || sid === ".." || isUnsafeBindKey(sid) || !isValidBoundProfileName(prof)) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
if (!isSafeDirOrMissing(configDir)) return;
|
|
458
|
+
const path = join(configDir, DEFAULT_SESSION_BINDS_FILENAME);
|
|
459
|
+
if (!isSafeTargetFileOrMissing(path)) return;
|
|
222
460
|
const targetAgentId = resolveAgentIdForProfileName(configDir, prof);
|
|
223
461
|
const isSameProfileOrAgent = (existingProf: string): boolean => {
|
|
224
462
|
if (existingProf === prof) return true;
|
|
225
463
|
if (!targetAgentId) return false;
|
|
226
464
|
return resolveAgentIdForProfileName(configDir, existingProf) === targetAgentId;
|
|
227
465
|
};
|
|
228
|
-
const path = join(configDir, DEFAULT_SESSION_BINDS_FILENAME);
|
|
229
466
|
let current: Record<string, string> = {};
|
|
230
|
-
|
|
231
|
-
|
|
467
|
+
const existingParsed = readBoundedRegularJson(path, SESSION_BINDS_MAX_BYTES);
|
|
468
|
+
if (existingParsed !== null) {
|
|
469
|
+
current = parseSessionBinds(existingParsed);
|
|
232
470
|
}
|
|
233
471
|
// Enforce 1:1 (profileName & agent_id) <-> sessionId mapping so re-binding a
|
|
234
472
|
// profile (or an alias file such as `profile.json` + `<Name>.json` sharing one
|
|
@@ -244,31 +482,37 @@ export function saveSessionBind(configDir: string, sessionId: string, profileNam
|
|
|
244
482
|
safeWriteProfile(path, current);
|
|
245
483
|
|
|
246
484
|
const legacyPath = join(configDir, LEGACY_AGY_BINDS_FILENAME);
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
485
|
+
if (isSafeTargetFileOrMissing(legacyPath)) {
|
|
486
|
+
const legacyParsed = readBoundedRegularJson(legacyPath, SESSION_BINDS_MAX_BYTES);
|
|
487
|
+
if (legacyParsed !== null) {
|
|
488
|
+
try {
|
|
489
|
+
const legacy = parseSessionBinds(legacyParsed);
|
|
490
|
+
let changed = false;
|
|
491
|
+
for (const [existingSid, existingProf] of Object.entries(legacy)) {
|
|
492
|
+
if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
|
|
493
|
+
delete legacy[existingSid];
|
|
494
|
+
changed = true;
|
|
495
|
+
}
|
|
255
496
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
}
|
|
497
|
+
if (changed) safeWriteProfile(legacyPath, legacy);
|
|
498
|
+
} catch {}
|
|
499
|
+
}
|
|
259
500
|
}
|
|
260
501
|
}
|
|
261
502
|
|
|
262
503
|
export function removeSessionBind(configDir: string, sessionId: string): boolean {
|
|
263
504
|
const sid = sessionId.trim();
|
|
264
|
-
if (!sid) return false;
|
|
505
|
+
if (!isValidBindToken(sid) || sid === "." || sid === ".." || isUnsafeBindKey(sid)) return false;
|
|
506
|
+
if (!isSafeDirOrMissing(configDir)) return false;
|
|
265
507
|
let removed = false;
|
|
266
508
|
for (const filename of [DEFAULT_SESSION_BINDS_FILENAME, LEGACY_AGY_BINDS_FILENAME]) {
|
|
267
509
|
const path = join(configDir, filename);
|
|
268
|
-
if (!
|
|
510
|
+
if (!isSafeTargetFileOrMissing(path)) continue;
|
|
511
|
+
const raw = readBoundedRegularJson(path, SESSION_BINDS_MAX_BYTES);
|
|
512
|
+
if (raw === null) continue;
|
|
269
513
|
try {
|
|
270
|
-
const current = parseSessionBinds(
|
|
271
|
-
if (sid
|
|
514
|
+
const current = parseSessionBinds(raw);
|
|
515
|
+
if (Object.hasOwn(current, sid)) {
|
|
272
516
|
delete current[sid];
|
|
273
517
|
safeWriteProfile(path, current);
|
|
274
518
|
removed = true;
|
|
@@ -295,48 +539,62 @@ export function findBoundSessionForProfile(
|
|
|
295
539
|
return matches.length > 0 ? matches[matches.length - 1]! : null;
|
|
296
540
|
}
|
|
297
541
|
|
|
542
|
+
function isSafeDetectedSessionId(sid: string): boolean {
|
|
543
|
+
return isValidBindToken(sid) && sid !== "." && !sid.includes("..") && !sid.includes("/") && !sid.includes("\\") && !isUnsafeBindKey(sid);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function cleanDetectedWorkspacePath(raw: unknown): string | undefined {
|
|
547
|
+
if (typeof raw !== "string") return undefined;
|
|
548
|
+
const s = raw.trim();
|
|
549
|
+
if (!s || s.length > 4096 || s.startsWith("-") || CONTROL_CHAR_RE.test(s)) return undefined;
|
|
550
|
+
return s;
|
|
551
|
+
}
|
|
552
|
+
|
|
298
553
|
/** Detect session ID from environment variables or MCP request `_meta` (ZCode). */
|
|
299
554
|
export function detectRuntimeSession(
|
|
300
555
|
env: Record<string, string | undefined> = process.env,
|
|
301
556
|
meta?: Record<string, any> | null,
|
|
302
557
|
): DetectedSession | null {
|
|
558
|
+
if (env.AGENTSCHAT_DSH_HEALTH_URL?.trim() || env.AGENTSCHAT_DSH_HOME?.trim()) {
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
|
|
303
562
|
// 1. ZCode MCP request `_meta` (injected on every tools/call by ZCode's NodeMcpAdapter)
|
|
304
563
|
const zcodeCtx = meta?.["com.zcode/request-context"];
|
|
305
564
|
const metaSessionId =
|
|
306
565
|
(typeof meta?.session_id === "string" && meta.session_id.trim()) ||
|
|
307
566
|
(typeof zcodeCtx?.session_id === "string" && zcodeCtx.session_id.trim()) ||
|
|
308
567
|
"";
|
|
309
|
-
if (metaSessionId) {
|
|
568
|
+
if (isSafeDetectedSessionId(metaSessionId)) {
|
|
310
569
|
const workspacePath =
|
|
311
|
-
(
|
|
312
|
-
(
|
|
313
|
-
undefined;
|
|
570
|
+
cleanDetectedWorkspacePath(meta?.workspace_path) ||
|
|
571
|
+
cleanDetectedWorkspacePath(zcodeCtx?.workspace_path);
|
|
314
572
|
return { sessionId: metaSessionId, runtime: "zcode", ...(workspacePath ? { workspacePath } : {}) };
|
|
315
573
|
}
|
|
316
574
|
|
|
317
575
|
// 2. ZCode environment variable
|
|
318
|
-
const zcodeEnvSid = env.ZCODE_SESSION_ID?.trim();
|
|
319
|
-
if (zcodeEnvSid) {
|
|
320
|
-
const workspacePath = env.ZCODE_PROJECT_DIR
|
|
576
|
+
const zcodeEnvSid = env.ZCODE_SESSION_ID?.trim() || "";
|
|
577
|
+
if (isSafeDetectedSessionId(zcodeEnvSid)) {
|
|
578
|
+
const workspacePath = cleanDetectedWorkspacePath(env.ZCODE_PROJECT_DIR);
|
|
321
579
|
return { sessionId: zcodeEnvSid, runtime: "zcode", ...(workspacePath ? { workspacePath } : {}) };
|
|
322
580
|
}
|
|
323
581
|
|
|
324
582
|
// 3. Antigravity explicit environment variable
|
|
325
|
-
const agySid = env.ANTIGRAVITY_CONVERSATION_ID?.trim();
|
|
326
|
-
if (agySid) {
|
|
583
|
+
const agySid = env.ANTIGRAVITY_CONVERSATION_ID?.trim() || "";
|
|
584
|
+
if (isSafeDetectedSessionId(agySid)) {
|
|
327
585
|
return { sessionId: agySid, runtime: "antigravity" };
|
|
328
586
|
}
|
|
329
587
|
|
|
330
588
|
// 4. Claude Code environment variable
|
|
331
589
|
const claudeSid = (env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || "").trim();
|
|
332
|
-
if (claudeSid) {
|
|
333
|
-
const workspacePath = env.CLAUDE_PROJECT_DIR
|
|
590
|
+
if (isSafeDetectedSessionId(claudeSid)) {
|
|
591
|
+
const workspacePath = cleanDetectedWorkspacePath(env.CLAUDE_PROJECT_DIR);
|
|
334
592
|
return { sessionId: claudeSid, runtime: "claude-code", ...(workspacePath ? { workspacePath } : {}) };
|
|
335
593
|
}
|
|
336
594
|
|
|
337
595
|
// 5. Explicit generic session ID override
|
|
338
596
|
const explicitSid = (env.AGENTSCHAT_SESSION_ID || env.AGENTCHAT_SESSION_ID || "").trim();
|
|
339
|
-
if (explicitSid) {
|
|
597
|
+
if (isSafeDetectedSessionId(explicitSid)) {
|
|
340
598
|
return { sessionId: explicitSid, runtime: "custom" };
|
|
341
599
|
}
|
|
342
600
|
|
|
@@ -403,7 +661,7 @@ export function parseAntigravityLsofOutput(
|
|
|
403
661
|
const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
|
|
404
662
|
if (portMatch) {
|
|
405
663
|
const p = Number(portMatch[1]);
|
|
406
|
-
if (p
|
|
664
|
+
if (Number.isSafeInteger(p) && p >= 1 && p <= 65535 && !ports.includes(p)) ports.push(p);
|
|
407
665
|
}
|
|
408
666
|
if (!isCliTarget && line.includes("/antigravity-cli/")) continue;
|
|
409
667
|
|
|
@@ -432,11 +690,213 @@ export function parseAntigravityLsofOutput(
|
|
|
432
690
|
return { ports, openConversations };
|
|
433
691
|
}
|
|
434
692
|
|
|
693
|
+
function extractCliFlagValue(cmd: string, flag: string): string {
|
|
694
|
+
const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
695
|
+
const re = new RegExp(`${escaped}(?:=|\\s+)(?:"([^"]+)"|'([^']+)'|([^\\s"']+))`);
|
|
696
|
+
const m = cmd.match(re);
|
|
697
|
+
return (m?.[1] ?? m?.[2] ?? m?.[3] ?? "").trim();
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Parse Windows `netstat -ano` output into listening loopback (`127.0.0.1` / `[::1]`)
|
|
702
|
+
* TCP ports owned by `targetPid`, sorted descending so plaintext HTTP Connect-RPC
|
|
703
|
+
* ports allocated after HTTPS are tried first.
|
|
704
|
+
*
|
|
705
|
+
* Matches foreign address `0.0.0.0:0` / `[::]:0` / `*:*` rather than English
|
|
706
|
+
* `"LISTENING"` text so localized Windows builds (German, French, Spanish, Chinese, etc.)
|
|
707
|
+
* work identically.
|
|
708
|
+
*/
|
|
709
|
+
export function parseWindowsNetstatOutput(stdout: string, targetPid: number): number[] {
|
|
710
|
+
if (!stdout || !Number.isSafeInteger(targetPid) || targetPid <= 0) return [];
|
|
711
|
+
const ports: number[] = [];
|
|
712
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
713
|
+
const m = line.match(
|
|
714
|
+
/^\s*TCP\s+(?:127\.0\.0\.1|\[::1\]):(\d+)\s+(?:0\.0\.0\.0:0|\[::\]:0|\*:\*)\s+\S+\s+(\d+)\s*$/i,
|
|
715
|
+
);
|
|
716
|
+
if (!m) continue;
|
|
717
|
+
const port = Number(m[1]);
|
|
718
|
+
const pid = Number(m[2]);
|
|
719
|
+
if (pid === targetPid && Number.isSafeInteger(port) && port >= 1 && port <= 65535 && !ports.includes(port)) {
|
|
720
|
+
ports.push(port);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
ports.sort((a, b) => b - a);
|
|
724
|
+
return ports;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Pure parser for the JSON emitted by `discoverWindowsAntigravityHost`'s PowerShell probe
|
|
729
|
+
* (`{ lsPid, lsCmd, ports, lockedPresence, lockedDbs }`), with optional `netstat -ano`
|
|
730
|
+
* fallback output when `Get-NetTCPConnection` is unavailable.
|
|
731
|
+
*/
|
|
732
|
+
export function parseWindowsAntigravityProbeJson(
|
|
733
|
+
stdout: string,
|
|
734
|
+
netstatStdout = "",
|
|
735
|
+
): AntigravityHostInfo | null {
|
|
736
|
+
const trimmed = (stdout || "").trim();
|
|
737
|
+
if (!trimmed || trimmed === "{}") return null;
|
|
738
|
+
let parsed: any;
|
|
739
|
+
try {
|
|
740
|
+
parsed = JSON.parse(trimmed);
|
|
741
|
+
} catch {
|
|
742
|
+
return null;
|
|
743
|
+
}
|
|
744
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
745
|
+
return null;
|
|
746
|
+
}
|
|
747
|
+
const lsPid = Number(parsed?.lsPid);
|
|
748
|
+
const lsCmd = typeof parsed?.lsCmd === "string" ? parsed.lsCmd : "";
|
|
749
|
+
if (!Number.isSafeInteger(lsPid) || lsPid <= 0 || !lsCmd) return null;
|
|
750
|
+
|
|
751
|
+
const csrfToken = extractCliFlagValue(lsCmd, "--csrf_token");
|
|
752
|
+
if (!csrfToken) return null;
|
|
753
|
+
|
|
754
|
+
const portSet = new Set<number>();
|
|
755
|
+
const rawPorts = Array.isArray(parsed?.ports)
|
|
756
|
+
? parsed.ports
|
|
757
|
+
: typeof parsed?.ports === "number"
|
|
758
|
+
? [parsed.ports]
|
|
759
|
+
: [];
|
|
760
|
+
for (const p of rawPorts) {
|
|
761
|
+
const num = Number(p);
|
|
762
|
+
if (Number.isSafeInteger(num) && num >= 1 && num <= 65535) portSet.add(num);
|
|
763
|
+
}
|
|
764
|
+
if (portSet.size === 0 && netstatStdout) {
|
|
765
|
+
for (const p of parseWindowsNetstatOutput(netstatStdout, lsPid)) {
|
|
766
|
+
portSet.add(p);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
const ports = [...portSet].sort((a, b) => b - a);
|
|
770
|
+
|
|
771
|
+
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
772
|
+
const toUuidList = (val: unknown): string[] => {
|
|
773
|
+
const arr = Array.isArray(val) ? val : typeof val === "string" ? [val] : [];
|
|
774
|
+
const out: string[] = [];
|
|
775
|
+
for (const item of arr) {
|
|
776
|
+
const s = String(item || "").trim();
|
|
777
|
+
if (uuidRe.test(s) && !out.includes(s)) out.push(s);
|
|
778
|
+
}
|
|
779
|
+
return out;
|
|
780
|
+
};
|
|
781
|
+
const lockedPresence = toUuidList(parsed?.lockedPresence);
|
|
782
|
+
const lockedDbs = toUuidList(parsed?.lockedDbs);
|
|
783
|
+
const openConversations = lockedPresence.length > 0 ? lockedPresence : lockedDbs;
|
|
784
|
+
|
|
785
|
+
return { lsPid, csrfToken, ports, openConversations };
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function runWindowsPowerShell(script: string, timeoutMs = 4000): string | null {
|
|
789
|
+
for (const bin of ["powershell.exe", "pwsh.exe", "pwsh"]) {
|
|
790
|
+
const res = spawnSync(
|
|
791
|
+
bin,
|
|
792
|
+
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
|
|
793
|
+
{ encoding: "utf8", timeout: timeoutMs, windowsHide: true },
|
|
794
|
+
);
|
|
795
|
+
if (!res.error && res.status === 0 && typeof res.stdout === "string") {
|
|
796
|
+
return res.stdout;
|
|
797
|
+
}
|
|
798
|
+
if (!res.error) break;
|
|
799
|
+
}
|
|
800
|
+
return null;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function discoverWindowsAntigravityHost(currentPid: number): AntigravityHostInfo | null {
|
|
804
|
+
// Walk up to 8 ancestor hops on Windows because npm/cmd shims (`language_server.exe` ->
|
|
805
|
+
// `cmd.exe` -> `node npx` -> `cmd.exe` -> `node server.js`) add extra intermediate hops.
|
|
806
|
+
// Active IDE windows hold an open OS file handle on `~/.gemini/<appDataDir>/presence/<uuid>.lock`
|
|
807
|
+
// while historical closed tabs leave unlocked `.lock` files on disk; probing with
|
|
808
|
+
// `[System.IO.File]::Open(..., FileShare.None)` triggers a kernel `SharingViolation`
|
|
809
|
+
// (`IOException`) if and only if another process currently holds an open handle, requiring
|
|
810
|
+
// zero administrator privileges and never mutating file contents or mtime.
|
|
811
|
+
const psScript = [
|
|
812
|
+
"$ErrorActionPreference = 'SilentlyContinue'",
|
|
813
|
+
`$p = ${Math.trunc(currentPid)}`,
|
|
814
|
+
"$lsPid = 0",
|
|
815
|
+
"$lsCmd = ''",
|
|
816
|
+
"for ($h = 0; $h -lt 8 -and $p -gt 0; $h++) {",
|
|
817
|
+
" $proc = Get-CimInstance Win32_Process -Filter \"ProcessId=$p\"",
|
|
818
|
+
" if (-not $proc) { break }",
|
|
819
|
+
" $cmd = [string]$proc.CommandLine",
|
|
820
|
+
" $name = [string]$proc.Name",
|
|
821
|
+
" if ($h -gt 0 -and ($cmd -match 'bun(?:\\.exe)?\\s+test' -or $cmd -match 'node(?:\\.exe)?\\s+--test')) { break }",
|
|
822
|
+
" if (($cmd -match 'language_server' -or $name -match 'language_server') -and $cmd -match '--csrf_token') {",
|
|
823
|
+
" $lsPid = [int]$proc.ProcessId",
|
|
824
|
+
" $lsCmd = $cmd",
|
|
825
|
+
" break",
|
|
826
|
+
" }",
|
|
827
|
+
" $nextP = [int]$proc.ParentProcessId",
|
|
828
|
+
" if ($nextP -le 0 -or $nextP -eq $p) { break }",
|
|
829
|
+
" $p = $nextP",
|
|
830
|
+
"}",
|
|
831
|
+
"if ($lsPid -le 0) { Write-Output '{}'; exit 0 }",
|
|
832
|
+
"$ports = @()",
|
|
833
|
+
"if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) {",
|
|
834
|
+
" $ports = @(Get-NetTCPConnection -OwningProcess $lsPid -State Listen | Where-Object { $_.LocalAddress -eq '127.0.0.1' -or $_.LocalAddress -eq '::1' } | ForEach-Object { [int]$_.LocalPort } | Select-Object -Unique)",
|
|
835
|
+
"}",
|
|
836
|
+
"$appDir = 'antigravity'",
|
|
837
|
+
"if ($lsCmd -match '--app_data_dir(?:=|\\s+)(?:\"([^\"]+)\"|''([^'']+)''|([^\\s\"'']+))') {",
|
|
838
|
+
" $appDir = if ($Matches[1]) { $Matches[1] } elseif ($Matches[2]) { $Matches[2] } else { $Matches[3] }",
|
|
839
|
+
"}",
|
|
840
|
+
"$homeDir = if ($env:USERPROFILE) { $env:USERPROFILE } else { [Environment]::GetFolderPath('UserProfile') }",
|
|
841
|
+
"$baseDir = Join-Path (Join-Path $homeDir '.gemini') $appDir",
|
|
842
|
+
"$lockedPresence = @()",
|
|
843
|
+
"$presDir = Join-Path $baseDir 'presence'",
|
|
844
|
+
"if (Test-Path -LiteralPath $presDir) {",
|
|
845
|
+
" Get-ChildItem -LiteralPath $presDir -Filter '*.lock' -File | ForEach-Object {",
|
|
846
|
+
" if ($_.BaseName -match '^[0-9a-fA-F-]{36}$') {",
|
|
847
|
+
" try {",
|
|
848
|
+
" $s = [System.IO.File]::Open($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::None)",
|
|
849
|
+
" $s.Dispose()",
|
|
850
|
+
" } catch [System.IO.IOException] {",
|
|
851
|
+
" $lockedPresence += $_.BaseName",
|
|
852
|
+
" } catch {}",
|
|
853
|
+
" }",
|
|
854
|
+
" }",
|
|
855
|
+
"}",
|
|
856
|
+
"$lockedDbs = @()",
|
|
857
|
+
"if ($lockedPresence.Count -eq 0 -and $appDir -ne 'antigravity-cli') {",
|
|
858
|
+
" $convDir = Join-Path $baseDir 'conversations'",
|
|
859
|
+
" if (Test-Path -LiteralPath $convDir) {",
|
|
860
|
+
" Get-ChildItem -LiteralPath $convDir -Filter '*.db' -File | ForEach-Object {",
|
|
861
|
+
" if ($_.BaseName -match '^[0-9a-fA-F-]{36}$') {",
|
|
862
|
+
" try {",
|
|
863
|
+
" $s = [System.IO.File]::Open($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::None)",
|
|
864
|
+
" $s.Dispose()",
|
|
865
|
+
" } catch [System.IO.IOException] {",
|
|
866
|
+
" $lockedDbs += $_.BaseName",
|
|
867
|
+
" } catch {}",
|
|
868
|
+
" }",
|
|
869
|
+
" }",
|
|
870
|
+
" }",
|
|
871
|
+
"}",
|
|
872
|
+
"[pscustomobject]@{ lsPid = $lsPid; lsCmd = $lsCmd; ports = $ports; lockedPresence = $lockedPresence; lockedDbs = $lockedDbs } | ConvertTo-Json -Compress",
|
|
873
|
+
].join("; ");
|
|
874
|
+
|
|
875
|
+
const stdout = runWindowsPowerShell(psScript, 4000);
|
|
876
|
+
if (!stdout) return null;
|
|
877
|
+
|
|
878
|
+
let info = parseWindowsAntigravityProbeJson(stdout);
|
|
879
|
+
if (info && info.ports.length === 0) {
|
|
880
|
+
const ns = spawnSync("netstat", ["-ano"], { encoding: "utf8", timeout: 2000, windowsHide: true });
|
|
881
|
+
if (ns.status === 0 && ns.stdout) {
|
|
882
|
+
info = parseWindowsAntigravityProbeJson(stdout, ns.stdout);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
return info;
|
|
886
|
+
}
|
|
887
|
+
|
|
435
888
|
export function discoverAntigravityHost(opts?: {
|
|
436
889
|
currentPid?: number;
|
|
437
890
|
cacheMs?: number;
|
|
438
891
|
}): AntigravityHostInfo | null {
|
|
439
892
|
if (!opts?.currentPid) {
|
|
893
|
+
if (
|
|
894
|
+
process.env.AGENTSCHAT_DSH_HEALTH_URL?.trim() ||
|
|
895
|
+
process.env.AGENTSCHAT_DSH_HOME?.trim() ||
|
|
896
|
+
process.env.DSH_HOME?.trim()
|
|
897
|
+
) {
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
440
900
|
const envAddr = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
|
|
441
901
|
const envCsrf = process.env.ANTIGRAVITY_CSRF_TOKEN?.trim() || "";
|
|
442
902
|
if (envAddr && envCsrf) {
|
|
@@ -461,14 +921,25 @@ export function discoverAntigravityHost(opts?: {
|
|
|
461
921
|
}
|
|
462
922
|
|
|
463
923
|
const now = Date.now();
|
|
464
|
-
const cacheMs =
|
|
924
|
+
const cacheMs =
|
|
925
|
+
typeof opts?.cacheMs === "number" && Number.isFinite(opts.cacheMs) && opts.cacheMs >= 0
|
|
926
|
+
? opts.cacheMs
|
|
927
|
+
: 5_000;
|
|
928
|
+
if (cachedAgyHost && now < cachedAgyHost.at) cachedAgyHost = null;
|
|
465
929
|
if (cachedAgyHost && now - cachedAgyHost.at < cacheMs) return cachedAgyHost.info;
|
|
466
930
|
|
|
467
931
|
try {
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
932
|
+
const startPid = opts?.currentPid ?? process.pid;
|
|
933
|
+
if (process.platform === "win32") {
|
|
934
|
+
const winInfo = discoverWindowsAntigravityHost(startPid);
|
|
935
|
+
cachedAgyHost = { at: now, info: winInfo };
|
|
936
|
+
return winInfo;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
// Walk up from currentPid using fast per-PID `ps -p` queries so we never scan
|
|
940
|
+
// the whole system process table or match an indirect test runner several hops
|
|
941
|
+
// below language_server.
|
|
942
|
+
let pid = startPid;
|
|
472
943
|
let lsPid = 0;
|
|
473
944
|
let lsCmd = "";
|
|
474
945
|
for (let hop = 0; hop < 4 && pid > 1; hop++) {
|
|
@@ -479,7 +950,7 @@ export function discoverAntigravityHost(opts?: {
|
|
|
479
950
|
if (!m) break;
|
|
480
951
|
const ppid = Number(m[1]);
|
|
481
952
|
const cmd = m[2]!;
|
|
482
|
-
if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test"))) break;
|
|
953
|
+
if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test") || matchesDshCommandLine(cmd))) break;
|
|
483
954
|
if (cmd.includes("language_server") && cmd.includes("--csrf_token")) {
|
|
484
955
|
lsPid = pid;
|
|
485
956
|
lsCmd = cmd;
|
|
@@ -493,15 +964,13 @@ export function discoverAntigravityHost(opts?: {
|
|
|
493
964
|
return null;
|
|
494
965
|
}
|
|
495
966
|
|
|
496
|
-
const
|
|
497
|
-
const csrfToken = csrfMatch?.[1]?.trim() || "";
|
|
967
|
+
const csrfToken = extractCliFlagValue(lsCmd, "--csrf_token");
|
|
498
968
|
if (!csrfToken) {
|
|
499
969
|
cachedAgyHost = { at: now, info: null };
|
|
500
970
|
return null;
|
|
501
971
|
}
|
|
502
972
|
|
|
503
|
-
const
|
|
504
|
-
const appDataDir = appDirMatch?.[1]?.trim() || "antigravity";
|
|
973
|
+
const appDataDir = extractCliFlagValue(lsCmd, "--app_data_dir") || "antigravity";
|
|
505
974
|
|
|
506
975
|
const lsof = spawnSync("lsof", ["-Pan", "-p", String(lsPid)], { encoding: "utf8", timeout: 1500 });
|
|
507
976
|
const { ports, openConversations } =
|
|
@@ -532,11 +1001,13 @@ export function detectAntigravityCallerSession(opts?: {
|
|
|
532
1001
|
nowMs?: number;
|
|
533
1002
|
maxAgeMs?: number;
|
|
534
1003
|
}): string | null {
|
|
1004
|
+
const home = process.env.HOME || process.env.USERPROFILE || homedir();
|
|
535
1005
|
const brainDir =
|
|
536
1006
|
opts?.brainDir?.trim() ||
|
|
537
1007
|
process.env.AGENTSCHAT_AGY_BRAIN_DIR?.trim() ||
|
|
538
|
-
join(
|
|
539
|
-
|
|
1008
|
+
join(home, ".gemini", "antigravity", "brain");
|
|
1009
|
+
const brainStat = safeLstat(brainDir);
|
|
1010
|
+
if (!brainStat || brainStat.isSymbolicLink() || !brainStat.isDirectory() || !isSafeDirOrMissing(brainDir)) return null;
|
|
540
1011
|
|
|
541
1012
|
const nowMs = opts?.nowMs ?? Date.now();
|
|
542
1013
|
const maxAgeMs = opts?.maxAgeMs ?? 30_000;
|
|
@@ -572,14 +1043,19 @@ export function detectAntigravityCallerSession(opts?: {
|
|
|
572
1043
|
const recentCids: { cid: string; mtimeMs: number }[] = [];
|
|
573
1044
|
|
|
574
1045
|
for (const cid of candidateSet) {
|
|
575
|
-
const
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
1046
|
+
const cidDir = join(brainDir, cid);
|
|
1047
|
+
const sysDir = join(cidDir, ".system_generated");
|
|
1048
|
+
const logsDir = join(sysDir, "logs");
|
|
1049
|
+
if (
|
|
1050
|
+
!isSafeDirOrMissing(cidDir) ||
|
|
1051
|
+
!isSafeDirOrMissing(sysDir) ||
|
|
1052
|
+
!isSafeDirOrMissing(logsDir)
|
|
1053
|
+
) {
|
|
580
1054
|
continue;
|
|
581
1055
|
}
|
|
582
|
-
|
|
1056
|
+
const transcriptPath = join(logsDir, "transcript.jsonl");
|
|
1057
|
+
const st = safeLstat(transcriptPath);
|
|
1058
|
+
if (!st || st.isSymbolicLink() || !st.isFile() || st.size <= 0 || nowMs - st.mtimeMs > maxAgeMs) continue;
|
|
583
1059
|
recentCids.push({ cid, mtimeMs: st.mtimeMs });
|
|
584
1060
|
|
|
585
1061
|
let tail = "";
|
|
@@ -639,6 +1115,16 @@ export function detectAntigravityCallerSession(opts?: {
|
|
|
639
1115
|
|
|
640
1116
|
let cachedIsDshHost: { at: number; value: boolean } | null = null;
|
|
641
1117
|
|
|
1118
|
+
function matchesDshCommandLine(cmd: string): boolean {
|
|
1119
|
+
return (
|
|
1120
|
+
cmd.includes("@deepseek-ai") ||
|
|
1121
|
+
cmd.includes("/.dsh/") ||
|
|
1122
|
+
cmd.toLowerCase().includes("\\.dsh\\") ||
|
|
1123
|
+
/deepseek[- ]harness/i.test(cmd) ||
|
|
1124
|
+
/\bdsh(?:\.cmd|\.exe)?\b/i.test(cmd)
|
|
1125
|
+
);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
642
1128
|
/** Check if this MCP server was spawned by DeepSeek Harness (`dsh`). */
|
|
643
1129
|
export function isDshHostProcess(opts?: {
|
|
644
1130
|
currentPid?: number;
|
|
@@ -654,10 +1140,45 @@ export function isDshHostProcess(opts?: {
|
|
|
654
1140
|
return true;
|
|
655
1141
|
}
|
|
656
1142
|
const now = Date.now();
|
|
657
|
-
const cacheMs =
|
|
1143
|
+
const cacheMs =
|
|
1144
|
+
typeof opts?.cacheMs === "number" && Number.isFinite(opts.cacheMs) && opts.cacheMs >= 0
|
|
1145
|
+
? opts.cacheMs
|
|
1146
|
+
: 15_000;
|
|
1147
|
+
if (cachedIsDshHost && now < cachedIsDshHost.at) cachedIsDshHost = null;
|
|
658
1148
|
if (cachedIsDshHost && now - cachedIsDshHost.at < cacheMs) return cachedIsDshHost.value;
|
|
659
1149
|
try {
|
|
660
1150
|
let pid = opts?.currentPid ?? process.pid;
|
|
1151
|
+
if (process.platform === "win32") {
|
|
1152
|
+
const psOut = runWindowsPowerShell(
|
|
1153
|
+
[
|
|
1154
|
+
"$ErrorActionPreference = 'SilentlyContinue'",
|
|
1155
|
+
`$p = ${Math.trunc(pid)}`,
|
|
1156
|
+
"for ($h = 0; $h -lt 8 -and $p -gt 0; $h++) {",
|
|
1157
|
+
" $proc = Get-CimInstance Win32_Process -Filter \"ProcessId=$p\"",
|
|
1158
|
+
" if (-not $proc) { break }",
|
|
1159
|
+
" Write-Output \"$($proc.ParentProcessId)`t$($proc.CommandLine)\"",
|
|
1160
|
+
" $nextP = [int]$proc.ParentProcessId",
|
|
1161
|
+
" if ($nextP -le 0 -or $nextP -eq $p) { break }",
|
|
1162
|
+
" $p = $nextP",
|
|
1163
|
+
"}",
|
|
1164
|
+
].join("; "),
|
|
1165
|
+
2500,
|
|
1166
|
+
);
|
|
1167
|
+
if (psOut) {
|
|
1168
|
+
const lines = psOut.split(/\r?\n/).filter(Boolean);
|
|
1169
|
+
for (let hop = 0; hop < lines.length; hop++) {
|
|
1170
|
+
const tab = lines[hop]!.indexOf("\t");
|
|
1171
|
+
const cmd = tab >= 0 ? lines[hop]!.slice(tab + 1) : lines[hop]!;
|
|
1172
|
+
if (hop > 0 && (/bun(?:\.exe)?\s+test/i.test(cmd) || /node(?:\.exe)?\s+--test/i.test(cmd))) break;
|
|
1173
|
+
if (matchesDshCommandLine(cmd)) {
|
|
1174
|
+
cachedIsDshHost = { at: now, value: true };
|
|
1175
|
+
return true;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
cachedIsDshHost = { at: now, value: false };
|
|
1180
|
+
return false;
|
|
1181
|
+
}
|
|
661
1182
|
for (let hop = 0; hop < 4 && pid > 1; hop++) {
|
|
662
1183
|
const ps = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "ppid=,command="], {
|
|
663
1184
|
encoding: "utf8",
|
|
@@ -670,7 +1191,7 @@ export function isDshHostProcess(opts?: {
|
|
|
670
1191
|
const ppid = Number(m[1]);
|
|
671
1192
|
const cmd = m[2]!;
|
|
672
1193
|
if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test"))) break;
|
|
673
|
-
if (
|
|
1194
|
+
if (matchesDshCommandLine(cmd)) {
|
|
674
1195
|
cachedIsDshHost = { at: now, value: true };
|
|
675
1196
|
return true;
|
|
676
1197
|
}
|
|
@@ -681,14 +1202,115 @@ export function isDshHostProcess(opts?: {
|
|
|
681
1202
|
return false;
|
|
682
1203
|
}
|
|
683
1204
|
|
|
1205
|
+
const SAFE_DSH_SESSION_ID_RE = /^session-[a-zA-Z0-9_-]{1,128}$/;
|
|
1206
|
+
const DSH_HEALTH_MAX_BYTES = 256 * 1024;
|
|
1207
|
+
|
|
1208
|
+
function isSafeDirEntryName(entry: string): boolean {
|
|
1209
|
+
return (
|
|
1210
|
+
entry.length > 0 &&
|
|
1211
|
+
entry.length <= 255 &&
|
|
1212
|
+
entry !== "." &&
|
|
1213
|
+
entry !== ".." &&
|
|
1214
|
+
!entry.includes("/") &&
|
|
1215
|
+
!entry.includes("\\") &&
|
|
1216
|
+
!CONTROL_CHAR_RE.test(entry)
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
function isLoopbackDshHealthUrl(rawUrl: string): boolean {
|
|
1221
|
+
if (!rawUrl || rawUrl !== rawUrl.trim() || CONTROL_CHAR_RE.test(rawUrl)) return false;
|
|
1222
|
+
let u: URL;
|
|
1223
|
+
try {
|
|
1224
|
+
u = new URL(rawUrl);
|
|
1225
|
+
} catch {
|
|
1226
|
+
return false;
|
|
1227
|
+
}
|
|
1228
|
+
if (u.protocol !== "http:") return false;
|
|
1229
|
+
if (u.username || u.password || u.search || u.hash) return false;
|
|
1230
|
+
const host = u.hostname.toLowerCase();
|
|
1231
|
+
if (host !== "127.0.0.1" && host !== "localhost" && host !== "[::1]" && host !== "::1") {
|
|
1232
|
+
return false;
|
|
1233
|
+
}
|
|
1234
|
+
if (/:0+(?:\/|$)/.test(rawUrl)) return false;
|
|
1235
|
+
if (u.port) {
|
|
1236
|
+
const port = Number(u.port);
|
|
1237
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return false;
|
|
1238
|
+
}
|
|
1239
|
+
return true;
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
async function readBoundedDshHealthJson(res: Response): Promise<unknown> {
|
|
1243
|
+
const rawLen = res.headers?.get?.("content-length");
|
|
1244
|
+
if (rawLen !== null && rawLen !== undefined && rawLen.trim() !== "") {
|
|
1245
|
+
const trimmedLen = rawLen.trim();
|
|
1246
|
+
if (!/^\d+$/.test(trimmedLen) || Number(trimmedLen) > DSH_HEALTH_MAX_BYTES) {
|
|
1247
|
+
await res.body?.cancel?.().catch(() => {});
|
|
1248
|
+
throw new Error("DSH /health response exceeded byte cap");
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
const reader = (res as any)?.body?.getReader?.();
|
|
1252
|
+
let parsed: unknown;
|
|
1253
|
+
if (!reader) {
|
|
1254
|
+
const text =
|
|
1255
|
+
typeof (res as any)?.text === "function"
|
|
1256
|
+
? await res.text()
|
|
1257
|
+
: JSON.stringify(await res.json());
|
|
1258
|
+
if (Buffer.byteLength(text, "utf8") > DSH_HEALTH_MAX_BYTES) {
|
|
1259
|
+
throw new Error("DSH /health response exceeded byte cap");
|
|
1260
|
+
}
|
|
1261
|
+
parsed = JSON.parse(text);
|
|
1262
|
+
} else {
|
|
1263
|
+
const chunks: Uint8Array[] = [];
|
|
1264
|
+
let total = 0;
|
|
1265
|
+
try {
|
|
1266
|
+
while (true) {
|
|
1267
|
+
const { done, value } = await reader.read();
|
|
1268
|
+
if (done) break;
|
|
1269
|
+
if (value instanceof Uint8Array) {
|
|
1270
|
+
total += value.byteLength;
|
|
1271
|
+
if (total > DSH_HEALTH_MAX_BYTES) {
|
|
1272
|
+
await reader.cancel().catch(() => {});
|
|
1273
|
+
throw new Error("DSH /health response exceeded byte cap");
|
|
1274
|
+
}
|
|
1275
|
+
chunks.push(value);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
} finally {
|
|
1279
|
+
try {
|
|
1280
|
+
reader.releaseLock?.();
|
|
1281
|
+
} catch {}
|
|
1282
|
+
}
|
|
1283
|
+
const merged = new Uint8Array(total);
|
|
1284
|
+
let offset = 0;
|
|
1285
|
+
for (const c of chunks) {
|
|
1286
|
+
merged.set(c, offset);
|
|
1287
|
+
offset += c.byteLength;
|
|
1288
|
+
}
|
|
1289
|
+
parsed = JSON.parse(Buffer.from(merged).toString("utf8"));
|
|
1290
|
+
}
|
|
1291
|
+
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
1292
|
+
throw new Error("Invalid DSH /health JSON object");
|
|
1293
|
+
}
|
|
1294
|
+
return parsed;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
684
1297
|
/** mtime of a session directory's log, or 0 when it has none. */
|
|
685
1298
|
function sessionDirMtime(dir: string): number {
|
|
1299
|
+
const dirStat = safeLstat(dir);
|
|
1300
|
+
if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) return 0;
|
|
686
1301
|
let newest = 0;
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
1302
|
+
let entries: string[] = [];
|
|
1303
|
+
try {
|
|
1304
|
+
entries = readdirSync(dir);
|
|
1305
|
+
} catch {
|
|
1306
|
+
entries = ["session.v4.jsonl.zstd", "session.v4.jsonl"];
|
|
1307
|
+
}
|
|
1308
|
+
for (const file of entries) {
|
|
1309
|
+
if (!/^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(file)) continue;
|
|
1310
|
+
const st = safeLstat(join(dir, file));
|
|
1311
|
+
if (st && !st.isSymbolicLink() && st.isFile() && st.mtimeMs > newest) {
|
|
1312
|
+
newest = st.mtimeMs;
|
|
1313
|
+
}
|
|
692
1314
|
}
|
|
693
1315
|
return newest;
|
|
694
1316
|
}
|
|
@@ -701,15 +1323,23 @@ function sessionDirMtime(dir: string): number {
|
|
|
701
1323
|
* two sessions that are both `running` at the same time.
|
|
702
1324
|
*/
|
|
703
1325
|
function sessionLogMtime(dshHome: string, sid: string): number {
|
|
1326
|
+
if (!SAFE_DSH_SESSION_ID_RE.test(sid)) return 0;
|
|
1327
|
+
const sessionsRoot = join(dshHome, "sessions");
|
|
1328
|
+
const rootStat = safeLstat(sessionsRoot);
|
|
1329
|
+
if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) return 0;
|
|
704
1330
|
let projects: string[];
|
|
705
1331
|
try {
|
|
706
|
-
projects = readdirSync(
|
|
1332
|
+
projects = readdirSync(sessionsRoot);
|
|
707
1333
|
} catch {
|
|
708
1334
|
return 0;
|
|
709
1335
|
}
|
|
710
1336
|
let newest = 0;
|
|
711
1337
|
for (const project of projects) {
|
|
712
|
-
|
|
1338
|
+
if (!isSafeDirEntryName(project)) continue;
|
|
1339
|
+
const projDir = join(sessionsRoot, project);
|
|
1340
|
+
const projStat = safeLstat(projDir);
|
|
1341
|
+
if (!projStat || projStat.isSymbolicLink() || !projStat.isDirectory()) continue;
|
|
1342
|
+
const mtime = sessionDirMtime(join(projDir, sid));
|
|
713
1343
|
if (mtime > newest) newest = mtime;
|
|
714
1344
|
}
|
|
715
1345
|
return newest;
|
|
@@ -718,6 +1348,8 @@ function sessionLogMtime(dshHome: string, sid: string): number {
|
|
|
718
1348
|
/** Newest session log within `maxAgeMs`; the fallback when `/health` is unavailable. */
|
|
719
1349
|
function newestSessionLog(dshHome: string, nowMs: number, maxAgeMs: number): string | null {
|
|
720
1350
|
const root = join(dshHome, "sessions");
|
|
1351
|
+
const rootStat = safeLstat(root);
|
|
1352
|
+
if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) return null;
|
|
721
1353
|
let projects: string[];
|
|
722
1354
|
try {
|
|
723
1355
|
projects = readdirSync(root);
|
|
@@ -726,15 +1358,19 @@ function newestSessionLog(dshHome: string, nowMs: number, maxAgeMs: number): str
|
|
|
726
1358
|
}
|
|
727
1359
|
let best: { sid: string; mtime: number } | null = null;
|
|
728
1360
|
for (const project of projects) {
|
|
1361
|
+
if (!isSafeDirEntryName(project)) continue;
|
|
1362
|
+
const projDir = join(root, project);
|
|
1363
|
+
const projStat = safeLstat(projDir);
|
|
1364
|
+
if (!projStat || projStat.isSymbolicLink() || !projStat.isDirectory()) continue;
|
|
729
1365
|
let entries: string[];
|
|
730
1366
|
try {
|
|
731
|
-
entries = readdirSync(
|
|
1367
|
+
entries = readdirSync(projDir);
|
|
732
1368
|
} catch {
|
|
733
1369
|
continue;
|
|
734
1370
|
}
|
|
735
1371
|
for (const entry of entries) {
|
|
736
|
-
if (!
|
|
737
|
-
const mtime = sessionDirMtime(join(
|
|
1372
|
+
if (!SAFE_DSH_SESSION_ID_RE.test(entry)) continue;
|
|
1373
|
+
const mtime = sessionDirMtime(join(projDir, entry));
|
|
738
1374
|
if (mtime === 0 || nowMs - mtime > maxAgeMs) continue;
|
|
739
1375
|
if (best === null || mtime > best.mtime) best = { sid: entry, mtime };
|
|
740
1376
|
}
|
|
@@ -773,46 +1409,53 @@ export async function detectDshCallerSession(opts?: {
|
|
|
773
1409
|
"http://127.0.0.1:8799/health";
|
|
774
1410
|
const nowMs = opts?.nowMs ?? Date.now();
|
|
775
1411
|
|
|
776
|
-
|
|
777
|
-
const f = opts?.fetchImpl ?? fetch;
|
|
778
|
-
const ctrl = new AbortController();
|
|
779
|
-
const timer = setTimeout(() => ctrl.abort(), 150);
|
|
1412
|
+
if (isLoopbackDshHealthUrl(healthUrl)) {
|
|
780
1413
|
try {
|
|
781
|
-
const
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
const
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1414
|
+
const f = opts?.fetchImpl ?? fetch;
|
|
1415
|
+
const ctrl = new AbortController();
|
|
1416
|
+
const timer = setTimeout(() => ctrl.abort(), 150);
|
|
1417
|
+
timer.unref?.();
|
|
1418
|
+
try {
|
|
1419
|
+
const res = await f(healthUrl, { signal: ctrl.signal, redirect: "error" });
|
|
1420
|
+
if (res.ok) {
|
|
1421
|
+
const data = (await readBoundedDshHealthJson(res)) as {
|
|
1422
|
+
roots?: Array<{ id?: string; status?: string }>;
|
|
1423
|
+
};
|
|
1424
|
+
const roots = Array.isArray(data?.roots) ? data.roots : [];
|
|
1425
|
+
const running = roots
|
|
1426
|
+
.filter((r) => typeof r?.id === "string" && SAFE_DSH_SESSION_ID_RE.test(r.id) && r.status === "running")
|
|
1427
|
+
.map((r) => r.id!);
|
|
1428
|
+
if (running.length === 1) return running[0]!;
|
|
1429
|
+
if (running.length > 1) {
|
|
1430
|
+
// More than one session is mid-turn; the caller is the one that just
|
|
1431
|
+
// wrote a row (its session log mtime is the newest). `roots` is
|
|
1432
|
+
// oldest-first, so the newest root is the fallback when logs are
|
|
1433
|
+
// unavailable — never `running[0]`, which is the *oldest*.
|
|
1434
|
+
const ranked = running
|
|
1435
|
+
.map((sid) => ({ sid, mtime: sessionLogMtime(dshHome, sid) }))
|
|
1436
|
+
.sort((a, b) => b.mtime - a.mtime);
|
|
1437
|
+
if (ranked[0]!.mtime > 0 && ranked[0]!.mtime >= ranked[1]!.mtime) return ranked[0]!.sid;
|
|
1438
|
+
return running[running.length - 1]!;
|
|
1439
|
+
}
|
|
1440
|
+
const allValid = roots
|
|
1441
|
+
.filter((r) => typeof r?.id === "string" && SAFE_DSH_SESSION_ID_RE.test(r.id))
|
|
1442
|
+
.map((r) => r.id!);
|
|
1443
|
+
if (allValid.length === 1) return allValid[0]!;
|
|
1444
|
+
} else {
|
|
1445
|
+
await res.body?.cancel().catch(() => {});
|
|
801
1446
|
}
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
.map((r) => r.id!);
|
|
805
|
-
if (allValid.length === 1) return allValid[0]!;
|
|
1447
|
+
} finally {
|
|
1448
|
+
clearTimeout(timer);
|
|
806
1449
|
}
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
}
|
|
810
|
-
} catch {}
|
|
1450
|
+
} catch {}
|
|
1451
|
+
}
|
|
811
1452
|
|
|
812
1453
|
// No health endpoint (older/newer DSH, or the inbound plugin is not
|
|
813
1454
|
// installed): the same log-mtime signal still identifies the session that
|
|
814
1455
|
// just ran a tool call. DSH writes one directory per session under
|
|
815
1456
|
// `<dshHome>/sessions/<project>/session-<uuid>/`.
|
|
1457
|
+
const homeStat = safeLstat(dshHome);
|
|
1458
|
+
if (!homeStat || homeStat.isSymbolicLink() || !homeStat.isDirectory() || !isSafeDirOrMissing(dshHome)) return null;
|
|
816
1459
|
const newestByLog = newestSessionLog(dshHome, nowMs, 30_000);
|
|
817
1460
|
if (newestByLog) return newestByLog;
|
|
818
1461
|
return null;
|