@ai-devkit/agent-manager 0.22.1 → 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/README.md +3 -0
- package/dist/__tests__/AgentManager.test.js +9 -1
- package/dist/__tests__/AgentManager.test.js.map +1 -1
- package/dist/__tests__/adapters/GrokCliAdapter.test.js +403 -0
- package/dist/__tests__/adapters/GrokCliAdapter.test.js.map +1 -0
- package/dist/__tests__/terminal/TerminalFocusManager.test.js +180 -0
- package/dist/__tests__/terminal/TerminalFocusManager.test.js.map +1 -1
- package/dist/__tests__/terminal/TtyWriter.test.js +206 -0
- package/dist/__tests__/terminal/TtyWriter.test.js.map +1 -1
- package/dist/__tests__/utils/agent-requests.test.js +90 -0
- package/dist/__tests__/utils/agent-requests.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 +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/terminal/TerminalFocusManager.d.ts +11 -0
- package/dist/terminal/TerminalFocusManager.d.ts.map +1 -1
- package/dist/terminal/TerminalFocusManager.js +84 -10
- package/dist/terminal/TerminalFocusManager.js.map +1 -1
- package/dist/terminal/TtyWriter.d.ts +19 -0
- package/dist/terminal/TtyWriter.d.ts.map +1 -1
- package/dist/terminal/TtyWriter.js +167 -1
- package/dist/terminal/TtyWriter.js.map +1 -1
- package/dist/utils/agent-requests.d.ts +10 -0
- package/dist/utils/agent-requests.d.ts.map +1 -0
- package/dist/utils/agent-requests.js +22 -0
- package/dist/utils/agent-requests.js.map +1 -0
- 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__/AgentManager.test.ts +7 -1
- package/src/__tests__/adapters/GrokCliAdapter.test.ts +307 -0
- package/src/__tests__/terminal/TerminalFocusManager.test.ts +187 -0
- package/src/__tests__/terminal/TtyWriter.test.ts +234 -0
- package/src/__tests__/utils/agent-requests.test.ts +74 -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 +4 -0
- package/src/terminal/TerminalFocusManager.ts +103 -11
- package/src/terminal/TtyWriter.ts +161 -1
- package/src/utils/agent-requests.ts +28 -0
- package/src/utils/agents.ts +2 -1
|
@@ -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
|
+
}
|
package/src/adapters/index.ts
CHANGED
|
@@ -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';
|
|
@@ -30,3 +31,6 @@ export type { RegistryEntry } from './utils/AgentRegistry.js';
|
|
|
30
31
|
export { TmuxManager } from './terminal/TmuxManager.js';
|
|
31
32
|
export { AGENTS } from './utils/agents.js';
|
|
32
33
|
export type { AgentConfig, StartableAgentType } from './utils/agents.js';
|
|
34
|
+
|
|
35
|
+
export type { AgentRequest } from './utils/agent-requests.js';
|
|
36
|
+
export { getAgentRequestPath, readLatestAgentRequest, writeAgentRequest } from './utils/agent-requests.js';
|
|
@@ -7,6 +7,7 @@ const execFileAsync = promisify(execFile);
|
|
|
7
7
|
|
|
8
8
|
export enum TerminalType {
|
|
9
9
|
TMUX = 'tmux',
|
|
10
|
+
WEZTERM = 'wezterm',
|
|
10
11
|
ITERM2 = 'iterm2',
|
|
11
12
|
TERMINAL_APP = 'terminal-app',
|
|
12
13
|
UNKNOWN = 'unknown',
|
|
@@ -14,11 +15,31 @@ export enum TerminalType {
|
|
|
14
15
|
|
|
15
16
|
export interface TerminalLocation {
|
|
16
17
|
type: TerminalType;
|
|
17
|
-
identifier: string; // e.g., "session:window.pane" for tmux, or TTY for others
|
|
18
|
+
identifier: string; // e.g., "session:window.pane" for tmux, WezTerm pane id, or TTY for others
|
|
18
19
|
tty: string; // e.g., "/dev/ttys030"
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Subset of a `wezterm cli list --format json` entry. Only `pane_id` and
|
|
24
|
+
* `tty_name` are read; extra fields are ignored so schema additions across
|
|
25
|
+
* WezTerm versions don't break parsing. (The TTY is exposed as `tty_name` in
|
|
26
|
+
* the JSON, not `tty`.)
|
|
27
|
+
*/
|
|
28
|
+
interface WeztermPaneEntry {
|
|
29
|
+
pane_id?: number;
|
|
30
|
+
tty_name?: string | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Optional trace sink. When provided to {@link TerminalFocusManager}, each
|
|
35
|
+
* discovery/focus step reports a human-readable line so callers (e.g. the
|
|
36
|
+
* `agent open --debug` command) can inspect the matching/focus decision path.
|
|
37
|
+
*/
|
|
38
|
+
export type TerminalDebugLogger = (message: string) => void;
|
|
39
|
+
|
|
21
40
|
export class TerminalFocusManager {
|
|
41
|
+
constructor(private readonly debug?: TerminalDebugLogger) {}
|
|
42
|
+
|
|
22
43
|
/**
|
|
23
44
|
* Find the terminal location (emulator info) for a given process ID
|
|
24
45
|
*/
|
|
@@ -27,24 +48,47 @@ export class TerminalFocusManager {
|
|
|
27
48
|
|
|
28
49
|
// If no TTY or invalid, we can't find the terminal
|
|
29
50
|
if (!ttyShort || ttyShort === '?') {
|
|
51
|
+
this.debug?.(`findTerminal(pid=${pid}): no usable TTY, cannot resolve terminal`);
|
|
30
52
|
return null;
|
|
31
53
|
}
|
|
32
54
|
|
|
33
55
|
const fullTty = `/dev/${ttyShort}`;
|
|
56
|
+
this.debug?.(`findTerminal(pid=${pid}): resolving terminal for ${fullTty}`);
|
|
34
57
|
|
|
35
58
|
// 1. Check tmux (most specific if running inside it)
|
|
36
59
|
const tmuxLocation = await this.findTmuxPane(fullTty);
|
|
37
|
-
if (tmuxLocation)
|
|
60
|
+
if (tmuxLocation) {
|
|
61
|
+
this.debug?.(`findTerminal: matched tmux (identifier=${tmuxLocation.identifier})`);
|
|
62
|
+
return tmuxLocation;
|
|
63
|
+
}
|
|
64
|
+
this.debug?.('findTerminal: tmux no match');
|
|
65
|
+
|
|
66
|
+
// 2. Check WezTerm (cross-platform, via its CLI — no AppleScript)
|
|
67
|
+
const weztermLocation = await this.findWeztermPane(fullTty);
|
|
68
|
+
if (weztermLocation) {
|
|
69
|
+
this.debug?.(`findTerminal: matched wezterm (pane_id=${weztermLocation.identifier})`);
|
|
70
|
+
return weztermLocation;
|
|
71
|
+
}
|
|
72
|
+
this.debug?.('findTerminal: wezterm no match');
|
|
38
73
|
|
|
39
|
-
//
|
|
74
|
+
// 3. Check iTerm2
|
|
40
75
|
const itermLocation = await this.findITerm2Session(fullTty);
|
|
41
|
-
if (itermLocation)
|
|
76
|
+
if (itermLocation) {
|
|
77
|
+
this.debug?.(`findTerminal: matched iTerm2 (tty=${itermLocation.tty})`);
|
|
78
|
+
return itermLocation;
|
|
79
|
+
}
|
|
80
|
+
this.debug?.('findTerminal: iTerm2 no match');
|
|
42
81
|
|
|
43
|
-
//
|
|
82
|
+
// 4. Check Terminal.app
|
|
44
83
|
const terminalAppLocation = await this.findTerminalAppWindow(fullTty);
|
|
45
|
-
if (terminalAppLocation)
|
|
84
|
+
if (terminalAppLocation) {
|
|
85
|
+
this.debug?.(`findTerminal: matched Terminal.app (tty=${terminalAppLocation.tty})`);
|
|
86
|
+
return terminalAppLocation;
|
|
87
|
+
}
|
|
88
|
+
this.debug?.('findTerminal: Terminal.app no match');
|
|
46
89
|
|
|
47
|
-
//
|
|
90
|
+
// 5. Fallback: we know the TTY but not the emulator wrapper
|
|
91
|
+
this.debug?.('findTerminal: no emulator matched; returning UNKNOWN');
|
|
48
92
|
return {
|
|
49
93
|
type: TerminalType.UNKNOWN,
|
|
50
94
|
identifier: '',
|
|
@@ -56,17 +100,65 @@ export class TerminalFocusManager {
|
|
|
56
100
|
* Focus the terminal identified by the location
|
|
57
101
|
*/
|
|
58
102
|
async focusTerminal(location: TerminalLocation): Promise<boolean> {
|
|
103
|
+
this.debug?.(`focusTerminal: focusing ${location.type} (identifier=${location.identifier}, tty=${location.tty})`);
|
|
104
|
+
let success = false;
|
|
59
105
|
try {
|
|
60
106
|
switch (location.type) {
|
|
61
107
|
case TerminalType.TMUX:
|
|
62
|
-
|
|
108
|
+
success = await this.focusTmuxPane(location.identifier);
|
|
109
|
+
break;
|
|
110
|
+
case TerminalType.WEZTERM:
|
|
111
|
+
success = await this.focusWeztermPane(location.identifier);
|
|
112
|
+
break;
|
|
63
113
|
case TerminalType.ITERM2:
|
|
64
|
-
|
|
114
|
+
success = await this.focusITerm2Session(location.tty);
|
|
115
|
+
break;
|
|
65
116
|
case TerminalType.TERMINAL_APP:
|
|
66
|
-
|
|
117
|
+
success = await this.focusTerminalAppWindow(location.tty);
|
|
118
|
+
break;
|
|
67
119
|
default:
|
|
68
|
-
|
|
120
|
+
success = false;
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
success = false;
|
|
124
|
+
}
|
|
125
|
+
this.debug?.(`focusTerminal: ${success ? 'succeeded' : 'failed'} for ${location.type}`);
|
|
126
|
+
return success;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private async findWeztermPane(tty: string): Promise<TerminalLocation | null> {
|
|
130
|
+
try {
|
|
131
|
+
const { stdout } = await execFileAsync('wezterm', [
|
|
132
|
+
'cli', 'list', '--format', 'json',
|
|
133
|
+
]);
|
|
134
|
+
|
|
135
|
+
const panes = JSON.parse(stdout) as WeztermPaneEntry[];
|
|
136
|
+
if (!Array.isArray(panes)) return null;
|
|
137
|
+
|
|
138
|
+
for (const pane of panes) {
|
|
139
|
+
if (
|
|
140
|
+
pane &&
|
|
141
|
+
typeof pane.tty_name === 'string' &&
|
|
142
|
+
pane.tty_name === tty &&
|
|
143
|
+
pane.pane_id != null
|
|
144
|
+
) {
|
|
145
|
+
return {
|
|
146
|
+
type: TerminalType.WEZTERM,
|
|
147
|
+
identifier: String(pane.pane_id),
|
|
148
|
+
tty,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
69
151
|
}
|
|
152
|
+
} catch {
|
|
153
|
+
// wezterm not installed, not running, or returned invalid JSON
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
private async focusWeztermPane(paneId: string): Promise<boolean> {
|
|
159
|
+
try {
|
|
160
|
+
await execFileAsync('wezterm', ['cli', 'activate-pane', '--pane-id', paneId]);
|
|
161
|
+
return true;
|
|
70
162
|
} catch {
|
|
71
163
|
return false;
|
|
72
164
|
}
|