@ai-devkit/agent-manager 0.7.0 → 0.9.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.
@@ -78,14 +78,19 @@ describe('TtyWriter', () => {
78
78
 
79
79
  await TtyWriter.send(location, 'hello');
80
80
 
81
+ // First call: send text without newline
81
82
  expect(mockedExecFile).toHaveBeenCalledWith(
82
83
  'osascript',
83
84
  ['-e', expect.stringContaining('write text "hello" newline no')],
84
85
  expect.any(Function),
85
86
  );
86
- const scriptArg = (mockedExecFile.mock.calls[0] as unknown[])[1] as string[];
87
- const script = scriptArg[1];
88
- expect(script).toContain('key code 36');
87
+ // Second call: send Enter via separate write text with newline
88
+ expect(mockedExecFile).toHaveBeenCalledWith(
89
+ 'osascript',
90
+ ['-e', expect.stringContaining('write text "" newline yes')],
91
+ expect.any(Function),
92
+ );
93
+ expect(mockedExecFile).toHaveBeenCalledTimes(2);
89
94
  });
90
95
 
91
96
  it('escapes special characters in message', async () => {
@@ -100,12 +105,37 @@ describe('TtyWriter', () => {
100
105
  );
101
106
  });
102
107
 
108
+ it('escapes newlines in message', async () => {
109
+ mockExecFileSuccess('ok');
110
+
111
+ await TtyWriter.send(location, 'line1\nline2');
112
+
113
+ expect(mockedExecFile).toHaveBeenCalledWith(
114
+ 'osascript',
115
+ ['-e', expect.stringContaining('write text "line1\\nline2" newline no')],
116
+ expect.any(Function),
117
+ );
118
+ });
119
+
103
120
  it('throws when session not found', async () => {
104
121
  mockExecFileSuccess('not_found');
105
122
 
106
123
  await expect(TtyWriter.send(location, 'test'))
107
124
  .rejects.toThrow('iTerm2 session not found');
108
125
  });
126
+
127
+ it('throws when session disappears before Enter', async () => {
128
+ // First call succeeds (text sent), second returns not_found
129
+ let callCount = 0;
130
+ mockedExecFile.mockImplementation((...args: unknown[]) => {
131
+ const cb = args[args.length - 1] as (err: Error | null, result: { stdout: string }, stderr: string) => void;
132
+ callCount++;
133
+ cb(null, { stdout: callCount === 1 ? 'ok' : 'not_found' }, '');
134
+ });
135
+
136
+ await expect(TtyWriter.send(location, 'test'))
137
+ .rejects.toThrow('iTerm2 session disappeared before Enter');
138
+ });
109
139
  });
110
140
 
111
141
  describe('Terminal.app', () => {
@@ -115,16 +145,24 @@ describe('TtyWriter', () => {
115
145
  tty: '/dev/ttys030',
116
146
  };
117
147
 
118
- it('sends message via System Events keystroke (not do script)', async () => {
148
+ it('sends message via do script (not System Events)', async () => {
119
149
  mockExecFileSuccess('ok');
120
150
 
121
151
  await TtyWriter.send(location, 'hello');
122
152
 
123
- const scriptArg = (mockedExecFile.mock.calls[0] as unknown[])[1] as string[];
124
- const script = scriptArg[1];
125
- expect(script).toContain('keystroke "hello"');
126
- expect(script).toContain('key code 36');
127
- expect(script).not.toContain('do script');
153
+ // First call: send text via do script
154
+ const firstCallArgs = (mockedExecFile.mock.calls[0] as unknown[])[1] as string[];
155
+ const textScript = firstCallArgs[1];
156
+ expect(textScript).toContain('do script "hello" in targetTab');
157
+ expect(textScript).not.toContain('keystroke');
158
+ expect(textScript).not.toContain('key code 36');
159
+
160
+ // Second call: send Enter via separate do script
161
+ const secondCallArgs = (mockedExecFile.mock.calls[1] as unknown[])[1] as string[];
162
+ const enterScript = secondCallArgs[1];
163
+ expect(enterScript).toContain('do script "" in targetTab');
164
+
165
+ expect(mockedExecFile).toHaveBeenCalledTimes(2);
128
166
  });
129
167
 
130
168
  it('throws when tab not found', async () => {
@@ -133,6 +171,18 @@ describe('TtyWriter', () => {
133
171
  await expect(TtyWriter.send(location, 'test'))
134
172
  .rejects.toThrow('Terminal.app tab not found');
135
173
  });
174
+
175
+ it('throws when tab disappears before Enter', async () => {
176
+ let callCount = 0;
177
+ mockedExecFile.mockImplementation((...args: unknown[]) => {
178
+ const cb = args[args.length - 1] as (err: Error | null, result: { stdout: string }, stderr: string) => void;
179
+ callCount++;
180
+ cb(null, { stdout: callCount === 1 ? 'ok' : 'not_found' }, '');
181
+ });
182
+
183
+ await expect(TtyWriter.send(location, 'test'))
184
+ .rejects.toThrow('Terminal.app tab disappeared before Enter');
185
+ });
136
186
  });
137
187
 
138
188
  describe('unsupported terminal', () => {
@@ -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
 
@@ -134,7 +134,7 @@ export class TerminalFocusManager {
134
134
  private async findTerminalAppWindow(tty: string): Promise<TerminalLocation | null> {
135
135
  try {
136
136
  // Check if Terminal is running
137
- const { stdout: isRunning } = await execAsync('pgrep -x Terminal || echo "no"');
137
+ const { stdout: isRunning } = await execAsync('ps -eo pid=,comm= | grep "Terminal.app" || echo "no"');
138
138
  if (isRunning.trim() === "no") return null;
139
139
 
140
140
  const script = `