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60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/**
 * Unified CLI Detection Framework
 *
 * Provides consistent CLI detection and management across all providers
 */

import { spawn, execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';

export interface CliInfo {
  name: string;
  command: string;
  version?: string;
  path?: string;
  installed: boolean;
  authenticated: boolean;
  authMethod: 'cli' | 'api_key' | 'none';
  platform?: string;
  architectures?: string[];
}

export interface CliDetectionOptions {
  timeout?: number;
  includeWsl?: boolean;
  wslDistribution?: string;
}

export interface CliDetectionResult {
  cli: CliInfo;
  detected: boolean;
  issues: string[];
}

export interface UnifiedCliDetection {
  claude?: CliDetectionResult;
  codex?: CliDetectionResult;
  cursor?: CliDetectionResult;
}

/**
 * CLI Configuration for different providers
 */
const CLI_CONFIGS = {
  claude: {
    name: 'Claude CLI',
    commands: ['claude'],
    versionArgs: ['--version'],
    installCommands: {
      darwin: 'brew install anthropics/claude/claude',
      linux: 'curl -fsSL https://claude.ai/install.sh | sh',
      win32: 'iwr https://claude.ai/install.ps1 -UseBasicParsing | iex',
    },
  },
  codex: {
    name: 'Codex CLI',
    commands: ['codex', 'openai'],
    versionArgs: ['--version'],
    installCommands: {
      darwin: 'npm install -g @openai/codex-cli',
      linux: 'npm install -g @openai/codex-cli',
      win32: 'npm install -g @openai/codex-cli',
    },
  },
  cursor: {
    name: 'Cursor CLI',
    commands: ['cursor-agent', 'cursor'],
    versionArgs: ['--version'],
    installCommands: {
      darwin: 'brew install cursor/cursor/cursor-agent',
      linux: 'curl -fsSL https://cursor.sh/install.sh | sh',
      win32: 'iwr https://cursor.sh/install.ps1 -UseBasicParsing | iex',
    },
  },
} as const;

/**
 * Detect if a CLI is installed and available
 */
export async function detectCli(
  provider: keyof typeof CLI_CONFIGS,
  options: CliDetectionOptions = {}
): Promise<CliDetectionResult> {
  const config = CLI_CONFIGS[provider];
  const { timeout = 5000 } = options;
  const issues: string[] = [];

  const cliInfo: CliInfo = {
    name: config.name,
    command: '',
    installed: false,
    authenticated: false,
    authMethod: 'none',
  };

  try {
    // Find the command in PATH
    const command = await findCommand([...config.commands]);
    if (command) {
      cliInfo.command = command;
    }

    if (!cliInfo.command) {
      issues.push(`${config.name} not found in PATH`);
      return { cli: cliInfo, detected: false, issues };
    }

    cliInfo.path = cliInfo.command;
    cliInfo.installed = true;

    // Get version
    try {
      cliInfo.version = await getCliVersion(cliInfo.command, [...config.versionArgs], timeout);
    } catch (error) {
      issues.push(`Failed to get ${config.name} version: ${error}`);
    }

    // Check authentication
    cliInfo.authMethod = await checkCliAuth(provider, cliInfo.command);
    cliInfo.authenticated = cliInfo.authMethod !== 'none';

    return { cli: cliInfo, detected: true, issues };
  } catch (error) {
    issues.push(`Error detecting ${config.name}: ${error}`);
    return { cli: cliInfo, detected: false, issues };
  }
}

/**
 * Detect all CLIs in the system
 */
export async function detectAllCLis(
  options: CliDetectionOptions = {}
): Promise<UnifiedCliDetection> {
  const results: UnifiedCliDetection = {};

  // Detect all providers in parallel
  const providers = Object.keys(CLI_CONFIGS) as Array<keyof typeof CLI_CONFIGS>;
  const detectionPromises = providers.map(async (provider) => {
    const result = await detectCli(provider, options);
    return { provider, result };
  });

  const detections = await Promise.all(detectionPromises);

  for (const { provider, result } of detections) {
    results[provider] = result;
  }

  return results;
}

/**
 * Find the first available command from a list of alternatives
 */
export async function findCommand(commands: string[]): Promise<string | null> {
  for (const command of commands) {
    try {
      const whichCommand = process.platform === 'win32' ? 'where' : 'which';
      const result = execSync(`${whichCommand} ${command}`, {
        encoding: 'utf8',
        timeout: 2000,
      }).trim();

      if (result) {
        return result.split('\n')[0]; // Take first result on Windows
      }
    } catch {
      // Command not found, try next
    }
  }
  return null;
}

/**
 * Get CLI version
 */
export async function getCliVersion(
  command: string,
  args: string[],
  timeout: number = 5000
): Promise<string> {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, {
      stdio: 'pipe',
      timeout,
    });

    let stdout = '';
    let stderr = '';

    child.stdout?.on('data', (data) => {
      stdout += data.toString();
    });

    child.stderr?.on('data', (data) => {
      stderr += data.toString();
    });

    child.on('close', (code) => {
      if (code === 0 && stdout) {
        resolve(stdout.trim());
      } else if (stderr) {
        reject(stderr.trim());
      } else {
        reject(`Command exited with code ${code}`);
      }
    });

    child.on('error', reject);
  });
}

/**
 * Check authentication status for a CLI
 */
export async function checkCliAuth(
  provider: keyof typeof CLI_CONFIGS,
  command: string
): Promise<'cli' | 'api_key' | 'none'> {
  try {
    switch (provider) {
      case 'claude':
        return await checkClaudeAuth(command);
      case 'codex':
        return await checkCodexAuth(command);
      case 'cursor':
        return await checkCursorAuth(command);
      default:
        return 'none';
    }
  } catch {
    return 'none';
  }
}

/**
 * Check Claude CLI authentication
 */
async function checkClaudeAuth(command: string): Promise<'cli' | 'api_key' | 'none'> {
  try {
    // Check for environment variable
    if (process.env.ANTHROPIC_API_KEY) {
      return 'api_key';
    }

    // Try running a simple command to check CLI auth
    const result = await getCliVersion(command, ['--version'], 3000);
    if (result) {
      return 'cli'; // If version works, assume CLI is authenticated
    }
  } catch {
    // Version command might work even without auth, so we need a better check
  }

  // Try a more specific auth check
  return new Promise((resolve) => {
    const child = spawn(command, ['whoami'], {
      stdio: 'pipe',
      timeout: 3000,
    });

    let stdout = '';
    let stderr = '';

    child.stdout?.on('data', (data) => {
      stdout += data.toString();
    });

    child.stderr?.on('data', (data) => {
      stderr += data.toString();
    });

    child.on('close', (code) => {
      if (code === 0 && stdout && !stderr.includes('not authenticated')) {
        resolve('cli');
      } else {
        resolve('none');
      }
    });

    child.on('error', () => {
      resolve('none');
    });
  });
}

/**
 * Check Codex CLI authentication
 */
async function checkCodexAuth(command: string): Promise<'cli' | 'api_key' | 'none'> {
  // Check for environment variable
  if (process.env.OPENAI_API_KEY) {
    return 'api_key';
  }

  try {
    // Try a simple auth check
    const result = await getCliVersion(command, ['--version'], 3000);
    if (result) {
      return 'cli';
    }
  } catch {
    // Version check failed
  }

  return 'none';
}

/**
 * Check Cursor CLI authentication
 */
async function checkCursorAuth(command: string): Promise<'cli' | 'api_key' | 'none'> {
  // Check for environment variable
  if (process.env.CURSOR_API_KEY) {
    return 'api_key';
  }

  // Check for credentials files
  const credentialPaths = [
    path.join(os.homedir(), '.cursor', 'credentials.json'),
    path.join(os.homedir(), '.config', 'cursor', 'credentials.json'),
    path.join(os.homedir(), '.cursor', 'auth.json'),
    path.join(os.homedir(), '.config', 'cursor', 'auth.json'),
  ];

  for (const credPath of credentialPaths) {
    try {
      if (fs.existsSync(credPath)) {
        const content = fs.readFileSync(credPath, 'utf8');
        const creds = JSON.parse(content);
        if (creds.accessToken || creds.token || creds.apiKey) {
          return 'cli';
        }
      }
    } catch {
      // Invalid credentials file
    }
  }

  // Try a simple command
  try {
    const result = await getCliVersion(command, ['--version'], 3000);
    if (result) {
      return 'cli';
    }
  } catch {
    // Version check failed
  }

  return 'none';
}

/**
 * Get installation instructions for a provider
 */
export function getInstallInstructions(
  provider: keyof typeof CLI_CONFIGS,
  platform: NodeJS.Platform = process.platform
): string {
  const config = CLI_CONFIGS[provider];
  const command = config.installCommands[platform as keyof typeof config.installCommands];

  if (!command) {
    return `No installation instructions available for ${provider} on ${platform}`;
  }

  return command;
}

/**
 * Get platform-specific CLI paths and versions
 */
export function getPlatformCliPaths(provider: keyof typeof CLI_CONFIGS): string[] {
  const config = CLI_CONFIGS[provider];
  const platform = process.platform;

  switch (platform) {
    case 'darwin':
      return [
        `/usr/local/bin/${config.commands[0]}`,
        `/opt/homebrew/bin/${config.commands[0]}`,
        path.join(os.homedir(), '.local', 'bin', config.commands[0]),
      ];

    case 'linux':
      return [
        `/usr/bin/${config.commands[0]}`,
        `/usr/local/bin/${config.commands[0]}`,
        path.join(os.homedir(), '.local', 'bin', config.commands[0]),
        path.join(os.homedir(), '.npm', 'global', 'bin', config.commands[0]),
      ];

    case 'win32':
      return [
        path.join(
          os.homedir(),
          'AppData',
          'Local',
          'Programs',
          config.commands[0],
          `${config.commands[0]}.exe`
        ),
        path.join(process.env.ProgramFiles || '', config.commands[0], `${config.commands[0]}.exe`),
        path.join(
          process.env.ProgramFiles || '',
          config.commands[0],
          'bin',
          `${config.commands[0]}.exe`
        ),
      ];

    default:
      return [];
  }
}

/**
 * Validate CLI installation
 */
export function validateCliInstallation(cliInfo: CliInfo): {
  valid: boolean;
  issues: string[];
} {
  const issues: string[] = [];

  if (!cliInfo.installed) {
    issues.push('CLI is not installed');
  }

  if (cliInfo.installed && !cliInfo.version) {
    issues.push('Could not determine CLI version');
  }

  if (cliInfo.installed && cliInfo.authMethod === 'none') {
    issues.push('CLI is not authenticated');
  }

  return {
    valid: issues.length === 0,
    issues,
  };
}