@ai-devkit/agent-manager 0.33.0 → 0.33.1

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.
Files changed (112) hide show
  1. package/dist/AgentManager.d.ts +11 -2
  2. package/dist/AgentManager.d.ts.map +1 -1
  3. package/dist/AgentManager.js +37 -6
  4. package/dist/AgentManager.js.map +1 -1
  5. package/dist/__tests__/AgentManager.test.js +212 -5
  6. package/dist/__tests__/AgentManager.test.js.map +1 -1
  7. package/dist/__tests__/adapters/OpenCodeAdapter.test.js +1 -0
  8. package/dist/__tests__/adapters/OpenCodeAdapter.test.js.map +1 -1
  9. package/dist/__tests__/{adapters → providers/copilot}/CopilotAdapter.test.js +19 -14
  10. package/dist/__tests__/providers/copilot/CopilotAdapter.test.js.map +1 -0
  11. package/dist/__tests__/{adapters → providers/gemini}/GeminiCliAdapter.test.js +37 -29
  12. package/dist/__tests__/providers/gemini/GeminiCliAdapter.test.js.map +1 -0
  13. package/dist/__tests__/runtime/HerdrAgentDiscovery.test.js +164 -0
  14. package/dist/__tests__/runtime/HerdrAgentDiscovery.test.js.map +1 -0
  15. package/dist/__tests__/runtime/HerdrAgentRuntime.test.js +37 -1
  16. package/dist/__tests__/runtime/HerdrAgentRuntime.test.js.map +1 -1
  17. package/dist/__tests__/utils/AgentRegistry.test.js +20 -13
  18. package/dist/__tests__/utils/AgentRegistry.test.js.map +1 -1
  19. package/dist/adapters/OpenCodeAdapter.d.ts +1 -0
  20. package/dist/adapters/OpenCodeAdapter.d.ts.map +1 -1
  21. package/dist/adapters/OpenCodeAdapter.js +7 -4
  22. package/dist/adapters/OpenCodeAdapter.js.map +1 -1
  23. package/dist/adapters/index.d.ts +2 -2
  24. package/dist/adapters/index.d.ts.map +1 -1
  25. package/dist/adapters/index.js +2 -2
  26. package/dist/adapters/index.js.map +1 -1
  27. package/dist/index.d.ts +5 -3
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +3 -2
  30. package/dist/index.js.map +1 -1
  31. package/dist/{adapters → providers/copilot}/CopilotAdapter.d.ts +11 -25
  32. package/dist/providers/copilot/CopilotAdapter.d.ts.map +1 -0
  33. package/dist/providers/copilot/CopilotAdapter.js +108 -0
  34. package/dist/providers/copilot/CopilotAdapter.js.map +1 -0
  35. package/dist/providers/copilot/CopilotAgentMapper.d.ts +9 -0
  36. package/dist/providers/copilot/CopilotAgentMapper.d.ts.map +1 -0
  37. package/dist/providers/copilot/CopilotAgentMapper.js +37 -0
  38. package/dist/providers/copilot/CopilotAgentMapper.js.map +1 -0
  39. package/dist/providers/copilot/CopilotSessionLocator.d.ts +19 -0
  40. package/dist/providers/copilot/CopilotSessionLocator.d.ts.map +1 -0
  41. package/dist/providers/copilot/CopilotSessionLocator.js +41 -0
  42. package/dist/providers/copilot/CopilotSessionLocator.js.map +1 -0
  43. package/dist/providers/copilot/CopilotSessionParser.d.ts +30 -0
  44. package/dist/providers/copilot/CopilotSessionParser.d.ts.map +1 -0
  45. package/dist/providers/copilot/CopilotSessionParser.js +181 -0
  46. package/dist/providers/copilot/CopilotSessionParser.js.map +1 -0
  47. package/dist/providers/gemini/GeminiAgentMapper.d.ts +9 -0
  48. package/dist/providers/gemini/GeminiAgentMapper.d.ts.map +1 -0
  49. package/dist/providers/gemini/GeminiAgentMapper.js +37 -0
  50. package/dist/providers/gemini/GeminiAgentMapper.js.map +1 -0
  51. package/dist/providers/gemini/GeminiCliAdapter.d.ts +52 -0
  52. package/dist/providers/gemini/GeminiCliAdapter.d.ts.map +1 -0
  53. package/dist/providers/gemini/GeminiCliAdapter.js +188 -0
  54. package/dist/providers/gemini/GeminiCliAdapter.js.map +1 -0
  55. package/dist/providers/gemini/GeminiSessionLocator.d.ts +30 -0
  56. package/dist/providers/gemini/GeminiSessionLocator.d.ts.map +1 -0
  57. package/dist/providers/gemini/GeminiSessionLocator.js +142 -0
  58. package/dist/providers/gemini/GeminiSessionLocator.js.map +1 -0
  59. package/dist/providers/gemini/GeminiSessionParser.d.ts +94 -0
  60. package/dist/providers/gemini/GeminiSessionParser.d.ts.map +1 -0
  61. package/dist/providers/gemini/GeminiSessionParser.js +166 -0
  62. package/dist/providers/gemini/GeminiSessionParser.js.map +1 -0
  63. package/dist/runtime/herdr/HerdrAgentDiscovery.d.ts +18 -0
  64. package/dist/runtime/herdr/HerdrAgentDiscovery.d.ts.map +1 -0
  65. package/dist/runtime/herdr/HerdrAgentDiscovery.js +183 -0
  66. package/dist/runtime/herdr/HerdrAgentDiscovery.js.map +1 -0
  67. package/dist/runtime/herdr/HerdrAgentRuntime.d.ts +5 -0
  68. package/dist/runtime/herdr/HerdrAgentRuntime.d.ts.map +1 -1
  69. package/dist/runtime/herdr/HerdrAgentRuntime.js +26 -8
  70. package/dist/runtime/herdr/HerdrAgentRuntime.js.map +1 -1
  71. package/dist/runtime/herdr/HerdrResponseParsers.d.ts +2 -0
  72. package/dist/runtime/herdr/HerdrResponseParsers.d.ts.map +1 -1
  73. package/dist/runtime/herdr/HerdrResponseParsers.js +12 -1
  74. package/dist/runtime/herdr/HerdrResponseParsers.js.map +1 -1
  75. package/dist/utils/AgentRegistry.d.ts.map +1 -1
  76. package/dist/utils/AgentRegistry.js +5 -5
  77. package/dist/utils/AgentRegistry.js.map +1 -1
  78. package/package.json +1 -1
  79. package/src/AgentManager.ts +67 -5
  80. package/src/__tests__/AgentManager.test.ts +231 -5
  81. package/src/__tests__/adapters/OpenCodeAdapter.test.ts +1 -0
  82. package/src/__tests__/{adapters → providers/copilot}/CopilotAdapter.test.ts +13 -16
  83. package/src/__tests__/{adapters → providers/gemini}/GeminiCliAdapter.test.ts +39 -31
  84. package/src/__tests__/runtime/HerdrAgentDiscovery.test.ts +131 -0
  85. package/src/__tests__/runtime/HerdrAgentRuntime.test.ts +20 -1
  86. package/src/__tests__/utils/AgentRegistry.test.ts +20 -10
  87. package/src/adapters/OpenCodeAdapter.ts +8 -4
  88. package/src/adapters/index.ts +2 -2
  89. package/src/index.ts +10 -3
  90. package/src/providers/copilot/CopilotAdapter.ts +145 -0
  91. package/src/providers/copilot/CopilotAgentMapper.ts +36 -0
  92. package/src/providers/copilot/CopilotSessionLocator.ts +57 -0
  93. package/src/providers/copilot/CopilotSessionParser.ts +289 -0
  94. package/src/providers/gemini/GeminiAgentMapper.ts +36 -0
  95. package/src/providers/gemini/GeminiCliAdapter.ts +266 -0
  96. package/src/providers/gemini/GeminiSessionLocator.ts +183 -0
  97. package/src/providers/gemini/GeminiSessionParser.ts +271 -0
  98. package/src/runtime/herdr/HerdrAgentDiscovery.ts +178 -0
  99. package/src/runtime/herdr/HerdrAgentRuntime.ts +33 -7
  100. package/src/runtime/herdr/HerdrResponseParsers.ts +11 -1
  101. package/src/utils/AgentRegistry.ts +8 -6
  102. package/dist/__tests__/adapters/CopilotAdapter.test.js.map +0 -1
  103. package/dist/__tests__/adapters/GeminiCliAdapter.test.js.map +0 -1
  104. package/dist/adapters/CopilotAdapter.d.ts.map +0 -1
  105. package/dist/adapters/CopilotAdapter.js +0 -329
  106. package/dist/adapters/CopilotAdapter.js.map +0 -1
  107. package/dist/adapters/GeminiCliAdapter.d.ts +0 -98
  108. package/dist/adapters/GeminiCliAdapter.d.ts.map +0 -1
  109. package/dist/adapters/GeminiCliAdapter.js +0 -513
  110. package/dist/adapters/GeminiCliAdapter.js.map +0 -1
  111. package/src/adapters/CopilotAdapter.ts +0 -483
  112. package/src/adapters/GeminiCliAdapter.ts +0 -699
@@ -0,0 +1,289 @@
1
+ import * as path from "path";
2
+ import type { ConversationMessage } from "../../adapters/AgentAdapter.js";
3
+ import { AgentStatus } from "../../adapters/AgentAdapter.js";
4
+ import { safeReadFile, safeStat } from "../../utils/session.js";
5
+
6
+ interface CopilotEventEntry {
7
+ type?: string;
8
+ data?: {
9
+ sessionId?: string;
10
+ startTime?: string;
11
+ context?: {
12
+ cwd?: string;
13
+ gitRoot?: string;
14
+ branch?: string;
15
+ };
16
+ content?: string;
17
+ transformedContent?: string;
18
+ message?: string;
19
+ text?: string;
20
+ result?: {
21
+ content?: string;
22
+ detailedContent?: string;
23
+ };
24
+ output?: string;
25
+ };
26
+ timestamp?: string;
27
+ }
28
+
29
+ interface CopilotWorkspace {
30
+ id?: string;
31
+ cwd?: string;
32
+ name?: string;
33
+ createdAt?: Date;
34
+ updatedAt?: Date;
35
+ }
36
+
37
+ export interface CopilotSession {
38
+ sessionId: string;
39
+ projectPath: string;
40
+ summary: string;
41
+ sessionStart: Date;
42
+ lastActive: Date;
43
+ lastEventType?: string;
44
+ firstUserMessage: string;
45
+ eventsFilePath: string;
46
+ }
47
+
48
+ interface CopilotEventSummary {
49
+ sessionId: string;
50
+ projectPath: string;
51
+ sessionStart: Date;
52
+ lastActive: Date;
53
+ firstUserMessage: string;
54
+ lastText: string;
55
+ lastEventType?: string;
56
+ }
57
+
58
+ const IDLE_THRESHOLD_MINUTES = 5;
59
+ const VERBOSE_SYSTEM_EVENTS = new Set([
60
+ "system.message",
61
+ "session.info",
62
+ "session.warning",
63
+ "tool.execution_start",
64
+ "tool.execution_complete",
65
+ "function",
66
+ "abort",
67
+ ]);
68
+ const WAITING_EVENTS = new Set([
69
+ "assistant.message",
70
+ "assistant.turn_end",
71
+ "session.shutdown",
72
+ "abort",
73
+ ]);
74
+
75
+ export class CopilotSessionParser {
76
+ readSessionDir(sessionDir: string, fallbackSessionId: string): CopilotSession | null {
77
+ const eventsFilePath = path.join(sessionDir, "events.jsonl");
78
+ const workspace = this.readWorkspaceMetadata(path.join(sessionDir, "workspace.yaml"));
79
+ const entries = this.readEventEntries(eventsFilePath);
80
+ if (entries.length === 0 && !this.hasWorkspaceMetadata(workspace)) {
81
+ return null;
82
+ }
83
+
84
+ const fileStat = safeStat(eventsFilePath);
85
+ const sessionStart = workspace.createdAt || fileStat?.birthtime || new Date();
86
+ const eventSummary = this.buildSessionFromEntries(entries, {
87
+ sessionId: workspace.id || fallbackSessionId,
88
+ projectPath: workspace.cwd || "",
89
+ sessionStart,
90
+ lastActive: workspace.updatedAt || fileStat?.mtime || sessionStart,
91
+ firstUserMessage: "",
92
+ lastText: "",
93
+ });
94
+
95
+ const summary =
96
+ eventSummary.firstUserMessage ||
97
+ eventSummary.lastText ||
98
+ workspace.name ||
99
+ "Copilot session active";
100
+
101
+ return {
102
+ sessionId: eventSummary.sessionId,
103
+ projectPath: eventSummary.projectPath,
104
+ summary: this.truncate(summary, 120),
105
+ sessionStart: eventSummary.sessionStart,
106
+ lastActive: eventSummary.lastActive,
107
+ lastEventType: eventSummary.lastEventType,
108
+ firstUserMessage: eventSummary.firstUserMessage,
109
+ eventsFilePath,
110
+ };
111
+ }
112
+
113
+ getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {
114
+ const verbose = options?.verbose ?? false;
115
+ const content = safeReadFile(sessionFilePath);
116
+ if (content === undefined) return [];
117
+
118
+ const messages: ConversationMessage[] = [];
119
+
120
+ for (const entry of this.parseEventLines(content)) {
121
+ const role = this.roleForEvent(entry.type, verbose);
122
+ if (!role) continue;
123
+
124
+ const text = this.extractEventText(entry, verbose);
125
+ if (!text) continue;
126
+
127
+ messages.push({
128
+ role,
129
+ content: text,
130
+ timestamp: entry.timestamp,
131
+ });
132
+ }
133
+
134
+ return messages;
135
+ }
136
+
137
+ determineStatus(session: CopilotSession): AgentStatus {
138
+ const diffMs = Date.now() - session.lastActive.getTime();
139
+ const diffMinutes = diffMs / 60000;
140
+ if (diffMinutes > IDLE_THRESHOLD_MINUTES) {
141
+ return AgentStatus.IDLE;
142
+ }
143
+
144
+ if (session.lastEventType !== undefined && WAITING_EVENTS.has(session.lastEventType)) {
145
+ return AgentStatus.WAITING;
146
+ }
147
+
148
+ return AgentStatus.RUNNING;
149
+ }
150
+
151
+ private readEventEntries(eventsFilePath: string): CopilotEventEntry[] {
152
+ const content = safeReadFile(eventsFilePath);
153
+ return content === undefined ? [] : this.parseEventLines(content);
154
+ }
155
+
156
+ private buildSessionFromEntries(
157
+ entries: CopilotEventEntry[],
158
+ initial: CopilotEventSummary,
159
+ ): CopilotEventSummary {
160
+ const summary = { ...initial };
161
+ for (const entry of entries) {
162
+ const timestamp = this.parseTimestamp(entry.timestamp);
163
+ if (timestamp) {
164
+ summary.lastActive = timestamp;
165
+ }
166
+ if (entry.type) {
167
+ summary.lastEventType = entry.type;
168
+ }
169
+
170
+ if (entry.type === "session.start") {
171
+ summary.sessionId = entry.data?.sessionId || summary.sessionId;
172
+ summary.projectPath = entry.data?.context?.cwd || summary.projectPath;
173
+ summary.sessionStart =
174
+ this.parseTimestamp(entry.data?.startTime) || timestamp || summary.sessionStart;
175
+ continue;
176
+ }
177
+
178
+ const text = this.extractEventText(entry, false);
179
+ if (!text) continue;
180
+
181
+ if (!summary.firstUserMessage && entry.type === "user.message") {
182
+ summary.firstUserMessage = text;
183
+ }
184
+
185
+ if (entry.type === "user.message" || entry.type === "assistant.message") {
186
+ summary.lastText = text;
187
+ }
188
+ }
189
+
190
+ return summary;
191
+ }
192
+
193
+ private hasWorkspaceMetadata(workspace: CopilotWorkspace): boolean {
194
+ return Boolean(
195
+ workspace.id || workspace.cwd || workspace.name || workspace.createdAt || workspace.updatedAt,
196
+ );
197
+ }
198
+
199
+ private readWorkspaceMetadata(filePath: string): CopilotWorkspace {
200
+ const content = safeReadFile(filePath);
201
+ if (content === undefined) return {};
202
+
203
+ const values = new Map<string, string>();
204
+ for (const rawLine of content.split("\n")) {
205
+ const line = rawLine.trim();
206
+ if (!line || line.startsWith("#")) continue;
207
+
208
+ const idx = line.indexOf(":");
209
+ if (idx === -1) continue;
210
+
211
+ const key = line.slice(0, idx).trim();
212
+ const value = this.stripYamlScalar(line.slice(idx + 1).trim());
213
+ values.set(key, value);
214
+ }
215
+
216
+ return {
217
+ id: values.get("id"),
218
+ cwd: values.get("cwd"),
219
+ name: values.get("name"),
220
+ createdAt: this.parseTimestamp(values.get("created_at")) || undefined,
221
+ updatedAt: this.parseTimestamp(values.get("updated_at")) || undefined,
222
+ };
223
+ }
224
+
225
+ private stripYamlScalar(value: string): string {
226
+ if (
227
+ (value.startsWith('"') && value.endsWith('"')) ||
228
+ (value.startsWith("'") && value.endsWith("'"))
229
+ ) {
230
+ return value.slice(1, -1);
231
+ }
232
+ return value;
233
+ }
234
+
235
+ private parseEventLines(content: string): CopilotEventEntry[] {
236
+ const entries: CopilotEventEntry[] = [];
237
+ for (const line of content.trim().split("\n")) {
238
+ const trimmed = line.trim();
239
+ if (!trimmed) continue;
240
+
241
+ try {
242
+ entries.push(JSON.parse(trimmed) as CopilotEventEntry);
243
+ } catch {
244
+ continue;
245
+ }
246
+ }
247
+ return entries;
248
+ }
249
+
250
+ private roleForEvent(
251
+ type: string | undefined,
252
+ verbose: boolean,
253
+ ): ConversationMessage["role"] | null {
254
+ if (type === "user.message") return "user";
255
+ if (type === "assistant.message") return "assistant";
256
+ if (verbose && type !== undefined && VERBOSE_SYSTEM_EVENTS.has(type)) {
257
+ return "system";
258
+ }
259
+ return null;
260
+ }
261
+
262
+ private extractEventText(entry: CopilotEventEntry, verbose: boolean): string {
263
+ const data = entry.data;
264
+ if (!data) return "";
265
+
266
+ const raw =
267
+ data.content ||
268
+ data.message ||
269
+ data.text ||
270
+ data.result?.content ||
271
+ data.result?.detailedContent ||
272
+ (verbose ? data.output : "") ||
273
+ "";
274
+
275
+ if (typeof raw !== "string") return "";
276
+ return raw.trim();
277
+ }
278
+
279
+ private parseTimestamp(value?: string): Date | null {
280
+ if (!value) return null;
281
+ const timestamp = new Date(value);
282
+ return Number.isNaN(timestamp.getTime()) ? null : timestamp;
283
+ }
284
+
285
+ private truncate(value: string, maxLength: number): string {
286
+ if (value.length <= maxLength) return value;
287
+ return `${value.slice(0, maxLength - 3)}...`;
288
+ }
289
+ }
@@ -0,0 +1,36 @@
1
+ import type { AgentInfo, ProcessInfo } from "../../adapters/AgentAdapter.js";
2
+ import { AgentStatus } from "../../adapters/AgentAdapter.js";
3
+ import { generateAgentName } from "../../utils/matching.js";
4
+ import { GeminiSessionParser, type GeminiSession } from "./GeminiSessionParser.js";
5
+
6
+ export class GeminiAgentMapper {
7
+ constructor(private readonly parser: GeminiSessionParser = new GeminiSessionParser()) {}
8
+
9
+ mapSessionToAgent(session: GeminiSession, processInfo: ProcessInfo, filePath: string): AgentInfo {
10
+ const projectPath = session.projectPath || processInfo.cwd || "";
11
+ return {
12
+ name: generateAgentName(projectPath, processInfo.pid),
13
+ type: "gemini_cli",
14
+ status: this.parser.determineStatus(session),
15
+ summary: session.summary || "Gemini CLI session active",
16
+ pid: processInfo.pid,
17
+ projectPath,
18
+ sessionId: session.sessionId,
19
+ lastActive: session.lastActive,
20
+ sessionFilePath: filePath,
21
+ };
22
+ }
23
+
24
+ mapProcessOnlyAgent(processInfo: ProcessInfo): AgentInfo {
25
+ return {
26
+ name: generateAgentName(processInfo.cwd || "", processInfo.pid),
27
+ type: "gemini_cli",
28
+ status: AgentStatus.RUNNING,
29
+ summary: "Gemini CLI process running",
30
+ pid: processInfo.pid,
31
+ projectPath: processInfo.cwd || "",
32
+ sessionId: `pid-${processInfo.pid}`,
33
+ lastActive: new Date(),
34
+ };
35
+ }
36
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Gemini CLI Adapter
3
+ *
4
+ * Detects running Gemini CLI agents by:
5
+ * 1. Filtering Gemini Node processes from a shared asynchronous process snapshot
6
+ * 2. Using snapshot CWD and start-time enrichment
7
+ * 3. Discovering session files from ~/.gemini/tmp/<shortId>/chats/session-*.json
8
+ * 4. Matching sessions to processes via shared matchProcessesToSessions()
9
+ * using sha256(cwd) === session.projectHash as the resolvedCwd source
10
+ * 5. Extracting summary from the most recent user message in the session JSON
11
+ */
12
+
13
+ import type {
14
+ AgentAdapter,
15
+ AgentInfo,
16
+ ProcessInfo,
17
+ ConversationMessage,
18
+ SessionSummary,
19
+ ListSessionsOptions,
20
+ AgentDetectionContext,
21
+ } from "../../adapters/AgentAdapter.js";
22
+ import {
23
+ captureProcessSnapshot,
24
+ executableBasename,
25
+ filterByProcessNames,
26
+ findWrapperProcess,
27
+ findWrapperProcessPids,
28
+ } from "../../utils/process.js";
29
+ import { matchProcessesToSessions } from "../../utils/matching.js";
30
+ import { AgentRegistry, type RegistryEntry } from "../../utils/AgentRegistry.js";
31
+ import { GeminiAgentMapper } from "./GeminiAgentMapper.js";
32
+ import { GeminiSessionLocator, type GeminiSessionDiscovery } from "./GeminiSessionLocator.js";
33
+ import { GeminiSessionParser } from "./GeminiSessionParser.js";
34
+
35
+ export interface GeminiCliAdapterOptions {
36
+ geminiTmpDir?: string;
37
+ }
38
+
39
+ export class GeminiCliAdapter implements AgentAdapter {
40
+ readonly type = "gemini_cli" as const;
41
+ readonly processNames = ["node"] as const;
42
+
43
+ private readonly registry: AgentRegistry;
44
+ private readonly parser: GeminiSessionParser;
45
+ private readonly mapper: GeminiAgentMapper;
46
+ private readonly locator: GeminiSessionLocator;
47
+
48
+ constructor(
49
+ registry: AgentRegistry = AgentRegistry.default(),
50
+ options: GeminiCliAdapterOptions = {},
51
+ ) {
52
+ this.registry = registry;
53
+ this.parser = new GeminiSessionParser();
54
+ this.mapper = new GeminiAgentMapper(this.parser);
55
+ this.locator = new GeminiSessionLocator(options);
56
+ }
57
+
58
+ canHandle(processInfo: ProcessInfo): boolean {
59
+ return this.isGeminiExecutable(processInfo.command);
60
+ }
61
+
62
+ /**
63
+ * Detect running Gemini CLI agents.
64
+ *
65
+ * Gemini CLI ships as a Node script (`bundle/gemini.js` with shebang
66
+ * `#!/usr/bin/env node`) — unlike Claude Code (native binary per
67
+ * platform) or Codex CLI (Node wrapper that execs a native Rust
68
+ * binary). The primary running process is therefore the Node runtime
69
+ * itself, and `ps aux` lists it as `node /path/to/gemini ...` with
70
+ * argv[0] = `node`. We scan the Node process pool via the shared
71
+ * snapshot and keep only those whose command line references the gemini
72
+ * executable or script via isGeminiExecutable().
73
+ */
74
+ async detectAgents(context?: AgentDetectionContext): Promise<AgentInfo[]> {
75
+ const processes = await this.getGeminiProcesses(context);
76
+ if (processes.length === 0) return [];
77
+
78
+ const wrapperPids = findWrapperProcessPids(processes);
79
+ const { cachedAgents, remaining } = this.tryRegistryCache(processes, wrapperPids);
80
+ if (remaining.length === 0) return this.deduplicateSessionAgents(cachedAgents);
81
+
82
+ const candidateProcesses = remaining.filter((proc) => !wrapperPids.has(proc.pid));
83
+ const registryEntriesByPid = new Map(this.registry.list().map((entry) => [entry.pid, entry]));
84
+ const discovery = this.locator.discoverSessions(candidateProcesses);
85
+
86
+ const agents =
87
+ discovery.sessions.length === 0
88
+ ? this.mapProcessOnlyAgents(candidateProcesses, processes, registryEntriesByPid)
89
+ : this.mapSessionDiscovery(discovery, candidateProcesses, processes, registryEntriesByPid);
90
+
91
+ return this.deduplicateSessionAgents([...cachedAgents, ...agents]);
92
+ }
93
+
94
+ getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {
95
+ return this.parser.getConversation(sessionFilePath, options);
96
+ }
97
+
98
+ async listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]> {
99
+ const summaries: SessionSummary[] = [];
100
+
101
+ for (const filePath of this.locator.discoverHistoricalSessionFiles()) {
102
+ const summary = this.parser.fileToSessionSummary(filePath);
103
+ if (!summary) continue;
104
+ if (opts?.cwd !== undefined && summary.cwd !== opts.cwd) continue;
105
+ summaries.push(summary);
106
+ }
107
+
108
+ return summaries;
109
+ }
110
+
111
+ private async getGeminiProcesses(context?: AgentDetectionContext): Promise<ProcessInfo[]> {
112
+ const snapshot = context?.processes ?? (await captureProcessSnapshot(this.processNames));
113
+ const relevant = filterByProcessNames(snapshot, this.processNames);
114
+ return relevant.filter((process) => this.canHandle(process));
115
+ }
116
+
117
+ private mapSessionDiscovery(
118
+ discovery: GeminiSessionDiscovery,
119
+ candidateProcesses: ProcessInfo[],
120
+ allProcesses: ProcessInfo[],
121
+ registryEntriesByPid: Map<number, RegistryEntry>,
122
+ ): AgentInfo[] {
123
+ const matches = matchProcessesToSessions(candidateProcesses, discovery.sessions);
124
+ const matchedPids = new Set(matches.map((m) => m.process.pid));
125
+ const matchedProcesses: ProcessInfo[] = [];
126
+ const agents: AgentInfo[] = [];
127
+
128
+ for (const match of matches) {
129
+ const cachedContent = discovery.contentCache.get(match.session.filePath);
130
+ const sessionData = this.parser.parseSession(cachedContent, match.session.filePath);
131
+ if (!sessionData) {
132
+ matchedPids.delete(match.process.pid);
133
+ continue;
134
+ }
135
+
136
+ const agent = this.mapper.mapSessionToAgent(
137
+ sessionData,
138
+ match.process,
139
+ match.session.filePath,
140
+ );
141
+ this.applyWrapperRegistryName(agent, match.process, allProcesses, registryEntriesByPid);
142
+ agents.push(agent);
143
+ matchedProcesses.push(match.process);
144
+ }
145
+
146
+ const matchedWrapperPids = findWrapperProcessPids(candidateProcesses, matchedProcesses);
147
+ const unmatchedProcesses = candidateProcesses.filter(
148
+ (process) => !matchedPids.has(process.pid) && !matchedWrapperPids.has(process.pid),
149
+ );
150
+
151
+ agents.push(
152
+ ...this.mapProcessOnlyAgents(unmatchedProcesses, allProcesses, registryEntriesByPid),
153
+ );
154
+ return agents;
155
+ }
156
+
157
+ private mapProcessOnlyAgents(
158
+ processes: ProcessInfo[],
159
+ allProcesses: ProcessInfo[],
160
+ registryEntriesByPid: Map<number, RegistryEntry>,
161
+ ): AgentInfo[] {
162
+ return processes.map((processInfo) => {
163
+ const agent = this.mapper.mapProcessOnlyAgent(processInfo);
164
+ this.applyWrapperRegistryName(agent, processInfo, allProcesses, registryEntriesByPid);
165
+ return agent;
166
+ });
167
+ }
168
+
169
+ private applyWrapperRegistryName(
170
+ agent: AgentInfo,
171
+ processInfo: ProcessInfo,
172
+ processes: ProcessInfo[],
173
+ registryEntriesByPid: Map<number, RegistryEntry>,
174
+ ): void {
175
+ const wrapper = findWrapperProcess(processes, processInfo);
176
+ const wrapperEntry = wrapper ? registryEntriesByPid.get(wrapper.pid) : undefined;
177
+ if (wrapperEntry?.type === this.type) {
178
+ agent.name = wrapperEntry.name;
179
+ }
180
+ }
181
+
182
+ private deduplicateSessionAgents(agents: AgentInfo[]): AgentInfo[] {
183
+ const bySession = new Map<string, AgentInfo>();
184
+ const result: AgentInfo[] = [];
185
+
186
+ for (const agent of agents) {
187
+ const sessionKey = this.sessionDeduplicationKey(agent);
188
+ if (!sessionKey) {
189
+ result.push(agent);
190
+ continue;
191
+ }
192
+
193
+ const existing = bySession.get(sessionKey);
194
+ if (!existing) {
195
+ bySession.set(sessionKey, agent);
196
+ result.push(agent);
197
+ continue;
198
+ }
199
+
200
+ if (agent.pid > existing.pid) {
201
+ bySession.set(sessionKey, agent);
202
+ const index = result.indexOf(existing);
203
+ if (index >= 0) result[index] = agent;
204
+ }
205
+ }
206
+
207
+ return result;
208
+ }
209
+
210
+ private sessionDeduplicationKey(agent: AgentInfo): string | null {
211
+ if (agent.sessionFilePath) return `file:${agent.sessionFilePath}`;
212
+ if (agent.sessionId && !agent.sessionId.startsWith("pid-")) {
213
+ return `session:${agent.sessionId}`;
214
+ }
215
+ return null;
216
+ }
217
+
218
+ private tryRegistryCache(
219
+ processes: ProcessInfo[],
220
+ wrapperPids: Set<number>,
221
+ ): {
222
+ cachedAgents: AgentInfo[];
223
+ remaining: ProcessInfo[];
224
+ } {
225
+ const cachedAgents: AgentInfo[] = [];
226
+ const remaining: ProcessInfo[] = [];
227
+ const byPid = new Map(this.registry.list().map((e) => [e.pid, e]));
228
+
229
+ for (const proc of processes) {
230
+ const entry = byPid.get(proc.pid);
231
+ if (
232
+ wrapperPids.has(proc.pid) ||
233
+ !entry ||
234
+ entry.type !== this.type ||
235
+ !entry.sessionFilePath
236
+ ) {
237
+ remaining.push(proc);
238
+ continue;
239
+ }
240
+
241
+ const sessionData = this.parser.parseSession(undefined, entry.sessionFilePath);
242
+ if (!sessionData) {
243
+ remaining.push(proc);
244
+ continue;
245
+ }
246
+
247
+ cachedAgents.push(this.mapper.mapSessionToAgent(sessionData, proc, entry.sessionFilePath));
248
+ }
249
+
250
+ return { cachedAgents, remaining };
251
+ }
252
+
253
+ private isGeminiExecutable(command: string): boolean {
254
+ // Accept any token in the command line whose basename matches a
255
+ // known gemini entrypoint. This is intentionally broader than the
256
+ // other adapters' argv[0]-only check because the Node-script
257
+ // distribution puts the real gemini path in argv[1..], not argv[0].
258
+ for (const token of command.trim().split(/\s+/)) {
259
+ const base = executableBasename(token);
260
+ if (base === "gemini" || base === "gemini.exe" || base === "gemini.js") {
261
+ return true;
262
+ }
263
+ }
264
+ return false;
265
+ }
266
+ }