"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClaudeRunner = void 0;
const logger_1 = require("../logger");
const platform_1 = require("../platform");
const DEFAULT_MODEL = 'opusplan';
class ClaudeRunner {
    constructor() {
        this.name = 'claude';
    }
    isAvailable() {
        return (0, platform_1.commandExists)('claude');
    }
    async run(prompt, notes) {
        const fullPrompt = notes ? `${prompt}\n\nAdditional context:\n${notes}` : prompt;
        logger_1.logger.info('Running Claude CLI...');
        logger_1.logger.debug(`Prompt: ${fullPrompt.slice(0, 200)}...`);
        const model = (process.env.CLAUDE_MODEL || '').trim() || DEFAULT_MODEL;
        const baseArgs = ['-p', fullPrompt, '--dangerously-skip-permissions'];
        // Default to CLAUDE_MODEL (opusplan routes plan→opus and code→sonnet, saving tokens).
        // Fall back to the CLI's own default model, then `--model auto` — both fail on
        // some installs/plans, so they come last.
        const attempts = [
            [...baseArgs, '--model', model],
            baseArgs,
            [...baseArgs, '--reasoning', 'auto'],
            [...baseArgs, '--model', 'auto'],
        ];
        let result = (0, platform_1.spawnCommand)('claude', attempts[0], {
            encoding: 'utf8',
            timeout: 10 * 60 * 1000,
            cwd: process.cwd(),
            env: (0, platform_1.getUserShellEnv)(),
        });
        for (let i = 1; i < attempts.length; i++) {
            if (result.status === 0)
                break;
            if (!(0, platform_1.shouldRetryAgentCliAttempt)(result.stderr || '', result.stdout || ''))
                break;
            result = (0, platform_1.spawnCommand)('claude', attempts[i], {
                encoding: 'utf8',
                timeout: 10 * 60 * 1000,
                cwd: process.cwd(),
                env: (0, platform_1.getUserShellEnv)(),
            });
        }
        const success = result.status === 0;
        const output = result.stdout || '';
        const error = result.stderr || '';
        if (!success) {
            logger_1.logger.warn(`Claude exited with status ${result.status}`);
            if (error)
                logger_1.logger.warn(`claude stderr: ${error.slice(0, 500)}`);
            if (result.error)
                logger_1.logger.warn(`claude spawn error: ${result.error.message}`);
        }
        return { success, output, error };
    }
}
exports.ClaudeRunner = ClaudeRunner;
//# sourceMappingURL=claude.js.map