@ai-devkit/agent-manager 0.16.0 → 0.17.0

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 (97) hide show
  1. package/.swcrc +27 -0
  2. package/dist/AgentManager.js +72 -74
  3. package/dist/AgentManager.js.map +1 -1
  4. package/dist/__tests__/AgentManager.test.js +564 -0
  5. package/dist/__tests__/AgentManager.test.js.map +1 -0
  6. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js +2157 -0
  7. package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js.map +1 -0
  8. package/dist/__tests__/adapters/CodexAdapter.test.js +1354 -0
  9. package/dist/__tests__/adapters/CodexAdapter.test.js.map +1 -0
  10. package/dist/__tests__/adapters/CopilotAdapter.test.js +500 -0
  11. package/dist/__tests__/adapters/CopilotAdapter.test.js.map +1 -0
  12. package/dist/__tests__/adapters/GeminiCliAdapter.test.js +1229 -0
  13. package/dist/__tests__/adapters/GeminiCliAdapter.test.js.map +1 -0
  14. package/dist/__tests__/adapters/OpenCodeAdapter.test.js +626 -0
  15. package/dist/__tests__/adapters/OpenCodeAdapter.test.js.map +1 -0
  16. package/dist/__tests__/terminal/TmuxManager.test.js +159 -0
  17. package/dist/__tests__/terminal/TmuxManager.test.js.map +1 -0
  18. package/dist/__tests__/terminal/TtyWriter.test.js +162 -0
  19. package/dist/__tests__/terminal/TtyWriter.test.js.map +1 -0
  20. package/dist/__tests__/utils/AgentRegistry.test.js +282 -0
  21. package/dist/__tests__/utils/AgentRegistry.test.js.map +1 -0
  22. package/dist/__tests__/utils/ClaudeSessionParser.test.js +312 -0
  23. package/dist/__tests__/utils/ClaudeSessionParser.test.js.map +1 -0
  24. package/dist/__tests__/utils/matching.test.js +324 -0
  25. package/dist/__tests__/utils/matching.test.js.map +1 -0
  26. package/dist/__tests__/utils/process.test.js +177 -0
  27. package/dist/__tests__/utils/process.test.js.map +1 -0
  28. package/dist/__tests__/utils/session.test.js +158 -0
  29. package/dist/__tests__/utils/session.test.js.map +1 -0
  30. package/dist/adapters/AgentAdapter.d.ts +1 -1
  31. package/dist/adapters/AgentAdapter.d.ts.map +1 -1
  32. package/dist/adapters/AgentAdapter.js +8 -7
  33. package/dist/adapters/AgentAdapter.js.map +1 -1
  34. package/dist/adapters/ClaudeCodeAdapter.js +66 -77
  35. package/dist/adapters/ClaudeCodeAdapter.js.map +1 -1
  36. package/dist/adapters/CodexAdapter.d.ts +9 -0
  37. package/dist/adapters/CodexAdapter.d.ts.map +1 -1
  38. package/dist/adapters/CodexAdapter.js +188 -141
  39. package/dist/adapters/CodexAdapter.js.map +1 -1
  40. package/dist/adapters/CopilotAdapter.d.ts +44 -0
  41. package/dist/adapters/CopilotAdapter.d.ts.map +1 -0
  42. package/dist/adapters/CopilotAdapter.js +314 -0
  43. package/dist/adapters/CopilotAdapter.js.map +1 -0
  44. package/dist/adapters/GeminiCliAdapter.d.ts +2 -0
  45. package/dist/adapters/GeminiCliAdapter.d.ts.map +1 -1
  46. package/dist/adapters/GeminiCliAdapter.js +138 -156
  47. package/dist/adapters/GeminiCliAdapter.js.map +1 -1
  48. package/dist/adapters/OpenCodeAdapter.js +60 -69
  49. package/dist/adapters/OpenCodeAdapter.js.map +1 -1
  50. package/dist/adapters/index.d.ts +1 -0
  51. package/dist/adapters/index.d.ts.map +1 -1
  52. package/dist/adapters/index.js +2 -0
  53. package/dist/adapters/index.js.map +1 -1
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +2 -0
  57. package/dist/index.js.map +1 -1
  58. package/dist/terminal/TerminalFocusManager.js +62 -49
  59. package/dist/terminal/TerminalFocusManager.js.map +1 -1
  60. package/dist/terminal/TmuxManager.js +59 -34
  61. package/dist/terminal/TmuxManager.js.map +1 -1
  62. package/dist/terminal/TtyWriter.js +37 -16
  63. package/dist/terminal/TtyWriter.js.map +1 -1
  64. package/dist/terminal/index.js +1 -0
  65. package/dist/terminal/index.js.map +1 -1
  66. package/dist/utils/AgentRegistry.js +41 -32
  67. package/dist/utils/AgentRegistry.js.map +1 -1
  68. package/dist/utils/ClaudeSessionParser.js +46 -87
  69. package/dist/utils/ClaudeSessionParser.js.map +1 -1
  70. package/dist/utils/agents.d.ts +1 -1
  71. package/dist/utils/agents.d.ts.map +1 -1
  72. package/dist/utils/agents.js +22 -11
  73. package/dist/utils/agents.js.map +1 -1
  74. package/dist/utils/applescript.js +3 -6
  75. package/dist/utils/applescript.js.map +1 -1
  76. package/dist/utils/index.js +1 -0
  77. package/dist/utils/index.js.map +1 -1
  78. package/dist/utils/matching.js +21 -29
  79. package/dist/utils/matching.js.map +1 -1
  80. package/dist/utils/process.js +77 -56
  81. package/dist/utils/process.js.map +1 -1
  82. package/dist/utils/session.js +20 -34
  83. package/dist/utils/session.js.map +1 -1
  84. package/dist/utils/sortAgents.js +6 -8
  85. package/dist/utils/sortAgents.js.map +1 -1
  86. package/package.json +11 -7
  87. package/src/__tests__/adapters/ClaudeCodeAdapter.test.ts +2 -0
  88. package/src/__tests__/adapters/CodexAdapter.test.ts +94 -0
  89. package/src/__tests__/adapters/CopilotAdapter.test.ts +411 -0
  90. package/src/__tests__/adapters/GeminiCliAdapter.test.ts +74 -1
  91. package/src/adapters/AgentAdapter.ts +1 -1
  92. package/src/adapters/CodexAdapter.ts +114 -6
  93. package/src/adapters/CopilotAdapter.ts +453 -0
  94. package/src/adapters/GeminiCliAdapter.ts +42 -3
  95. package/src/adapters/index.ts +1 -0
  96. package/src/index.ts +1 -0
  97. package/src/utils/agents.ts +1 -1
@@ -38,7 +38,7 @@ describe('GeminiCliAdapter', () => {
38
38
  tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gemini-adapter-test-'));
39
39
  process.env.HOME = tmpHome;
40
40
 
41
- adapter = new GeminiCliAdapter();
41
+ adapter = new GeminiCliAdapter(new AgentRegistry(path.join(tmpHome, 'agents.json')));
42
42
  mockedListAgentProcesses.mockReset();
43
43
  mockedEnrichProcesses.mockReset();
44
44
  mockedMatchProcessesToSessions.mockReset();
@@ -214,6 +214,79 @@ describe('GeminiCliAdapter', () => {
214
214
  expect(agents[0].summary).toContain('hello gemini');
215
215
  });
216
216
 
217
+ it('should collapse Gemini wrapper and child processes matched to the same session', async () => {
218
+ const cwd = '/repo/project-a';
219
+ const projectHash = hashProjectRoot(cwd);
220
+ const shortId = 'abc123';
221
+ const chatsDir = path.join(tmpHome, '.gemini', 'tmp', shortId, 'chats');
222
+ fs.mkdirSync(chatsDir, { recursive: true });
223
+ const sessionPath = path.join(chatsDir, 'session-2026-04-18T00-00-session1.json');
224
+ const sessionStart = new Date('2026-04-18T00:00:00Z').toISOString();
225
+ fs.writeFileSync(
226
+ sessionPath,
227
+ JSON.stringify({
228
+ sessionId: 'session1',
229
+ projectHash,
230
+ startTime: sessionStart,
231
+ lastUpdated: sessionStart,
232
+ kind: 'main',
233
+ directories: [cwd],
234
+ messages: [
235
+ { id: 'm1', timestamp: sessionStart, type: 'user', content: 'hello gemini' },
236
+ ],
237
+ }),
238
+ );
239
+
240
+ const wrapperProc: ProcessInfo = {
241
+ pid: 88394,
242
+ command: 'node /Users/foo/.nvm/versions/node/v23.9.0/bin/gemini',
243
+ cwd,
244
+ tty: 'ttys015',
245
+ startTime: new Date('2026-04-18T00:00:00Z'),
246
+ };
247
+ const childProc: ProcessInfo = {
248
+ pid: 88460,
249
+ command: '/Users/foo/.nvm/versions/node/v24.13.1/bin/node /Users/foo/.nvm/versions/node/v23.9.0/bin/gemini',
250
+ cwd,
251
+ tty: 'ttys015',
252
+ startTime: new Date('2026-04-18T00:00:01Z'),
253
+ };
254
+ mockedListAgentProcesses.mockReturnValue([wrapperProc, childProc]);
255
+ mockedMatchProcessesToSessions.mockReturnValue([
256
+ {
257
+ process: wrapperProc,
258
+ session: {
259
+ sessionId: 'session1',
260
+ filePath: sessionPath,
261
+ projectDir: chatsDir,
262
+ birthtimeMs: Date.now(),
263
+ resolvedCwd: cwd,
264
+ },
265
+ deltaMs: 0,
266
+ },
267
+ {
268
+ process: childProc,
269
+ session: {
270
+ sessionId: 'session1',
271
+ filePath: sessionPath,
272
+ projectDir: chatsDir,
273
+ birthtimeMs: Date.now(),
274
+ resolvedCwd: cwd,
275
+ },
276
+ deltaMs: 0,
277
+ },
278
+ ]);
279
+
280
+ const agents = await adapter.detectAgents();
281
+
282
+ expect(agents).toHaveLength(1);
283
+ expect(agents[0]).toMatchObject({
284
+ pid: 88460,
285
+ sessionId: 'session1',
286
+ sessionFilePath: sessionPath,
287
+ });
288
+ });
289
+
217
290
  it('should not match sessions from other projects', async () => {
218
291
  const procCwd = '/repo/project-a';
219
292
  const otherCwd = '/repo/project-b';
@@ -8,7 +8,7 @@
8
8
  /**
9
9
  * Type of AI agent
10
10
  */
11
- export type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'other';
11
+ export type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'other';
12
12
 
13
13
  /**
14
14
  * Current status of an agent
@@ -48,6 +48,16 @@ interface CodexSession {
48
48
  lastPayloadType?: string;
49
49
  }
50
50
 
51
+ interface DirectMatch {
52
+ process: ProcessInfo;
53
+ sessionFile: SessionFile;
54
+ }
55
+
56
+ interface DirectMatchResult {
57
+ agents: AgentInfo[];
58
+ failedProcesses: ProcessInfo[];
59
+ }
60
+
51
61
  export class CodexAdapter implements AgentAdapter {
52
62
  readonly type = 'codex' as const;
53
63
 
@@ -78,14 +88,24 @@ export class CodexAdapter implements AgentAdapter {
78
88
  const { cachedAgents, remaining } = this.tryRegistryCache(processes);
79
89
  if (remaining.length === 0) return cachedAgents;
80
90
 
81
- const { sessions, contentCache } = this.discoverSessions(remaining);
91
+ const { direct, fallback } = this.tryResumeMatching(remaining);
92
+ const directResult = this.mapDirectMatches(direct);
93
+ const { sessions, contentCache } = this.discoverSessions(fallback);
82
94
  if (sessions.length === 0) {
83
- return [...cachedAgents, ...remaining.map((p) => this.mapProcessOnlyAgent(p))];
95
+ return [
96
+ ...cachedAgents,
97
+ ...directResult.agents,
98
+ ...directResult.failedProcesses.map((p) => this.mapProcessOnlyAgent(p)),
99
+ ...fallback.map((p) => this.mapProcessOnlyAgent(p)),
100
+ ];
84
101
  }
85
102
 
86
- const matches = matchProcessesToSessions(remaining, sessions);
87
- const matchedPids = new Set(matches.map((m) => m.process.pid));
88
- const agents: AgentInfo[] = [];
103
+ const matches = matchProcessesToSessions(fallback, sessions);
104
+ const matchedPids = new Set([
105
+ ...directResult.agents.map((a) => a.pid),
106
+ ...matches.map((m) => m.process.pid),
107
+ ]);
108
+ const agents: AgentInfo[] = [...directResult.agents];
89
109
 
90
110
  for (const match of matches) {
91
111
  const cachedContent = contentCache.get(match.session.filePath);
@@ -97,12 +117,16 @@ export class CodexAdapter implements AgentAdapter {
97
117
  }
98
118
  }
99
119
 
100
- for (const proc of remaining) {
120
+ for (const proc of fallback) {
101
121
  if (!matchedPids.has(proc.pid)) {
102
122
  agents.push(this.mapProcessOnlyAgent(proc));
103
123
  }
104
124
  }
105
125
 
126
+ for (const proc of directResult.failedProcesses) {
127
+ agents.push(this.mapProcessOnlyAgent(proc));
128
+ }
129
+
106
130
  return [...cachedAgents, ...agents];
107
131
  }
108
132
 
@@ -139,6 +163,90 @@ export class CodexAdapter implements AgentAdapter {
139
163
  return { cachedAgents, remaining };
140
164
  }
141
165
 
166
+ /**
167
+ * Match processes via `codex resume <uuid>` in their command line.
168
+ * Resumed sessions predate the process, so birth-time proximity cannot
169
+ * reliably pair them with the running PID.
170
+ */
171
+ private tryResumeMatching(processes: ProcessInfo[]): {
172
+ direct: DirectMatch[];
173
+ fallback: ProcessInfo[];
174
+ } {
175
+ const direct: DirectMatch[] = [];
176
+ const fallback: ProcessInfo[] = [];
177
+
178
+ for (const proc of processes) {
179
+ const sessionId = this.extractResumeSessionId(proc.command);
180
+ if (!sessionId) {
181
+ fallback.push(proc);
182
+ continue;
183
+ }
184
+
185
+ const sessionFile = this.findSessionFileById(sessionId);
186
+ if (!sessionFile) {
187
+ fallback.push(proc);
188
+ continue;
189
+ }
190
+
191
+ direct.push({ process: proc, sessionFile });
192
+ }
193
+
194
+ return { direct, fallback };
195
+ }
196
+
197
+ private extractResumeSessionId(command: string): string | null {
198
+ const match = command.match(/(?:^|\s)resume\s+([0-9a-f-]{36})(?:\s|$)/i);
199
+ return match?.[1] ?? null;
200
+ }
201
+
202
+ private findSessionFileById(sessionId: string): SessionFile | null {
203
+ for (const filePath of this.collectAllSessionFiles()) {
204
+ if (!path.basename(filePath).includes(sessionId)) continue;
205
+
206
+ const content = safeReadFile(filePath);
207
+ const firstLine = content?.split('\n')[0]?.trim();
208
+ if (!firstLine) continue;
209
+
210
+ try {
211
+ const parsed = JSON.parse(firstLine) as CodexEventEntry;
212
+ if (parsed.type !== 'session_meta' || parsed.payload?.id !== sessionId) {
213
+ continue;
214
+ }
215
+
216
+ const stat = safeStat(filePath);
217
+ if (!stat) continue;
218
+
219
+ return {
220
+ sessionId,
221
+ filePath,
222
+ projectDir: path.dirname(filePath),
223
+ birthtimeMs: stat.birthtimeMs,
224
+ resolvedCwd: parsed.payload.cwd || '',
225
+ };
226
+ } catch {
227
+ continue;
228
+ }
229
+ }
230
+
231
+ return null;
232
+ }
233
+
234
+ private mapDirectMatches(matches: DirectMatch[]): DirectMatchResult {
235
+ const agents: AgentInfo[] = [];
236
+ const failedProcesses: ProcessInfo[] = [];
237
+
238
+ for (const match of matches) {
239
+ const sessionData = this.parseSession(undefined, match.sessionFile.filePath);
240
+ if (sessionData) {
241
+ agents.push(this.mapSessionToAgent(sessionData, match.process, match.sessionFile.filePath));
242
+ } else {
243
+ failedProcesses.push(match.process);
244
+ }
245
+ }
246
+
247
+ return { agents, failedProcesses };
248
+ }
249
+
142
250
  /**
143
251
  * Discover session files for the given processes.
144
252
  *
@@ -0,0 +1,453 @@
1
+ /**
2
+ * Copilot Adapter
3
+ *
4
+ * Detects running GitHub Copilot CLI agents by:
5
+ * 1. Finding running copilot processes via shared listAgentProcesses()
6
+ * 2. Enriching with CWD and start times via shared enrichProcesses()
7
+ * 3. Mapping active ~/.copilot/session-state/{sessionId}/inuse.{pid}.lock files to processes
8
+ * 4. Reading events.jsonl as the primary session/conversation source
9
+ * 5. Reading workspace.yaml as a flat fallback metadata source
10
+ */
11
+
12
+ import * as path from 'path';
13
+ import type {
14
+ AgentAdapter,
15
+ AgentInfo,
16
+ ConversationMessage,
17
+ ListSessionsOptions,
18
+ ProcessInfo,
19
+ SessionSummary,
20
+ } from './AgentAdapter.js';
21
+ import { AgentStatus } from './AgentAdapter.js';
22
+ import { enrichProcesses, listAgentProcesses } from '../utils/process.js';
23
+ import { generateAgentName } from '../utils/matching.js';
24
+ import { isDirectory, safeReadFile, safeReaddir, safeStat } from '../utils/session.js';
25
+
26
+ interface CopilotEventEntry {
27
+ type?: string;
28
+ data?: {
29
+ sessionId?: string;
30
+ startTime?: string;
31
+ context?: {
32
+ cwd?: string;
33
+ gitRoot?: string;
34
+ branch?: string;
35
+ };
36
+ content?: string;
37
+ transformedContent?: string;
38
+ message?: string;
39
+ text?: string;
40
+ result?: {
41
+ content?: string;
42
+ detailedContent?: string;
43
+ };
44
+ output?: string;
45
+ };
46
+ timestamp?: string;
47
+ }
48
+
49
+ interface CopilotWorkspace {
50
+ id?: string;
51
+ cwd?: string;
52
+ name?: string;
53
+ createdAt?: Date;
54
+ updatedAt?: Date;
55
+ }
56
+
57
+ interface CopilotSession {
58
+ sessionId: string;
59
+ projectPath: string;
60
+ summary: string;
61
+ sessionStart: Date;
62
+ lastActive: Date;
63
+ lastEventType?: string;
64
+ firstUserMessage: string;
65
+ eventsFilePath: string;
66
+ }
67
+
68
+ interface CopilotLock {
69
+ sessionDir: string;
70
+ sessionId: string;
71
+ pid: number;
72
+ }
73
+
74
+ interface CopilotSessionDir {
75
+ sessionDir: string;
76
+ sessionId: string;
77
+ }
78
+
79
+ interface CopilotEventSummary {
80
+ sessionId: string;
81
+ projectPath: string;
82
+ sessionStart: Date;
83
+ lastActive: Date;
84
+ firstUserMessage: string;
85
+ lastText: string;
86
+ lastEventType?: string;
87
+ }
88
+
89
+ export class CopilotAdapter implements AgentAdapter {
90
+ readonly type = 'copilot' as const;
91
+
92
+ private static readonly IDLE_THRESHOLD_MINUTES = 5;
93
+ private static readonly VERBOSE_SYSTEM_EVENTS = new Set([
94
+ 'system.message',
95
+ 'session.info',
96
+ 'session.warning',
97
+ 'tool.execution_start',
98
+ 'tool.execution_complete',
99
+ 'function',
100
+ 'abort',
101
+ ]);
102
+ private static readonly WAITING_EVENTS = new Set([
103
+ 'assistant.message',
104
+ 'assistant.turn_end',
105
+ 'session.shutdown',
106
+ 'abort',
107
+ ]);
108
+
109
+ private sessionStateDir: string;
110
+
111
+ constructor() {
112
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
113
+ this.sessionStateDir = path.join(homeDir, '.copilot', 'session-state');
114
+ }
115
+
116
+ canHandle(processInfo: ProcessInfo): boolean {
117
+ return this.isCopilotExecutable(processInfo.command);
118
+ }
119
+
120
+ async detectAgents(): Promise<AgentInfo[]> {
121
+ const processes = enrichProcesses(listAgentProcesses('copilot'));
122
+ if (processes.length === 0) return [];
123
+
124
+ const processByPid = new Map(processes.map((proc) => [proc.pid, proc]));
125
+ const matchedPids = new Set<number>();
126
+ const matchedProcesses: ProcessInfo[] = [];
127
+ const agents: AgentInfo[] = [];
128
+
129
+ for (const lock of this.discoverActiveLocks()) {
130
+ const proc = processByPid.get(lock.pid);
131
+ if (!proc) continue;
132
+
133
+ const session = this.readSessionDir(lock.sessionDir, lock.sessionId);
134
+ if (!session) continue;
135
+
136
+ agents.push(this.mapSessionToAgent(session, proc));
137
+ matchedPids.add(proc.pid);
138
+ matchedProcesses.push(proc);
139
+ }
140
+
141
+ for (const proc of processes) {
142
+ if (!matchedPids.has(proc.pid) && !this.isDuplicateProcess(proc, matchedProcesses)) {
143
+ agents.push(this.mapProcessOnlyAgent(proc));
144
+ }
145
+ }
146
+
147
+ return agents;
148
+ }
149
+
150
+ private isDuplicateProcess(proc: ProcessInfo, matchedProcesses: ProcessInfo[]): boolean {
151
+ return matchedProcesses.some((matched) => {
152
+ if (proc.pid === matched.pid) return true;
153
+
154
+ const sameTty = proc.tty !== '' && proc.tty !== '?' && proc.tty === matched.tty;
155
+ const sameCwd = proc.cwd !== '' && proc.cwd === matched.cwd;
156
+
157
+ return sameTty && (sameCwd || proc.cwd === '' || matched.cwd === '');
158
+ });
159
+ }
160
+
161
+ getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {
162
+ const verbose = options?.verbose ?? false;
163
+ const content = safeReadFile(sessionFilePath);
164
+ if (content === undefined) return [];
165
+
166
+ const messages: ConversationMessage[] = [];
167
+
168
+ for (const entry of this.parseEventLines(content)) {
169
+ const role = this.roleForEvent(entry.type, verbose);
170
+ if (!role) continue;
171
+
172
+ const text = this.extractEventText(entry, verbose);
173
+ if (!text) continue;
174
+
175
+ messages.push({
176
+ role,
177
+ content: text,
178
+ timestamp: entry.timestamp,
179
+ });
180
+ }
181
+
182
+ return messages;
183
+ }
184
+
185
+ async listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]> {
186
+ const summaries: SessionSummary[] = [];
187
+
188
+ for (const { sessionDir, sessionId } of this.listSessionDirs()) {
189
+ const session = this.readSessionDir(sessionDir, sessionId);
190
+ if (!session) continue;
191
+ if (opts?.cwd !== undefined && session.projectPath !== opts.cwd) continue;
192
+
193
+ summaries.push({
194
+ type: this.type,
195
+ sessionId: session.sessionId,
196
+ cwd: session.projectPath,
197
+ firstUserMessage: session.firstUserMessage,
198
+ lastActive: session.lastActive,
199
+ startedAt: session.sessionStart,
200
+ sessionFilePath: session.eventsFilePath,
201
+ });
202
+ }
203
+
204
+ return summaries;
205
+ }
206
+
207
+ private listSessionDirs(): CopilotSessionDir[] {
208
+ if (!isDirectory(this.sessionStateDir)) return [];
209
+
210
+ const sessionDirs: CopilotSessionDir[] = [];
211
+ for (const sessionId of safeReaddir(this.sessionStateDir)) {
212
+ const sessionDir = path.join(this.sessionStateDir, sessionId);
213
+ if (!isDirectory(sessionDir)) continue;
214
+
215
+ sessionDirs.push({ sessionDir, sessionId });
216
+ }
217
+
218
+ return sessionDirs;
219
+ }
220
+
221
+ private discoverActiveLocks(): CopilotLock[] {
222
+ const locks: CopilotLock[] = [];
223
+ for (const { sessionDir, sessionId } of this.listSessionDirs()) {
224
+ for (const entry of safeReaddir(sessionDir)) {
225
+ const match = entry.match(/^inuse\.(\d+)\.lock$/);
226
+ if (!match) continue;
227
+
228
+ const pid = Number.parseInt(match[1], 10);
229
+ if (!Number.isFinite(pid)) continue;
230
+ locks.push({ sessionDir, sessionId, pid });
231
+ }
232
+ }
233
+
234
+ return locks;
235
+ }
236
+
237
+ private readSessionDir(sessionDir: string, fallbackSessionId: string): CopilotSession | null {
238
+ const eventsFilePath = path.join(sessionDir, 'events.jsonl');
239
+ const workspace = this.readWorkspace(path.join(sessionDir, 'workspace.yaml'));
240
+ const entries = this.readEvents(eventsFilePath);
241
+ if (entries.length === 0 && !this.hasWorkspaceMetadata(workspace)) {
242
+ return null;
243
+ }
244
+
245
+ const fileStat = safeStat(eventsFilePath);
246
+ const sessionStart = workspace.createdAt || fileStat?.birthtime || new Date();
247
+ const eventSummary = this.summarizeEvents(entries, {
248
+ sessionId: workspace.id || fallbackSessionId,
249
+ projectPath: workspace.cwd || '',
250
+ sessionStart,
251
+ lastActive: workspace.updatedAt || fileStat?.mtime || sessionStart,
252
+ firstUserMessage: '',
253
+ lastText: '',
254
+ });
255
+
256
+ const summary = eventSummary.firstUserMessage || eventSummary.lastText || workspace.name || 'Copilot session active';
257
+
258
+ return {
259
+ sessionId: eventSummary.sessionId,
260
+ projectPath: eventSummary.projectPath,
261
+ summary: this.truncate(summary, 120),
262
+ sessionStart: eventSummary.sessionStart,
263
+ lastActive: eventSummary.lastActive,
264
+ lastEventType: eventSummary.lastEventType,
265
+ firstUserMessage: eventSummary.firstUserMessage,
266
+ eventsFilePath,
267
+ };
268
+ }
269
+
270
+ private readEvents(eventsFilePath: string): CopilotEventEntry[] {
271
+ const content = safeReadFile(eventsFilePath);
272
+ return content === undefined ? [] : this.parseEventLines(content);
273
+ }
274
+
275
+ private summarizeEvents(entries: CopilotEventEntry[], initial: CopilotEventSummary): CopilotEventSummary {
276
+ const summary = { ...initial };
277
+ for (const entry of entries) {
278
+ const timestamp = this.parseTimestamp(entry.timestamp);
279
+ if (timestamp) {
280
+ summary.lastActive = timestamp;
281
+ }
282
+ if (entry.type) {
283
+ summary.lastEventType = entry.type;
284
+ }
285
+
286
+ if (entry.type === 'session.start') {
287
+ summary.sessionId = entry.data?.sessionId || summary.sessionId;
288
+ summary.projectPath = entry.data?.context?.cwd || summary.projectPath;
289
+ summary.sessionStart = this.parseTimestamp(entry.data?.startTime) || timestamp || summary.sessionStart;
290
+ continue;
291
+ }
292
+
293
+ const text = this.extractEventText(entry, false);
294
+ if (!text) continue;
295
+
296
+ if (!summary.firstUserMessage && entry.type === 'user.message') {
297
+ summary.firstUserMessage = text;
298
+ }
299
+
300
+ if (entry.type === 'user.message' || entry.type === 'assistant.message') {
301
+ summary.lastText = text;
302
+ }
303
+ }
304
+
305
+ return summary;
306
+ }
307
+
308
+ private hasWorkspaceMetadata(workspace: CopilotWorkspace): boolean {
309
+ return Boolean(
310
+ workspace.id ||
311
+ workspace.cwd ||
312
+ workspace.name ||
313
+ workspace.createdAt ||
314
+ workspace.updatedAt,
315
+ );
316
+ }
317
+
318
+ private readWorkspace(filePath: string): CopilotWorkspace {
319
+ const content = safeReadFile(filePath);
320
+ if (content === undefined) return {};
321
+
322
+ const values = new Map<string, string>();
323
+ for (const rawLine of content.split('\n')) {
324
+ const line = rawLine.trim();
325
+ if (!line || line.startsWith('#')) continue;
326
+
327
+ const idx = line.indexOf(':');
328
+ if (idx === -1) continue;
329
+
330
+ const key = line.slice(0, idx).trim();
331
+ const value = this.stripYamlScalar(line.slice(idx + 1).trim());
332
+ values.set(key, value);
333
+ }
334
+
335
+ return {
336
+ id: values.get('id'),
337
+ cwd: values.get('cwd'),
338
+ name: values.get('name'),
339
+ createdAt: this.parseTimestamp(values.get('created_at')) || undefined,
340
+ updatedAt: this.parseTimestamp(values.get('updated_at')) || undefined,
341
+ };
342
+ }
343
+
344
+ private stripYamlScalar(value: string): string {
345
+ if (
346
+ (value.startsWith('"') && value.endsWith('"')) ||
347
+ (value.startsWith("'") && value.endsWith("'"))
348
+ ) {
349
+ return value.slice(1, -1);
350
+ }
351
+ return value;
352
+ }
353
+
354
+ private parseEventLines(content: string): CopilotEventEntry[] {
355
+ const entries: CopilotEventEntry[] = [];
356
+ for (const line of content.trim().split('\n')) {
357
+ const trimmed = line.trim();
358
+ if (!trimmed) continue;
359
+
360
+ try {
361
+ entries.push(JSON.parse(trimmed) as CopilotEventEntry);
362
+ } catch {
363
+ continue;
364
+ }
365
+ }
366
+ return entries;
367
+ }
368
+
369
+ private roleForEvent(type: string | undefined, verbose: boolean): ConversationMessage['role'] | null {
370
+ if (type === 'user.message') return 'user';
371
+ if (type === 'assistant.message') return 'assistant';
372
+ if (verbose && type !== undefined && CopilotAdapter.VERBOSE_SYSTEM_EVENTS.has(type)) {
373
+ return 'system';
374
+ }
375
+ return null;
376
+ }
377
+
378
+ private extractEventText(entry: CopilotEventEntry, verbose: boolean): string {
379
+ const data = entry.data;
380
+ if (!data) return '';
381
+
382
+ const raw =
383
+ data.content ||
384
+ data.message ||
385
+ data.text ||
386
+ data.result?.content ||
387
+ data.result?.detailedContent ||
388
+ (verbose ? data.output : '') ||
389
+ '';
390
+
391
+ if (typeof raw !== 'string') return '';
392
+ return raw.trim();
393
+ }
394
+
395
+ private mapSessionToAgent(session: CopilotSession, proc: ProcessInfo): AgentInfo {
396
+ const projectPath = session.projectPath || proc.cwd || '';
397
+ return {
398
+ name: generateAgentName(projectPath, proc.pid),
399
+ type: this.type,
400
+ status: this.determineStatus(session),
401
+ summary: session.summary || 'Copilot session active',
402
+ pid: proc.pid,
403
+ projectPath,
404
+ sessionId: session.sessionId,
405
+ lastActive: session.lastActive,
406
+ sessionFilePath: session.eventsFilePath,
407
+ };
408
+ }
409
+
410
+ private mapProcessOnlyAgent(proc: ProcessInfo): AgentInfo {
411
+ return {
412
+ name: generateAgentName(proc.cwd || '', proc.pid),
413
+ type: this.type,
414
+ status: AgentStatus.RUNNING,
415
+ summary: 'Copilot process running',
416
+ pid: proc.pid,
417
+ projectPath: proc.cwd || '',
418
+ sessionId: `pid-${proc.pid}`,
419
+ lastActive: new Date(),
420
+ };
421
+ }
422
+
423
+ private determineStatus(session: CopilotSession): AgentStatus {
424
+ const diffMs = Date.now() - session.lastActive.getTime();
425
+ const diffMinutes = diffMs / 60000;
426
+ if (diffMinutes > CopilotAdapter.IDLE_THRESHOLD_MINUTES) {
427
+ return AgentStatus.IDLE;
428
+ }
429
+
430
+ if (session.lastEventType !== undefined && CopilotAdapter.WAITING_EVENTS.has(session.lastEventType)) {
431
+ return AgentStatus.WAITING;
432
+ }
433
+
434
+ return AgentStatus.RUNNING;
435
+ }
436
+
437
+ private parseTimestamp(value?: string): Date | null {
438
+ if (!value) return null;
439
+ const timestamp = new Date(value);
440
+ return Number.isNaN(timestamp.getTime()) ? null : timestamp;
441
+ }
442
+
443
+ private truncate(value: string, maxLength: number): string {
444
+ if (value.length <= maxLength) return value;
445
+ return `${value.slice(0, maxLength - 3)}...`;
446
+ }
447
+
448
+ private isCopilotExecutable(command: string): boolean {
449
+ const executable = command.trim().split(/\s+/)[0] || '';
450
+ const base = path.basename(executable).toLowerCase();
451
+ return base === 'copilot' || base === 'copilot.exe';
452
+ }
453
+ }