@ai-devkit/agent-manager 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/AgentManager.d.ts +7 -0
  2. package/dist/AgentManager.d.ts.map +1 -1
  3. package/dist/AgentManager.js +9 -0
  4. package/dist/AgentManager.js.map +1 -1
  5. package/dist/adapters/ClaudeCodeAdapter.d.ts +2 -44
  6. package/dist/adapters/ClaudeCodeAdapter.d.ts.map +1 -1
  7. package/dist/adapters/ClaudeCodeAdapter.js +10 -285
  8. package/dist/adapters/ClaudeCodeAdapter.js.map +1 -1
  9. package/dist/adapters/GeminiCliAdapter.d.ts +83 -0
  10. package/dist/adapters/GeminiCliAdapter.d.ts.map +1 -0
  11. package/dist/adapters/GeminiCliAdapter.js +438 -0
  12. package/dist/adapters/GeminiCliAdapter.js.map +1 -0
  13. package/dist/adapters/index.d.ts +1 -0
  14. package/dist/adapters/index.d.ts.map +1 -1
  15. package/dist/adapters/index.js +3 -1
  16. package/dist/adapters/index.js.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/terminal/TerminalFocusManager.d.ts.map +1 -1
  22. package/dist/terminal/TerminalFocusManager.js +38 -27
  23. package/dist/terminal/TerminalFocusManager.js.map +1 -1
  24. package/dist/utils/ClaudeSessionParser.d.ts +112 -0
  25. package/dist/utils/ClaudeSessionParser.d.ts.map +1 -0
  26. package/dist/utils/ClaudeSessionParser.js +334 -0
  27. package/dist/utils/ClaudeSessionParser.js.map +1 -0
  28. package/dist/utils/process.d.ts +3 -4
  29. package/dist/utils/process.d.ts.map +1 -1
  30. package/dist/utils/process.js +11 -15
  31. package/dist/utils/process.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/AgentManager.ts +11 -1
  34. package/src/__tests__/adapters/ClaudeCodeAdapter.test.ts +29 -29
  35. package/src/__tests__/adapters/GeminiCliAdapter.test.ts +790 -0
  36. package/src/__tests__/utils/process.test.ts +27 -27
  37. package/src/adapters/ClaudeCodeAdapter.ts +17 -365
  38. package/src/adapters/GeminiCliAdapter.ts +488 -0
  39. package/src/adapters/index.ts +1 -0
  40. package/src/index.ts +1 -0
  41. package/src/terminal/TerminalFocusManager.ts +38 -26
  42. package/src/utils/ClaudeSessionParser.ts +383 -0
  43. package/src/utils/process.ts +21 -24
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Gemini CLI Adapter
3
+ *
4
+ * Detects running Gemini CLI agents by:
5
+ * 1. Finding running gemini processes via shared listAgentProcesses()
6
+ * 2. Enriching with CWD and start times via shared enrichProcesses()
7
+ * 3. Discovering session files from ~/.gemini/tmp/<shortId>/chats/session-*.json
8
+ * 4. Matching sessions to processes via shared matchProcessesToSessions()
9
+ * using sha256(cwd) === session.projectHash as the resolvedCwd source
10
+ * 5. Extracting summary from the most recent user message in the session JSON
11
+ */
12
+
13
+ import * as crypto from 'crypto';
14
+ import * as fs from 'fs';
15
+ import * as path from 'path';
16
+ import type { AgentAdapter, AgentInfo, ProcessInfo, ConversationMessage } from './AgentAdapter';
17
+ import { AgentStatus } from './AgentAdapter';
18
+ import { listAgentProcesses, enrichProcesses } from '../utils/process';
19
+ import type { SessionFile } from '../utils/session';
20
+ import { matchProcessesToSessions, generateAgentName } from '../utils/matching';
21
+
22
+ /**
23
+ * A single Gemini CLI message content part. Mirrors the `{text?: string}`
24
+ * shape that Gemini writes for user message parts (derived from the
25
+ * Gemini API `Content.parts[]` schema). Non-text part variants (data,
26
+ * file, etc.) are preserved via the index signature but ignored by
27
+ * `resolveContent` since the adapter only surfaces human-readable text.
28
+ */
29
+ interface GeminiContentPart {
30
+ text?: string;
31
+ [key: string]: unknown;
32
+ }
33
+
34
+ type GeminiMessageContent = string | GeminiContentPart[];
35
+
36
+ interface GeminiMessageEntry {
37
+ id?: string;
38
+ timestamp?: string;
39
+ type?: string;
40
+ /**
41
+ * Gemini CLI stores two different content shapes depending on the
42
+ * message origin:
43
+ * - `type: "user"` messages carry the raw Part[] from userContent.parts
44
+ * (e.g. `[{ text: "hello" }]`).
45
+ * - `type: "gemini"` (assistant) messages carry a pre-joined string
46
+ * built from `consolidatedParts.filter(p => p.text).join('').trim()`.
47
+ * Both forms must be normalized via resolveContent before any string
48
+ * operation is applied.
49
+ */
50
+ content?: GeminiMessageContent;
51
+ displayContent?: GeminiMessageContent;
52
+ }
53
+
54
+ interface GeminiSessionFile {
55
+ sessionId?: string;
56
+ projectHash?: string;
57
+ startTime?: string;
58
+ lastUpdated?: string;
59
+ messages?: GeminiMessageEntry[];
60
+ directories?: string[];
61
+ kind?: string;
62
+ }
63
+
64
+ interface GeminiSession {
65
+ sessionId: string;
66
+ projectPath: string;
67
+ summary: string;
68
+ sessionStart: Date;
69
+ lastActive: Date;
70
+ lastMessageType?: string;
71
+ }
72
+
73
+ export class GeminiCliAdapter implements AgentAdapter {
74
+ readonly type = 'gemini_cli' as const;
75
+
76
+ private static readonly IDLE_THRESHOLD_MINUTES = 5;
77
+ private static readonly SESSION_FILE_PREFIX = 'session-';
78
+ private static readonly CHATS_DIR_NAME = 'chats';
79
+ private static readonly TMP_DIR_NAME = 'tmp';
80
+
81
+ private geminiTmpDir: string;
82
+
83
+ constructor() {
84
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
85
+ this.geminiTmpDir = path.join(homeDir, '.gemini', GeminiCliAdapter.TMP_DIR_NAME);
86
+ }
87
+
88
+ canHandle(processInfo: ProcessInfo): boolean {
89
+ return this.isGeminiExecutable(processInfo.command);
90
+ }
91
+
92
+ /**
93
+ * Detect running Gemini CLI agents.
94
+ *
95
+ * Gemini CLI ships as a Node script (`bundle/gemini.js` with shebang
96
+ * `#!/usr/bin/env node`) — unlike Claude Code (native binary per
97
+ * platform) or Codex CLI (Node wrapper that execs a native Rust
98
+ * binary). The primary running process is therefore the Node runtime
99
+ * itself, and `ps aux` lists it as `node /path/to/gemini ...` with
100
+ * argv[0] = `node`. We scan the Node process pool via the shared
101
+ * helper and keep only those whose command line references the gemini
102
+ * executable or script via isGeminiExecutable().
103
+ */
104
+ async detectAgents(): Promise<AgentInfo[]> {
105
+ const nodeProcesses = enrichProcesses(listAgentProcesses('node'));
106
+ const processes = nodeProcesses.filter((proc) => this.isGeminiExecutable(proc.command));
107
+ if (processes.length === 0) return [];
108
+
109
+ const { sessions, contentCache } = this.discoverSessions(processes);
110
+ if (sessions.length === 0) {
111
+ return processes.map((p) => this.mapProcessOnlyAgent(p));
112
+ }
113
+
114
+ const matches = matchProcessesToSessions(processes, sessions);
115
+ const matchedPids = new Set(matches.map((m) => m.process.pid));
116
+ const agents: AgentInfo[] = [];
117
+
118
+ for (const match of matches) {
119
+ const cachedContent = contentCache.get(match.session.filePath);
120
+ const sessionData = this.parseSession(cachedContent, match.session.filePath);
121
+ if (sessionData) {
122
+ agents.push(this.mapSessionToAgent(sessionData, match.process, match.session.filePath));
123
+ } else {
124
+ matchedPids.delete(match.process.pid);
125
+ }
126
+ }
127
+
128
+ for (const proc of processes) {
129
+ if (!matchedPids.has(proc.pid)) {
130
+ agents.push(this.mapProcessOnlyAgent(proc));
131
+ }
132
+ }
133
+
134
+ return agents;
135
+ }
136
+
137
+ /**
138
+ * Discover session files for the given processes.
139
+ *
140
+ * Gemini CLI writes sessions to ~/.gemini/tmp/<shortId>/chats/session-*.json
141
+ * where <shortId> is opaque (managed by a project registry). We scan every
142
+ * shortId directory and filter by matching session.projectHash against
143
+ * sha256(process.cwd) to bind each session to a candidate process CWD.
144
+ */
145
+ private discoverSessions(processes: ProcessInfo[]): {
146
+ sessions: SessionFile[];
147
+ contentCache: Map<string, string>;
148
+ } {
149
+ const empty = { sessions: [] as SessionFile[], contentCache: new Map<string, string>() };
150
+ if (!fs.existsSync(this.geminiTmpDir)) return empty;
151
+
152
+ const cwdHashMap = this.buildCwdHashMap(processes);
153
+ if (cwdHashMap.size === 0) return empty;
154
+
155
+ const contentCache = new Map<string, string>();
156
+ const sessions: SessionFile[] = [];
157
+
158
+ let shortIdEntries: string[];
159
+ try {
160
+ shortIdEntries = fs.readdirSync(this.geminiTmpDir);
161
+ } catch {
162
+ return empty;
163
+ }
164
+
165
+ for (const shortId of shortIdEntries) {
166
+ const chatsDir = path.join(this.geminiTmpDir, shortId, GeminiCliAdapter.CHATS_DIR_NAME);
167
+ try {
168
+ if (!fs.statSync(chatsDir).isDirectory()) continue;
169
+ } catch {
170
+ continue;
171
+ }
172
+
173
+ let chatFiles: string[];
174
+ try {
175
+ chatFiles = fs.readdirSync(chatsDir);
176
+ } catch {
177
+ continue;
178
+ }
179
+
180
+ for (const fileName of chatFiles) {
181
+ if (!fileName.startsWith(GeminiCliAdapter.SESSION_FILE_PREFIX) || !fileName.endsWith('.json')) {
182
+ continue;
183
+ }
184
+
185
+ const filePath = path.join(chatsDir, fileName);
186
+
187
+ let content: string;
188
+ try {
189
+ content = fs.readFileSync(filePath, 'utf-8');
190
+ } catch {
191
+ continue;
192
+ }
193
+
194
+ let parsed: GeminiSessionFile;
195
+ try {
196
+ parsed = JSON.parse(content);
197
+ } catch {
198
+ continue;
199
+ }
200
+
201
+ if (!parsed.projectHash) continue;
202
+ const resolvedCwd = cwdHashMap.get(parsed.projectHash);
203
+ if (!resolvedCwd) continue;
204
+
205
+ let birthtimeMs = 0;
206
+ try {
207
+ birthtimeMs = fs.statSync(filePath).birthtimeMs;
208
+ } catch {
209
+ continue;
210
+ }
211
+
212
+ const sessionId =
213
+ parsed.sessionId || fileName.replace(/\.json$/, '');
214
+
215
+ contentCache.set(filePath, content);
216
+ sessions.push({
217
+ sessionId,
218
+ filePath,
219
+ projectDir: chatsDir,
220
+ birthtimeMs,
221
+ resolvedCwd,
222
+ });
223
+ }
224
+ }
225
+
226
+ return { sessions, contentCache };
227
+ }
228
+
229
+ private buildCwdHashMap(processes: ProcessInfo[]): Map<string, string> {
230
+ const map = new Map<string, string>();
231
+ for (const proc of processes) {
232
+ if (!proc.cwd) continue;
233
+ // Gemini CLI resolves its project root by walking up from the
234
+ // startup directory looking for a `.git` boundary marker. A
235
+ // session's projectHash therefore tracks that ancestor rather
236
+ // than the process' actual CWD. Enumerate every ancestor as a
237
+ // candidate so subdirectory invocations still line up with the
238
+ // session the Gemini process wrote.
239
+ for (const candidate of this.candidateProjectRoots(proc.cwd)) {
240
+ if (!map.has(this.hashProjectRoot(candidate))) {
241
+ map.set(this.hashProjectRoot(candidate), proc.cwd);
242
+ }
243
+ }
244
+ }
245
+ return map;
246
+ }
247
+
248
+ private candidateProjectRoots(cwd: string): string[] {
249
+ const roots: string[] = [];
250
+ let current = path.resolve(cwd);
251
+ let parent = path.dirname(current);
252
+ while (parent !== current) {
253
+ roots.push(current);
254
+ current = parent;
255
+ parent = path.dirname(current);
256
+ }
257
+ roots.push(current);
258
+ return roots;
259
+ }
260
+
261
+ private hashProjectRoot(projectRoot: string): string {
262
+ return crypto.createHash('sha256').update(projectRoot).digest('hex');
263
+ }
264
+
265
+ /**
266
+ * Parse session file content into GeminiSession.
267
+ * Uses cached content if available, otherwise reads from disk.
268
+ */
269
+ private parseSession(cachedContent: string | undefined, filePath: string): GeminiSession | null {
270
+ let content: string;
271
+ if (cachedContent !== undefined) {
272
+ content = cachedContent;
273
+ } else {
274
+ try {
275
+ content = fs.readFileSync(filePath, 'utf-8');
276
+ } catch {
277
+ return null;
278
+ }
279
+ }
280
+
281
+ let parsed: GeminiSessionFile;
282
+ try {
283
+ parsed = JSON.parse(content);
284
+ } catch {
285
+ return null;
286
+ }
287
+
288
+ if (!parsed.sessionId) return null;
289
+
290
+ const messages = Array.isArray(parsed.messages) ? parsed.messages : [];
291
+ const lastEntry = messages.length > 0 ? messages[messages.length - 1] : undefined;
292
+
293
+ let mtime: Date | null = null;
294
+ try {
295
+ mtime = fs.statSync(filePath).mtime;
296
+ } catch {
297
+ mtime = null;
298
+ }
299
+
300
+ const lastActive =
301
+ this.parseTimestamp(parsed.lastUpdated) ||
302
+ this.parseTimestamp(lastEntry?.timestamp) ||
303
+ mtime ||
304
+ new Date();
305
+
306
+ const sessionStart =
307
+ this.parseTimestamp(parsed.startTime) || lastActive;
308
+
309
+ const projectPath =
310
+ Array.isArray(parsed.directories) && parsed.directories.length > 0
311
+ ? parsed.directories[0]
312
+ : '';
313
+
314
+ return {
315
+ sessionId: parsed.sessionId,
316
+ projectPath,
317
+ summary: this.extractSummary(messages),
318
+ sessionStart,
319
+ lastActive,
320
+ lastMessageType: lastEntry?.type,
321
+ };
322
+ }
323
+
324
+ private mapSessionToAgent(session: GeminiSession, processInfo: ProcessInfo, filePath: string): AgentInfo {
325
+ const projectPath = session.projectPath || processInfo.cwd || '';
326
+ return {
327
+ name: generateAgentName(projectPath, processInfo.pid),
328
+ type: this.type,
329
+ status: this.determineStatus(session),
330
+ summary: session.summary || 'Gemini CLI session active',
331
+ pid: processInfo.pid,
332
+ projectPath,
333
+ sessionId: session.sessionId,
334
+ lastActive: session.lastActive,
335
+ sessionFilePath: filePath,
336
+ };
337
+ }
338
+
339
+ private mapProcessOnlyAgent(processInfo: ProcessInfo): AgentInfo {
340
+ return {
341
+ name: generateAgentName(processInfo.cwd || '', processInfo.pid),
342
+ type: this.type,
343
+ status: AgentStatus.RUNNING,
344
+ summary: 'Gemini CLI process running',
345
+ pid: processInfo.pid,
346
+ projectPath: processInfo.cwd || '',
347
+ sessionId: `pid-${processInfo.pid}`,
348
+ lastActive: new Date(),
349
+ };
350
+ }
351
+
352
+ private parseTimestamp(value?: string): Date | null {
353
+ if (!value) return null;
354
+ const timestamp = new Date(value);
355
+ return Number.isNaN(timestamp.getTime()) ? null : timestamp;
356
+ }
357
+
358
+ private determineStatus(session: GeminiSession): AgentStatus {
359
+ const diffMs = Date.now() - session.lastActive.getTime();
360
+ const diffMinutes = diffMs / 60000;
361
+
362
+ if (diffMinutes > GeminiCliAdapter.IDLE_THRESHOLD_MINUTES) {
363
+ return AgentStatus.IDLE;
364
+ }
365
+
366
+ if (session.lastMessageType === 'gemini' || session.lastMessageType === 'assistant') {
367
+ return AgentStatus.WAITING;
368
+ }
369
+
370
+ return AgentStatus.RUNNING;
371
+ }
372
+
373
+ private extractSummary(messages: GeminiMessageEntry[]): string {
374
+ for (let i = messages.length - 1; i >= 0; i--) {
375
+ const entry = messages[i];
376
+ if (entry?.type !== 'user') continue;
377
+ const text = this.messageText(entry).trim();
378
+ if (text) return this.truncate(text, 120);
379
+ }
380
+
381
+ return 'Gemini CLI session active';
382
+ }
383
+
384
+ /**
385
+ * Normalize an entry's content/displayContent into a plain string.
386
+ * Prefers displayContent when both are present (matches Gemini CLI's
387
+ * own rendering priority for the /chat UI).
388
+ */
389
+ private messageText(entry: GeminiMessageEntry): string {
390
+ const displayText = this.resolveContent(entry.displayContent);
391
+ if (displayText) return displayText;
392
+ return this.resolveContent(entry.content);
393
+ }
394
+
395
+ /**
396
+ * Collapse a Gemini message content field into plain text.
397
+ * Accepts either a pre-joined string (assistant turns) or a Part[]
398
+ * list (user turns carrying `[{text: "..."}]`). Non-text part
399
+ * variants (data, file) are dropped since this helper is only used
400
+ * for summary/conversation rendering.
401
+ */
402
+ private resolveContent(content: GeminiMessageContent | undefined): string {
403
+ if (!content) return '';
404
+ if (typeof content === 'string') return content;
405
+ if (!Array.isArray(content)) return '';
406
+
407
+ const parts: string[] = [];
408
+ for (const part of content) {
409
+ if (part && typeof part.text === 'string' && part.text) {
410
+ parts.push(part.text);
411
+ }
412
+ }
413
+ return parts.join('');
414
+ }
415
+
416
+ private truncate(value: string, maxLength: number): string {
417
+ if (value.length <= maxLength) return value;
418
+ return `${value.slice(0, maxLength - 3)}...`;
419
+ }
420
+
421
+ private isGeminiExecutable(command: string): boolean {
422
+ // Accept any token in the command line whose basename matches a
423
+ // known gemini entrypoint. This is intentionally broader than the
424
+ // other adapters' argv[0]-only check because the Node-script
425
+ // distribution puts the real gemini path in argv[1..], not argv[0].
426
+ for (const token of command.trim().split(/\s+/)) {
427
+ const base = path.basename(token).toLowerCase();
428
+ if (base === 'gemini' || base === 'gemini.exe' || base === 'gemini.js') {
429
+ return true;
430
+ }
431
+ }
432
+ return false;
433
+ }
434
+
435
+ /**
436
+ * Read the full conversation from a Gemini CLI session JSON file.
437
+ *
438
+ * Gemini sessions store messages in an array with `type` field — typically
439
+ * 'user' or 'gemini' for visible turns, with tool and system entries mixed in.
440
+ */
441
+ getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {
442
+ const verbose = options?.verbose ?? false;
443
+
444
+ let content: string;
445
+ try {
446
+ content = fs.readFileSync(sessionFilePath, 'utf-8');
447
+ } catch {
448
+ return [];
449
+ }
450
+
451
+ let parsed: GeminiSessionFile;
452
+ try {
453
+ parsed = JSON.parse(content);
454
+ } catch {
455
+ return [];
456
+ }
457
+
458
+ const messages: ConversationMessage[] = [];
459
+ if (!Array.isArray(parsed.messages)) return messages;
460
+
461
+ for (const entry of parsed.messages) {
462
+ const entryType = entry?.type;
463
+ if (!entryType) continue;
464
+
465
+ let role: ConversationMessage['role'];
466
+ if (entryType === 'user') {
467
+ role = 'user';
468
+ } else if (entryType === 'gemini' || entryType === 'assistant') {
469
+ role = 'assistant';
470
+ } else if (verbose) {
471
+ role = 'system';
472
+ } else {
473
+ continue;
474
+ }
475
+
476
+ const text = this.messageText(entry).trim();
477
+ if (!text) continue;
478
+
479
+ messages.push({
480
+ role,
481
+ content: text,
482
+ timestamp: entry.timestamp,
483
+ });
484
+ }
485
+
486
+ return messages;
487
+ }
488
+ }
@@ -1,4 +1,5 @@
1
1
  export { ClaudeCodeAdapter } from './ClaudeCodeAdapter';
2
2
  export { CodexAdapter } from './CodexAdapter';
3
+ export { GeminiCliAdapter } from './GeminiCliAdapter';
3
4
  export { AgentStatus } from './AgentAdapter';
4
5
  export type { AgentAdapter, AgentType, AgentInfo, ProcessInfo } from './AgentAdapter';
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ export { AgentManager } from './AgentManager';
2
2
 
3
3
  export { ClaudeCodeAdapter } from './adapters/ClaudeCodeAdapter';
4
4
  export { CodexAdapter } from './adapters/CodexAdapter';
5
+ export { GeminiCliAdapter } from './adapters/GeminiCliAdapter';
5
6
  export { AgentStatus } from './adapters/AgentAdapter';
6
7
  export type { AgentAdapter, AgentType, AgentInfo, ProcessInfo, ConversationMessage } from './adapters/AgentAdapter';
7
8
 
@@ -1,8 +1,7 @@
1
- import { exec, execFile } from 'child_process';
1
+ import { execFile } from 'child_process';
2
2
  import { promisify } from 'util';
3
3
  import { getProcessTty } from '../utils/process';
4
4
 
5
- const execAsync = promisify(exec);
6
5
  const execFileAsync = promisify(execFile);
7
6
 
8
7
  export enum TerminalType {
@@ -18,6 +17,10 @@ export interface TerminalLocation {
18
17
  tty: string; // e.g., "/dev/ttys030"
19
18
  }
20
19
 
20
+ function escapeAppleScript(text: string): string {
21
+ return text.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
22
+ }
23
+
21
24
  export class TerminalFocusManager {
22
25
  /**
23
26
  * Find the terminal location (emulator info) for a given process ID
@@ -67,17 +70,16 @@ export class TerminalFocusManager {
67
70
  default:
68
71
  return false;
69
72
  }
70
- } catch (error) {
73
+ } catch {
71
74
  return false;
72
75
  }
73
76
  }
74
77
 
75
78
  private async findTmuxPane(tty: string): Promise<TerminalLocation | null> {
76
79
  try {
77
- // List all panes with their TTYs and identifiers
78
- // Format: /dev/ttys001|my-session:1.1
79
- // using | as separator to handle spaces in session names
80
- const { stdout } = await execAsync("tmux list-panes -a -F '#{pane_tty}|#{session_name}:#{window_index}.#{pane_index}'");
80
+ const { stdout } = await execFileAsync('tmux', [
81
+ 'list-panes', '-a', '-F', '#{pane_tty}|#{session_name}:#{window_index}.#{pane_index}'
82
+ ]);
81
83
 
82
84
  const lines = stdout.trim().split('\n');
83
85
  for (const line of lines) {
@@ -91,7 +93,7 @@ export class TerminalFocusManager {
91
93
  };
92
94
  }
93
95
  }
94
- } catch (error) {
96
+ } catch {
95
97
  // tmux might not be installed or running
96
98
  }
97
99
  return null;
@@ -100,15 +102,19 @@ export class TerminalFocusManager {
100
102
  private async findITerm2Session(tty: string): Promise<TerminalLocation | null> {
101
103
  try {
102
104
  // Check if iTerm2 is running first to avoid launching it
103
- const { stdout: isRunning } = await execAsync('pgrep -x iTerm2 || echo "no"');
104
- if (isRunning.trim() === "no") return null;
105
+ await execFileAsync('pgrep', ['-x', 'iTerm2']);
106
+ } catch {
107
+ return null;
108
+ }
105
109
 
110
+ try {
111
+ const escapedTty = escapeAppleScript(tty);
106
112
  const script = `
107
113
  tell application "iTerm"
108
114
  repeat with w in windows
109
115
  repeat with t in tabs of w
110
116
  repeat with s in sessions of t
111
- if tty of s is "${tty}" then
117
+ if tty of s is "${escapedTty}" then
112
118
  return "found"
113
119
  end if
114
120
  end repeat
@@ -117,7 +123,7 @@ export class TerminalFocusManager {
117
123
  end tell
118
124
  `;
119
125
 
120
- const { stdout } = await execAsync(`osascript -e '${script}'`);
126
+ const { stdout } = await execFileAsync('osascript', ['-e', script]);
121
127
  if (stdout.trim() === "found") {
122
128
  return {
123
129
  type: TerminalType.ITERM2,
@@ -125,23 +131,27 @@ export class TerminalFocusManager {
125
131
  tty
126
132
  };
127
133
  }
128
- } catch (error) {
129
- // iTerm2 not found or script failed
134
+ } catch {
135
+ // iTerm2 script failed
130
136
  }
131
137
  return null;
132
138
  }
133
139
 
134
140
  private async findTerminalAppWindow(tty: string): Promise<TerminalLocation | null> {
135
141
  try {
136
- // Check if Terminal is running
137
- const { stdout: isRunning } = await execAsync('ps -eo pid=,comm= | grep "Terminal.app" || echo "no"');
138
- if (isRunning.trim() === "no") return null;
142
+ // Check if Terminal.app is running
143
+ await execFileAsync('pgrep', ['-x', 'Terminal']);
144
+ } catch {
145
+ return null;
146
+ }
139
147
 
148
+ try {
149
+ const escapedTty = escapeAppleScript(tty);
140
150
  const script = `
141
151
  tell application "Terminal"
142
152
  repeat with w in windows
143
153
  repeat with t in tabs of w
144
- if tty of t is "${tty}" then
154
+ if tty of t is "${escapedTty}" then
145
155
  return "found"
146
156
  end if
147
157
  end repeat
@@ -149,7 +159,7 @@ export class TerminalFocusManager {
149
159
  end tell
150
160
  `;
151
161
 
152
- const { stdout } = await execAsync(`osascript -e '${script}'`);
162
+ const { stdout } = await execFileAsync('osascript', ['-e', script]);
153
163
  if (stdout.trim() === "found") {
154
164
  return {
155
165
  type: TerminalType.TERMINAL_APP,
@@ -157,8 +167,8 @@ export class TerminalFocusManager {
157
167
  tty
158
168
  };
159
169
  }
160
- } catch (error) {
161
- // Terminal not found or script failed
170
+ } catch {
171
+ // Terminal.app script failed
162
172
  }
163
173
  return null;
164
174
  }
@@ -167,19 +177,20 @@ export class TerminalFocusManager {
167
177
  try {
168
178
  await execFileAsync('tmux', ['switch-client', '-t', identifier]);
169
179
  return true;
170
- } catch (error) {
180
+ } catch {
171
181
  return false;
172
182
  }
173
183
  }
174
184
 
175
185
  private async focusITerm2Session(tty: string): Promise<boolean> {
186
+ const escapedTty = escapeAppleScript(tty);
176
187
  const script = `
177
188
  tell application "iTerm"
178
189
  activate
179
190
  repeat with w in windows
180
191
  repeat with t in tabs of w
181
192
  repeat with s in sessions of t
182
- if tty of s is "${tty}" then
193
+ if tty of s is "${escapedTty}" then
183
194
  select s
184
195
  return "true"
185
196
  end if
@@ -188,17 +199,18 @@ export class TerminalFocusManager {
188
199
  end repeat
189
200
  end tell
190
201
  `;
191
- const { stdout } = await execAsync(`osascript -e '${script}'`);
202
+ const { stdout } = await execFileAsync('osascript', ['-e', script]);
192
203
  return stdout.trim() === "true";
193
204
  }
194
205
 
195
206
  private async focusTerminalAppWindow(tty: string): Promise<boolean> {
207
+ const escapedTty = escapeAppleScript(tty);
196
208
  const script = `
197
209
  tell application "Terminal"
198
210
  activate
199
211
  repeat with w in windows
200
212
  repeat with t in tabs of w
201
- if tty of t is "${tty}" then
213
+ if tty of t is "${escapedTty}" then
202
214
  set index of w to 1
203
215
  set selected tab of w to t
204
216
  return "true"
@@ -207,7 +219,7 @@ export class TerminalFocusManager {
207
219
  end repeat
208
220
  end tell
209
221
  `;
210
- const { stdout } = await execAsync(`osascript -e '${script}'`);
222
+ const { stdout } = await execFileAsync('osascript', ['-e', script]);
211
223
  return stdout.trim() === "true";
212
224
  }
213
225
  }