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/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,199 @@ 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
|
+
// NOTE: "profile" MUST NEVER be added here — `profile.json` is the default boot identity slot.
|
|
85
|
+
const RESERVED_BIND_SIDECARS = new Set([
|
|
86
|
+
"session-binds",
|
|
87
|
+
"session-binds.meta",
|
|
88
|
+
"session-binds_meta",
|
|
89
|
+
"agy-binds",
|
|
90
|
+
"agy-binds.meta",
|
|
91
|
+
"agy-binds_meta",
|
|
92
|
+
"grok-binds",
|
|
93
|
+
"grok-binds.meta",
|
|
94
|
+
"grok-binds_meta",
|
|
95
|
+
"agy-session-binds",
|
|
96
|
+
"identity-guard",
|
|
97
|
+
"cursor",
|
|
98
|
+
"read-cursors",
|
|
99
|
+
"mention-timestamps",
|
|
100
|
+
"wake-pids",
|
|
101
|
+
"config",
|
|
102
|
+
"codex-bots",
|
|
103
|
+
"dsh",
|
|
104
|
+
"muse",
|
|
105
|
+
]);
|
|
106
|
+
|
|
107
|
+
function safeLstat(path: string): Stats | null {
|
|
108
|
+
try {
|
|
109
|
+
return lstatSync(path);
|
|
110
|
+
} catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
73
113
|
}
|
|
74
114
|
|
|
75
|
-
|
|
76
|
-
if (!agentId) return null;
|
|
77
|
-
const file = lockFilePath(lockDir, agentId);
|
|
78
|
-
if (!existsSync(file)) return null;
|
|
115
|
+
function readBoundedRegularJson(path: string, maxBytes: number): unknown | null {
|
|
79
116
|
try {
|
|
80
|
-
const
|
|
81
|
-
if (
|
|
117
|
+
const st = lstatSync(path);
|
|
118
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > maxBytes) return null;
|
|
119
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
120
|
+
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
82
121
|
return null;
|
|
83
122
|
}
|
|
84
|
-
return
|
|
123
|
+
return parsed;
|
|
85
124
|
} catch {
|
|
86
125
|
return null;
|
|
87
126
|
}
|
|
88
127
|
}
|
|
89
128
|
|
|
129
|
+
function isSafeTargetFileOrMissing(path: string): boolean {
|
|
130
|
+
try {
|
|
131
|
+
const st = lstatSync(path);
|
|
132
|
+
return !st.isSymbolicLink() && st.isFile();
|
|
133
|
+
} catch (e: any) {
|
|
134
|
+
return Boolean(e && typeof e === "object" && e.code === "ENOENT");
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function isAllowedDarwinSystemLink(dirPath: string): boolean {
|
|
139
|
+
if (process.platform !== "darwin") return false;
|
|
140
|
+
if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc") return false;
|
|
141
|
+
try {
|
|
142
|
+
const expected = `/private${dirPath}`;
|
|
143
|
+
return (
|
|
144
|
+
readlinkSync(dirPath) === `private${dirPath}` &&
|
|
145
|
+
realpathSync(dirPath) === expected &&
|
|
146
|
+
!lstatSync("/private").isSymbolicLink() &&
|
|
147
|
+
lstatSync("/private").isDirectory() &&
|
|
148
|
+
!lstatSync(expected).isSymbolicLink() &&
|
|
149
|
+
statSync(expected).isDirectory()
|
|
150
|
+
);
|
|
151
|
+
} catch {
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function hasSafeRawDotDotSegments(rawPath: string): boolean {
|
|
157
|
+
if (!rawPath.includes("..")) return true;
|
|
158
|
+
const baseAbs = isAbsolute(rawPath) ? rawPath : `${process.cwd()}/${rawPath}`;
|
|
159
|
+
const root = parse(baseAbs).root;
|
|
160
|
+
const rawParts = baseAbs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
161
|
+
let cur = root;
|
|
162
|
+
for (const part of rawParts) {
|
|
163
|
+
if (part === ".") continue;
|
|
164
|
+
if (part === "..") {
|
|
165
|
+
cur = resolve(cur, "..");
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
cur = join(cur, part);
|
|
169
|
+
try {
|
|
170
|
+
const st = lstatSync(cur);
|
|
171
|
+
if (st.isSymbolicLink()) {
|
|
172
|
+
if (isAllowedDarwinSystemLink(cur)) continue;
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
if (!st.isDirectory()) return false;
|
|
176
|
+
} catch (e: any) {
|
|
177
|
+
if (e && typeof e === "object" && e.code === "ENOENT") continue;
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function isSafeDirOrMissing(dirPath: string): boolean {
|
|
185
|
+
if (!dirPath || CONTROL_CHAR_RE.test(dirPath)) return false;
|
|
186
|
+
if (!hasSafeRawDotDotSegments(dirPath)) return false;
|
|
187
|
+
const abs = resolve(dirPath);
|
|
188
|
+
const root = parse(abs).root;
|
|
189
|
+
const segments = abs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
190
|
+
let cur = root;
|
|
191
|
+
for (let i = 0; i < segments.length; i++) {
|
|
192
|
+
cur = join(cur, segments[i]!);
|
|
193
|
+
try {
|
|
194
|
+
const st = lstatSync(cur);
|
|
195
|
+
if (st.isSymbolicLink()) {
|
|
196
|
+
if (isAllowedDarwinSystemLink(cur)) continue;
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
if (!st.isDirectory()) return false;
|
|
200
|
+
} catch (e: any) {
|
|
201
|
+
if (e && typeof e === "object" && e.code === "ENOENT") return true;
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function isValidBindToken(value: string): boolean {
|
|
209
|
+
return value.length > 0 && value.length <= 256 && !CONTROL_CHAR_RE.test(value);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function isValidBoundProfileName(value: string): boolean {
|
|
213
|
+
if (!isValidBindToken(value) || value === "." || value === ".." || value.includes("/") || value.includes("\\")) {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
const stem = value.replace(/\.json$/i, "").toLowerCase();
|
|
217
|
+
const normalizedStem = stem.replace(/[^a-z0-9_-]/g, "_");
|
|
218
|
+
return (
|
|
219
|
+
Boolean(stem) &&
|
|
220
|
+
!isUnsafeBindKey(value) &&
|
|
221
|
+
!isUnsafeBindKey(stem) &&
|
|
222
|
+
!RESERVED_BIND_SIDECARS.has(stem) &&
|
|
223
|
+
!RESERVED_BIND_SIDECARS.has(normalizedStem)
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function lockFilePath(lockDir: string, agentId: string): string {
|
|
228
|
+
const trimmed = String(agentId || "").trim();
|
|
229
|
+
let safe = trimmed.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
230
|
+
if (safe.length > LOCK_KEY_MAX_CHARS) {
|
|
231
|
+
const digest = createHash("sha256").update(trimmed).digest("hex").slice(0, 12);
|
|
232
|
+
safe = `${safe.slice(0, LOCK_KEY_MAX_CHARS - 13)}_${digest}`;
|
|
233
|
+
}
|
|
234
|
+
if (!safe || isUnsafeBindKey(safe)) {
|
|
235
|
+
safe = `_${safe}`;
|
|
236
|
+
}
|
|
237
|
+
return join(lockDir, `${safe}.lock`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function readAgentLock(lockDir: string, agentId: string): AgentLockRecord | null {
|
|
241
|
+
if (!agentId || !isSafeDirOrMissing(lockDir)) return null;
|
|
242
|
+
const file = lockFilePath(lockDir, agentId);
|
|
243
|
+
const raw = readBoundedRegularJson(file, LOCK_FILE_MAX_BYTES) as Record<string, unknown> | null;
|
|
244
|
+
if (
|
|
245
|
+
!raw ||
|
|
246
|
+
typeof raw !== "object" ||
|
|
247
|
+
Array.isArray(raw) ||
|
|
248
|
+
Object.prototype.hasOwnProperty.call(raw, "__proto__") ||
|
|
249
|
+
typeof raw.pid !== "number" ||
|
|
250
|
+
typeof raw.agentId !== "string"
|
|
251
|
+
) {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
return raw as unknown as AgentLockRecord;
|
|
255
|
+
}
|
|
256
|
+
|
|
90
257
|
/**
|
|
91
258
|
* Check if `agentId` is currently locked by ANOTHER live process.
|
|
92
259
|
* Returns `{ locked: false }` if unlocked, if the lock holder PID exited,
|
|
@@ -102,11 +269,19 @@ export function checkAgentLock(opts: {
|
|
|
102
269
|
}): AgentLockCheck {
|
|
103
270
|
const { lockDir, agentId } = opts;
|
|
104
271
|
const currentPid = opts.currentPid ?? process.pid;
|
|
105
|
-
if (!agentId) return { locked: false };
|
|
272
|
+
if (!agentId || !isSafeDirOrMissing(lockDir)) return { locked: false };
|
|
273
|
+
const file = lockFilePath(lockDir, agentId);
|
|
106
274
|
const record = readAgentLock(lockDir, agentId);
|
|
107
|
-
if (!record)
|
|
275
|
+
if (!record) {
|
|
276
|
+
try {
|
|
277
|
+
const st = lstatSync(file);
|
|
278
|
+
const ageMs = Date.now() - st.mtimeMs;
|
|
279
|
+
if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1_000 || ageMs < -1_000)) unlinkSync(file);
|
|
280
|
+
} catch {}
|
|
281
|
+
return { locked: false };
|
|
282
|
+
}
|
|
108
283
|
if (!isPidAlive(record.pid)) {
|
|
109
|
-
try { unlinkSync(
|
|
284
|
+
try { unlinkSync(file); } catch {}
|
|
110
285
|
return { locked: false, stale: true };
|
|
111
286
|
}
|
|
112
287
|
if (record.pid === currentPid) {
|
|
@@ -132,6 +307,8 @@ export function acquireAgentLock(opts: {
|
|
|
132
307
|
currentPid?: number;
|
|
133
308
|
}): AgentLockRecord | null {
|
|
134
309
|
if (!opts.agentId) return null;
|
|
310
|
+
const file = lockFilePath(opts.lockDir, opts.agentId);
|
|
311
|
+
if (!isSafeDirOrMissing(opts.lockDir) || !isSafeTargetFileOrMissing(file)) return null;
|
|
135
312
|
const record: AgentLockRecord = {
|
|
136
313
|
pid: opts.currentPid ?? process.pid,
|
|
137
314
|
agentId: opts.agentId,
|
|
@@ -142,7 +319,7 @@ export function acquireAgentLock(opts: {
|
|
|
142
319
|
};
|
|
143
320
|
try {
|
|
144
321
|
mkdirSync(opts.lockDir, { recursive: true, mode: 0o700 });
|
|
145
|
-
safeWriteProfile(
|
|
322
|
+
safeWriteProfile(file, record);
|
|
146
323
|
return record;
|
|
147
324
|
} catch {
|
|
148
325
|
return null;
|
|
@@ -156,61 +333,100 @@ export function releaseAgentLock(opts: {
|
|
|
156
333
|
currentPid?: number;
|
|
157
334
|
currentSessionId?: string | null;
|
|
158
335
|
}): boolean {
|
|
159
|
-
if (!opts.agentId) return false;
|
|
336
|
+
if (!opts.agentId || !isSafeDirOrMissing(opts.lockDir)) return false;
|
|
160
337
|
const currentPid = opts.currentPid ?? process.pid;
|
|
338
|
+
const file = lockFilePath(opts.lockDir, opts.agentId);
|
|
161
339
|
const existing = readAgentLock(opts.lockDir, opts.agentId);
|
|
162
|
-
if (!existing)
|
|
340
|
+
if (!existing) {
|
|
341
|
+
try {
|
|
342
|
+
const st = lstatSync(file);
|
|
343
|
+
const ageMs = Date.now() - st.mtimeMs;
|
|
344
|
+
if (!st.isSymbolicLink() && st.isFile() && (ageMs > 1_000 || ageMs < -1_000)) {
|
|
345
|
+
unlinkSync(file);
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
} catch {}
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
163
351
|
const samePid = existing.pid === currentPid;
|
|
164
352
|
const sameSession = Boolean(opts.currentSessionId && existing.sessionId && opts.currentSessionId === existing.sessionId);
|
|
165
353
|
const dead = !isPidAlive(existing.pid);
|
|
166
354
|
if (!samePid && !sameSession && !dead) return false;
|
|
167
355
|
try {
|
|
168
|
-
unlinkSync(
|
|
356
|
+
unlinkSync(file);
|
|
169
357
|
return true;
|
|
170
358
|
} catch {
|
|
171
359
|
return false;
|
|
172
360
|
}
|
|
173
361
|
}
|
|
174
362
|
|
|
363
|
+
function isUnsafeBindKey(key: string): boolean {
|
|
364
|
+
const lower = key.toLowerCase();
|
|
365
|
+
return lower === "__proto__" || lower === "constructor" || lower === "prototype";
|
|
366
|
+
}
|
|
367
|
+
|
|
175
368
|
/** Parse a `session-binds.json` (or `agy-binds.json`) payload into `sessionId -> profileName`. */
|
|
176
369
|
export function parseSessionBinds(raw: unknown): Record<string, string> {
|
|
177
370
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
178
371
|
const out: Record<string, string> = {};
|
|
372
|
+
let count = 0;
|
|
179
373
|
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
374
|
+
if (count >= MAX_SESSION_BINDS_ENTRIES) break;
|
|
180
375
|
const key = k.trim();
|
|
181
|
-
if (!key) continue;
|
|
182
|
-
if (typeof v === "string"
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
376
|
+
if (!isValidBindToken(key) || key === "." || key === ".." || isUnsafeBindKey(key)) continue;
|
|
377
|
+
if (typeof v === "string") {
|
|
378
|
+
const val = v.trim();
|
|
379
|
+
if (isValidBoundProfileName(val)) {
|
|
380
|
+
out[key] = val;
|
|
381
|
+
count += 1;
|
|
382
|
+
}
|
|
383
|
+
} else if (v && typeof v === "object" && typeof (v as any).profile === "string") {
|
|
384
|
+
const val = (v as any).profile.trim();
|
|
385
|
+
if (isValidBoundProfileName(val)) {
|
|
386
|
+
out[key] = val;
|
|
387
|
+
count += 1;
|
|
388
|
+
}
|
|
186
389
|
}
|
|
187
390
|
}
|
|
188
391
|
return out;
|
|
189
392
|
}
|
|
190
393
|
|
|
191
394
|
export function loadSessionBinds(configDir: string): Record<string, string> {
|
|
395
|
+
if (!isSafeDirOrMissing(configDir)) return {};
|
|
192
396
|
const merged: Record<string, string> = {};
|
|
193
397
|
for (const filename of [LEGACY_AGY_BINDS_FILENAME, DEFAULT_SESSION_BINDS_FILENAME]) {
|
|
194
398
|
const path = join(configDir, filename);
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
Object.assign(merged, parseSessionBinds(
|
|
198
|
-
}
|
|
399
|
+
const parsed = readBoundedRegularJson(path, SESSION_BINDS_MAX_BYTES);
|
|
400
|
+
if (parsed !== null) {
|
|
401
|
+
Object.assign(merged, parseSessionBinds(parsed));
|
|
402
|
+
}
|
|
199
403
|
}
|
|
200
404
|
return merged;
|
|
201
405
|
}
|
|
202
406
|
|
|
203
407
|
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
|
-
|
|
408
|
+
if (!name || name === "." || name === ".." || name.includes("/") || name.includes("\\") || CONTROL_CHAR_RE.test(name)) return null;
|
|
409
|
+
if (!isSafeDirOrMissing(configDir)) return null;
|
|
410
|
+
const stem = name.replace(/\.json$/i, "").toLowerCase();
|
|
411
|
+
const base = name.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
412
|
+
if (
|
|
413
|
+
!base ||
|
|
414
|
+
base.length > LOCK_KEY_MAX_CHARS ||
|
|
415
|
+
isUnsafeBindKey(base) ||
|
|
416
|
+
RESERVED_BIND_SIDECARS.has(stem) ||
|
|
417
|
+
RESERVED_BIND_SIDECARS.has(base.toLowerCase())
|
|
418
|
+
) {
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
const profilesDir = join(configDir, "profiles");
|
|
422
|
+
const candidates = isSafeDirOrMissing(profilesDir)
|
|
423
|
+
? [join(profilesDir, `${base}.json`), join(configDir, `${base}.json`)]
|
|
424
|
+
: [join(configDir, `${base}.json`)];
|
|
425
|
+
for (const candidate of candidates) {
|
|
426
|
+
const parsed = readBoundedRegularJson(candidate, SESSION_BINDS_MAX_BYTES) as { agent_id?: unknown } | null;
|
|
427
|
+
if (typeof parsed?.agent_id === "string" && parsed.agent_id.trim()) {
|
|
428
|
+
return parsed.agent_id.trim();
|
|
429
|
+
}
|
|
214
430
|
}
|
|
215
431
|
return null;
|
|
216
432
|
}
|
|
@@ -218,17 +434,22 @@ function resolveAgentIdForProfileName(configDir: string, name: string): string |
|
|
|
218
434
|
export function saveSessionBind(configDir: string, sessionId: string, profileName: string): void {
|
|
219
435
|
const sid = sessionId.trim();
|
|
220
436
|
const prof = profileName.trim();
|
|
221
|
-
if (!sid || !prof)
|
|
437
|
+
if (!isValidBindToken(sid) || sid === "." || sid === ".." || isUnsafeBindKey(sid) || !isValidBoundProfileName(prof)) {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (!isSafeDirOrMissing(configDir)) return;
|
|
441
|
+
const path = join(configDir, DEFAULT_SESSION_BINDS_FILENAME);
|
|
442
|
+
if (!isSafeTargetFileOrMissing(path)) return;
|
|
222
443
|
const targetAgentId = resolveAgentIdForProfileName(configDir, prof);
|
|
223
444
|
const isSameProfileOrAgent = (existingProf: string): boolean => {
|
|
224
445
|
if (existingProf === prof) return true;
|
|
225
446
|
if (!targetAgentId) return false;
|
|
226
447
|
return resolveAgentIdForProfileName(configDir, existingProf) === targetAgentId;
|
|
227
448
|
};
|
|
228
|
-
const path = join(configDir, DEFAULT_SESSION_BINDS_FILENAME);
|
|
229
449
|
let current: Record<string, string> = {};
|
|
230
|
-
|
|
231
|
-
|
|
450
|
+
const existingParsed = readBoundedRegularJson(path, SESSION_BINDS_MAX_BYTES);
|
|
451
|
+
if (existingParsed !== null) {
|
|
452
|
+
current = parseSessionBinds(existingParsed);
|
|
232
453
|
}
|
|
233
454
|
// Enforce 1:1 (profileName & agent_id) <-> sessionId mapping so re-binding a
|
|
234
455
|
// profile (or an alias file such as `profile.json` + `<Name>.json` sharing one
|
|
@@ -244,31 +465,37 @@ export function saveSessionBind(configDir: string, sessionId: string, profileNam
|
|
|
244
465
|
safeWriteProfile(path, current);
|
|
245
466
|
|
|
246
467
|
const legacyPath = join(configDir, LEGACY_AGY_BINDS_FILENAME);
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
468
|
+
if (isSafeTargetFileOrMissing(legacyPath)) {
|
|
469
|
+
const legacyParsed = readBoundedRegularJson(legacyPath, SESSION_BINDS_MAX_BYTES);
|
|
470
|
+
if (legacyParsed !== null) {
|
|
471
|
+
try {
|
|
472
|
+
const legacy = parseSessionBinds(legacyParsed);
|
|
473
|
+
let changed = false;
|
|
474
|
+
for (const [existingSid, existingProf] of Object.entries(legacy)) {
|
|
475
|
+
if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
|
|
476
|
+
delete legacy[existingSid];
|
|
477
|
+
changed = true;
|
|
478
|
+
}
|
|
255
479
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
}
|
|
480
|
+
if (changed) safeWriteProfile(legacyPath, legacy);
|
|
481
|
+
} catch {}
|
|
482
|
+
}
|
|
259
483
|
}
|
|
260
484
|
}
|
|
261
485
|
|
|
262
486
|
export function removeSessionBind(configDir: string, sessionId: string): boolean {
|
|
263
487
|
const sid = sessionId.trim();
|
|
264
|
-
if (!sid) return false;
|
|
488
|
+
if (!isValidBindToken(sid) || sid === "." || sid === ".." || isUnsafeBindKey(sid)) return false;
|
|
489
|
+
if (!isSafeDirOrMissing(configDir)) return false;
|
|
265
490
|
let removed = false;
|
|
266
491
|
for (const filename of [DEFAULT_SESSION_BINDS_FILENAME, LEGACY_AGY_BINDS_FILENAME]) {
|
|
267
492
|
const path = join(configDir, filename);
|
|
268
|
-
if (!
|
|
493
|
+
if (!isSafeTargetFileOrMissing(path)) continue;
|
|
494
|
+
const raw = readBoundedRegularJson(path, SESSION_BINDS_MAX_BYTES);
|
|
495
|
+
if (raw === null) continue;
|
|
269
496
|
try {
|
|
270
|
-
const current = parseSessionBinds(
|
|
271
|
-
if (sid
|
|
497
|
+
const current = parseSessionBinds(raw);
|
|
498
|
+
if (Object.hasOwn(current, sid)) {
|
|
272
499
|
delete current[sid];
|
|
273
500
|
safeWriteProfile(path, current);
|
|
274
501
|
removed = true;
|
|
@@ -295,6 +522,17 @@ export function findBoundSessionForProfile(
|
|
|
295
522
|
return matches.length > 0 ? matches[matches.length - 1]! : null;
|
|
296
523
|
}
|
|
297
524
|
|
|
525
|
+
function isSafeDetectedSessionId(sid: string): boolean {
|
|
526
|
+
return isValidBindToken(sid) && sid !== "." && sid !== ".." && !sid.includes("/") && !sid.includes("\\") && !isUnsafeBindKey(sid);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function cleanDetectedWorkspacePath(raw: unknown): string | undefined {
|
|
530
|
+
if (typeof raw !== "string") return undefined;
|
|
531
|
+
const s = raw.trim();
|
|
532
|
+
if (!s || s.length > 4096 || s.startsWith("-") || CONTROL_CHAR_RE.test(s)) return undefined;
|
|
533
|
+
return s;
|
|
534
|
+
}
|
|
535
|
+
|
|
298
536
|
/** Detect session ID from environment variables or MCP request `_meta` (ZCode). */
|
|
299
537
|
export function detectRuntimeSession(
|
|
300
538
|
env: Record<string, string | undefined> = process.env,
|
|
@@ -306,37 +544,36 @@ export function detectRuntimeSession(
|
|
|
306
544
|
(typeof meta?.session_id === "string" && meta.session_id.trim()) ||
|
|
307
545
|
(typeof zcodeCtx?.session_id === "string" && zcodeCtx.session_id.trim()) ||
|
|
308
546
|
"";
|
|
309
|
-
if (metaSessionId) {
|
|
547
|
+
if (isSafeDetectedSessionId(metaSessionId)) {
|
|
310
548
|
const workspacePath =
|
|
311
|
-
(
|
|
312
|
-
(
|
|
313
|
-
undefined;
|
|
549
|
+
cleanDetectedWorkspacePath(meta?.workspace_path) ||
|
|
550
|
+
cleanDetectedWorkspacePath(zcodeCtx?.workspace_path);
|
|
314
551
|
return { sessionId: metaSessionId, runtime: "zcode", ...(workspacePath ? { workspacePath } : {}) };
|
|
315
552
|
}
|
|
316
553
|
|
|
317
554
|
// 2. ZCode environment variable
|
|
318
|
-
const zcodeEnvSid = env.ZCODE_SESSION_ID?.trim();
|
|
319
|
-
if (zcodeEnvSid) {
|
|
320
|
-
const workspacePath = env.ZCODE_PROJECT_DIR
|
|
555
|
+
const zcodeEnvSid = env.ZCODE_SESSION_ID?.trim() || "";
|
|
556
|
+
if (isSafeDetectedSessionId(zcodeEnvSid)) {
|
|
557
|
+
const workspacePath = cleanDetectedWorkspacePath(env.ZCODE_PROJECT_DIR);
|
|
321
558
|
return { sessionId: zcodeEnvSid, runtime: "zcode", ...(workspacePath ? { workspacePath } : {}) };
|
|
322
559
|
}
|
|
323
560
|
|
|
324
561
|
// 3. Antigravity explicit environment variable
|
|
325
|
-
const agySid = env.ANTIGRAVITY_CONVERSATION_ID?.trim();
|
|
326
|
-
if (agySid) {
|
|
562
|
+
const agySid = env.ANTIGRAVITY_CONVERSATION_ID?.trim() || "";
|
|
563
|
+
if (isSafeDetectedSessionId(agySid)) {
|
|
327
564
|
return { sessionId: agySid, runtime: "antigravity" };
|
|
328
565
|
}
|
|
329
566
|
|
|
330
567
|
// 4. Claude Code environment variable
|
|
331
568
|
const claudeSid = (env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || "").trim();
|
|
332
|
-
if (claudeSid) {
|
|
333
|
-
const workspacePath = env.CLAUDE_PROJECT_DIR
|
|
569
|
+
if (isSafeDetectedSessionId(claudeSid)) {
|
|
570
|
+
const workspacePath = cleanDetectedWorkspacePath(env.CLAUDE_PROJECT_DIR);
|
|
334
571
|
return { sessionId: claudeSid, runtime: "claude-code", ...(workspacePath ? { workspacePath } : {}) };
|
|
335
572
|
}
|
|
336
573
|
|
|
337
574
|
// 5. Explicit generic session ID override
|
|
338
575
|
const explicitSid = (env.AGENTSCHAT_SESSION_ID || env.AGENTCHAT_SESSION_ID || "").trim();
|
|
339
|
-
if (explicitSid) {
|
|
576
|
+
if (isSafeDetectedSessionId(explicitSid)) {
|
|
340
577
|
return { sessionId: explicitSid, runtime: "custom" };
|
|
341
578
|
}
|
|
342
579
|
|
|
@@ -403,7 +640,7 @@ export function parseAntigravityLsofOutput(
|
|
|
403
640
|
const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
|
|
404
641
|
if (portMatch) {
|
|
405
642
|
const p = Number(portMatch[1]);
|
|
406
|
-
if (p
|
|
643
|
+
if (Number.isSafeInteger(p) && p >= 1 && p <= 65535 && !ports.includes(p)) ports.push(p);
|
|
407
644
|
}
|
|
408
645
|
if (!isCliTarget && line.includes("/antigravity-cli/")) continue;
|
|
409
646
|
|
|
@@ -432,6 +669,201 @@ export function parseAntigravityLsofOutput(
|
|
|
432
669
|
return { ports, openConversations };
|
|
433
670
|
}
|
|
434
671
|
|
|
672
|
+
function extractCliFlagValue(cmd: string, flag: string): string {
|
|
673
|
+
const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
674
|
+
const re = new RegExp(`${escaped}(?:=|\\s+)(?:"([^"]+)"|'([^']+)'|([^\\s"']+))`);
|
|
675
|
+
const m = cmd.match(re);
|
|
676
|
+
return (m?.[1] ?? m?.[2] ?? m?.[3] ?? "").trim();
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Parse Windows `netstat -ano` output into listening loopback (`127.0.0.1` / `[::1]`)
|
|
681
|
+
* TCP ports owned by `targetPid`, sorted descending so plaintext HTTP Connect-RPC
|
|
682
|
+
* ports allocated after HTTPS are tried first.
|
|
683
|
+
*
|
|
684
|
+
* Matches foreign address `0.0.0.0:0` / `[::]:0` / `*:*` rather than English
|
|
685
|
+
* `"LISTENING"` text so localized Windows builds (German, French, Spanish, Chinese, etc.)
|
|
686
|
+
* work identically.
|
|
687
|
+
*/
|
|
688
|
+
export function parseWindowsNetstatOutput(stdout: string, targetPid: number): number[] {
|
|
689
|
+
if (!stdout || !Number.isSafeInteger(targetPid) || targetPid <= 0) return [];
|
|
690
|
+
const ports: number[] = [];
|
|
691
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
692
|
+
const m = line.match(
|
|
693
|
+
/^\s*TCP\s+(?:127\.0\.0\.1|\[::1\]):(\d+)\s+(?:0\.0\.0\.0:0|\[::\]:0|\*:\*)\s+\S+\s+(\d+)\s*$/i,
|
|
694
|
+
);
|
|
695
|
+
if (!m) continue;
|
|
696
|
+
const port = Number(m[1]);
|
|
697
|
+
const pid = Number(m[2]);
|
|
698
|
+
if (pid === targetPid && Number.isSafeInteger(port) && port >= 1 && port <= 65535 && !ports.includes(port)) {
|
|
699
|
+
ports.push(port);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
ports.sort((a, b) => b - a);
|
|
703
|
+
return ports;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Pure parser for the JSON emitted by `discoverWindowsAntigravityHost`'s PowerShell probe
|
|
708
|
+
* (`{ lsPid, lsCmd, ports, lockedPresence, lockedDbs }`), with optional `netstat -ano`
|
|
709
|
+
* fallback output when `Get-NetTCPConnection` is unavailable.
|
|
710
|
+
*/
|
|
711
|
+
export function parseWindowsAntigravityProbeJson(
|
|
712
|
+
stdout: string,
|
|
713
|
+
netstatStdout = "",
|
|
714
|
+
): AntigravityHostInfo | null {
|
|
715
|
+
const trimmed = (stdout || "").trim();
|
|
716
|
+
if (!trimmed || trimmed === "{}") return null;
|
|
717
|
+
let parsed: any;
|
|
718
|
+
try {
|
|
719
|
+
parsed = JSON.parse(trimmed);
|
|
720
|
+
} catch {
|
|
721
|
+
return null;
|
|
722
|
+
}
|
|
723
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
const lsPid = Number(parsed?.lsPid);
|
|
727
|
+
const lsCmd = typeof parsed?.lsCmd === "string" ? parsed.lsCmd : "";
|
|
728
|
+
if (!Number.isSafeInteger(lsPid) || lsPid <= 0 || !lsCmd) return null;
|
|
729
|
+
|
|
730
|
+
const csrfToken = extractCliFlagValue(lsCmd, "--csrf_token");
|
|
731
|
+
if (!csrfToken) return null;
|
|
732
|
+
|
|
733
|
+
const portSet = new Set<number>();
|
|
734
|
+
const rawPorts = Array.isArray(parsed?.ports)
|
|
735
|
+
? parsed.ports
|
|
736
|
+
: typeof parsed?.ports === "number"
|
|
737
|
+
? [parsed.ports]
|
|
738
|
+
: [];
|
|
739
|
+
for (const p of rawPorts) {
|
|
740
|
+
const num = Number(p);
|
|
741
|
+
if (Number.isSafeInteger(num) && num >= 1 && num <= 65535) portSet.add(num);
|
|
742
|
+
}
|
|
743
|
+
if (portSet.size === 0 && netstatStdout) {
|
|
744
|
+
for (const p of parseWindowsNetstatOutput(netstatStdout, lsPid)) {
|
|
745
|
+
portSet.add(p);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
const ports = [...portSet].sort((a, b) => b - a);
|
|
749
|
+
|
|
750
|
+
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
751
|
+
const toUuidList = (val: unknown): string[] => {
|
|
752
|
+
const arr = Array.isArray(val) ? val : typeof val === "string" ? [val] : [];
|
|
753
|
+
const out: string[] = [];
|
|
754
|
+
for (const item of arr) {
|
|
755
|
+
const s = String(item || "").trim();
|
|
756
|
+
if (uuidRe.test(s) && !out.includes(s)) out.push(s);
|
|
757
|
+
}
|
|
758
|
+
return out;
|
|
759
|
+
};
|
|
760
|
+
const lockedPresence = toUuidList(parsed?.lockedPresence);
|
|
761
|
+
const lockedDbs = toUuidList(parsed?.lockedDbs);
|
|
762
|
+
const openConversations = lockedPresence.length > 0 ? lockedPresence : lockedDbs;
|
|
763
|
+
|
|
764
|
+
return { lsPid, csrfToken, ports, openConversations };
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
function runWindowsPowerShell(script: string, timeoutMs = 4000): string | null {
|
|
768
|
+
for (const bin of ["powershell.exe", "pwsh.exe", "pwsh"]) {
|
|
769
|
+
const res = spawnSync(
|
|
770
|
+
bin,
|
|
771
|
+
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
|
|
772
|
+
{ encoding: "utf8", timeout: timeoutMs, windowsHide: true },
|
|
773
|
+
);
|
|
774
|
+
if (!res.error && res.status === 0 && typeof res.stdout === "string") {
|
|
775
|
+
return res.stdout;
|
|
776
|
+
}
|
|
777
|
+
if (!res.error) break;
|
|
778
|
+
}
|
|
779
|
+
return null;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function discoverWindowsAntigravityHost(currentPid: number): AntigravityHostInfo | null {
|
|
783
|
+
// Walk up to 8 ancestor hops on Windows because npm/cmd shims (`language_server.exe` ->
|
|
784
|
+
// `cmd.exe` -> `node npx` -> `cmd.exe` -> `node server.js`) add extra intermediate hops.
|
|
785
|
+
// Active IDE windows hold an open OS file handle on `~/.gemini/<appDataDir>/presence/<uuid>.lock`
|
|
786
|
+
// while historical closed tabs leave unlocked `.lock` files on disk; probing with
|
|
787
|
+
// `[System.IO.File]::Open(..., FileShare.None)` triggers a kernel `SharingViolation`
|
|
788
|
+
// (`IOException`) if and only if another process currently holds an open handle, requiring
|
|
789
|
+
// zero administrator privileges and never mutating file contents or mtime.
|
|
790
|
+
const psScript = [
|
|
791
|
+
"$ErrorActionPreference = 'SilentlyContinue'",
|
|
792
|
+
`$p = ${Math.trunc(currentPid)}`,
|
|
793
|
+
"$lsPid = 0",
|
|
794
|
+
"$lsCmd = ''",
|
|
795
|
+
"for ($h = 0; $h -lt 8 -and $p -gt 0; $h++) {",
|
|
796
|
+
" $proc = Get-CimInstance Win32_Process -Filter \"ProcessId=$p\"",
|
|
797
|
+
" if (-not $proc) { break }",
|
|
798
|
+
" $cmd = [string]$proc.CommandLine",
|
|
799
|
+
" $name = [string]$proc.Name",
|
|
800
|
+
" if ($h -gt 0 -and ($cmd -match 'bun(?:\\.exe)?\\s+test' -or $cmd -match 'node(?:\\.exe)?\\s+--test')) { break }",
|
|
801
|
+
" if (($cmd -match 'language_server' -or $name -match 'language_server') -and $cmd -match '--csrf_token') {",
|
|
802
|
+
" $lsPid = [int]$proc.ProcessId",
|
|
803
|
+
" $lsCmd = $cmd",
|
|
804
|
+
" break",
|
|
805
|
+
" }",
|
|
806
|
+
" $nextP = [int]$proc.ParentProcessId",
|
|
807
|
+
" if ($nextP -le 0 -or $nextP -eq $p) { break }",
|
|
808
|
+
" $p = $nextP",
|
|
809
|
+
"}",
|
|
810
|
+
"if ($lsPid -le 0) { Write-Output '{}'; exit 0 }",
|
|
811
|
+
"$ports = @()",
|
|
812
|
+
"if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) {",
|
|
813
|
+
" $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)",
|
|
814
|
+
"}",
|
|
815
|
+
"$appDir = 'antigravity'",
|
|
816
|
+
"if ($lsCmd -match '--app_data_dir(?:=|\\s+)(?:\"([^\"]+)\"|''([^'']+)''|([^\\s\"'']+))') {",
|
|
817
|
+
" $appDir = if ($Matches[1]) { $Matches[1] } elseif ($Matches[2]) { $Matches[2] } else { $Matches[3] }",
|
|
818
|
+
"}",
|
|
819
|
+
"$homeDir = if ($env:USERPROFILE) { $env:USERPROFILE } else { [Environment]::GetFolderPath('UserProfile') }",
|
|
820
|
+
"$baseDir = Join-Path (Join-Path $homeDir '.gemini') $appDir",
|
|
821
|
+
"$lockedPresence = @()",
|
|
822
|
+
"$presDir = Join-Path $baseDir 'presence'",
|
|
823
|
+
"if (Test-Path -LiteralPath $presDir) {",
|
|
824
|
+
" Get-ChildItem -LiteralPath $presDir -Filter '*.lock' -File | ForEach-Object {",
|
|
825
|
+
" if ($_.BaseName -match '^[0-9a-fA-F-]{36}$') {",
|
|
826
|
+
" try {",
|
|
827
|
+
" $s = [System.IO.File]::Open($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::None)",
|
|
828
|
+
" $s.Dispose()",
|
|
829
|
+
" } catch [System.IO.IOException] {",
|
|
830
|
+
" $lockedPresence += $_.BaseName",
|
|
831
|
+
" } catch {}",
|
|
832
|
+
" }",
|
|
833
|
+
" }",
|
|
834
|
+
"}",
|
|
835
|
+
"$lockedDbs = @()",
|
|
836
|
+
"if ($lockedPresence.Count -eq 0 -and $appDir -ne 'antigravity-cli') {",
|
|
837
|
+
" $convDir = Join-Path $baseDir 'conversations'",
|
|
838
|
+
" if (Test-Path -LiteralPath $convDir) {",
|
|
839
|
+
" Get-ChildItem -LiteralPath $convDir -Filter '*.db' -File | ForEach-Object {",
|
|
840
|
+
" if ($_.BaseName -match '^[0-9a-fA-F-]{36}$') {",
|
|
841
|
+
" try {",
|
|
842
|
+
" $s = [System.IO.File]::Open($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::None)",
|
|
843
|
+
" $s.Dispose()",
|
|
844
|
+
" } catch [System.IO.IOException] {",
|
|
845
|
+
" $lockedDbs += $_.BaseName",
|
|
846
|
+
" } catch {}",
|
|
847
|
+
" }",
|
|
848
|
+
" }",
|
|
849
|
+
" }",
|
|
850
|
+
"}",
|
|
851
|
+
"[pscustomobject]@{ lsPid = $lsPid; lsCmd = $lsCmd; ports = $ports; lockedPresence = $lockedPresence; lockedDbs = $lockedDbs } | ConvertTo-Json -Compress",
|
|
852
|
+
].join("; ");
|
|
853
|
+
|
|
854
|
+
const stdout = runWindowsPowerShell(psScript, 4000);
|
|
855
|
+
if (!stdout) return null;
|
|
856
|
+
|
|
857
|
+
let info = parseWindowsAntigravityProbeJson(stdout);
|
|
858
|
+
if (info && info.ports.length === 0) {
|
|
859
|
+
const ns = spawnSync("netstat", ["-ano"], { encoding: "utf8", timeout: 2000, windowsHide: true });
|
|
860
|
+
if (ns.status === 0 && ns.stdout) {
|
|
861
|
+
info = parseWindowsAntigravityProbeJson(stdout, ns.stdout);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return info;
|
|
865
|
+
}
|
|
866
|
+
|
|
435
867
|
export function discoverAntigravityHost(opts?: {
|
|
436
868
|
currentPid?: number;
|
|
437
869
|
cacheMs?: number;
|
|
@@ -462,13 +894,20 @@ export function discoverAntigravityHost(opts?: {
|
|
|
462
894
|
|
|
463
895
|
const now = Date.now();
|
|
464
896
|
const cacheMs = opts?.cacheMs ?? 5_000;
|
|
465
|
-
if (cachedAgyHost && now - cachedAgyHost.at < cacheMs) return cachedAgyHost.info;
|
|
897
|
+
if (cachedAgyHost && now >= cachedAgyHost.at && now - cachedAgyHost.at < cacheMs) return cachedAgyHost.info;
|
|
466
898
|
|
|
467
899
|
try {
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
900
|
+
const startPid = opts?.currentPid ?? process.pid;
|
|
901
|
+
if (process.platform === "win32") {
|
|
902
|
+
const winInfo = discoverWindowsAntigravityHost(startPid);
|
|
903
|
+
cachedAgyHost = { at: now, info: winInfo };
|
|
904
|
+
return winInfo;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// Walk up from currentPid using fast per-PID `ps -p` queries so we never scan
|
|
908
|
+
// the whole system process table or match an indirect test runner several hops
|
|
909
|
+
// below language_server.
|
|
910
|
+
let pid = startPid;
|
|
472
911
|
let lsPid = 0;
|
|
473
912
|
let lsCmd = "";
|
|
474
913
|
for (let hop = 0; hop < 4 && pid > 1; hop++) {
|
|
@@ -493,15 +932,13 @@ export function discoverAntigravityHost(opts?: {
|
|
|
493
932
|
return null;
|
|
494
933
|
}
|
|
495
934
|
|
|
496
|
-
const
|
|
497
|
-
const csrfToken = csrfMatch?.[1]?.trim() || "";
|
|
935
|
+
const csrfToken = extractCliFlagValue(lsCmd, "--csrf_token");
|
|
498
936
|
if (!csrfToken) {
|
|
499
937
|
cachedAgyHost = { at: now, info: null };
|
|
500
938
|
return null;
|
|
501
939
|
}
|
|
502
940
|
|
|
503
|
-
const
|
|
504
|
-
const appDataDir = appDirMatch?.[1]?.trim() || "antigravity";
|
|
941
|
+
const appDataDir = extractCliFlagValue(lsCmd, "--app_data_dir") || "antigravity";
|
|
505
942
|
|
|
506
943
|
const lsof = spawnSync("lsof", ["-Pan", "-p", String(lsPid)], { encoding: "utf8", timeout: 1500 });
|
|
507
944
|
const { ports, openConversations } =
|
|
@@ -532,11 +969,13 @@ export function detectAntigravityCallerSession(opts?: {
|
|
|
532
969
|
nowMs?: number;
|
|
533
970
|
maxAgeMs?: number;
|
|
534
971
|
}): string | null {
|
|
972
|
+
const home = process.env.HOME || process.env.USERPROFILE || homedir();
|
|
535
973
|
const brainDir =
|
|
536
974
|
opts?.brainDir?.trim() ||
|
|
537
975
|
process.env.AGENTSCHAT_AGY_BRAIN_DIR?.trim() ||
|
|
538
|
-
join(
|
|
539
|
-
|
|
976
|
+
join(home, ".gemini", "antigravity", "brain");
|
|
977
|
+
const brainStat = safeLstat(brainDir);
|
|
978
|
+
if (!brainStat || brainStat.isSymbolicLink() || !brainStat.isDirectory() || !isSafeDirOrMissing(brainDir)) return null;
|
|
540
979
|
|
|
541
980
|
const nowMs = opts?.nowMs ?? Date.now();
|
|
542
981
|
const maxAgeMs = opts?.maxAgeMs ?? 30_000;
|
|
@@ -572,14 +1011,19 @@ export function detectAntigravityCallerSession(opts?: {
|
|
|
572
1011
|
const recentCids: { cid: string; mtimeMs: number }[] = [];
|
|
573
1012
|
|
|
574
1013
|
for (const cid of candidateSet) {
|
|
575
|
-
const
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
1014
|
+
const cidDir = join(brainDir, cid);
|
|
1015
|
+
const sysDir = join(cidDir, ".system_generated");
|
|
1016
|
+
const logsDir = join(sysDir, "logs");
|
|
1017
|
+
if (
|
|
1018
|
+
!isSafeDirOrMissing(cidDir) ||
|
|
1019
|
+
!isSafeDirOrMissing(sysDir) ||
|
|
1020
|
+
!isSafeDirOrMissing(logsDir)
|
|
1021
|
+
) {
|
|
580
1022
|
continue;
|
|
581
1023
|
}
|
|
582
|
-
|
|
1024
|
+
const transcriptPath = join(logsDir, "transcript.jsonl");
|
|
1025
|
+
const st = safeLstat(transcriptPath);
|
|
1026
|
+
if (!st || st.isSymbolicLink() || !st.isFile() || st.size <= 0 || nowMs - st.mtimeMs > maxAgeMs) continue;
|
|
583
1027
|
recentCids.push({ cid, mtimeMs: st.mtimeMs });
|
|
584
1028
|
|
|
585
1029
|
let tail = "";
|
|
@@ -639,6 +1083,15 @@ export function detectAntigravityCallerSession(opts?: {
|
|
|
639
1083
|
|
|
640
1084
|
let cachedIsDshHost: { at: number; value: boolean } | null = null;
|
|
641
1085
|
|
|
1086
|
+
function matchesDshCommandLine(cmd: string): boolean {
|
|
1087
|
+
return (
|
|
1088
|
+
cmd.includes("@deepseek-ai") ||
|
|
1089
|
+
cmd.includes("/.dsh/") ||
|
|
1090
|
+
cmd.toLowerCase().includes("\\.dsh\\") ||
|
|
1091
|
+
/\bdsh(?:\.cmd|\.exe)?\b/i.test(cmd)
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
642
1095
|
/** Check if this MCP server was spawned by DeepSeek Harness (`dsh`). */
|
|
643
1096
|
export function isDshHostProcess(opts?: {
|
|
644
1097
|
currentPid?: number;
|
|
@@ -655,9 +1108,40 @@ export function isDshHostProcess(opts?: {
|
|
|
655
1108
|
}
|
|
656
1109
|
const now = Date.now();
|
|
657
1110
|
const cacheMs = opts?.cacheMs ?? 15_000;
|
|
658
|
-
if (cachedIsDshHost && now - cachedIsDshHost.at < cacheMs) return cachedIsDshHost.value;
|
|
1111
|
+
if (cachedIsDshHost && now >= cachedIsDshHost.at && now - cachedIsDshHost.at < cacheMs) return cachedIsDshHost.value;
|
|
659
1112
|
try {
|
|
660
1113
|
let pid = opts?.currentPid ?? process.pid;
|
|
1114
|
+
if (process.platform === "win32") {
|
|
1115
|
+
const psOut = runWindowsPowerShell(
|
|
1116
|
+
[
|
|
1117
|
+
"$ErrorActionPreference = 'SilentlyContinue'",
|
|
1118
|
+
`$p = ${Math.trunc(pid)}`,
|
|
1119
|
+
"for ($h = 0; $h -lt 8 -and $p -gt 0; $h++) {",
|
|
1120
|
+
" $proc = Get-CimInstance Win32_Process -Filter \"ProcessId=$p\"",
|
|
1121
|
+
" if (-not $proc) { break }",
|
|
1122
|
+
" Write-Output \"$($proc.ParentProcessId)`t$($proc.CommandLine)\"",
|
|
1123
|
+
" $nextP = [int]$proc.ParentProcessId",
|
|
1124
|
+
" if ($nextP -le 0 -or $nextP -eq $p) { break }",
|
|
1125
|
+
" $p = $nextP",
|
|
1126
|
+
"}",
|
|
1127
|
+
].join("; "),
|
|
1128
|
+
2500,
|
|
1129
|
+
);
|
|
1130
|
+
if (psOut) {
|
|
1131
|
+
const lines = psOut.split(/\r?\n/).filter(Boolean);
|
|
1132
|
+
for (let hop = 0; hop < lines.length; hop++) {
|
|
1133
|
+
const tab = lines[hop]!.indexOf("\t");
|
|
1134
|
+
const cmd = tab >= 0 ? lines[hop]!.slice(tab + 1) : lines[hop]!;
|
|
1135
|
+
if (hop > 0 && (/bun(?:\.exe)?\s+test/i.test(cmd) || /node(?:\.exe)?\s+--test/i.test(cmd))) break;
|
|
1136
|
+
if (matchesDshCommandLine(cmd)) {
|
|
1137
|
+
cachedIsDshHost = { at: now, value: true };
|
|
1138
|
+
return true;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
cachedIsDshHost = { at: now, value: false };
|
|
1143
|
+
return false;
|
|
1144
|
+
}
|
|
661
1145
|
for (let hop = 0; hop < 4 && pid > 1; hop++) {
|
|
662
1146
|
const ps = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "ppid=,command="], {
|
|
663
1147
|
encoding: "utf8",
|
|
@@ -670,7 +1154,7 @@ export function isDshHostProcess(opts?: {
|
|
|
670
1154
|
const ppid = Number(m[1]);
|
|
671
1155
|
const cmd = m[2]!;
|
|
672
1156
|
if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test"))) break;
|
|
673
|
-
if (
|
|
1157
|
+
if (matchesDshCommandLine(cmd)) {
|
|
674
1158
|
cachedIsDshHost = { at: now, value: true };
|
|
675
1159
|
return true;
|
|
676
1160
|
}
|
|
@@ -681,14 +1165,108 @@ export function isDshHostProcess(opts?: {
|
|
|
681
1165
|
return false;
|
|
682
1166
|
}
|
|
683
1167
|
|
|
1168
|
+
const SAFE_DSH_SESSION_ID_RE = /^session-[a-zA-Z0-9_-]{1,128}$/;
|
|
1169
|
+
const DSH_HEALTH_MAX_BYTES = 256 * 1024;
|
|
1170
|
+
|
|
1171
|
+
function isSafeDirEntryName(entry: string): boolean {
|
|
1172
|
+
return (
|
|
1173
|
+
entry.length > 0 &&
|
|
1174
|
+
entry.length <= 255 &&
|
|
1175
|
+
entry !== "." &&
|
|
1176
|
+
entry !== ".." &&
|
|
1177
|
+
!entry.includes("/") &&
|
|
1178
|
+
!entry.includes("\\") &&
|
|
1179
|
+
!CONTROL_CHAR_RE.test(entry)
|
|
1180
|
+
);
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
function isLoopbackDshHealthUrl(rawUrl: string): boolean {
|
|
1184
|
+
if (!rawUrl || rawUrl !== rawUrl.trim() || CONTROL_CHAR_RE.test(rawUrl)) return false;
|
|
1185
|
+
let u: URL;
|
|
1186
|
+
try {
|
|
1187
|
+
u = new URL(rawUrl);
|
|
1188
|
+
} catch {
|
|
1189
|
+
return false;
|
|
1190
|
+
}
|
|
1191
|
+
if (u.protocol !== "http:") return false;
|
|
1192
|
+
if (u.username || u.password || u.search || u.hash) return false;
|
|
1193
|
+
const host = u.hostname.toLowerCase();
|
|
1194
|
+
if (host !== "127.0.0.1" && host !== "localhost" && host !== "[::1]" && host !== "::1") {
|
|
1195
|
+
return false;
|
|
1196
|
+
}
|
|
1197
|
+
if (/:0+(?:\/|$)/.test(rawUrl)) return false;
|
|
1198
|
+
if (u.port) {
|
|
1199
|
+
const port = Number(u.port);
|
|
1200
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return false;
|
|
1201
|
+
}
|
|
1202
|
+
return true;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
async function readBoundedDshHealthJson(res: Response): Promise<unknown> {
|
|
1206
|
+
const rawLen = res.headers?.get?.("content-length");
|
|
1207
|
+
if (rawLen !== null && rawLen !== undefined && rawLen.trim() !== "") {
|
|
1208
|
+
const trimmedLen = rawLen.trim();
|
|
1209
|
+
if (!/^\d+$/.test(trimmedLen) || Number(trimmedLen) > DSH_HEALTH_MAX_BYTES) {
|
|
1210
|
+
await res.body?.cancel?.().catch(() => {});
|
|
1211
|
+
throw new Error("DSH /health response exceeded byte cap");
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
const reader = (res as any)?.body?.getReader?.();
|
|
1215
|
+
let parsed: unknown;
|
|
1216
|
+
if (!reader) {
|
|
1217
|
+
const text =
|
|
1218
|
+
typeof (res as any)?.text === "function"
|
|
1219
|
+
? await res.text()
|
|
1220
|
+
: JSON.stringify(await res.json());
|
|
1221
|
+
if (Buffer.byteLength(text, "utf8") > DSH_HEALTH_MAX_BYTES) {
|
|
1222
|
+
throw new Error("DSH /health response exceeded byte cap");
|
|
1223
|
+
}
|
|
1224
|
+
parsed = JSON.parse(text);
|
|
1225
|
+
} else {
|
|
1226
|
+
const chunks: Uint8Array[] = [];
|
|
1227
|
+
let total = 0;
|
|
1228
|
+
try {
|
|
1229
|
+
while (true) {
|
|
1230
|
+
const { done, value } = await reader.read();
|
|
1231
|
+
if (done) break;
|
|
1232
|
+
if (value instanceof Uint8Array) {
|
|
1233
|
+
total += value.byteLength;
|
|
1234
|
+
if (total > DSH_HEALTH_MAX_BYTES) {
|
|
1235
|
+
await reader.cancel().catch(() => {});
|
|
1236
|
+
throw new Error("DSH /health response exceeded byte cap");
|
|
1237
|
+
}
|
|
1238
|
+
chunks.push(value);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
} finally {
|
|
1242
|
+
try {
|
|
1243
|
+
reader.releaseLock?.();
|
|
1244
|
+
} catch {}
|
|
1245
|
+
}
|
|
1246
|
+
const merged = new Uint8Array(total);
|
|
1247
|
+
let offset = 0;
|
|
1248
|
+
for (const c of chunks) {
|
|
1249
|
+
merged.set(c, offset);
|
|
1250
|
+
offset += c.byteLength;
|
|
1251
|
+
}
|
|
1252
|
+
parsed = JSON.parse(Buffer.from(merged).toString("utf8"));
|
|
1253
|
+
}
|
|
1254
|
+
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
1255
|
+
throw new Error("Invalid DSH /health JSON object");
|
|
1256
|
+
}
|
|
1257
|
+
return parsed;
|
|
1258
|
+
}
|
|
1259
|
+
|
|
684
1260
|
/** mtime of a session directory's log, or 0 when it has none. */
|
|
685
1261
|
function sessionDirMtime(dir: string): number {
|
|
1262
|
+
const dirStat = safeLstat(dir);
|
|
1263
|
+
if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) return 0;
|
|
686
1264
|
let newest = 0;
|
|
687
1265
|
for (const file of ["session.v4.jsonl.zstd", "session.v4.jsonl"]) {
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
}
|
|
1266
|
+
const st = safeLstat(join(dir, file));
|
|
1267
|
+
if (st && !st.isSymbolicLink() && st.isFile() && st.mtimeMs > newest) {
|
|
1268
|
+
newest = st.mtimeMs;
|
|
1269
|
+
}
|
|
692
1270
|
}
|
|
693
1271
|
return newest;
|
|
694
1272
|
}
|
|
@@ -701,15 +1279,23 @@ function sessionDirMtime(dir: string): number {
|
|
|
701
1279
|
* two sessions that are both `running` at the same time.
|
|
702
1280
|
*/
|
|
703
1281
|
function sessionLogMtime(dshHome: string, sid: string): number {
|
|
1282
|
+
if (!SAFE_DSH_SESSION_ID_RE.test(sid)) return 0;
|
|
1283
|
+
const sessionsRoot = join(dshHome, "sessions");
|
|
1284
|
+
const rootStat = safeLstat(sessionsRoot);
|
|
1285
|
+
if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) return 0;
|
|
704
1286
|
let projects: string[];
|
|
705
1287
|
try {
|
|
706
|
-
projects = readdirSync(
|
|
1288
|
+
projects = readdirSync(sessionsRoot);
|
|
707
1289
|
} catch {
|
|
708
1290
|
return 0;
|
|
709
1291
|
}
|
|
710
1292
|
let newest = 0;
|
|
711
1293
|
for (const project of projects) {
|
|
712
|
-
|
|
1294
|
+
if (!isSafeDirEntryName(project)) continue;
|
|
1295
|
+
const projDir = join(sessionsRoot, project);
|
|
1296
|
+
const projStat = safeLstat(projDir);
|
|
1297
|
+
if (!projStat || projStat.isSymbolicLink() || !projStat.isDirectory()) continue;
|
|
1298
|
+
const mtime = sessionDirMtime(join(projDir, sid));
|
|
713
1299
|
if (mtime > newest) newest = mtime;
|
|
714
1300
|
}
|
|
715
1301
|
return newest;
|
|
@@ -718,6 +1304,8 @@ function sessionLogMtime(dshHome: string, sid: string): number {
|
|
|
718
1304
|
/** Newest session log within `maxAgeMs`; the fallback when `/health` is unavailable. */
|
|
719
1305
|
function newestSessionLog(dshHome: string, nowMs: number, maxAgeMs: number): string | null {
|
|
720
1306
|
const root = join(dshHome, "sessions");
|
|
1307
|
+
const rootStat = safeLstat(root);
|
|
1308
|
+
if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) return null;
|
|
721
1309
|
let projects: string[];
|
|
722
1310
|
try {
|
|
723
1311
|
projects = readdirSync(root);
|
|
@@ -726,15 +1314,19 @@ function newestSessionLog(dshHome: string, nowMs: number, maxAgeMs: number): str
|
|
|
726
1314
|
}
|
|
727
1315
|
let best: { sid: string; mtime: number } | null = null;
|
|
728
1316
|
for (const project of projects) {
|
|
1317
|
+
if (!isSafeDirEntryName(project)) continue;
|
|
1318
|
+
const projDir = join(root, project);
|
|
1319
|
+
const projStat = safeLstat(projDir);
|
|
1320
|
+
if (!projStat || projStat.isSymbolicLink() || !projStat.isDirectory()) continue;
|
|
729
1321
|
let entries: string[];
|
|
730
1322
|
try {
|
|
731
|
-
entries = readdirSync(
|
|
1323
|
+
entries = readdirSync(projDir);
|
|
732
1324
|
} catch {
|
|
733
1325
|
continue;
|
|
734
1326
|
}
|
|
735
1327
|
for (const entry of entries) {
|
|
736
|
-
if (!
|
|
737
|
-
const mtime = sessionDirMtime(join(
|
|
1328
|
+
if (!SAFE_DSH_SESSION_ID_RE.test(entry)) continue;
|
|
1329
|
+
const mtime = sessionDirMtime(join(projDir, entry));
|
|
738
1330
|
if (mtime === 0 || nowMs - mtime > maxAgeMs) continue;
|
|
739
1331
|
if (best === null || mtime > best.mtime) best = { sid: entry, mtime };
|
|
740
1332
|
}
|
|
@@ -773,46 +1365,53 @@ export async function detectDshCallerSession(opts?: {
|
|
|
773
1365
|
"http://127.0.0.1:8799/health";
|
|
774
1366
|
const nowMs = opts?.nowMs ?? Date.now();
|
|
775
1367
|
|
|
776
|
-
|
|
777
|
-
const f = opts?.fetchImpl ?? fetch;
|
|
778
|
-
const ctrl = new AbortController();
|
|
779
|
-
const timer = setTimeout(() => ctrl.abort(), 150);
|
|
1368
|
+
if (isLoopbackDshHealthUrl(healthUrl)) {
|
|
780
1369
|
try {
|
|
781
|
-
const
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
const
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1370
|
+
const f = opts?.fetchImpl ?? fetch;
|
|
1371
|
+
const ctrl = new AbortController();
|
|
1372
|
+
const timer = setTimeout(() => ctrl.abort(), 150);
|
|
1373
|
+
timer.unref?.();
|
|
1374
|
+
try {
|
|
1375
|
+
const res = await f(healthUrl, { signal: ctrl.signal, redirect: "error" });
|
|
1376
|
+
if (res.ok) {
|
|
1377
|
+
const data = (await readBoundedDshHealthJson(res)) as {
|
|
1378
|
+
roots?: Array<{ id?: string; status?: string }>;
|
|
1379
|
+
};
|
|
1380
|
+
const roots = Array.isArray(data?.roots) ? data.roots : [];
|
|
1381
|
+
const running = roots
|
|
1382
|
+
.filter((r) => typeof r?.id === "string" && SAFE_DSH_SESSION_ID_RE.test(r.id) && r.status === "running")
|
|
1383
|
+
.map((r) => r.id!);
|
|
1384
|
+
if (running.length === 1) return running[0]!;
|
|
1385
|
+
if (running.length > 1) {
|
|
1386
|
+
// More than one session is mid-turn; the caller is the one that just
|
|
1387
|
+
// wrote a row (its session log mtime is the newest). `roots` is
|
|
1388
|
+
// oldest-first, so the newest root is the fallback when logs are
|
|
1389
|
+
// unavailable — never `running[0]`, which is the *oldest*.
|
|
1390
|
+
const ranked = running
|
|
1391
|
+
.map((sid) => ({ sid, mtime: sessionLogMtime(dshHome, sid) }))
|
|
1392
|
+
.sort((a, b) => b.mtime - a.mtime);
|
|
1393
|
+
if (ranked[0]!.mtime > 0 && ranked[0]!.mtime >= ranked[1]!.mtime) return ranked[0]!.sid;
|
|
1394
|
+
return running[running.length - 1]!;
|
|
1395
|
+
}
|
|
1396
|
+
const allValid = roots
|
|
1397
|
+
.filter((r) => typeof r?.id === "string" && SAFE_DSH_SESSION_ID_RE.test(r.id))
|
|
1398
|
+
.map((r) => r.id!);
|
|
1399
|
+
if (allValid.length === 1) return allValid[0]!;
|
|
1400
|
+
} else {
|
|
1401
|
+
await res.body?.cancel().catch(() => {});
|
|
801
1402
|
}
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
.map((r) => r.id!);
|
|
805
|
-
if (allValid.length === 1) return allValid[0]!;
|
|
1403
|
+
} finally {
|
|
1404
|
+
clearTimeout(timer);
|
|
806
1405
|
}
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
}
|
|
810
|
-
} catch {}
|
|
1406
|
+
} catch {}
|
|
1407
|
+
}
|
|
811
1408
|
|
|
812
1409
|
// No health endpoint (older/newer DSH, or the inbound plugin is not
|
|
813
1410
|
// installed): the same log-mtime signal still identifies the session that
|
|
814
1411
|
// just ran a tool call. DSH writes one directory per session under
|
|
815
1412
|
// `<dshHome>/sessions/<project>/session-<uuid>/`.
|
|
1413
|
+
const homeStat = safeLstat(dshHome);
|
|
1414
|
+
if (!homeStat || homeStat.isSymbolicLink() || !homeStat.isDirectory() || !isSafeDirOrMissing(dshHome)) return null;
|
|
816
1415
|
const newestByLog = newestSessionLog(dshHome, nowMs, 30_000);
|
|
817
1416
|
if (newestByLog) return newestByLog;
|
|
818
1417
|
return null;
|