agentschat-mcp 0.36.22 → 0.36.24

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.
@@ -200,19 +200,41 @@ export function loadSessionBinds(configDir: string): Record<string, string> {
200
200
  return merged;
201
201
  }
202
202
 
203
+ function resolveAgentIdForProfileName(configDir: string, name: string): string | null {
204
+ if (!name || name.includes("/") || name.includes("\\")) return null;
205
+ const base = name.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
206
+ for (const candidate of [join(configDir, "profiles", `${base}.json`), join(configDir, `${base}.json`)]) {
207
+ if (!existsSync(candidate)) continue;
208
+ try {
209
+ const parsed = JSON.parse(readFileSync(candidate, "utf8")) as { agent_id?: unknown };
210
+ if (typeof parsed?.agent_id === "string" && parsed.agent_id.trim()) {
211
+ return parsed.agent_id.trim();
212
+ }
213
+ } catch {}
214
+ }
215
+ return null;
216
+ }
217
+
203
218
  export function saveSessionBind(configDir: string, sessionId: string, profileName: string): void {
204
219
  const sid = sessionId.trim();
205
220
  const prof = profileName.trim();
206
221
  if (!sid || !prof) return;
222
+ const targetAgentId = resolveAgentIdForProfileName(configDir, prof);
223
+ const isSameProfileOrAgent = (existingProf: string): boolean => {
224
+ if (existingProf === prof) return true;
225
+ if (!targetAgentId) return false;
226
+ return resolveAgentIdForProfileName(configDir, existingProf) === targetAgentId;
227
+ };
207
228
  const path = join(configDir, DEFAULT_SESSION_BINDS_FILENAME);
208
229
  let current: Record<string, string> = {};
209
230
  if (existsSync(path)) {
210
231
  try { current = parseSessionBinds(JSON.parse(readFileSync(path, "utf8"))); } catch {}
211
232
  }
212
- // Enforce 1:1 profileName <-> sessionId mapping so re-binding a profile to a
213
- // conversation replaces any stale conversation bound to the same profile.
233
+ // Enforce 1:1 (profileName & agent_id) <-> sessionId mapping so re-binding a
234
+ // profile (or an alias file such as `profile.json` + `<Name>.json` sharing one
235
+ // `agent_id`) replaces any stale conversation bound to the same identity.
214
236
  for (const [existingSid, existingProf] of Object.entries(current)) {
215
- if (existingProf === prof && existingSid !== sid) {
237
+ if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
216
238
  delete current[existingSid];
217
239
  }
218
240
  }
@@ -227,7 +249,7 @@ export function saveSessionBind(configDir: string, sessionId: string, profileNam
227
249
  const legacy = parseSessionBinds(JSON.parse(readFileSync(legacyPath, "utf8")));
228
250
  let changed = false;
229
251
  for (const [existingSid, existingProf] of Object.entries(legacy)) {
230
- if (existingProf === prof && existingSid !== sid) {
252
+ if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
231
253
  delete legacy[existingSid];
232
254
  changed = true;
233
255
  }
@@ -318,12 +340,19 @@ export function detectRuntimeSession(
318
340
  return { sessionId: explicitSid, runtime: "custom" };
319
341
  }
320
342
 
321
- // 6. Antigravity parent language_server discovery (macOS & Linux)
322
- if (
323
- env === process.env ||
343
+ // 6. Antigravity parent language_server discovery (macOS & Linux).
344
+ // Skip expensive ps/lsof parent-tree probing when running against a loopback mock
345
+ // hub in tests with a stripped env (unless explicit Antigravity env vars are set).
346
+ const hasExplicitAgyEnv =
324
347
  env.__CFBundleIdentifier === "com.google.antigravity" ||
325
- Boolean(env.AGY_BROWSER_WS_URL)
326
- ) {
348
+ Boolean(env.AGY_BROWSER_WS_URL) ||
349
+ Boolean(env.ANTIGRAVITY_LS_ADDRESS) ||
350
+ Boolean(env.ANTIGRAVITY_CSRF_TOKEN);
351
+ const isMockHubSubprocess =
352
+ !hasExplicitAgyEnv &&
353
+ typeof env.AGENTCHAT_REST_URL === "string" &&
354
+ /^http:\/\/127\.0\.0\.1:\d+/.test(env.AGENTCHAT_REST_URL);
355
+ if (!isMockHubSubprocess && (env === process.env || hasExplicitAgyEnv)) {
327
356
  const agyHost = discoverAntigravityHost();
328
357
  if (agyHost && agyHost.openConversations.length === 1) {
329
358
  return { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" };
@@ -347,10 +376,90 @@ let cachedAgyHost: { at: number; info: AntigravityHostInfo | null } | null = nul
347
376
  * was spawned by Antigravity's `language_server`. Extracts `--csrf_token`,
348
377
  * listening loopback ports, and open `presence/<conversation_id>.lock` files.
349
378
  */
379
+ /**
380
+ * Parse `lsof -Pan -p <language_server_pid>` output into listening loopback ports
381
+ * and currently open Antigravity IDE conversation UUIDs.
382
+ *
383
+ * Important distinctions verified on live Antigravity `language_server` processes:
384
+ * 1. `language_server` keeps all historical `~/.gemini/antigravity-cli/conversations/*.db`
385
+ * files open read-only (`61r..137r`); those archived CLI DBs are NOT open IDE windows.
386
+ * 2. Active IDE windows hold an open FD on `/<appDataDir>/presence/<uuid>.lock`, whereas
387
+ * closed tabs immediately release their presence lock while SQLite may keep their
388
+ * `/<appDataDir>/conversations/<uuid>.db` cached in its pool. Prefer active presence
389
+ * locks whenever present, falling back to non-CLI `.db` handles only when no presence
390
+ * locks exist.
391
+ */
392
+ export function parseAntigravityLsofOutput(
393
+ stdout: string,
394
+ appDataDir = "antigravity",
395
+ ): { ports: number[]; openConversations: string[] } {
396
+ const ports: number[] = [];
397
+ const presenceConversations: string[] = [];
398
+ const dbConversations: string[] = [];
399
+ const cleanAppDir = (appDataDir || "antigravity").trim().replace(/^\/+|\/+$/g, "");
400
+ const isCliTarget = cleanAppDir === "antigravity-cli";
401
+
402
+ for (const line of (stdout || "").split(/\r?\n/)) {
403
+ const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
404
+ if (portMatch) {
405
+ const p = Number(portMatch[1]);
406
+ if (p > 0 && !ports.includes(p)) ports.push(p);
407
+ }
408
+ if (!isCliTarget && line.includes("/antigravity-cli/")) continue;
409
+
410
+ const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/);
411
+ if (presMatch) {
412
+ const cid = presMatch[1]!;
413
+ if (!presenceConversations.includes(cid)) presenceConversations.push(cid);
414
+ continue;
415
+ }
416
+
417
+ const dbMatch = line.match(/\/conversations\/([0-9a-fA-F-]{36})\.db$/);
418
+ if (dbMatch) {
419
+ if (cleanAppDir && line.includes("/.gemini/") && !line.includes(`/${cleanAppDir}/conversations/`)) {
420
+ continue;
421
+ }
422
+ const cid = dbMatch[1]!;
423
+ if (!dbConversations.includes(cid)) dbConversations.push(cid);
424
+ }
425
+ }
426
+
427
+ // Antigravity allocates https_server_port first and http_server_port second;
428
+ // sort descending so the plaintext HTTP Connect-RPC port is tried first.
429
+ ports.sort((a, b) => b - a);
430
+ const openConversations =
431
+ presenceConversations.length > 0 ? presenceConversations : dbConversations;
432
+ return { ports, openConversations };
433
+ }
434
+
350
435
  export function discoverAntigravityHost(opts?: {
351
436
  currentPid?: number;
352
437
  cacheMs?: number;
353
438
  }): AntigravityHostInfo | null {
439
+ if (!opts?.currentPid) {
440
+ const envAddr = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
441
+ const envCsrf = process.env.ANTIGRAVITY_CSRF_TOKEN?.trim() || "";
442
+ if (envAddr && envCsrf) {
443
+ const portMatch = envAddr.match(/:(\d+)$/);
444
+ const ports = portMatch ? [Number(portMatch[1])] : [];
445
+ const openConversations = (process.env.ANTIGRAVITY_OPEN_CONVERSATIONS || "")
446
+ .split(",")
447
+ .map((s) => s.trim())
448
+ .filter((s) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s));
449
+ return { lsPid: process.ppid, csrfToken: envCsrf, ports, openConversations };
450
+ }
451
+ const hasExplicitAgyEnv =
452
+ process.env.__CFBundleIdentifier === "com.google.antigravity" ||
453
+ Boolean(process.env.AGY_BROWSER_WS_URL);
454
+ if (
455
+ !hasExplicitAgyEnv &&
456
+ typeof process.env.AGENTCHAT_REST_URL === "string" &&
457
+ /^http:\/\/127\.0\.0\.1:\d+/.test(process.env.AGENTCHAT_REST_URL)
458
+ ) {
459
+ return null;
460
+ }
461
+ }
462
+
354
463
  const now = Date.now();
355
464
  const cacheMs = opts?.cacheMs ?? 5_000;
356
465
  if (cachedAgyHost && now - cachedAgyHost.at < cacheMs) return cachedAgyHost.info;
@@ -391,28 +500,14 @@ export function discoverAntigravityHost(opts?: {
391
500
  return null;
392
501
  }
393
502
 
503
+ const appDirMatch = lsCmd.match(/--app_data_dir[=\s]+([^\s]+)/);
504
+ const appDataDir = appDirMatch?.[1]?.trim() || "antigravity";
505
+
394
506
  const lsof = spawnSync("lsof", ["-Pan", "-p", String(lsPid)], { encoding: "utf8", timeout: 1500 });
395
- const ports: number[] = [];
396
- const openConversations: string[] = [];
397
- if (lsof.status === 0 && lsof.stdout) {
398
- for (const line of lsof.stdout.split(/\r?\n/)) {
399
- const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
400
- if (portMatch) {
401
- const p = Number(portMatch[1]);
402
- if (p > 0 && !ports.includes(p)) ports.push(p);
403
- }
404
- const presMatch =
405
- line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/) ||
406
- line.match(/\/conversations\/([0-9a-fA-F-]{36})\.db$/);
407
- if (presMatch) {
408
- const cid = presMatch[1]!;
409
- if (!openConversations.includes(cid)) openConversations.push(cid);
410
- }
411
- }
412
- }
413
- // Antigravity allocates https_server_port first and http_server_port second;
414
- // sort descending so the plaintext HTTP Connect-RPC port is tried first.
415
- ports.sort((a, b) => b - a);
507
+ const { ports, openConversations } =
508
+ lsof.status === 0 && lsof.stdout
509
+ ? parseAntigravityLsofOutput(lsof.stdout, appDataDir)
510
+ : { ports: [], openConversations: [] };
416
511
 
417
512
  const info: AntigravityHostInfo = { lsPid, csrfToken, ports, openConversations };
418
513
  cachedAgyHost = { at: now, info };
@@ -67,7 +67,11 @@ function readAgentId(path: string): string | undefined {
67
67
  */
68
68
  export function resolveSessionForAgent(
69
69
  agentId: string | null | undefined,
70
- opts: { configDir?: string; env?: Record<string, string | undefined> } = {},
70
+ opts: {
71
+ configDir?: string;
72
+ env?: Record<string, string | undefined>;
73
+ filter?: (sessionId: string) => boolean;
74
+ } = {},
71
75
  ): AgentSessionRoute | undefined {
72
76
  if (typeof agentId !== "string" || agentId.length === 0) return undefined;
73
77
  const configDir = opts.configDir ?? agentschatConfigDir(opts.env);
@@ -78,6 +82,7 @@ export function resolveSessionForAgent(
78
82
  return undefined;
79
83
  }
80
84
  for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
85
+ if (opts.filter && !opts.filter(sessionId)) continue;
81
86
  const path = profilePathForName(configDir, profileName);
82
87
  if (path === undefined) continue;
83
88
  if (readAgentId(path) !== agentId) continue;