@ai-devkit/agent-manager 0.17.0 → 0.18.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.
@@ -277,22 +277,73 @@ describe('CodexAdapter', () => {
277
277
 
278
278
  (adapter as any).codexSessionsDir = sessionsDir;
279
279
  mockedBatchGetSessionFileBirthtimes.mockReturnValue([]);
280
+ const collectAllSpy = vi.spyOn(adapter as any, 'collectAllSessionFiles');
280
281
 
281
- const agents = await adapter.detectAgents();
282
+ try {
283
+ const agents = await adapter.detectAgents();
282
284
 
283
- expect(mockedBatchGetSessionFileBirthtimes).not.toHaveBeenCalled();
284
- expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled();
285
- expect(agents).toHaveLength(1);
286
- expect(agents[0]).toMatchObject({
287
- type: 'codex',
288
- pid: 88018,
289
- sessionId,
290
- projectPath: '/repo-a',
291
- sessionFilePath: sessionFile,
292
- });
293
- expect(agents[0].summary).toBe('resumed codex conversation');
285
+ expect(mockedBatchGetSessionFileBirthtimes).not.toHaveBeenCalled();
286
+ expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled();
287
+ expect(collectAllSpy).not.toHaveBeenCalled();
288
+ expect(agents).toHaveLength(1);
289
+ expect(agents[0]).toMatchObject({
290
+ type: 'codex',
291
+ pid: 88018,
292
+ sessionId,
293
+ projectPath: '/repo-a',
294
+ sessionFilePath: sessionFile,
295
+ });
296
+ expect(agents[0].summary).toBe('resumed codex conversation');
297
+ } finally {
298
+ collectAllSpy.mockRestore();
299
+ fs.rmSync(tmpDir, { recursive: true, force: true });
300
+ }
301
+ });
294
302
 
295
- fs.rmSync(tmpDir, { recursive: true, force: true });
303
+ it('should fall back to all session files for non-time-sortable resume ids', async () => {
304
+ const sessionId = 'aaaaaaaa-bbbb-4ccc-dddd-eeeeeeeeeeee';
305
+ const processes: ProcessInfo[] = [
306
+ {
307
+ pid: 88020,
308
+ command: `codex resume ${sessionId}`,
309
+ cwd: '/repo-a',
310
+ tty: 'ttys001',
311
+ startTime: new Date('2026-06-10T12:00:00.000Z'),
312
+ },
313
+ ];
314
+ mockedListAgentProcesses.mockReturnValue(processes);
315
+ mockedEnrichProcesses.mockReturnValue(processes);
316
+
317
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-resume-v4-'));
318
+ const sessionsDir = path.join(tmpDir, 'sessions');
319
+ const dateDir = path.join(sessionsDir, '2026', '01', '02');
320
+ fs.mkdirSync(dateDir, { recursive: true });
321
+
322
+ const recentTs = new Date().toISOString();
323
+ const sessionFile = path.join(dateDir, `${sessionId}.jsonl`);
324
+ fs.writeFileSync(sessionFile, [
325
+ JSON.stringify({ type: 'session_meta', payload: { id: sessionId, timestamp: recentTs, cwd: '/repo-a' } }),
326
+ JSON.stringify({ type: 'event', timestamp: recentTs, payload: { type: 'agent_message', message: 'legacy id conversation' } }),
327
+ ].join('\n'));
328
+
329
+ (adapter as any).codexSessionsDir = sessionsDir;
330
+ mockedBatchGetSessionFileBirthtimes.mockReturnValue([]);
331
+ const collectAllSpy = vi.spyOn(adapter as any, 'collectAllSessionFiles');
332
+
333
+ try {
334
+ const agents = await adapter.detectAgents();
335
+
336
+ expect(collectAllSpy).toHaveBeenCalledOnce();
337
+ expect(agents).toHaveLength(1);
338
+ expect(agents[0]).toMatchObject({
339
+ pid: 88020,
340
+ sessionId,
341
+ sessionFilePath: sessionFile,
342
+ });
343
+ } finally {
344
+ collectAllSpy.mockRestore();
345
+ fs.rmSync(tmpDir, { recursive: true, force: true });
346
+ }
296
347
  });
297
348
 
298
349
  it('should fall back to process-only when a resumed session becomes unreadable after direct matching', async () => {
@@ -0,0 +1,435 @@
1
+ /**
2
+ * Tests for PiAdapter
3
+ */
4
+
5
+ import type { MockedFunction } from 'vitest';
6
+ import * as fs from 'fs';
7
+ import * as os from 'os';
8
+ import * as path from 'path';
9
+
10
+ import { PiAdapter } from '../../adapters/PiAdapter.js';
11
+ import type { ProcessInfo } from '../../adapters/AgentAdapter.js';
12
+ import { AgentStatus } from '../../adapters/AgentAdapter.js';
13
+ import { AgentRegistry } from '../../utils/AgentRegistry.js';
14
+ import { listAgentProcesses, enrichProcesses } from '../../utils/process.js';
15
+ import { matchProcessesToSessions, generateAgentName } from '../../utils/matching.js';
16
+
17
+ vi.mock('../../utils/process.js', () => ({
18
+ listAgentProcesses: vi.fn(),
19
+ enrichProcesses: vi.fn(),
20
+ }));
21
+
22
+ vi.mock('../../utils/matching.js', () => ({
23
+ matchProcessesToSessions: vi.fn(),
24
+ generateAgentName: vi.fn(),
25
+ }));
26
+
27
+ const mockedListAgentProcesses = listAgentProcesses as MockedFunction<typeof listAgentProcesses>;
28
+ const mockedEnrichProcesses = enrichProcesses as MockedFunction<typeof enrichProcesses>;
29
+ const mockedMatchProcessesToSessions = matchProcessesToSessions as MockedFunction<typeof matchProcessesToSessions>;
30
+ const mockedGenerateAgentName = generateAgentName as MockedFunction<typeof generateAgentName>;
31
+
32
+ describe('PiAdapter', () => {
33
+ let adapter: PiAdapter;
34
+ let tmpHome: string;
35
+ let sessionsDir: string;
36
+
37
+ beforeEach(() => {
38
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'pi-adapter-test-'));
39
+ process.env.HOME = tmpHome;
40
+ sessionsDir = path.join(tmpHome, '.pi', 'agent', 'sessions');
41
+ fs.mkdirSync(sessionsDir, { recursive: true });
42
+
43
+ adapter = new PiAdapter(new AgentRegistry(path.join(tmpHome, 'agents.json')));
44
+ mockedListAgentProcesses.mockReset();
45
+ mockedEnrichProcesses.mockReset();
46
+ mockedMatchProcessesToSessions.mockReset();
47
+ mockedGenerateAgentName.mockReset();
48
+
49
+ mockedEnrichProcesses.mockImplementation((procs) => procs);
50
+ mockedMatchProcessesToSessions.mockReturnValue([]);
51
+ mockedGenerateAgentName.mockImplementation((cwd: string, pid: number) => {
52
+ const folder = path.basename(cwd) || 'unknown';
53
+ return `${folder} (${pid})`;
54
+ });
55
+ });
56
+
57
+ afterEach(() => {
58
+ fs.rmSync(tmpHome, { recursive: true, force: true });
59
+ });
60
+
61
+ it('exposes pi type', () => {
62
+ expect(adapter.type).toBe('pi');
63
+ });
64
+
65
+ it('identifies Pi commands without matching unrelated paths', () => {
66
+ expect(adapter.canHandle({ pid: 1, command: 'pi', cwd: '/repo', tty: 'ttys001' })).toBe(true);
67
+ expect(adapter.canHandle({ pid: 2, command: '/usr/local/bin/PI --model x', cwd: '/repo', tty: 'ttys002' })).toBe(true);
68
+ expect(adapter.canHandle({ pid: 3, command: 'node /opt/pi/bin/pi.js', cwd: '/repo', tty: 'ttys003' })).toBe(true);
69
+ expect(adapter.canHandle({ pid: 4, command: 'node /repo/feature-pi-adapter/script.js', cwd: '/repo', tty: 'ttys004' })).toBe(false);
70
+ });
71
+
72
+ it('maps a running Pi process to the tracker session for its PID', async () => {
73
+ const cwd = '/repo/project-a';
74
+ const proc = makeProcess({ pid: 101, cwd });
75
+ const sessionFile = writePiSession(cwd, [
76
+ { type: 'session_meta', timestamp: '2026-06-10T08:58:20.754Z', sessionId: 'sess-101', cwd },
77
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'implement Pi adapter' },
78
+ { role: 'assistant', timestamp: new Date().toISOString(), content: 'working on it' },
79
+ ]);
80
+ fs.writeFileSync(
81
+ path.join(tmpHome, '.pi', 'agent', 'sessions.json'),
82
+ JSON.stringify({ 101: sessionFile }),
83
+ );
84
+ mockedListAgentProcesses.mockReturnValue([proc]);
85
+
86
+ const agents = await adapter.detectAgents();
87
+
88
+ expect(agents).toHaveLength(1);
89
+ expect(agents[0]).toMatchObject({
90
+ type: 'pi',
91
+ pid: 101,
92
+ projectPath: cwd,
93
+ sessionId: 'sess-101',
94
+ summary: 'implement Pi adapter',
95
+ status: AgentStatus.WAITING,
96
+ sessionFilePath: sessionFile,
97
+ });
98
+ expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled();
99
+ });
100
+
101
+ it('truncates long user prompts in detected agent summaries', async () => {
102
+ const cwd = '/repo/project-long-summary';
103
+ const proc = makeProcess({ pid: 112, cwd });
104
+ const longPrompt = 'x'.repeat(140);
105
+ const sessionFile = writePiSession(cwd, [
106
+ { type: 'session', timestamp: '2026-06-10T08:58:20.754Z', id: 'sess-long', cwd },
107
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: longPrompt },
108
+ ]);
109
+ fs.writeFileSync(
110
+ path.join(tmpHome, '.pi', 'agent', 'sessions.json'),
111
+ JSON.stringify({ 112: sessionFile }),
112
+ );
113
+ mockedListAgentProcesses.mockReturnValue([proc]);
114
+
115
+ const agents = await adapter.detectAgents();
116
+
117
+ expect(agents[0].summary).toHaveLength(120);
118
+ expect(agents[0].summary.endsWith('...')).toBe(true);
119
+ });
120
+
121
+ it('uses the filename session id fallback and reports running when the latest message is from the user', async () => {
122
+ const cwd = '/repo/project-filename-fallback';
123
+ const proc = makeProcess({ pid: 113, cwd });
124
+ const sessionFile = writePiSessionWithFileName(cwd, 'plain-session.jsonl', [
125
+ { role: 'user', timestamp: new Date().toISOString(), content: 'still working' },
126
+ ]);
127
+ fs.writeFileSync(
128
+ path.join(tmpHome, '.pi', 'agent', 'sessions.json'),
129
+ JSON.stringify({ 113: sessionFile }),
130
+ );
131
+ mockedListAgentProcesses.mockReturnValue([proc]);
132
+
133
+ const agents = await adapter.detectAgents();
134
+
135
+ expect(agents[0]).toMatchObject({
136
+ sessionId: 'plain-session',
137
+ summary: 'still working',
138
+ status: AgentStatus.RUNNING,
139
+ });
140
+ });
141
+
142
+ it('falls back to legacy matching when sessions.json is missing', async () => {
143
+ const cwd = '/repo/project-b';
144
+ const proc = makeProcess({ pid: 202, cwd });
145
+ const sessionFile = writePiSession(cwd, [
146
+ { timestamp: '2026-06-10T08:58:20.754Z', sessionId: 'sess-202' },
147
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'fallback matching please' },
148
+ ]);
149
+ mockedListAgentProcesses.mockReturnValue([proc]);
150
+ mockedMatchProcessesToSessions.mockReturnValue([
151
+ {
152
+ process: proc,
153
+ session: {
154
+ sessionId: 'sess-202',
155
+ filePath: sessionFile,
156
+ projectDir: path.dirname(sessionFile),
157
+ birthtimeMs: Date.now(),
158
+ resolvedCwd: cwd,
159
+ },
160
+ deltaMs: 0,
161
+ },
162
+ ]);
163
+
164
+ const agents = await adapter.detectAgents();
165
+
166
+ expect(agents).toHaveLength(1);
167
+ expect(agents[0]).toMatchObject({
168
+ type: 'pi',
169
+ pid: 202,
170
+ projectPath: cwd,
171
+ sessionId: 'sess-202',
172
+ summary: 'fallback matching please',
173
+ });
174
+ expect(mockedMatchProcessesToSessions).toHaveBeenCalledWith(
175
+ [proc],
176
+ expect.arrayContaining([
177
+ expect.objectContaining({ filePath: sessionFile, resolvedCwd: cwd }),
178
+ ]),
179
+ );
180
+ });
181
+
182
+ it('ignores malformed tracker metadata and still falls back to legacy matching', async () => {
183
+ const cwd = '/repo/project-c';
184
+ const proc = makeProcess({ pid: 303, cwd });
185
+ const sessionFile = writePiSession(cwd, [
186
+ { timestamp: '2026-06-10T08:58:20.754Z', sessionId: 'sess-303', cwd },
187
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'recover from bad tracker' },
188
+ ]);
189
+ fs.writeFileSync(path.join(tmpHome, '.pi', 'agent', 'sessions.json'), '{bad json');
190
+ mockedListAgentProcesses.mockReturnValue([proc]);
191
+ mockedMatchProcessesToSessions.mockReturnValue([
192
+ {
193
+ process: proc,
194
+ session: {
195
+ sessionId: 'sess-303',
196
+ filePath: sessionFile,
197
+ projectDir: path.dirname(sessionFile),
198
+ birthtimeMs: Date.now(),
199
+ resolvedCwd: cwd,
200
+ },
201
+ deltaMs: 0,
202
+ },
203
+ ]);
204
+
205
+ const agents = await adapter.detectAgents();
206
+
207
+ expect(agents).toHaveLength(1);
208
+ expect(agents[0].sessionId).toBe('sess-303');
209
+ });
210
+
211
+ it('falls back to legacy matching when a trusted tracker session is unparseable', async () => {
212
+ const cwd = '/repo/project-bad-tracker-session';
213
+ const proc = makeProcess({ pid: 304, cwd });
214
+ const badSessionFile = writePiSessionWithFileName(cwd, 'bad.jsonl', ['{not json']);
215
+ const fallbackSessionFile = writePiSession(cwd, [
216
+ { timestamp: '2026-06-10T08:58:20.754Z', sessionId: 'sess-304', cwd },
217
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'fallback after bad tracker session' },
218
+ ]);
219
+ fs.writeFileSync(
220
+ path.join(tmpHome, '.pi', 'agent', 'sessions.json'),
221
+ JSON.stringify({ 304: badSessionFile }),
222
+ );
223
+ mockedListAgentProcesses.mockReturnValue([proc]);
224
+ mockedMatchProcessesToSessions.mockReturnValue([
225
+ {
226
+ process: proc,
227
+ session: {
228
+ sessionId: 'sess-304',
229
+ filePath: fallbackSessionFile,
230
+ projectDir: path.dirname(fallbackSessionFile),
231
+ birthtimeMs: Date.now(),
232
+ resolvedCwd: cwd,
233
+ },
234
+ deltaMs: 0,
235
+ },
236
+ ]);
237
+
238
+ const agents = await adapter.detectAgents();
239
+
240
+ expect(agents).toHaveLength(1);
241
+ expect(agents[0]).toMatchObject({
242
+ sessionId: 'sess-304',
243
+ summary: 'fallback after bad tracker session',
244
+ sessionFilePath: fallbackSessionFile,
245
+ });
246
+ expect(mockedMatchProcessesToSessions).toHaveBeenCalled();
247
+ });
248
+
249
+ it('does not trust tracker paths outside the Pi sessions directory', async () => {
250
+ const cwd = '/repo/project-d';
251
+ const proc = makeProcess({ pid: 404, cwd });
252
+ const outside = path.join(tmpHome, 'outside.jsonl');
253
+ fs.writeFileSync(outside, JSON.stringify({ role: 'user', content: 'nope' }));
254
+ fs.writeFileSync(
255
+ path.join(tmpHome, '.pi', 'agent', 'sessions.json'),
256
+ JSON.stringify({ 404: outside }),
257
+ );
258
+ mockedListAgentProcesses.mockReturnValue([proc]);
259
+
260
+ const agents = await adapter.detectAgents();
261
+
262
+ expect(agents).toHaveLength(1);
263
+ expect(agents[0]).toMatchObject({
264
+ type: 'pi',
265
+ pid: 404,
266
+ sessionId: 'pid-404',
267
+ summary: 'Pi process running',
268
+ });
269
+ });
270
+
271
+ it('returns a process-only agent when no session can be matched', async () => {
272
+ const proc = makeProcess({ pid: 505, cwd: '/repo/project-e' });
273
+ mockedListAgentProcesses.mockReturnValue([proc]);
274
+
275
+ const agents = await adapter.detectAgents();
276
+
277
+ expect(agents).toHaveLength(1);
278
+ expect(agents[0]).toMatchObject({
279
+ type: 'pi',
280
+ status: AgentStatus.RUNNING,
281
+ pid: 505,
282
+ projectPath: '/repo/project-e',
283
+ sessionId: 'pid-505',
284
+ summary: 'Pi process running',
285
+ });
286
+ });
287
+
288
+ it('reads user and assistant conversation messages from JSONL', () => {
289
+ const cwd = '/repo/project-f';
290
+ const sessionFile = writePiSession(cwd, [
291
+ { role: 'system', timestamp: '2026-06-10T08:58:20.000Z', content: 'hidden' },
292
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'hello pi' },
293
+ { type: 'assistant', timestamp: '2026-06-10T08:58:22.000Z', message: { content: 'hello human' } },
294
+ '{not json',
295
+ ]);
296
+
297
+ expect(adapter.getConversation(sessionFile)).toEqual([
298
+ { role: 'user', content: 'hello pi', timestamp: '2026-06-10T08:58:21.000Z' },
299
+ { role: 'assistant', content: 'hello human', timestamp: '2026-06-10T08:58:22.000Z' },
300
+ ]);
301
+ });
302
+
303
+ it('includes system entries only in verbose conversation mode', () => {
304
+ const cwd = '/repo/project-verbose';
305
+ const sessionFile = writePiSession(cwd, [
306
+ { role: 'system', timestamp: '2026-06-10T08:58:20.000Z', content: 'model changed' },
307
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'visible' },
308
+ ]);
309
+
310
+ expect(adapter.getConversation(sessionFile)).toEqual([
311
+ { role: 'user', content: 'visible', timestamp: '2026-06-10T08:58:21.000Z' },
312
+ ]);
313
+ expect(adapter.getConversation(sessionFile, { verbose: true })).toEqual([
314
+ { role: 'system', content: 'model changed', timestamp: '2026-06-10T08:58:20.000Z' },
315
+ { role: 'user', content: 'visible', timestamp: '2026-06-10T08:58:21.000Z' },
316
+ ]);
317
+ });
318
+
319
+ it('reads real Pi message entries with nested role and text parts', async () => {
320
+ const cwd = '/repo/project-real';
321
+ const proc = makeProcess({ pid: 606, cwd });
322
+ const sessionFile = writePiSession(cwd, [
323
+ { type: 'session', version: 3, id: 'sess-real', timestamp: '2026-06-10T13:27:17.581Z', cwd },
324
+ { type: 'model_change', id: 'model-1', timestamp: '2026-06-10T13:27:17.655Z', modelId: 'claude-sonnet-4-6' },
325
+ {
326
+ type: 'message',
327
+ id: 'msg-user',
328
+ timestamp: '2026-06-10T13:27:37.975Z',
329
+ message: {
330
+ role: 'user',
331
+ content: [{ type: 'text', text: 'hello' }],
332
+ timestamp: 1781098057974,
333
+ },
334
+ },
335
+ {
336
+ type: 'message',
337
+ id: 'msg-assistant',
338
+ timestamp: '2026-06-10T13:27:40.161Z',
339
+ message: {
340
+ role: 'assistant',
341
+ content: [{ type: 'text', text: 'Hello! How can I help you today?' }],
342
+ provider: 'anthropic',
343
+ model: 'claude-sonnet-4-6',
344
+ timestamp: 1781098058012,
345
+ },
346
+ },
347
+ ]);
348
+ fs.writeFileSync(
349
+ path.join(tmpHome, '.pi', 'agent', 'sessions.json'),
350
+ JSON.stringify({ 606: sessionFile }),
351
+ );
352
+ mockedListAgentProcesses.mockReturnValue([proc]);
353
+
354
+ expect(adapter.getConversation(sessionFile)).toEqual([
355
+ { role: 'user', content: 'hello', timestamp: '2026-06-10T13:27:37.975Z' },
356
+ { role: 'assistant', content: 'Hello! How can I help you today?', timestamp: '2026-06-10T13:27:40.161Z' },
357
+ ]);
358
+
359
+ const agents = await adapter.detectAgents();
360
+ expect(agents[0]).toMatchObject({
361
+ sessionId: 'sess-real',
362
+ summary: 'hello',
363
+ lastActive: new Date('2026-06-10T13:27:40.161Z'),
364
+ });
365
+ });
366
+
367
+ it('lists historical sessions and applies cwd filtering', async () => {
368
+ const matchingCwd = '/repo/project-g';
369
+ const otherCwd = '/repo/project-h';
370
+ const matchingSession = writePiSession(matchingCwd, [
371
+ { timestamp: '2026-06-10T08:58:20.754Z', sessionId: 'sess-g', cwd: matchingCwd },
372
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'first matching message' },
373
+ ]);
374
+ writePiSession(otherCwd, [
375
+ { timestamp: '2026-06-10T08:58:20.754Z', sessionId: 'sess-h', cwd: otherCwd },
376
+ { role: 'user', timestamp: '2026-06-10T08:58:21.000Z', content: 'other message' },
377
+ ]);
378
+
379
+ const sessions = await adapter.listSessions({ cwd: matchingCwd });
380
+
381
+ expect(sessions).toEqual([
382
+ expect.objectContaining({
383
+ type: 'pi',
384
+ sessionId: 'sess-g',
385
+ cwd: matchingCwd,
386
+ firstUserMessage: 'first matching message',
387
+ sessionFilePath: matchingSession,
388
+ }),
389
+ ]);
390
+ });
391
+
392
+ function makeProcess(overrides: Partial<ProcessInfo>): ProcessInfo {
393
+ return {
394
+ pid: 1,
395
+ command: 'pi',
396
+ cwd: '/repo',
397
+ tty: 'ttys001',
398
+ startTime: new Date('2026-06-10T08:58:20.000Z'),
399
+ ...overrides,
400
+ };
401
+ }
402
+
403
+ function writePiSession(cwd: string, entries: Array<Record<string, unknown> | string>): string {
404
+ const projectDir = path.join(sessionsDir, encodeProjectDir(cwd));
405
+ fs.mkdirSync(projectDir, { recursive: true });
406
+ const sessionId = entries
407
+ .map((entry) => typeof entry === 'string' ? undefined : entry.sessionId)
408
+ .find((value): value is string => typeof value === 'string') ?? cryptoRandomSessionId();
409
+ const filePath = path.join(projectDir, `2026-06-10T08-58-20-754Z_${sessionId}.jsonl`);
410
+ fs.writeFileSync(
411
+ filePath,
412
+ entries.map((entry) => typeof entry === 'string' ? entry : JSON.stringify(entry)).join('\n'),
413
+ );
414
+ return filePath;
415
+ }
416
+
417
+ function writePiSessionWithFileName(cwd: string, fileName: string, entries: Array<Record<string, unknown> | string>): string {
418
+ const projectDir = path.join(sessionsDir, encodeProjectDir(cwd));
419
+ fs.mkdirSync(projectDir, { recursive: true });
420
+ const filePath = path.join(projectDir, fileName);
421
+ fs.writeFileSync(
422
+ filePath,
423
+ entries.map((entry) => typeof entry === 'string' ? entry : JSON.stringify(entry)).join('\n'),
424
+ );
425
+ return filePath;
426
+ }
427
+
428
+ function encodeProjectDir(cwd: string): string {
429
+ return cwd.replace(/\//g, '-').replace(/^-?/, '--') + '--';
430
+ }
431
+
432
+ function cryptoRandomSessionId(): string {
433
+ return `019eb0c1-06d2-71ed-90ee-${Math.random().toString(16).slice(2, 14).padEnd(12, '0')}`;
434
+ }
435
+ });
@@ -8,7 +8,7 @@
8
8
  /**
9
9
  * Type of AI agent
10
10
  */
11
- export type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'other';
11
+ export type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';
12
12
 
13
13
  /**
14
14
  * Current status of an agent
@@ -200,7 +200,7 @@ export class CodexAdapter implements AgentAdapter {
200
200
  }
201
201
 
202
202
  private findSessionFileById(sessionId: string): SessionFile | null {
203
- for (const filePath of this.collectAllSessionFiles()) {
203
+ for (const filePath of this.getCandidateSessionFiles(sessionId)) {
204
204
  if (!path.basename(filePath).includes(sessionId)) continue;
205
205
 
206
206
  const content = safeReadFile(filePath);
@@ -231,6 +231,17 @@ export class CodexAdapter implements AgentAdapter {
231
231
  return null;
232
232
  }
233
233
 
234
+ private getCandidateSessionFiles(sessionId: string): string[] {
235
+ // Codex currently writes UUIDv7 session IDs, so the ID can narrow lookup
236
+ // to the creation-date directory. Fall back for older or changed formats.
237
+ const sessionDate = this.tryParseUuidV7Date(sessionId);
238
+ if (!sessionDate) return this.collectAllSessionFiles();
239
+
240
+ return this.collectSessionFilesInDateDirs(
241
+ this.getDateDirsAroundDate(sessionDate, CodexAdapter.PROCESS_START_DAY_WINDOW_DAYS),
242
+ );
243
+ }
244
+
234
245
  private mapDirectMatches(matches: DirectMatch[]): DirectMatchResult {
235
246
  const agents: AgentInfo[] = [];
236
247
  const failedProcesses: ProcessInfo[] = [];
@@ -321,6 +332,21 @@ export class CodexAdapter implements AgentAdapter {
321
332
  return dirs;
322
333
  }
323
334
 
335
+ private getDateDirsAroundDate(date: Date, windowDays: number): string[] {
336
+ const dirs: string[] = [];
337
+
338
+ for (let offset = -windowDays; offset <= windowDays; offset++) {
339
+ const day = new Date(date.getTime());
340
+ day.setDate(day.getDate() + offset);
341
+ const dayDir = path.join(this.codexSessionsDir, this.toSessionDayKey(day));
342
+ if (isDirectory(dayDir)) {
343
+ dirs.push(dayDir);
344
+ }
345
+ }
346
+
347
+ return dirs;
348
+ }
349
+
324
350
  private toSessionDayKey(date: Date): string {
325
351
  const yyyy = String(date.getFullYear()).padStart(4, '0');
326
352
  const mm = String(date.getMonth() + 1).padStart(2, '0');
@@ -328,6 +354,17 @@ export class CodexAdapter implements AgentAdapter {
328
354
  return path.join(yyyy, mm, dd);
329
355
  }
330
356
 
357
+ private tryParseUuidV7Date(sessionId: string): Date | null {
358
+ const match = sessionId.match(/^([0-9a-f]{8})-([0-9a-f]{4})-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
359
+ if (!match) return null;
360
+
361
+ const timestampMs = Number.parseInt(`${match[1]}${match[2]}`, 16);
362
+ if (!Number.isSafeInteger(timestampMs) || timestampMs <= 0) return null;
363
+
364
+ const date = new Date(timestampMs);
365
+ return Number.isNaN(date.getTime()) ? null : date;
366
+ }
367
+
331
368
  /**
332
369
  * Parse session file content into CodexSession.
333
370
  * Uses cached content if available, otherwise reads from disk.
@@ -570,6 +607,19 @@ export class CodexAdapter implements AgentAdapter {
570
607
  return out;
571
608
  }
572
609
 
610
+ private collectSessionFilesInDateDirs(dateDirs: string[]): string[] {
611
+ const out: string[] = [];
612
+
613
+ for (const dayDir of dateDirs) {
614
+ for (const fileEntry of safeReaddir(dayDir)) {
615
+ if (!fileEntry.endsWith('.jsonl')) continue;
616
+ out.push(path.join(dayDir, fileEntry));
617
+ }
618
+ }
619
+
620
+ return out;
621
+ }
622
+
573
623
  /**
574
624
  * Read a Codex session JSONL file and produce a {@link SessionSummary}.
575
625
  * Returns null when the file is unreadable, has no `session_meta`, or