@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.
@@ -0,0 +1,394 @@
1
+ import * as path from 'path';
2
+ import type {
3
+ AgentAdapter,
4
+ AgentInfo,
5
+ ProcessInfo,
6
+ ConversationMessage,
7
+ SessionSummary,
8
+ ListSessionsOptions,
9
+ } from './AgentAdapter.js';
10
+ import { AgentStatus } from './AgentAdapter.js';
11
+ import { listAgentProcesses, enrichProcesses } from '../utils/process.js';
12
+ import { isDirectory, safeReadFile, safeReaddir, safeStat } from '../utils/session.js';
13
+ import { generateAgentName } from '../utils/matching.js';
14
+
15
+ /**
16
+ * Grok Build CLI Adapter
17
+ *
18
+ * Detects running Grok Build CLI agents by:
19
+ * 1. Finding running `grok` processes via shared listAgentProcesses() — Grok is
20
+ * a native binary at ~/.grok/bin/grok, so argv[0] basename is `grok`.
21
+ * 2. Resolving each live process to its working directory via
22
+ * ~/.grok/active_sessions.json, which Grok maintains as a list of
23
+ * { pid, cwd, opened_at } for every running session. The cwd is then encoded
24
+ * into the session group dir ~/.grok/sessions/<encodeURIComponent(cwd)>/, and
25
+ * the most recently active session subdirectory is picked from it. The
26
+ * process cwd from lsof is only a fallback when the PID is not registered.
27
+ * 3. Reading the session transcript from chat_history.jsonl (the authoritative
28
+ * record of the conversation). The last user turn (the text inside
29
+ * <user_query>...</user_query>) is the summary; the file's mtime is the last
30
+ * activity time. summary.json / updates.jsonl are intentionally not used.
31
+ */
32
+
33
+ const CHAT_HISTORY_FILE = 'chat_history.jsonl';
34
+ const ACTIVE_SESSIONS_FILE = 'active_sessions.json';
35
+ const CWD_FILE = '.cwd';
36
+ const IDLE_THRESHOLD_MINUTES = 5;
37
+
38
+ /** One entry of ~/.grok/active_sessions.json. */
39
+ interface ActiveSessionEntry {
40
+ pid?: number;
41
+ cwd?: string;
42
+ opened_at?: number | string;
43
+ }
44
+
45
+ /** One line of chat_history.jsonl. */
46
+ interface ChatRecord {
47
+ type?: string;
48
+ content?: unknown;
49
+ }
50
+
51
+ interface ChatScan {
52
+ messages: ConversationMessage[];
53
+ firstUserMessage?: string;
54
+ lastUserMessage?: string;
55
+ lastRole?: ConversationMessage['role'];
56
+ }
57
+
58
+ /** Parsed state for a single ~/.grok/sessions/<cwd>/<id>/ directory. */
59
+ interface GrokSession {
60
+ sessionId: string;
61
+ projectPath: string;
62
+ summary: string;
63
+ sessionStart: Date;
64
+ lastActive: Date;
65
+ firstUserMessage?: string;
66
+ lastUserMessage?: string;
67
+ lastRole?: ConversationMessage['role'];
68
+ }
69
+
70
+ export class GrokCliAdapter implements AgentAdapter {
71
+ readonly type = 'grok_cli' as const;
72
+
73
+ private base: string;
74
+ private sessionsDir: string;
75
+
76
+ constructor() {
77
+ // GROK_HOME overrides the ~/.grok base directory; sessions live under
78
+ // <base>/sessions/ and the active-session registry at
79
+ // <base>/active_sessions.json.
80
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
81
+ this.base = process.env.GROK_HOME || path.join(homeDir, '.grok');
82
+ this.sessionsDir = path.join(this.base, 'sessions');
83
+ }
84
+
85
+ canHandle(processInfo: ProcessInfo): boolean {
86
+ return this.isGrokExecutable(processInfo.command);
87
+ }
88
+
89
+ private isGrokExecutable(command: string): boolean {
90
+ const executable = command.trim().split(/\s+/)[0] || '';
91
+ const base = path.basename(executable).toLowerCase();
92
+ return base === 'grok' || base === 'grok.exe';
93
+ }
94
+
95
+ async detectAgents(): Promise<AgentInfo[]> {
96
+ const processes = enrichProcesses(listAgentProcesses('grok'));
97
+ if (processes.length === 0) {
98
+ return [];
99
+ }
100
+
101
+ // active_sessions.json is the authoritative pid -> cwd map for live
102
+ // sessions; the lsof-derived process cwd is only a fallback.
103
+ const pidToCwd = this.readActiveSessions();
104
+
105
+ const agents: AgentInfo[] = [];
106
+ for (const proc of processes) {
107
+ const cwd = pidToCwd.get(proc.pid) || proc.cwd || '';
108
+ const sessionDir = cwd ? this.latestSessionDir(cwd) : null;
109
+ const session = sessionDir ? this.readSession(sessionDir, cwd) : null;
110
+
111
+ if (session && sessionDir) {
112
+ agents.push(this.mapSessionToAgent(session, proc, sessionDir));
113
+ } else {
114
+ agents.push(this.mapProcessOnlyAgent(proc, cwd));
115
+ }
116
+ }
117
+
118
+ return agents;
119
+ }
120
+
121
+ /**
122
+ * Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one
123
+ * { pid, cwd, opened_at } entry per running session and removes it on exit,
124
+ * so this is the reliable way to learn a live process's working directory.
125
+ */
126
+ private readActiveSessions(): Map<number, string> {
127
+ const map = new Map<number, string>();
128
+ const content = safeReadFile(path.join(this.base, ACTIVE_SESSIONS_FILE));
129
+ if (content === undefined) return map;
130
+
131
+ let entries: unknown;
132
+ try {
133
+ entries = JSON.parse(content);
134
+ } catch {
135
+ return map;
136
+ }
137
+ if (!Array.isArray(entries)) return map;
138
+
139
+ for (const entry of entries as ActiveSessionEntry[]) {
140
+ if (typeof entry?.pid === 'number' && typeof entry?.cwd === 'string' && entry.cwd) {
141
+ map.set(entry.pid, entry.cwd);
142
+ }
143
+ }
144
+ return map;
145
+ }
146
+
147
+ /**
148
+ * Full paths of the session subdirectories directly under a group dir,
149
+ * skipping any non-directory entries. Shared by latestSessionDir() and
150
+ * listSessions() so both enumerate session dirs the same way.
151
+ */
152
+ private listSessionDirs(groupDir: string): string[] {
153
+ return safeReaddir(groupDir)
154
+ .map((sessionId) => path.join(groupDir, sessionId))
155
+ .filter((sessionDir) => isDirectory(sessionDir));
156
+ }
157
+
158
+ /**
159
+ * Return the most recently active session subdirectory for a cwd, i.e. the
160
+ * ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl
161
+ * was written last. Returns null when the group dir or any transcript is
162
+ * missing.
163
+ */
164
+ private latestSessionDir(cwd: string): string | null {
165
+ const groupDir = this.getProjectDir(cwd);
166
+ if (!isDirectory(groupDir)) return null;
167
+
168
+ let best: { dir: string; mtimeMs: number } | null = null;
169
+ for (const sessionDir of this.listSessionDirs(groupDir)) {
170
+ const stat = safeStat(path.join(sessionDir, CHAT_HISTORY_FILE));
171
+ if (!stat) continue;
172
+ if (!best || stat.mtimeMs > best.mtimeMs) {
173
+ best = { dir: sessionDir, mtimeMs: stat.mtimeMs };
174
+ }
175
+ }
176
+ return best?.dir ?? null;
177
+ }
178
+
179
+ private mapSessionToAgent(session: GrokSession, processInfo: ProcessInfo, sessionDir: string): AgentInfo {
180
+ const projectPath = session.projectPath || processInfo.cwd || '';
181
+ return {
182
+ name: generateAgentName(projectPath, processInfo.pid),
183
+ type: this.type,
184
+ status: this.determineStatus(session),
185
+ summary: session.summary || 'Grok CLI session active',
186
+ pid: processInfo.pid,
187
+ projectPath,
188
+ sessionId: session.sessionId,
189
+ lastActive: session.lastActive,
190
+ sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE),
191
+ };
192
+ }
193
+
194
+ private mapProcessOnlyAgent(processInfo: ProcessInfo, cwd: string): AgentInfo {
195
+ const projectPath = cwd || processInfo.cwd || '';
196
+ return {
197
+ name: generateAgentName(projectPath, processInfo.pid),
198
+ type: this.type,
199
+ status: AgentStatus.RUNNING,
200
+ summary: 'Grok CLI process running',
201
+ pid: processInfo.pid,
202
+ projectPath,
203
+ sessionId: `pid-${processInfo.pid}`,
204
+ lastActive: new Date(),
205
+ };
206
+ }
207
+
208
+ getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {
209
+ return this.parseChatHistory(this.resolveChatPath(sessionFilePath), options?.verbose ?? false).messages;
210
+ }
211
+
212
+ async listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]> {
213
+ if (!isDirectory(this.sessionsDir)) return [];
214
+
215
+ const filterCwd = opts?.cwd;
216
+ const summaries: SessionSummary[] = [];
217
+
218
+ for (const groupName of safeReaddir(this.sessionsDir)) {
219
+ const groupDir = path.join(this.sessionsDir, groupName);
220
+ if (!isDirectory(groupDir)) continue;
221
+
222
+ const decodedCwd = this.decodeGroupCwd(groupName, groupDir);
223
+
224
+ for (const sessionDir of this.listSessionDirs(groupDir)) {
225
+ const session = this.readSession(sessionDir, decodedCwd);
226
+ if (!session) continue;
227
+
228
+ const cwd = session.projectPath || decodedCwd;
229
+ if (filterCwd !== undefined && cwd !== filterCwd) continue;
230
+
231
+ summaries.push({
232
+ type: this.type,
233
+ sessionId: session.sessionId,
234
+ cwd,
235
+ firstUserMessage: session.firstUserMessage || '',
236
+ lastActive: session.lastActive,
237
+ startedAt: session.sessionStart,
238
+ sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE),
239
+ });
240
+ }
241
+ }
242
+
243
+ return summaries;
244
+ }
245
+
246
+ // --- Session parsing (chat_history.jsonl) ---
247
+
248
+ /**
249
+ * Parse a session directory into a {@link GrokSession} from its
250
+ * chat_history.jsonl transcript. Returns null when the transcript is
251
+ * missing — i.e. there is no real session to surface.
252
+ */
253
+ private readSession(sessionDir: string, defaultCwd: string): GrokSession | null {
254
+ const chatPath = path.join(sessionDir, CHAT_HISTORY_FILE);
255
+ const chatStat = safeStat(chatPath);
256
+ if (!chatStat) return null;
257
+
258
+ const scan = this.parseChatHistory(chatPath, false);
259
+ const dirStat = safeStat(sessionDir);
260
+ const lastActive = chatStat.mtime;
261
+
262
+ return {
263
+ sessionId: path.basename(sessionDir),
264
+ projectPath: defaultCwd || '',
265
+ summary: scan.lastUserMessage || 'Grok CLI session active',
266
+ sessionStart: dirStat?.birthtime || lastActive,
267
+ lastActive,
268
+ firstUserMessage: scan.firstUserMessage,
269
+ lastUserMessage: scan.lastUserMessage,
270
+ lastRole: scan.lastRole,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Determine agent status from parsed session state.
276
+ *
277
+ * - past the idle threshold → IDLE
278
+ * - last transcript turn is an assistant message → WAITING (awaiting user)
279
+ * - otherwise (last turn was a user message, or unknown) → RUNNING
280
+ */
281
+ private determineStatus(session: GrokSession): AgentStatus {
282
+ const diffMinutes = (Date.now() - session.lastActive.getTime()) / 60000;
283
+ if (diffMinutes > IDLE_THRESHOLD_MINUTES) {
284
+ return AgentStatus.IDLE;
285
+ }
286
+ if (session.lastRole === 'assistant') {
287
+ return AgentStatus.WAITING;
288
+ }
289
+ return AgentStatus.RUNNING;
290
+ }
291
+
292
+ /**
293
+ * Single pass over chat_history.jsonl. Each line is a
294
+ * { type: 'system' | 'user' | 'assistant', content } record where content is
295
+ * either a string or an array of { type: 'text', text } blocks.
296
+ *
297
+ * Grok wraps the real user prompt in <user_query>...</user_query>; the other
298
+ * user records are context injections (<user_info>, <system-reminder>, ...)
299
+ * and are skipped so the summary is the actual prompt, not boilerplate.
300
+ */
301
+ private parseChatHistory(chatPath: string, verbose: boolean): ChatScan {
302
+ const empty: ChatScan = { messages: [] };
303
+ const content = safeReadFile(chatPath);
304
+ if (content === undefined) return empty;
305
+
306
+ const messages: ConversationMessage[] = [];
307
+ let lastRole: ConversationMessage['role'] | undefined;
308
+
309
+ for (const line of content.trim().split('\n')) {
310
+ if (!line.trim()) continue;
311
+
312
+ let record: ChatRecord;
313
+ try {
314
+ record = JSON.parse(line);
315
+ } catch {
316
+ continue;
317
+ }
318
+
319
+ const text = this.extractText(record.content);
320
+ if (record.type === 'user') {
321
+ const query = this.extractUserQuery(text);
322
+ if (query === null) continue; // context injection, not a real prompt
323
+ messages.push({ role: 'user', content: query });
324
+ lastRole = 'user';
325
+ } else if (record.type === 'assistant') {
326
+ if (!text) continue;
327
+ messages.push({ role: 'assistant', content: text });
328
+ lastRole = 'assistant';
329
+ } else if (verbose && record.type === 'system') {
330
+ if (!text) continue;
331
+ messages.push({ role: 'system', content: text });
332
+ }
333
+ }
334
+
335
+ const userTurns = messages.filter((m) => m.role === 'user');
336
+ return {
337
+ messages,
338
+ firstUserMessage: userTurns[0]?.content,
339
+ lastUserMessage: userTurns[userTurns.length - 1]?.content,
340
+ lastRole,
341
+ };
342
+ }
343
+
344
+ /** Flatten a chat record's content (string or text-block array) to text. */
345
+ private extractText(content: unknown): string {
346
+ if (typeof content === 'string') return content;
347
+ if (Array.isArray(content)) {
348
+ return content
349
+ .map((block) =>
350
+ block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'
351
+ ? (block as { text: string }).text
352
+ : '',
353
+ )
354
+ .join('');
355
+ }
356
+ return '';
357
+ }
358
+
359
+ /**
360
+ * Extract the prompt inside <user_query>...</user_query>. Returns null when
361
+ * the record has no such tag (a context injection rather than a prompt).
362
+ */
363
+ private extractUserQuery(text: string): string | null {
364
+ const match = text.match(/<user_query>\s*([\s\S]*?)\s*<\/user_query>/);
365
+ return match ? match[1].trim() : null;
366
+ }
367
+
368
+ /** Resolve a session dir or an explicit chat_history.jsonl path to the file. */
369
+ private resolveChatPath(sessionPath: string): string {
370
+ return sessionPath.endsWith('.jsonl') ? sessionPath : path.join(sessionPath, CHAT_HISTORY_FILE);
371
+ }
372
+
373
+ private getProjectDir(cwd: string): string {
374
+ return path.join(this.sessionsDir, encodeURIComponent(cwd));
375
+ }
376
+
377
+ /**
378
+ * Resolve the working directory a session group dir was created for.
379
+ *
380
+ * The common case is `decodeURIComponent(<group-name>)`. For paths whose
381
+ * encoded form exceeds the filesystem limit Grok uses a slug+hash and records
382
+ * the original path in a `.cwd` file inside the group — prefer that when
383
+ * present.
384
+ */
385
+ private decodeGroupCwd(groupName: string, groupDir: string): string {
386
+ const fromFile = safeReadFile(path.join(groupDir, CWD_FILE));
387
+ if (fromFile !== undefined && fromFile.trim()) return fromFile.trim();
388
+ try {
389
+ return decodeURIComponent(groupName);
390
+ } catch {
391
+ return '';
392
+ }
393
+ }
394
+ }
@@ -2,6 +2,7 @@ export { ClaudeCodeAdapter } from './ClaudeCodeAdapter.js';
2
2
  export { CodexAdapter } from './CodexAdapter.js';
3
3
  export { CopilotAdapter } from './CopilotAdapter.js';
4
4
  export { GeminiCliAdapter } from './GeminiCliAdapter.js';
5
+ export { GrokCliAdapter } from './GrokCliAdapter.js';
5
6
  export { OpenCodeAdapter } from './OpenCodeAdapter.js';
6
7
  export { PiAdapter } from './PiAdapter.js';
7
8
  export { AgentStatus } from './AgentAdapter.js';
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ export { ClaudeCodeAdapter } from './adapters/ClaudeCodeAdapter.js';
4
4
  export { CodexAdapter } from './adapters/CodexAdapter.js';
5
5
  export { CopilotAdapter } from './adapters/CopilotAdapter.js';
6
6
  export { GeminiCliAdapter } from './adapters/GeminiCliAdapter.js';
7
+ export { GrokCliAdapter } from './adapters/GrokCliAdapter.js';
7
8
  export { OpenCodeAdapter } from './adapters/OpenCodeAdapter.js';
8
9
  export { PiAdapter } from './adapters/PiAdapter.js';
9
10
  export { AgentStatus } from './adapters/AgentAdapter.js';
@@ -1,7 +1,7 @@
1
1
  import path from 'path';
2
2
  import type { AgentType } from '../adapters/AgentAdapter.js';
3
3
 
4
- export type StartableAgentType = Extract<AgentType, 'claude' | 'codex' | 'copilot' | 'gemini_cli' | 'opencode' | 'pi'>;
4
+ export type StartableAgentType = Extract<AgentType, 'claude' | 'codex' | 'copilot' | 'gemini_cli' | 'grok_cli' | 'opencode' | 'pi'>;
5
5
 
6
6
  export interface AgentConfig {
7
7
  /** Shell command to launch the agent (sent to tmux via `send-keys`). */
@@ -20,6 +20,7 @@ export const AGENTS: Record<StartableAgentType, AgentConfig> = {
20
20
  codex: { command: 'codex', matches: matchArgv0('codex') },
21
21
  copilot: { command: 'copilot', matches: matchArgv0Name('copilot-cli') },
22
22
  gemini_cli: { command: 'gemini', matches: matchAnyToken('gemini') },
23
+ grok_cli: { command: 'grok', matches: matchArgv0('grok') },
23
24
  opencode: { command: 'opencode', matches: matchArgv0('opencode') },
24
25
  pi: { command: 'pi', matches: matchAnyBasename(['pi']) },
25
26
  };