"use strict";
// src/orchestrator/story/adapters/CodexAdapter.ts
// v1.17.0 — Spawns `codex exec` and parses the JSONL stdout via the
// existing `TaskExecutor.extractCodexFinalMessage` helper.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodexAdapter = void 0;
const child_process_1 = require("child_process");
const util_1 = require("util");
const child_process_2 = require("child_process");
const execFileP = (0, util_1.promisify)(child_process_2.execFile);
class CodexAdapter {
    name = 'codex';
    async isAvailable() {
        try {
            await execFileP('codex', ['--version'], { timeout: 5_000 });
            return true;
        }
        catch {
            return false;
        }
    }
    async invoke(prompt, opts = {}) {
        const start = Date.now();
        const timeoutMs = opts.timeoutMs ?? 300_000;
        const args = ['exec'];
        if (opts.model)
            args.push('--model', opts.model);
        let stdout = '';
        let stderr = '';
        let exitCode = -1;
        let timedOut = false;
        try {
            await new Promise((resolve, reject) => {
                const child = (0, child_process_1.spawn)('codex', args, {
                    cwd: opts.cwd || process.cwd(),
                    env: { ...process.env, ...(opts.env || {}) },
                    stdio: ['pipe', 'pipe', 'pipe'],
                });
                const t = setTimeout(() => {
                    timedOut = true;
                    try {
                        child.kill('SIGTERM');
                    }
                    catch { /* */ }
                    setTimeout(() => { try {
                        child.kill('SIGKILL');
                    }
                    catch { /* */ } }, 2000).unref();
                }, timeoutMs);
                if (typeof t.unref === 'function')
                    t.unref();
                child.stdout?.on('data', (c) => { stdout += String(c); });
                child.stderr?.on('data', (c) => { stderr += String(c); });
                child.on('error', (err) => { clearTimeout(t); reject(err); });
                child.on('exit', (code) => {
                    clearTimeout(t);
                    exitCode = typeof code === 'number' ? code : -1;
                    resolve();
                });
                child.stdin?.write(prompt);
                child.stdin?.end();
            });
        }
        catch (err) {
            return {
                ok: false,
                text: stdout,
                exitCode: -1,
                durationMs: Date.now() - start,
                adapter: this.name,
                error: `spawn_error: ${err instanceof Error ? err.message : String(err)}; stderr: ${stderr.slice(0, 200)}`,
            };
        }
        // Reuse TaskExecutor.extractCodexFinalMessage when present — Codex emits
        // newline-delimited JSON events; the final message has the user-facing text.
        let extracted = stdout;
        try {
            // eslint-disable-next-line @typescript-eslint/no-var-requires
            const { extractCodexFinalMessage } = require('../../TaskExecutor');
            if (typeof extractCodexFinalMessage === 'function') {
                const fromHelper = extractCodexFinalMessage(stdout);
                if (typeof fromHelper === 'string' && fromHelper.length > 0) {
                    extracted = fromHelper;
                }
            }
        }
        catch { /* helper may not export — fall back to raw stdout */ }
        return {
            ok: exitCode === 0 && !timedOut,
            text: extracted,
            exitCode,
            durationMs: Date.now() - start,
            adapter: this.name,
            error: timedOut ? `timeout_after_${timeoutMs}ms` : (exitCode !== 0 ? `exit_${exitCode}: ${stderr.slice(0, 200)}` : undefined),
        };
    }
}
exports.CodexAdapter = CodexAdapter;
