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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/**
 * CliProvider - Abstract base class for CLI-based AI providers
 *
 * Provides common infrastructure for CLI tools that spawn subprocesses
 * and stream JSONL output. Handles:
 * - Platform-specific CLI detection (PATH, common locations)
 * - Windows execution strategies (WSL, npx, direct, cmd)
 * - JSONL subprocess spawning and streaming
 * - Error mapping infrastructure
 *
 * @example
 * ```typescript
 * class CursorProvider extends CliProvider {
 *   getCliName(): string { return 'cursor-agent'; }
 *   getSpawnConfig(): CliSpawnConfig {
 *     return {
 *       windowsStrategy: 'wsl',
 *       commonPaths: {
 *         linux: ['~/.local/bin/cursor-agent'],
 *         darwin: ['~/.local/bin/cursor-agent'],
 *       }
 *     };
 *   }
 *   // ... implement abstract methods
 * }
 * ```
 */

import {
  createWslCommand,
  findCliInWsl,
  isWslAvailable,
  spawnJSONLProcess,
  windowsToWslPath,
  type SubprocessOptions,
  type WslCliResult,
} from '@automaker/platform';
import { calculateReasoningTimeout } from '@automaker/types';
import { createLogger, isAbortError } from '@automaker/utils';
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { BaseProvider } from './base-provider.js';
import type { ExecuteOptions, ProviderConfig, ProviderMessage } from './types.js';

/**
 * Spawn strategy for CLI tools on Windows
 *
 * Different CLI tools require different execution strategies:
 * - 'wsl': Requires WSL, CLI only available on Linux/macOS (e.g., cursor-agent)
 * - 'npx': Installed globally via npm/npx, use `npx <package>` to run
 * - 'direct': Native Windows binary, can spawn directly
 * - 'cmd': Windows batch file (.cmd/.bat), needs cmd.exe shell
 */
export type SpawnStrategy = 'wsl' | 'npx' | 'direct' | 'cmd';

/**
 * Configuration for CLI tool spawning
 */
export interface CliSpawnConfig {
  /** How to spawn on Windows */
  windowsStrategy: SpawnStrategy;

  /** NPX package name (required if windowsStrategy is 'npx') */
  npxPackage?: string;

  /** Preferred WSL distribution (if windowsStrategy is 'wsl') */
  wslDistribution?: string;

  /**
   * Common installation paths per platform
   * Use ~ for home directory (will be expanded)
   * Keys: 'linux', 'darwin', 'win32'
   */
  commonPaths: Record<string, string[]>;

  /** Version check command (defaults to --version) */
  versionCommand?: string;
}

/**
 * CLI error information for consistent error handling
 */
export interface CliErrorInfo {
  code: string;
  message: string;
  recoverable: boolean;
  suggestion?: string;
}

/**
 * Detection result from CLI path finding
 */
export interface CliDetectionResult {
  /** Path to the CLI (or 'npx' for npx strategy) */
  cliPath: string | null;
  /** Whether using WSL mode */
  useWsl: boolean;
  /** WSL path if using WSL */
  wslCliPath?: string;
  /** WSL distribution if using WSL */
  wslDistribution?: string;
  /** Detected strategy used */
  strategy: SpawnStrategy | 'native';
}

// Create logger for CLI operations
const cliLogger = createLogger('CliProvider');

/**
 * Base timeout for CLI operations in milliseconds.
 * CLI tools have longer startup and processing times compared to direct API calls,
 * so we use a higher base timeout (120s) than the default provider timeout (30s).
 * This is multiplied by reasoning effort multipliers when applicable.
 * @see calculateReasoningTimeout from @automaker/types
 */
const CLI_BASE_TIMEOUT_MS = 120000;

/**
 * Abstract base class for CLI-based providers
 *
 * Subclasses must implement:
 * - getCliName(): CLI executable name
 * - getSpawnConfig(): Platform-specific spawn configuration
 * - buildCliArgs(): Convert ExecuteOptions to CLI arguments
 * - normalizeEvent(): Convert CLI output to ProviderMessage
 */
export abstract class CliProvider extends BaseProvider {
  // CLI detection results (cached after first detection)
  protected cliPath: string | null = null;
  protected useWsl: boolean = false;
  protected wslCliPath: string | null = null;
  protected wslDistribution: string | undefined = undefined;
  protected detectedStrategy: SpawnStrategy | 'native' = 'native';

  // NPX args (used when strategy is 'npx')
  protected npxArgs: string[] = [];

  constructor(config: ProviderConfig = {}) {
    super(config);
    // Detection happens lazily on first use
  }

  // ==========================================================================
  // Abstract methods - must be implemented by subclasses
  // ==========================================================================

  /**
   * Get the CLI executable name (e.g., 'cursor-agent', 'aider')
   */
  abstract getCliName(): string;

  /**
   * Get spawn configuration for this CLI
   */
  abstract getSpawnConfig(): CliSpawnConfig;

  /**
   * Build CLI arguments from execution options
   * @param options Execution options
   * @returns Array of CLI arguments
   */
  abstract buildCliArgs(options: ExecuteOptions): string[];

  /**
   * Normalize a raw CLI event to ProviderMessage format
   * @param event Raw event from CLI JSONL output
   * @returns Normalized ProviderMessage or null to skip
   */
  abstract normalizeEvent(event: unknown): ProviderMessage | null;

  // ==========================================================================
  // Optional overrides
  // ==========================================================================

  /**
   * Map CLI stderr/exit code to error info
   * Override to provide CLI-specific error mapping
   */
  protected mapError(stderr: string, exitCode: number | null): CliErrorInfo {
    const lower = stderr.toLowerCase();

    // Common authentication errors
    if (
      lower.includes('not authenticated') ||
      lower.includes('please log in') ||
      lower.includes('unauthorized')
    ) {
      return {
        code: 'NOT_AUTHENTICATED',
        message: `${this.getCliName()} is not authenticated`,
        recoverable: true,
        suggestion: `Run "${this.getCliName()} login" to authenticate`,
      };
    }

    // Rate limiting
    if (
      lower.includes('rate limit') ||
      lower.includes('too many requests') ||
      lower.includes('429')
    ) {
      return {
        code: 'RATE_LIMITED',
        message: 'API rate limit exceeded',
        recoverable: true,
        suggestion: 'Wait a few minutes and try again',
      };
    }

    // Network errors
    if (
      lower.includes('network') ||
      lower.includes('connection') ||
      lower.includes('econnrefused') ||
      lower.includes('timeout')
    ) {
      return {
        code: 'NETWORK_ERROR',
        message: 'Network connection error',
        recoverable: true,
        suggestion: 'Check your internet connection and try again',
      };
    }

    // Process killed
    if (exitCode === 137 || lower.includes('killed') || lower.includes('sigterm')) {
      return {
        code: 'PROCESS_CRASHED',
        message: 'Process was terminated',
        recoverable: true,
        suggestion: 'The process may have run out of memory. Try a simpler task.',
      };
    }

    // Generic error
    return {
      code: 'UNKNOWN_ERROR',
      message: stderr || `Process exited with code ${exitCode}`,
      recoverable: false,
    };
  }

  /**
   * Get installation instructions for this CLI
   * Override to provide CLI-specific instructions
   */
  protected getInstallInstructions(): string {
    const cliName = this.getCliName();
    const config = this.getSpawnConfig();

    if (process.platform === 'win32') {
      switch (config.windowsStrategy) {
        case 'wsl':
          return `${cliName} requires WSL on Windows. Install WSL, then run inside WSL to install.`;
        case 'npx':
          return `Install with: npm install -g ${config.npxPackage || cliName}`;
        case 'cmd':
        case 'direct':
          return `${cliName} is not installed. Check the documentation for installation instructions.`;
      }
    }

    return `${cliName} is not installed. Check the documentation for installation instructions.`;
  }

  // ==========================================================================
  // CLI Detection
  // ==========================================================================

  /**
   * Expand ~ to home directory in path
   */
  private expandPath(p: string): string {
    if (p.startsWith('~')) {
      return path.join(os.homedir(), p.slice(1));
    }
    return p;
  }

  /**
   * Find CLI in PATH using 'which' (Unix) or 'where' (Windows)
   */
  private findCliInPath(): string | null {
    const cliName = this.getCliName();

    try {
      const command = process.platform === 'win32' ? 'where' : 'which';
      const result = execSync(`${command} ${cliName}`, {
        encoding: 'utf8',
        timeout: 5000,
        stdio: ['pipe', 'pipe', 'pipe'],
        windowsHide: true,
      })
        .trim()
        .split('\n')[0];

      if (result && fs.existsSync(result)) {
        cliLogger.debug(`Found ${cliName} in PATH: ${result}`);
        return result;
      }
    } catch {
      // Not in PATH
    }

    return null;
  }

  /**
   * Find CLI in common installation paths for current platform
   */
  private findCliInCommonPaths(): string | null {
    const config = this.getSpawnConfig();
    const cliName = this.getCliName();
    const platform = process.platform as 'linux' | 'darwin' | 'win32';
    const paths = config.commonPaths[platform] || [];

    for (const p of paths) {
      const expandedPath = this.expandPath(p);
      if (fs.existsSync(expandedPath)) {
        cliLogger.debug(`Found ${cliName} at: ${expandedPath}`);
        return expandedPath;
      }
    }

    return null;
  }

  /**
   * Detect CLI installation using appropriate strategy
   */
  protected detectCli(): CliDetectionResult {
    const config = this.getSpawnConfig();
    const cliName = this.getCliName();
    const wslLogger = (msg: string) => cliLogger.debug(msg);

    // Windows - use configured strategy
    if (process.platform === 'win32') {
      switch (config.windowsStrategy) {
        case 'wsl': {
          // Check WSL for CLI
          if (isWslAvailable({ logger: wslLogger })) {
            const wslResult: WslCliResult | null = findCliInWsl(cliName, {
              logger: wslLogger,
              distribution: config.wslDistribution,
            });
            if (wslResult) {
              cliLogger.debug(
                `Using ${cliName} via WSL (${wslResult.distribution || 'default'}): ${wslResult.wslPath}`
              );
              return {
                cliPath: 'wsl.exe',
                useWsl: true,
                wslCliPath: wslResult.wslPath,
                wslDistribution: wslResult.distribution,
                strategy: 'wsl',
              };
            }
          }
          cliLogger.debug(`${cliName} not found (WSL not available or CLI not installed in WSL)`);
          return { cliPath: null, useWsl: false, strategy: 'wsl' };
        }

        case 'npx': {
          // For npx, we don't need to find the CLI, just return npx
          cliLogger.debug(`Using ${cliName} via npx (package: ${config.npxPackage})`);
          return {
            cliPath: 'npx',
            useWsl: false,
            strategy: 'npx',
          };
        }

        case 'direct':
        case 'cmd': {
          // Native Windows - check PATH and common paths
          const pathResult = this.findCliInPath();
          if (pathResult) {
            return { cliPath: pathResult, useWsl: false, strategy: config.windowsStrategy };
          }

          const commonResult = this.findCliInCommonPaths();
          if (commonResult) {
            return { cliPath: commonResult, useWsl: false, strategy: config.windowsStrategy };
          }

          cliLogger.debug(`${cliName} not found on Windows`);
          return { cliPath: null, useWsl: false, strategy: config.windowsStrategy };
        }
      }
    }

    // Linux/macOS - native execution
    const pathResult = this.findCliInPath();
    if (pathResult) {
      return { cliPath: pathResult, useWsl: false, strategy: 'native' };
    }

    const commonResult = this.findCliInCommonPaths();
    if (commonResult) {
      return { cliPath: commonResult, useWsl: false, strategy: 'native' };
    }

    cliLogger.debug(`${cliName} not found`);
    return { cliPath: null, useWsl: false, strategy: 'native' };
  }

  /**
   * Ensure CLI is detected (lazy initialization)
   */
  protected ensureCliDetected(): void {
    if (this.cliPath !== null || this.detectedStrategy !== 'native') {
      return; // Already detected
    }

    const result = this.detectCli();
    this.cliPath = result.cliPath;
    this.useWsl = result.useWsl;
    this.wslCliPath = result.wslCliPath || null;
    this.wslDistribution = result.wslDistribution;
    this.detectedStrategy = result.strategy;

    // Set up npx args if using npx strategy
    const config = this.getSpawnConfig();
    if (result.strategy === 'npx' && config.npxPackage) {
      this.npxArgs = [config.npxPackage];
    }
  }

  /**
   * Check if CLI is installed
   */
  async isInstalled(): Promise<boolean> {
    this.ensureCliDetected();
    return this.cliPath !== null;
  }

  // ==========================================================================
  // Subprocess Spawning
  // ==========================================================================

  /**
   * Build subprocess options based on detected strategy
   */
  protected buildSubprocessOptions(options: ExecuteOptions, cliArgs: string[]): SubprocessOptions {
    this.ensureCliDetected();

    if (!this.cliPath) {
      throw new Error(`${this.getCliName()} CLI not found. ${this.getInstallInstructions()}`);
    }

    const cwd = options.cwd || process.cwd();

    // Filter undefined values from process.env
    const filteredEnv: Record<string, string> = {};
    for (const [key, value] of Object.entries(process.env)) {
      if (value !== undefined) {
        filteredEnv[key] = value;
      }
    }

    // Calculate dynamic timeout based on reasoning effort.
    // This addresses GitHub issue #530 where reasoning models with 'xhigh' effort would timeout.
    const timeout = calculateReasoningTimeout(options.reasoningEffort, CLI_BASE_TIMEOUT_MS);

    // WSL strategy
    if (this.useWsl && this.wslCliPath) {
      const wslCwd = windowsToWslPath(cwd);
      const wslCmd = createWslCommand(this.wslCliPath, cliArgs, {
        distribution: this.wslDistribution,
      });

      // Add --cd flag to change directory inside WSL
      let args: string[];
      if (this.wslDistribution) {
        args = ['-d', this.wslDistribution, '--cd', wslCwd, this.wslCliPath, ...cliArgs];
      } else {
        args = ['--cd', wslCwd, this.wslCliPath, ...cliArgs];
      }

      cliLogger.debug(`WSL spawn: ${wslCmd.command} ${args.slice(0, 6).join(' ')}...`);

      return {
        command: wslCmd.command,
        args,
        cwd, // Windows cwd for spawn
        env: filteredEnv,
        abortController: options.abortController,
        timeout,
      };
    }

    // NPX strategy
    if (this.detectedStrategy === 'npx') {
      const allArgs = [...this.npxArgs, ...cliArgs];
      cliLogger.debug(`NPX spawn: npx ${allArgs.slice(0, 6).join(' ')}...`);

      return {
        command: 'npx',
        args: allArgs,
        cwd,
        env: filteredEnv,
        abortController: options.abortController,
        timeout,
      };
    }

    // Direct strategy (native Unix or Windows direct/cmd)
    cliLogger.debug(`Direct spawn: ${this.cliPath} ${cliArgs.slice(0, 6).join(' ')}...`);

    return {
      command: this.cliPath,
      args: cliArgs,
      cwd,
      env: filteredEnv,
      abortController: options.abortController,
      timeout,
    };
  }

  /**
   * Execute a query using the CLI with JSONL streaming
   *
   * This is a default implementation that:
   * 1. Builds CLI args from options
   * 2. Spawns the subprocess with appropriate strategy
   * 3. Streams and normalizes events
   *
   * Subclasses can override for custom behavior.
   */
  async *executeQuery(options: ExecuteOptions): AsyncGenerator<ProviderMessage> {
    this.ensureCliDetected();

    if (!this.cliPath) {
      throw new Error(`${this.getCliName()} CLI not found. ${this.getInstallInstructions()}`);
    }

    // Many CLI-based providers do not support a separate "system" message.
    // If a systemPrompt is provided, embed it into the prompt so downstream models
    // still receive critical formatting/schema instructions (e.g., JSON-only outputs).
    const effectiveOptions = this.embedSystemPromptIntoPrompt(options);

    const cliArgs = this.buildCliArgs(effectiveOptions);
    const subprocessOptions = this.buildSubprocessOptions(effectiveOptions, cliArgs);

    try {
      for await (const rawEvent of spawnJSONLProcess(subprocessOptions)) {
        const normalized = this.normalizeEvent(rawEvent);
        if (normalized) {
          yield normalized;
        }
      }
    } catch (error) {
      if (isAbortError(error)) {
        cliLogger.debug('Query aborted');
        return;
      }

      // Map CLI errors
      if (error instanceof Error && 'stderr' in error) {
        const errorInfo = this.mapError(
          (error as { stderr?: string }).stderr || error.message,
          (error as { exitCode?: number | null }).exitCode ?? null
        );

        const cliError = new Error(errorInfo.message) as Error & CliErrorInfo;
        cliError.code = errorInfo.code;
        cliError.recoverable = errorInfo.recoverable;
        cliError.suggestion = errorInfo.suggestion;
        throw cliError;
      }

      throw error;
    }
  }

  /**
   * Embed system prompt text into the user prompt for CLI providers.
   *
   * Most CLI providers we integrate with only accept a single prompt via stdin/args.
   * When upstream code supplies `options.systemPrompt`, we prepend it to the prompt
   * content and clear `systemPrompt` to avoid any accidental double-injection by
   * subclasses.
   */
  protected embedSystemPromptIntoPrompt(options: ExecuteOptions): ExecuteOptions {
    if (!options.systemPrompt) {
      return options;
    }

    // Only string system prompts can be reliably embedded for CLI providers.
    // Presets are provider-specific (e.g., Claude SDK) and cannot be represented
    // universally. If a preset is provided, we only embed its optional `append`.
    const systemText =
      typeof options.systemPrompt === 'string'
        ? options.systemPrompt
        : options.systemPrompt.append
          ? options.systemPrompt.append
          : '';

    if (!systemText) {
      return { ...options, systemPrompt: undefined };
    }

    // Preserve original prompt structure.
    if (typeof options.prompt === 'string') {
      return {
        ...options,
        prompt: `${systemText}\n\n---\n\n${options.prompt}`,
        systemPrompt: undefined,
      };
    }

    if (Array.isArray(options.prompt)) {
      return {
        ...options,
        prompt: [{ type: 'text', text: systemText }, ...options.prompt],
        systemPrompt: undefined,
      };
    }

    // Should be unreachable due to ExecuteOptions typing, but keep safe.
    return { ...options, systemPrompt: undefined };
  }
}