@ai-devkit/agent-manager 0.24.0 → 0.25.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.
- package/dist/__tests__/adapters/GrokCliAdapter.test.js +403 -0
- package/dist/__tests__/adapters/GrokCliAdapter.test.js.map +1 -0
- package/dist/__tests__/utils/agents.test.js +6 -0
- package/dist/__tests__/utils/agents.test.js.map +1 -1
- package/dist/adapters/AgentAdapter.d.ts +1 -1
- package/dist/adapters/AgentAdapter.d.ts.map +1 -1
- package/dist/adapters/AgentAdapter.js.map +1 -1
- package/dist/adapters/GrokCliAdapter.d.ts +79 -0
- package/dist/adapters/GrokCliAdapter.d.ts.map +1 -0
- package/dist/adapters/GrokCliAdapter.js +306 -0
- package/dist/adapters/GrokCliAdapter.js.map +1 -0
- package/dist/adapters/index.d.ts +1 -0
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -0
- package/dist/adapters/index.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/utils/agents.d.ts +1 -1
- package/dist/utils/agents.d.ts.map +1 -1
- package/dist/utils/agents.js +4 -0
- package/dist/utils/agents.js.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/adapters/GrokCliAdapter.test.ts +307 -0
- package/src/__tests__/utils/agents.test.ts +7 -0
- package/src/adapters/AgentAdapter.ts +1 -1
- package/src/adapters/GrokCliAdapter.ts +394 -0
- package/src/adapters/index.ts +1 -0
- package/src/index.ts +1 -0
- package/src/utils/agents.ts +2 -1
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for GrokCliAdapter
|
|
3
|
+
*
|
|
4
|
+
* The adapter resolves a live process to its cwd via ~/.grok/active_sessions.json
|
|
5
|
+
* and reads session details from chat_history.jsonl (not summary.json/updates.jsonl).
|
|
6
|
+
*/ import * as fs from 'fs';
|
|
7
|
+
import * as os from 'os';
|
|
8
|
+
import * as path from 'path';
|
|
9
|
+
import { GrokCliAdapter } from '../../adapters/GrokCliAdapter.js';
|
|
10
|
+
import { AgentStatus } from '../../adapters/AgentAdapter.js';
|
|
11
|
+
import { listAgentProcesses, enrichProcesses } from '../../utils/process.js';
|
|
12
|
+
import { generateAgentName } from '../../utils/matching.js';
|
|
13
|
+
vi.mock('../../utils/process.js', async (importOriginal)=>{
|
|
14
|
+
const actual = await importOriginal();
|
|
15
|
+
return {
|
|
16
|
+
...actual,
|
|
17
|
+
listAgentProcesses: vi.fn(),
|
|
18
|
+
enrichProcesses: vi.fn()
|
|
19
|
+
};
|
|
20
|
+
});
|
|
21
|
+
vi.mock('../../utils/matching.js', async (importOriginal)=>{
|
|
22
|
+
const actual = await importOriginal();
|
|
23
|
+
return {
|
|
24
|
+
...actual,
|
|
25
|
+
generateAgentName: vi.fn()
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
const mockedListAgentProcesses = listAgentProcesses;
|
|
29
|
+
const mockedEnrichProcesses = enrichProcesses;
|
|
30
|
+
const mockedGenerateAgentName = generateAgentName;
|
|
31
|
+
const SESSION_ID = '019f16c3-5d5d-7dc3-85d1-bc629416ca2d';
|
|
32
|
+
/** A user transcript record: the real prompt wrapped in <user_query> like Grok writes it. */ const userRecord = (text)=>({
|
|
33
|
+
type: 'user',
|
|
34
|
+
content: [
|
|
35
|
+
{
|
|
36
|
+
type: 'text',
|
|
37
|
+
text: `<user_query>\n${text}\n</user_query>`
|
|
38
|
+
}
|
|
39
|
+
]
|
|
40
|
+
});
|
|
41
|
+
/** A user context-injection record (no <user_query>) — should be ignored as a prompt. */ const contextRecord = (text)=>({
|
|
42
|
+
type: 'user',
|
|
43
|
+
content: [
|
|
44
|
+
{
|
|
45
|
+
type: 'text',
|
|
46
|
+
text
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
});
|
|
50
|
+
const assistantRecord = (text)=>({
|
|
51
|
+
type: 'assistant',
|
|
52
|
+
content: [
|
|
53
|
+
{
|
|
54
|
+
type: 'text',
|
|
55
|
+
text
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
});
|
|
59
|
+
const systemRecord = (text)=>({
|
|
60
|
+
type: 'system',
|
|
61
|
+
content: text
|
|
62
|
+
});
|
|
63
|
+
describe('GrokCliAdapter', ()=>{
|
|
64
|
+
let adapter;
|
|
65
|
+
let tmpHome;
|
|
66
|
+
let cwd;
|
|
67
|
+
beforeEach(()=>{
|
|
68
|
+
tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-adapter-test-'));
|
|
69
|
+
process.env.HOME = tmpHome;
|
|
70
|
+
delete process.env.GROK_HOME;
|
|
71
|
+
cwd = '/Users/dev/my-project';
|
|
72
|
+
adapter = new GrokCliAdapter();
|
|
73
|
+
mockedListAgentProcesses.mockReset();
|
|
74
|
+
mockedEnrichProcesses.mockReset();
|
|
75
|
+
mockedGenerateAgentName.mockReset();
|
|
76
|
+
mockedEnrichProcesses.mockImplementation((procs)=>procs);
|
|
77
|
+
mockedGenerateAgentName.mockImplementation((c, pid)=>`${path.basename(c) || 'unknown'}-${pid}`);
|
|
78
|
+
});
|
|
79
|
+
afterEach(()=>{
|
|
80
|
+
fs.rmSync(tmpHome, {
|
|
81
|
+
recursive: true,
|
|
82
|
+
force: true
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
/** Write a session dir under ~/.grok/sessions/<enc(cwd)>/<id>/chat_history.jsonl. */ function writeSession(opts) {
|
|
86
|
+
const sessionCwd = opts.sessionCwd ?? cwd;
|
|
87
|
+
const id = opts.id ?? SESSION_ID;
|
|
88
|
+
const sessionDir = path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(sessionCwd), id);
|
|
89
|
+
fs.mkdirSync(sessionDir, {
|
|
90
|
+
recursive: true
|
|
91
|
+
});
|
|
92
|
+
if (opts.chat !== false) {
|
|
93
|
+
const records = opts.records ?? [
|
|
94
|
+
userRecord('fix the bug')
|
|
95
|
+
];
|
|
96
|
+
const chatPath = path.join(sessionDir, 'chat_history.jsonl');
|
|
97
|
+
fs.writeFileSync(chatPath, records.map((r)=>JSON.stringify(r)).join('\n'));
|
|
98
|
+
if (opts.mtime) fs.utimesSync(chatPath, opts.mtime, opts.mtime);
|
|
99
|
+
}
|
|
100
|
+
return sessionDir;
|
|
101
|
+
}
|
|
102
|
+
/** Write ~/.grok/active_sessions.json (the live pid -> cwd registry). */ function writeActiveSessions(entries) {
|
|
103
|
+
fs.mkdirSync(path.join(tmpHome, '.grok'), {
|
|
104
|
+
recursive: true
|
|
105
|
+
});
|
|
106
|
+
fs.writeFileSync(path.join(tmpHome, '.grok', 'active_sessions.json'), JSON.stringify(entries));
|
|
107
|
+
}
|
|
108
|
+
function proc(overrides = {}) {
|
|
109
|
+
return {
|
|
110
|
+
pid: 4242,
|
|
111
|
+
ppid: 1,
|
|
112
|
+
command: 'grok',
|
|
113
|
+
cwd,
|
|
114
|
+
tty: 'ttys010',
|
|
115
|
+
startTime: new Date(),
|
|
116
|
+
...overrides
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
describe('initialization', ()=>{
|
|
120
|
+
it('exposes the grok_cli type', ()=>{
|
|
121
|
+
expect(adapter.type).toBe('grok_cli');
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
describe('canHandle', ()=>{
|
|
125
|
+
it('returns true for a plain grok command', ()=>{
|
|
126
|
+
expect(adapter.canHandle(proc({
|
|
127
|
+
command: 'grok'
|
|
128
|
+
}))).toBe(true);
|
|
129
|
+
});
|
|
130
|
+
it('returns true for grok with a full path and args', ()=>{
|
|
131
|
+
expect(adapter.canHandle(proc({
|
|
132
|
+
command: '/Users/dev/.grok/bin/grok --always-approve'
|
|
133
|
+
}))).toBe(true);
|
|
134
|
+
});
|
|
135
|
+
it('returns false for non-grok processes', ()=>{
|
|
136
|
+
expect(adapter.canHandle(proc({
|
|
137
|
+
command: 'node app.js'
|
|
138
|
+
}))).toBe(false);
|
|
139
|
+
});
|
|
140
|
+
it('returns false when "grok" appears only in an argument path', ()=>{
|
|
141
|
+
expect(adapter.canHandle(proc({
|
|
142
|
+
command: 'node /path/to/grok-thing.js'
|
|
143
|
+
}))).toBe(false);
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
describe('detectAgents', ()=>{
|
|
147
|
+
it('returns [] when there are no grok processes', async ()=>{
|
|
148
|
+
mockedListAgentProcesses.mockReturnValue([]);
|
|
149
|
+
expect(await adapter.detectAgents()).toEqual([]);
|
|
150
|
+
});
|
|
151
|
+
it('resolves the cwd via active_sessions.json (authoritative over the process cwd)', async ()=>{
|
|
152
|
+
const realCwd = '/Users/dev/real-project';
|
|
153
|
+
writeSession({
|
|
154
|
+
sessionCwd: realCwd
|
|
155
|
+
});
|
|
156
|
+
// The process cwd is stale/wrong; active_sessions.json has the truth.
|
|
157
|
+
writeActiveSessions([
|
|
158
|
+
{
|
|
159
|
+
pid: 4242,
|
|
160
|
+
cwd: realCwd,
|
|
161
|
+
opened_at: 1
|
|
162
|
+
}
|
|
163
|
+
]);
|
|
164
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
165
|
+
proc({
|
|
166
|
+
cwd: '/wrong/path'
|
|
167
|
+
})
|
|
168
|
+
]);
|
|
169
|
+
const agents = await adapter.detectAgents();
|
|
170
|
+
expect(agents).toHaveLength(1);
|
|
171
|
+
expect(agents[0]).toMatchObject({
|
|
172
|
+
type: 'grok_cli',
|
|
173
|
+
pid: 4242,
|
|
174
|
+
projectPath: realCwd,
|
|
175
|
+
sessionId: SESSION_ID,
|
|
176
|
+
summary: 'fix the bug'
|
|
177
|
+
});
|
|
178
|
+
expect(agents[0].sessionFilePath).toBe(path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(realCwd), SESSION_ID, 'chat_history.jsonl'));
|
|
179
|
+
});
|
|
180
|
+
it('falls back to the process cwd when the pid is not in active_sessions.json', async ()=>{
|
|
181
|
+
writeSession({});
|
|
182
|
+
writeActiveSessions([
|
|
183
|
+
{
|
|
184
|
+
pid: 9999,
|
|
185
|
+
cwd: '/somewhere/else'
|
|
186
|
+
}
|
|
187
|
+
]);
|
|
188
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
189
|
+
proc()
|
|
190
|
+
]);
|
|
191
|
+
const agents = await adapter.detectAgents();
|
|
192
|
+
expect(agents[0]).toMatchObject({
|
|
193
|
+
projectPath: cwd,
|
|
194
|
+
sessionId: SESSION_ID
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
it('picks the most recently active session dir when a cwd has several', async ()=>{
|
|
198
|
+
const older = new Date(Date.now() - 60 * 60 * 1000);
|
|
199
|
+
writeSession({
|
|
200
|
+
id: '019f0000-0000-7000-8000-00000000000a',
|
|
201
|
+
records: [
|
|
202
|
+
userRecord('old one')
|
|
203
|
+
],
|
|
204
|
+
mtime: older
|
|
205
|
+
});
|
|
206
|
+
writeSession({
|
|
207
|
+
id: '019f0000-0000-7000-8000-00000000000b',
|
|
208
|
+
records: [
|
|
209
|
+
userRecord('newest one')
|
|
210
|
+
]
|
|
211
|
+
});
|
|
212
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
213
|
+
proc()
|
|
214
|
+
]);
|
|
215
|
+
const agents = await adapter.detectAgents();
|
|
216
|
+
expect(agents[0].sessionId).toBe('019f0000-0000-7000-8000-00000000000b');
|
|
217
|
+
expect(agents[0].summary).toBe('newest one');
|
|
218
|
+
});
|
|
219
|
+
it('falls back to a process-only RUNNING agent when no session matches', async ()=>{
|
|
220
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
221
|
+
proc()
|
|
222
|
+
]);
|
|
223
|
+
const agents = await adapter.detectAgents();
|
|
224
|
+
expect(agents).toHaveLength(1);
|
|
225
|
+
expect(agents[0].status).toBe(AgentStatus.RUNNING);
|
|
226
|
+
expect(agents[0].sessionId).toBe('pid-4242');
|
|
227
|
+
expect(agents[0].sessionFilePath).toBeUndefined();
|
|
228
|
+
});
|
|
229
|
+
it('treats a session dir without chat_history.jsonl as no match (process-only)', async ()=>{
|
|
230
|
+
writeSession({
|
|
231
|
+
chat: false
|
|
232
|
+
});
|
|
233
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
234
|
+
proc()
|
|
235
|
+
]);
|
|
236
|
+
const agents = await adapter.detectAgents();
|
|
237
|
+
expect(agents).toHaveLength(1);
|
|
238
|
+
expect(agents[0].sessionId).toBe('pid-4242');
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
describe('getConversation', ()=>{
|
|
242
|
+
it('maps user (<user_query>) and assistant records to roles', ()=>{
|
|
243
|
+
const dir = writeSession({
|
|
244
|
+
records: [
|
|
245
|
+
userRecord('hi'),
|
|
246
|
+
assistantRecord('hello')
|
|
247
|
+
]
|
|
248
|
+
});
|
|
249
|
+
expect(adapter.getConversation(path.join(dir, 'chat_history.jsonl'))).toEqual([
|
|
250
|
+
{
|
|
251
|
+
role: 'user',
|
|
252
|
+
content: 'hi'
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
role: 'assistant',
|
|
256
|
+
content: 'hello'
|
|
257
|
+
}
|
|
258
|
+
]);
|
|
259
|
+
});
|
|
260
|
+
it('accepts a session dir path and skips context-injection user records', ()=>{
|
|
261
|
+
const dir = writeSession({
|
|
262
|
+
records: [
|
|
263
|
+
contextRecord('<user_info>OS: macos</user_info>'),
|
|
264
|
+
userRecord('do the thing')
|
|
265
|
+
]
|
|
266
|
+
});
|
|
267
|
+
expect(adapter.getConversation(dir)).toEqual([
|
|
268
|
+
{
|
|
269
|
+
role: 'user',
|
|
270
|
+
content: 'do the thing'
|
|
271
|
+
}
|
|
272
|
+
]);
|
|
273
|
+
});
|
|
274
|
+
it('skips malformed lines', ()=>{
|
|
275
|
+
const dir = writeSession({
|
|
276
|
+
records: [
|
|
277
|
+
userRecord('hi')
|
|
278
|
+
]
|
|
279
|
+
});
|
|
280
|
+
fs.appendFileSync(path.join(dir, 'chat_history.jsonl'), '\n{bad json');
|
|
281
|
+
expect(adapter.getConversation(dir)).toEqual([
|
|
282
|
+
{
|
|
283
|
+
role: 'user',
|
|
284
|
+
content: 'hi'
|
|
285
|
+
}
|
|
286
|
+
]);
|
|
287
|
+
});
|
|
288
|
+
it('excludes system records unless verbose', ()=>{
|
|
289
|
+
const dir = writeSession({
|
|
290
|
+
records: [
|
|
291
|
+
systemRecord('You are Grok'),
|
|
292
|
+
userRecord('go')
|
|
293
|
+
]
|
|
294
|
+
});
|
|
295
|
+
expect(adapter.getConversation(dir)).toEqual([
|
|
296
|
+
{
|
|
297
|
+
role: 'user',
|
|
298
|
+
content: 'go'
|
|
299
|
+
}
|
|
300
|
+
]);
|
|
301
|
+
expect(adapter.getConversation(dir, {
|
|
302
|
+
verbose: true
|
|
303
|
+
}).map((m)=>m.role)).toEqual([
|
|
304
|
+
'system',
|
|
305
|
+
'user'
|
|
306
|
+
]);
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
describe('detectAgents status + summary mapping', ()=>{
|
|
310
|
+
const detectFirst = async ()=>(await adapter.detectAgents())[0];
|
|
311
|
+
it('marks WAITING when the last transcript turn is an assistant message', async ()=>{
|
|
312
|
+
writeSession({
|
|
313
|
+
records: [
|
|
314
|
+
userRecord('go'),
|
|
315
|
+
assistantRecord('done')
|
|
316
|
+
]
|
|
317
|
+
});
|
|
318
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
319
|
+
proc()
|
|
320
|
+
]);
|
|
321
|
+
expect((await detectFirst()).status).toBe(AgentStatus.WAITING);
|
|
322
|
+
});
|
|
323
|
+
it('marks RUNNING when the last transcript turn is a user message', async ()=>{
|
|
324
|
+
writeSession({
|
|
325
|
+
records: [
|
|
326
|
+
userRecord('still there?')
|
|
327
|
+
]
|
|
328
|
+
});
|
|
329
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
330
|
+
proc()
|
|
331
|
+
]);
|
|
332
|
+
expect((await detectFirst()).status).toBe(AgentStatus.RUNNING);
|
|
333
|
+
});
|
|
334
|
+
it('marks IDLE when chat_history.jsonl is older than the threshold', async ()=>{
|
|
335
|
+
const old = new Date(Date.now() - 10 * 60 * 1000);
|
|
336
|
+
writeSession({
|
|
337
|
+
records: [
|
|
338
|
+
userRecord('go')
|
|
339
|
+
],
|
|
340
|
+
mtime: old
|
|
341
|
+
});
|
|
342
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
343
|
+
proc()
|
|
344
|
+
]);
|
|
345
|
+
expect((await detectFirst()).status).toBe(AgentStatus.IDLE);
|
|
346
|
+
});
|
|
347
|
+
it('uses the last user prompt as the agent summary', async ()=>{
|
|
348
|
+
writeSession({
|
|
349
|
+
records: [
|
|
350
|
+
userRecord('refactor the parser'),
|
|
351
|
+
assistantRecord('on it')
|
|
352
|
+
]
|
|
353
|
+
});
|
|
354
|
+
mockedListAgentProcesses.mockReturnValue([
|
|
355
|
+
proc()
|
|
356
|
+
]);
|
|
357
|
+
expect((await detectFirst()).summary).toBe('refactor the parser');
|
|
358
|
+
});
|
|
359
|
+
});
|
|
360
|
+
describe('listSessions', ()=>{
|
|
361
|
+
it('returns [] when the sessions dir does not exist', async ()=>{
|
|
362
|
+
expect(await adapter.listSessions()).toEqual([]);
|
|
363
|
+
});
|
|
364
|
+
it('lists historical sessions with cwd decoded from the group dir', async ()=>{
|
|
365
|
+
writeSession({});
|
|
366
|
+
const summaries = await adapter.listSessions();
|
|
367
|
+
expect(summaries).toHaveLength(1);
|
|
368
|
+
expect(summaries[0]).toMatchObject({
|
|
369
|
+
type: 'grok_cli',
|
|
370
|
+
sessionId: SESSION_ID,
|
|
371
|
+
cwd,
|
|
372
|
+
firstUserMessage: 'fix the bug'
|
|
373
|
+
});
|
|
374
|
+
expect(summaries[0].sessionFilePath).toBe(path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), SESSION_ID, 'chat_history.jsonl'));
|
|
375
|
+
});
|
|
376
|
+
it('applies the cwd filter against the decoded cwd', async ()=>{
|
|
377
|
+
writeSession({
|
|
378
|
+
sessionCwd: '/Users/dev/project-a',
|
|
379
|
+
id: '019f0000-0000-7000-8000-00000000000a'
|
|
380
|
+
});
|
|
381
|
+
writeSession({
|
|
382
|
+
sessionCwd: '/Users/dev/project-b',
|
|
383
|
+
id: '019f0000-0000-7000-8000-00000000000b'
|
|
384
|
+
});
|
|
385
|
+
const all = await adapter.listSessions();
|
|
386
|
+
expect(all).toHaveLength(2);
|
|
387
|
+
const filtered = await adapter.listSessions({
|
|
388
|
+
cwd: '/Users/dev/project-a'
|
|
389
|
+
});
|
|
390
|
+
expect(filtered).toHaveLength(1);
|
|
391
|
+
expect(filtered[0].cwd).toBe('/Users/dev/project-a');
|
|
392
|
+
});
|
|
393
|
+
it('skips non-session entries (e.g. prompt_history.jsonl) in a group dir', async ()=>{
|
|
394
|
+
writeSession({});
|
|
395
|
+
// Grok writes a group-level prompt_history.jsonl alongside session dirs.
|
|
396
|
+
fs.writeFileSync(path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), 'prompt_history.jsonl'), '{"text":"noise"}');
|
|
397
|
+
const summaries = await adapter.listSessions();
|
|
398
|
+
expect(summaries).toHaveLength(1);
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
//# sourceMappingURL=GrokCliAdapter.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/__tests__/adapters/GrokCliAdapter.test.ts"],"sourcesContent":["/**\n * Tests for GrokCliAdapter\n *\n * The adapter resolves a live process to its cwd via ~/.grok/active_sessions.json\n * and reads session details from chat_history.jsonl (not summary.json/updates.jsonl).\n */\n\nimport type { MockedFunction } from 'vitest';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\nimport { GrokCliAdapter } from '../../adapters/GrokCliAdapter.js';\nimport type { ProcessInfo } from '../../adapters/AgentAdapter.js';\nimport { AgentStatus } from '../../adapters/AgentAdapter.js';\nimport { listAgentProcesses, enrichProcesses } from '../../utils/process.js';\nimport { generateAgentName } from '../../utils/matching.js';\n\nvi.mock('../../utils/process.js', async (importOriginal) => {\n const actual = (await importOriginal()) as typeof import('../../utils/process.js');\n return {\n ...actual,\n listAgentProcesses: vi.fn(),\n enrichProcesses: vi.fn(),\n };\n});\n\nvi.mock('../../utils/matching.js', async (importOriginal) => {\n const actual = (await importOriginal()) as typeof import('../../utils/matching.js');\n return {\n ...actual,\n generateAgentName: vi.fn(),\n };\n});\n\nconst mockedListAgentProcesses = listAgentProcesses as MockedFunction<typeof listAgentProcesses>;\nconst mockedEnrichProcesses = enrichProcesses as MockedFunction<typeof enrichProcesses>;\nconst mockedGenerateAgentName = generateAgentName as MockedFunction<typeof generateAgentName>;\n\nconst SESSION_ID = '019f16c3-5d5d-7dc3-85d1-bc629416ca2d';\n\n/** A user transcript record: the real prompt wrapped in <user_query> like Grok writes it. */\nconst userRecord = (text: string) => ({\n type: 'user',\n content: [{ type: 'text', text: `<user_query>\\n${text}\\n</user_query>` }],\n});\n/** A user context-injection record (no <user_query>) — should be ignored as a prompt. */\nconst contextRecord = (text: string) => ({ type: 'user', content: [{ type: 'text', text }] });\nconst assistantRecord = (text: string) => ({ type: 'assistant', content: [{ type: 'text', text }] });\nconst systemRecord = (text: string) => ({ type: 'system', content: text });\n\ndescribe('GrokCliAdapter', () => {\n let adapter: GrokCliAdapter;\n let tmpHome: string;\n let cwd: string;\n\n beforeEach(() => {\n tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-adapter-test-'));\n process.env.HOME = tmpHome;\n delete process.env.GROK_HOME;\n cwd = '/Users/dev/my-project';\n\n adapter = new GrokCliAdapter();\n\n mockedListAgentProcesses.mockReset();\n mockedEnrichProcesses.mockReset();\n mockedGenerateAgentName.mockReset();\n\n mockedEnrichProcesses.mockImplementation((procs) => procs);\n mockedGenerateAgentName.mockImplementation((c: string, pid: number) => `${path.basename(c) || 'unknown'}-${pid}`);\n });\n\n afterEach(() => {\n fs.rmSync(tmpHome, { recursive: true, force: true });\n });\n\n /** Write a session dir under ~/.grok/sessions/<enc(cwd)>/<id>/chat_history.jsonl. */\n function writeSession(opts: {\n sessionCwd?: string;\n id?: string;\n records?: object[];\n chat?: boolean;\n mtime?: Date;\n }): string {\n const sessionCwd = opts.sessionCwd ?? cwd;\n const id = opts.id ?? SESSION_ID;\n const sessionDir = path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(sessionCwd), id);\n fs.mkdirSync(sessionDir, { recursive: true });\n\n if (opts.chat !== false) {\n const records = opts.records ?? [userRecord('fix the bug')];\n const chatPath = path.join(sessionDir, 'chat_history.jsonl');\n fs.writeFileSync(chatPath, records.map((r) => JSON.stringify(r)).join('\\n'));\n if (opts.mtime) fs.utimesSync(chatPath, opts.mtime, opts.mtime);\n }\n\n return sessionDir;\n }\n\n /** Write ~/.grok/active_sessions.json (the live pid -> cwd registry). */\n function writeActiveSessions(entries: Array<{ pid: number; cwd: string; opened_at?: number }>): void {\n fs.mkdirSync(path.join(tmpHome, '.grok'), { recursive: true });\n fs.writeFileSync(path.join(tmpHome, '.grok', 'active_sessions.json'), JSON.stringify(entries));\n }\n\n function proc(overrides: Partial<ProcessInfo> = {}): ProcessInfo {\n return { pid: 4242, ppid: 1, command: 'grok', cwd, tty: 'ttys010', startTime: new Date(), ...overrides };\n }\n\n describe('initialization', () => {\n it('exposes the grok_cli type', () => {\n expect(adapter.type).toBe('grok_cli');\n });\n });\n\n describe('canHandle', () => {\n it('returns true for a plain grok command', () => {\n expect(adapter.canHandle(proc({ command: 'grok' }))).toBe(true);\n });\n\n it('returns true for grok with a full path and args', () => {\n expect(adapter.canHandle(proc({ command: '/Users/dev/.grok/bin/grok --always-approve' }))).toBe(true);\n });\n\n it('returns false for non-grok processes', () => {\n expect(adapter.canHandle(proc({ command: 'node app.js' }))).toBe(false);\n });\n\n it('returns false when \"grok\" appears only in an argument path', () => {\n expect(adapter.canHandle(proc({ command: 'node /path/to/grok-thing.js' }))).toBe(false);\n });\n });\n\n describe('detectAgents', () => {\n it('returns [] when there are no grok processes', async () => {\n mockedListAgentProcesses.mockReturnValue([]);\n expect(await adapter.detectAgents()).toEqual([]);\n });\n\n it('resolves the cwd via active_sessions.json (authoritative over the process cwd)', async () => {\n const realCwd = '/Users/dev/real-project';\n writeSession({ sessionCwd: realCwd });\n // The process cwd is stale/wrong; active_sessions.json has the truth.\n writeActiveSessions([{ pid: 4242, cwd: realCwd, opened_at: 1 }]);\n mockedListAgentProcesses.mockReturnValue([proc({ cwd: '/wrong/path' })]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0]).toMatchObject({\n type: 'grok_cli',\n pid: 4242,\n projectPath: realCwd,\n sessionId: SESSION_ID,\n summary: 'fix the bug',\n });\n expect(agents[0].sessionFilePath).toBe(\n path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(realCwd), SESSION_ID, 'chat_history.jsonl'),\n );\n });\n\n it('falls back to the process cwd when the pid is not in active_sessions.json', async () => {\n writeSession({});\n writeActiveSessions([{ pid: 9999, cwd: '/somewhere/else' }]);\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents[0]).toMatchObject({ projectPath: cwd, sessionId: SESSION_ID });\n });\n\n it('picks the most recently active session dir when a cwd has several', async () => {\n const older = new Date(Date.now() - 60 * 60 * 1000);\n writeSession({ id: '019f0000-0000-7000-8000-00000000000a', records: [userRecord('old one')], mtime: older });\n writeSession({ id: '019f0000-0000-7000-8000-00000000000b', records: [userRecord('newest one')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents[0].sessionId).toBe('019f0000-0000-7000-8000-00000000000b');\n expect(agents[0].summary).toBe('newest one');\n });\n\n it('falls back to a process-only RUNNING agent when no session matches', async () => {\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0].status).toBe(AgentStatus.RUNNING);\n expect(agents[0].sessionId).toBe('pid-4242');\n expect(agents[0].sessionFilePath).toBeUndefined();\n });\n\n it('treats a session dir without chat_history.jsonl as no match (process-only)', async () => {\n writeSession({ chat: false });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0].sessionId).toBe('pid-4242');\n });\n });\n\n describe('getConversation', () => {\n it('maps user (<user_query>) and assistant records to roles', () => {\n const dir = writeSession({ records: [userRecord('hi'), assistantRecord('hello')] });\n expect(adapter.getConversation(path.join(dir, 'chat_history.jsonl'))).toEqual([\n { role: 'user', content: 'hi' },\n { role: 'assistant', content: 'hello' },\n ]);\n });\n\n it('accepts a session dir path and skips context-injection user records', () => {\n const dir = writeSession({\n records: [contextRecord('<user_info>OS: macos</user_info>'), userRecord('do the thing')],\n });\n expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'do the thing' }]);\n });\n\n it('skips malformed lines', () => {\n const dir = writeSession({ records: [userRecord('hi')] });\n fs.appendFileSync(path.join(dir, 'chat_history.jsonl'), '\\n{bad json');\n expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'hi' }]);\n });\n\n it('excludes system records unless verbose', () => {\n const dir = writeSession({ records: [systemRecord('You are Grok'), userRecord('go')] });\n expect(adapter.getConversation(dir)).toEqual([{ role: 'user', content: 'go' }]);\n expect(adapter.getConversation(dir, { verbose: true }).map((m) => m.role)).toEqual(['system', 'user']);\n });\n });\n\n describe('detectAgents status + summary mapping', () => {\n const detectFirst = async () => (await adapter.detectAgents())[0];\n\n it('marks WAITING when the last transcript turn is an assistant message', async () => {\n writeSession({ records: [userRecord('go'), assistantRecord('done')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.WAITING);\n });\n\n it('marks RUNNING when the last transcript turn is a user message', async () => {\n writeSession({ records: [userRecord('still there?')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.RUNNING);\n });\n\n it('marks IDLE when chat_history.jsonl is older than the threshold', async () => {\n const old = new Date(Date.now() - 10 * 60 * 1000);\n writeSession({ records: [userRecord('go')], mtime: old });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.IDLE);\n });\n\n it('uses the last user prompt as the agent summary', async () => {\n writeSession({ records: [userRecord('refactor the parser'), assistantRecord('on it')] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).summary).toBe('refactor the parser');\n });\n });\n\n describe('listSessions', () => {\n it('returns [] when the sessions dir does not exist', async () => {\n expect(await adapter.listSessions()).toEqual([]);\n });\n\n it('lists historical sessions with cwd decoded from the group dir', async () => {\n writeSession({});\n const summaries = await adapter.listSessions();\n expect(summaries).toHaveLength(1);\n expect(summaries[0]).toMatchObject({\n type: 'grok_cli',\n sessionId: SESSION_ID,\n cwd,\n firstUserMessage: 'fix the bug',\n });\n expect(summaries[0].sessionFilePath).toBe(\n path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), SESSION_ID, 'chat_history.jsonl'),\n );\n });\n\n it('applies the cwd filter against the decoded cwd', async () => {\n writeSession({ sessionCwd: '/Users/dev/project-a', id: '019f0000-0000-7000-8000-00000000000a' });\n writeSession({ sessionCwd: '/Users/dev/project-b', id: '019f0000-0000-7000-8000-00000000000b' });\n\n const all = await adapter.listSessions();\n expect(all).toHaveLength(2);\n\n const filtered = await adapter.listSessions({ cwd: '/Users/dev/project-a' });\n expect(filtered).toHaveLength(1);\n expect(filtered[0].cwd).toBe('/Users/dev/project-a');\n });\n\n it('skips non-session entries (e.g. prompt_history.jsonl) in a group dir', async () => {\n writeSession({});\n // Grok writes a group-level prompt_history.jsonl alongside session dirs.\n fs.writeFileSync(\n path.join(tmpHome, '.grok', 'sessions', encodeURIComponent(cwd), 'prompt_history.jsonl'),\n '{\"text\":\"noise\"}',\n );\n const summaries = await adapter.listSessions();\n expect(summaries).toHaveLength(1);\n });\n });\n});\n"],"names":["fs","os","path","GrokCliAdapter","AgentStatus","listAgentProcesses","enrichProcesses","generateAgentName","vi","mock","importOriginal","actual","fn","mockedListAgentProcesses","mockedEnrichProcesses","mockedGenerateAgentName","SESSION_ID","userRecord","text","type","content","contextRecord","assistantRecord","systemRecord","describe","adapter","tmpHome","cwd","beforeEach","mkdtempSync","join","tmpdir","process","env","HOME","GROK_HOME","mockReset","mockImplementation","procs","c","pid","basename","afterEach","rmSync","recursive","force","writeSession","opts","sessionCwd","id","sessionDir","encodeURIComponent","mkdirSync","chat","records","chatPath","writeFileSync","map","r","JSON","stringify","mtime","utimesSync","writeActiveSessions","entries","proc","overrides","ppid","command","tty","startTime","Date","it","expect","toBe","canHandle","mockReturnValue","detectAgents","toEqual","realCwd","opened_at","agents","toHaveLength","toMatchObject","projectPath","sessionId","summary","sessionFilePath","older","now","status","RUNNING","toBeUndefined","dir","getConversation","role","appendFileSync","verbose","m","detectFirst","WAITING","old","IDLE","listSessions","summaries","firstUserMessage","all","filtered"],"mappings":"AAAA;;;;;CAKC,GAGD,YAAYA,QAAQ,KAAK;AACzB,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAE7B,SAASC,cAAc,QAAQ,mCAAmC;AAElE,SAASC,WAAW,QAAQ,iCAAiC;AAC7D,SAASC,kBAAkB,EAAEC,eAAe,QAAQ,yBAAyB;AAC7E,SAASC,iBAAiB,QAAQ,0BAA0B;AAE5DC,GAAGC,IAAI,CAAC,0BAA0B,OAAOC;IACrC,MAAMC,SAAU,MAAMD;IACtB,OAAO;QACH,GAAGC,MAAM;QACTN,oBAAoBG,GAAGI,EAAE;QACzBN,iBAAiBE,GAAGI,EAAE;IAC1B;AACJ;AAEAJ,GAAGC,IAAI,CAAC,2BAA2B,OAAOC;IACtC,MAAMC,SAAU,MAAMD;IACtB,OAAO;QACH,GAAGC,MAAM;QACTJ,mBAAmBC,GAAGI,EAAE;IAC5B;AACJ;AAEA,MAAMC,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apter/script.js')).toBe(false);
|
|
14
14
|
});
|
|
15
|
+
it('includes Grok as a startable agent', ()=>{
|
|
16
|
+
expect(AGENTS.grok_cli.command).toBe('grok');
|
|
17
|
+
expect(AGENTS.grok_cli.matches('grok')).toBe(true);
|
|
18
|
+
expect(AGENTS.grok_cli.matches('/Users/dev/.grok/bin/grok --always-approve')).toBe(true);
|
|
19
|
+
expect(AGENTS.grok_cli.matches('node /repo/feature-grok-cli/script.js')).toBe(false);
|
|
20
|
+
});
|
|
15
21
|
});
|
|
16
22
|
|
|
17
23
|
//# sourceMappingURL=agents.test.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/__tests__/utils/agents.test.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest';\nimport { AGENTS } from '../../../src/utils/agents.js';\n\ndescribe('AGENTS', () => {\n it('includes Copilot as a startable agent', () => {\n expect(AGENTS.copilot.command).toBe('copilot');\n expect(AGENTS.copilot.matches('/opt/homebrew/Caskroom/copilot-cli/1.0.60/copilot')).toBe(true);\n expect(AGENTS.copilot.matches('node /repo/feature-cli-copilot-cli/script.js')).toBe(false);\n });\n\n it('includes Pi as a startable agent', () => {\n expect(AGENTS.pi.command).toBe('pi');\n expect(AGENTS.pi.matches('pi')).toBe(true);\n expect(AGENTS.pi.matches('/usr/local/bin/pi --model x')).toBe(true);\n expect(AGENTS.pi.matches('node /repo/feature-pi-adapter/script.js')).toBe(false);\n });\n});\n"],"names":["describe","expect","it","AGENTS","copilot","command","toBe","matches","pi"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAC9C,SAASC,MAAM,QAAQ,+BAA+B;AAEtDH,SAAS,UAAU;IACfE,GAAG,yCAAyC;QACxCD,OAAOE,OAAOC,OAAO,CAACC,OAAO,EAAEC,IAAI,CAAC;QACpCL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,sDAAsDD,IAAI,CAAC;QACzFL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,iDAAiDD,IAAI,CAAC;IACxF;IAEAJ,GAAG,oCAAoC;QACnCD,OAAOE,OAAOK,EAAE,CAACH,OAAO,EAAEC,IAAI,CAAC;QAC/BL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,OAAOD,IAAI,CAAC;QACrCL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,gCAAgCD,IAAI,CAAC;QAC9DL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,4CAA4CD,IAAI,CAAC;IAC9E;AACJ"}
|
|
1
|
+
{"version":3,"sources":["../../../src/__tests__/utils/agents.test.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest';\nimport { AGENTS } from '../../../src/utils/agents.js';\n\ndescribe('AGENTS', () => {\n it('includes Copilot as a startable agent', () => {\n expect(AGENTS.copilot.command).toBe('copilot');\n expect(AGENTS.copilot.matches('/opt/homebrew/Caskroom/copilot-cli/1.0.60/copilot')).toBe(true);\n expect(AGENTS.copilot.matches('node /repo/feature-cli-copilot-cli/script.js')).toBe(false);\n });\n\n it('includes Pi as a startable agent', () => {\n expect(AGENTS.pi.command).toBe('pi');\n expect(AGENTS.pi.matches('pi')).toBe(true);\n expect(AGENTS.pi.matches('/usr/local/bin/pi --model x')).toBe(true);\n expect(AGENTS.pi.matches('node /repo/feature-pi-adapter/script.js')).toBe(false);\n });\n\n it('includes Grok as a startable agent', () => {\n expect(AGENTS.grok_cli.command).toBe('grok');\n expect(AGENTS.grok_cli.matches('grok')).toBe(true);\n expect(AGENTS.grok_cli.matches('/Users/dev/.grok/bin/grok --always-approve')).toBe(true);\n expect(AGENTS.grok_cli.matches('node /repo/feature-grok-cli/script.js')).toBe(false);\n });\n});\n"],"names":["describe","expect","it","AGENTS","copilot","command","toBe","matches","pi","grok_cli"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAC9C,SAASC,MAAM,QAAQ,+BAA+B;AAEtDH,SAAS,UAAU;IACfE,GAAG,yCAAyC;QACxCD,OAAOE,OAAOC,OAAO,CAACC,OAAO,EAAEC,IAAI,CAAC;QACpCL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,sDAAsDD,IAAI,CAAC;QACzFL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,iDAAiDD,IAAI,CAAC;IACxF;IAEAJ,GAAG,oCAAoC;QACnCD,OAAOE,OAAOK,EAAE,CAACH,OAAO,EAAEC,IAAI,CAAC;QAC/BL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,OAAOD,IAAI,CAAC;QACrCL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,gCAAgCD,IAAI,CAAC;QAC9DL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,4CAA4CD,IAAI,CAAC;IAC9E;IAEAJ,GAAG,sCAAsC;QACrCD,OAAOE,OAAOM,QAAQ,CAACJ,OAAO,EAAEC,IAAI,CAAC;QACrCL,OAAOE,OAAOM,QAAQ,CAACF,OAAO,CAAC,SAASD,IAAI,CAAC;QAC7CL,OAAOE,OAAOM,QAAQ,CAACF,OAAO,CAAC,+CAA+CD,IAAI,CAAC;QACnFL,OAAOE,OAAOM,QAAQ,CAACF,OAAO,CAAC,0CAA0CD,IAAI,CAAC;IAClF;AACJ"}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
/**
|
|
8
8
|
* Type of AI agent
|
|
9
9
|
*/
|
|
10
|
-
export type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';
|
|
10
|
+
export type AgentType = 'claude' | 'gemini_cli' | 'grok_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';
|
|
11
11
|
/**
|
|
12
12
|
* Current status of an agent
|
|
13
13
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/AgentAdapter.ts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AC,CAAC;CACvE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/AgentAdapter.ts"],"sourcesContent":["/**\n * Agent Adapter Interface\n * \n * Defines the contract for detecting and managing different types of AI agents.\n * Each adapter is responsible for detecting agents of a specific type (e.g., claude).\n */\n\n/**\n * Type of AI agent\n */\nexport type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';\n\n/**\n * Current status of an agent\n */\nexport enum AgentStatus {\n RUNNING = 'running',\n WAITING = 'waiting',\n IDLE = 'idle',\n UNKNOWN = 'unknown'\n}\n\n/**\n * Information about a detected agent\n */\nexport interface AgentInfo {\n /** Project-based name (e.g., \"ai-devkit\" or \"ai-devkit (merry)\") */\n name: string;\n\n /** Type of agent */\n type: AgentType;\n\n /** Current status */\n status: AgentStatus;\n\n /** Last user prompt from history */\n summary: string;\n\n /** Process ID */\n pid: number;\n\n /** Working directory/project path */\n projectPath: string;\n\n /** Session UUID */\n sessionId: string;\n\n /** Timestamp of last activity */\n lastActive: Date;\n\n /** Path to the session JSONL file on disk */\n sessionFilePath?: string;\n}\n\n/**\n * Information about a running process\n */\nexport interface ProcessInfo {\n /** Process ID */\n pid: number;\n\n /** Parent process ID, populated by listAgentProcesses when available */\n ppid?: number;\n\n /** Process command */\n command: string;\n\n /** Working directory */\n cwd: string;\n\n /** Terminal TTY (e.g., \"ttys030\") */\n tty: string;\n\n /** Process start time, populated by enrichProcesses */\n startTime?: Date;\n}\n\n/**\n * A single message in a conversation\n */\nexport interface ConversationMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp?: string;\n}\n\n/**\n * A historical session discovered on disk (running or not).\n *\n * Used by `listSessions` to surface enough context for a user to identify\n * a session and resume it via the originating tool's resume command.\n */\nexport interface SessionSummary {\n /** Tool that produced this session */\n type: AgentType;\n\n /**\n * ID accepted by the tool's resume command. Adapters MUST pass this\n * through verbatim — no normalization, no encoding/decoding — so it\n * round-trips into `claude --resume <id>` (and equivalents).\n */\n sessionId: string;\n\n /** Working directory the session was started in (best-known value) */\n cwd: string;\n\n /**\n * Trimmed first user message; empty string if none. Adapters apply\n * the same noise-filter their existing parsers use (skip tool_result\n * blocks, request-interruption notices, system-injected skill\n * content). The CLI table renderer substitutes a placeholder for\n * empty values; JSON output keeps the empty string raw.\n */\n firstUserMessage: string;\n\n /** Last activity timestamp (from session content; falls back to file mtime) */\n lastActive: Date;\n\n /** Session start time (from session content; falls back to file birthtime/mtime) */\n startedAt: Date;\n\n /** Absolute path to the session file on disk (debug/diagnostics) */\n sessionFilePath: string;\n}\n\n/**\n * Filters passed by the CLI to {@link AgentAdapter.listSessions}.\n *\n * The CLI is the source of truth for filter defaults and semantics\n * (e.g. cwd defaults to process.cwd(); --all clears it). Adapters apply\n * the values they receive — they don't invent defaults.\n */\nexport interface ListSessionsOptions {\n /**\n * Filter to sessions whose recorded cwd matches this path using strict\n * equality (no prefix/ancestor matching in v1). Undefined = no cwd\n * filter.\n */\n cwd?: string;\n\n /**\n * Filter to a single tool. Enforced by `AgentManager.listSessions`,\n * which skips adapters whose `type` doesn't match. Adapters MAY\n * ignore this field — by the time their `listSessions` runs, the\n * type filter is already satisfied. Undefined = include every\n * registered adapter.\n */\n type?: AgentType;\n}\n\n/**\n * Agent Adapter Interface\n *\n * Implementations must provide detection logic for a specific agent type.\n */\nexport interface AgentAdapter {\n /** Type of agent this adapter handles */\n readonly type: AgentType;\n\n /**\n * Detect running agents of this type\n * @returns List of detected agents\n */\n detectAgents(): Promise<AgentInfo[]>;\n\n /**\n * Check if this adapter can handle the given process\n * @param processInfo Process information\n * @returns True if this adapter can handle the process\n */\n canHandle(processInfo: ProcessInfo): boolean;\n\n /**\n * Read the full conversation from a session file\n * @param sessionFilePath Path to the session JSONL file\n * @param options.verbose Include tool call/result details\n * @returns Array of conversation messages\n */\n getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[];\n\n /**\n * Enumerate historical sessions for this tool from disk.\n *\n * Applies `opts.cwd` as a strict-equality filter when set. Returns\n * {@link SessionSummary} entries unsorted; sorting and global filters\n * are handled by `AgentManager` and the CLI.\n *\n * @param opts Filter options computed by the CLI\n * @returns Array of sessions discovered on disk\n */\n listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;\n}\n"],"names":["AgentStatus"],"mappings":"AAAA;;;;;CAKC,GAED;;CAEC,GAGD;;CAEC,GACD,OAAO,IAAA,AAAKA,qCAAAA;;;;;WAAAA;MAKX"}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/AgentAdapter.ts"],"sourcesContent":["/**\n * Agent Adapter Interface\n * \n * Defines the contract for detecting and managing different types of AI agents.\n * Each adapter is responsible for detecting agents of a specific type (e.g., claude).\n */\n\n/**\n * Type of AI agent\n */\nexport type AgentType = 'claude' | 'gemini_cli' | 'grok_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';\n\n/**\n * Current status of an agent\n */\nexport enum AgentStatus {\n RUNNING = 'running',\n WAITING = 'waiting',\n IDLE = 'idle',\n UNKNOWN = 'unknown'\n}\n\n/**\n * Information about a detected agent\n */\nexport interface AgentInfo {\n /** Project-based name (e.g., \"ai-devkit\" or \"ai-devkit (merry)\") */\n name: string;\n\n /** Type of agent */\n type: AgentType;\n\n /** Current status */\n status: AgentStatus;\n\n /** Last user prompt from history */\n summary: string;\n\n /** Process ID */\n pid: number;\n\n /** Working directory/project path */\n projectPath: string;\n\n /** Session UUID */\n sessionId: string;\n\n /** Timestamp of last activity */\n lastActive: Date;\n\n /** Path to the session JSONL file on disk */\n sessionFilePath?: string;\n}\n\n/**\n * Information about a running process\n */\nexport interface ProcessInfo {\n /** Process ID */\n pid: number;\n\n /** Parent process ID, populated by listAgentProcesses when available */\n ppid?: number;\n\n /** Process command */\n command: string;\n\n /** Working directory */\n cwd: string;\n\n /** Terminal TTY (e.g., \"ttys030\") */\n tty: string;\n\n /** Process start time, populated by enrichProcesses */\n startTime?: Date;\n}\n\n/**\n * A single message in a conversation\n */\nexport interface ConversationMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp?: string;\n}\n\n/**\n * A historical session discovered on disk (running or not).\n *\n * Used by `listSessions` to surface enough context for a user to identify\n * a session and resume it via the originating tool's resume command.\n */\nexport interface SessionSummary {\n /** Tool that produced this session */\n type: AgentType;\n\n /**\n * ID accepted by the tool's resume command. Adapters MUST pass this\n * through verbatim — no normalization, no encoding/decoding — so it\n * round-trips into `claude --resume <id>` (and equivalents).\n */\n sessionId: string;\n\n /** Working directory the session was started in (best-known value) */\n cwd: string;\n\n /**\n * Trimmed first user message; empty string if none. Adapters apply\n * the same noise-filter their existing parsers use (skip tool_result\n * blocks, request-interruption notices, system-injected skill\n * content). The CLI table renderer substitutes a placeholder for\n * empty values; JSON output keeps the empty string raw.\n */\n firstUserMessage: string;\n\n /** Last activity timestamp (from session content; falls back to file mtime) */\n lastActive: Date;\n\n /** Session start time (from session content; falls back to file birthtime/mtime) */\n startedAt: Date;\n\n /** Absolute path to the session file on disk (debug/diagnostics) */\n sessionFilePath: string;\n}\n\n/**\n * Filters passed by the CLI to {@link AgentAdapter.listSessions}.\n *\n * The CLI is the source of truth for filter defaults and semantics\n * (e.g. cwd defaults to process.cwd(); --all clears it). Adapters apply\n * the values they receive — they don't invent defaults.\n */\nexport interface ListSessionsOptions {\n /**\n * Filter to sessions whose recorded cwd matches this path using strict\n * equality (no prefix/ancestor matching in v1). Undefined = no cwd\n * filter.\n */\n cwd?: string;\n\n /**\n * Filter to a single tool. Enforced by `AgentManager.listSessions`,\n * which skips adapters whose `type` doesn't match. Adapters MAY\n * ignore this field — by the time their `listSessions` runs, the\n * type filter is already satisfied. Undefined = include every\n * registered adapter.\n */\n type?: AgentType;\n}\n\n/**\n * Agent Adapter Interface\n *\n * Implementations must provide detection logic for a specific agent type.\n */\nexport interface AgentAdapter {\n /** Type of agent this adapter handles */\n readonly type: AgentType;\n\n /**\n * Detect running agents of this type\n * @returns List of detected agents\n */\n detectAgents(): Promise<AgentInfo[]>;\n\n /**\n * Check if this adapter can handle the given process\n * @param processInfo Process information\n * @returns True if this adapter can handle the process\n */\n canHandle(processInfo: ProcessInfo): boolean;\n\n /**\n * Read the full conversation from a session file\n * @param sessionFilePath Path to the session JSONL file\n * @param options.verbose Include tool call/result details\n * @returns Array of conversation messages\n */\n getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[];\n\n /**\n * Enumerate historical sessions for this tool from disk.\n *\n * Applies `opts.cwd` as a strict-equality filter when set. Returns\n * {@link SessionSummary} entries unsorted; sorting and global filters\n * are handled by `AgentManager` and the CLI.\n *\n * @param opts Filter options computed by the CLI\n * @returns Array of sessions discovered on disk\n */\n listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;\n}\n"],"names":["AgentStatus"],"mappings":"AAAA;;;;;CAKC,GAED;;CAEC,GAGD;;CAEC,GACD,OAAO,IAAA,AAAKA,qCAAAA;;;;;WAAAA;MAKX"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { AgentAdapter, AgentInfo, ProcessInfo, ConversationMessage, SessionSummary, ListSessionsOptions } from './AgentAdapter.js';
|
|
2
|
+
export declare class GrokCliAdapter implements AgentAdapter {
|
|
3
|
+
readonly type: "grok_cli";
|
|
4
|
+
private base;
|
|
5
|
+
private sessionsDir;
|
|
6
|
+
constructor();
|
|
7
|
+
canHandle(processInfo: ProcessInfo): boolean;
|
|
8
|
+
private isGrokExecutable;
|
|
9
|
+
detectAgents(): Promise<AgentInfo[]>;
|
|
10
|
+
/**
|
|
11
|
+
* Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one
|
|
12
|
+
* { pid, cwd, opened_at } entry per running session and removes it on exit,
|
|
13
|
+
* so this is the reliable way to learn a live process's working directory.
|
|
14
|
+
*/
|
|
15
|
+
private readActiveSessions;
|
|
16
|
+
/**
|
|
17
|
+
* Full paths of the session subdirectories directly under a group dir,
|
|
18
|
+
* skipping any non-directory entries. Shared by latestSessionDir() and
|
|
19
|
+
* listSessions() so both enumerate session dirs the same way.
|
|
20
|
+
*/
|
|
21
|
+
private listSessionDirs;
|
|
22
|
+
/**
|
|
23
|
+
* Return the most recently active session subdirectory for a cwd, i.e. the
|
|
24
|
+
* ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl
|
|
25
|
+
* was written last. Returns null when the group dir or any transcript is
|
|
26
|
+
* missing.
|
|
27
|
+
*/
|
|
28
|
+
private latestSessionDir;
|
|
29
|
+
private mapSessionToAgent;
|
|
30
|
+
private mapProcessOnlyAgent;
|
|
31
|
+
getConversation(sessionFilePath: string, options?: {
|
|
32
|
+
verbose?: boolean;
|
|
33
|
+
}): ConversationMessage[];
|
|
34
|
+
listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;
|
|
35
|
+
/**
|
|
36
|
+
* Parse a session directory into a {@link GrokSession} from its
|
|
37
|
+
* chat_history.jsonl transcript. Returns null when the transcript is
|
|
38
|
+
* missing — i.e. there is no real session to surface.
|
|
39
|
+
*/
|
|
40
|
+
private readSession;
|
|
41
|
+
/**
|
|
42
|
+
* Determine agent status from parsed session state.
|
|
43
|
+
*
|
|
44
|
+
* - past the idle threshold → IDLE
|
|
45
|
+
* - last transcript turn is an assistant message → WAITING (awaiting user)
|
|
46
|
+
* - otherwise (last turn was a user message, or unknown) → RUNNING
|
|
47
|
+
*/
|
|
48
|
+
private determineStatus;
|
|
49
|
+
/**
|
|
50
|
+
* Single pass over chat_history.jsonl. Each line is a
|
|
51
|
+
* { type: 'system' | 'user' | 'assistant', content } record where content is
|
|
52
|
+
* either a string or an array of { type: 'text', text } blocks.
|
|
53
|
+
*
|
|
54
|
+
* Grok wraps the real user prompt in <user_query>...</user_query>; the other
|
|
55
|
+
* user records are context injections (<user_info>, <system-reminder>, ...)
|
|
56
|
+
* and are skipped so the summary is the actual prompt, not boilerplate.
|
|
57
|
+
*/
|
|
58
|
+
private parseChatHistory;
|
|
59
|
+
/** Flatten a chat record's content (string or text-block array) to text. */
|
|
60
|
+
private extractText;
|
|
61
|
+
/**
|
|
62
|
+
* Extract the prompt inside <user_query>...</user_query>. Returns null when
|
|
63
|
+
* the record has no such tag (a context injection rather than a prompt).
|
|
64
|
+
*/
|
|
65
|
+
private extractUserQuery;
|
|
66
|
+
/** Resolve a session dir or an explicit chat_history.jsonl path to the file. */
|
|
67
|
+
private resolveChatPath;
|
|
68
|
+
private getProjectDir;
|
|
69
|
+
/**
|
|
70
|
+
* Resolve the working directory a session group dir was created for.
|
|
71
|
+
*
|
|
72
|
+
* The common case is `decodeURIComponent(<group-name>)`. For paths whose
|
|
73
|
+
* encoded form exceeds the filesystem limit Grok uses a slug+hash and records
|
|
74
|
+
* the original path in a `.cwd` file inside the group — prefer that when
|
|
75
|
+
* present.
|
|
76
|
+
*/
|
|
77
|
+
private decodeGroupCwd;
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=GrokCliAdapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"GrokCliAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/GrokCliAdapter.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACR,YAAY,EACZ,SAAS,EACT,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,mBAAmB,EACtB,MAAM,mBAAmB,CAAC;AA6D3B,qBAAa,cAAe,YAAW,YAAY;IAC/C,QAAQ,CAAC,IAAI,EAAG,UAAU,CAAU;IAEpC,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,WAAW,CAAS;;IAW5B,SAAS,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO;IAI5C,OAAO,CAAC,gBAAgB;IAMlB,YAAY,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IA0B1C;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;IAqB1B;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAMvB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IAexB,OAAO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