/**
 * ProviderCliAdapter — Script-based CLI Adapter
 *
 * All CLI providers use versioned scripts (like IDE providers).
 * Scripts are Node.js functions that receive PTY buffer data and return structured results.
 *
 * Required scripts in scripts/{version}/scripts.js:
 *   - detectStatus(input)  → AgentStatus string ('idle' | 'generating' | 'waiting_approval')
 *   - parseOutput(input)   → ReadChatResult { messages, status, activeModal, ... }
 *   - parseApproval(input) → ModalInfo | null
 *
 * provider.json contract:
 *   type, name, category: 'cli', binary, spawn, approvalKeys
 *   compatibility: [{ ideVersion, scriptDir }]  ← versioned scripts
 */
import type { CliAdapter } from '../cli-adapter-types.js';
import type { ProviderResumeCapability } from '../providers/contracts.js';
import { type PtyRuntimeMetadata, type PtyTransportFactory } from './pty-transport.js';
export interface CliChatMessage {
    role: 'user' | 'assistant';
    content: string;
    timestamp?: number;
}
export interface CliSessionStatus {
    status: 'idle' | 'generating' | 'waiting_approval' | 'error' | 'stopped' | 'starting';
    messages: CliChatMessage[];
    workingDir: string;
    activeModal: {
        message: string;
        buttons: string[];
    } | null;
}
/**
 * CLI Script Functions.
 * Unlike IDE scripts (which return JS code strings for CDP evaluate),
 * CLI scripts are Node.js functions that receive PTY buffer data and return structured results.
 */
export interface CliScripts {
    /** Full PTY buffer → ReadChatResult (messages, status, activeModal) */
    parseOutput?: (input: CliScriptInput) => any;
    /** Lightweight status detection (high-frequency polling) → AgentStatus string */
    detectStatus?: (input: {
        tail: string;
        screenText?: string;
        rawBuffer?: string;
    }) => string | null;
    /** Parse approval modal from PTY output → ModalInfo | null */
    parseApproval?: (input: {
        buffer: string;
        screenText?: string;
        rawBuffer?: string;
        tail: string;
    }) => {
        message: string;
        buttons: string[];
    } | null;
    /** Produce a cli-specific prompt from a dashboard action payload */
    resolveAction?: (data: any) => string;
    /** Custom scripts */
    [name: string]: ((input: any) => any) | undefined;
}
export interface CliScriptInput {
    buffer: string;
    rawBuffer: string;
    recentBuffer: string;
    screenText: string;
    messages: CliChatMessage[];
    partialResponse: string;
}
export interface CliTraceEntry {
    id: number;
    at: number;
    type: string;
    status: CliSessionStatus['status'];
    isWaitingForResponse: boolean;
    activeModal: {
        message: string;
        buttons: string[];
    } | null;
    payload: Record<string, any>;
}
export interface CliProviderModule {
    type: string;
    name: string;
    category: 'cli';
    binary: string;
    sendDelayMs?: number;
    sendKey?: string;
    submitStrategy?: 'wait_for_echo' | 'immediate';
    spawn: {
        command: string;
        args: string[];
        shell: boolean;
        env: Record<string, string>;
    };
    timeouts?: {
        /** PTY output batch transmit interval (default 50ms) */
        ptyFlush?: number;
        /** Wait for startup dialog auto-proceed (default 300ms) */
        dialogAccept?: number;
        /** Approval detect cooldown (default 2000ms) */
        approvalCooldown?: number;
        /** Check for completion on no-response during generating (default 6000ms) */
        generatingIdle?: number;
        /** Check for completion on no-response (default 5000ms) */
        idleFinish?: number;
        /** Max response wait (default 300000ms = 5min) */
        maxResponse?: number;
        /** shutdown after kill wait (default 1000ms) */
        shutdownGrace?: number;
        /** Output settle debounce before evaluating status (default 300ms) */
        outputSettle?: number;
    };
    resume?: ProviderResumeCapability;
}
/**
 * Normalize raw provider JSON for auto-implement approval patterns.
 * Used by dev-server only — ProviderCliAdapter itself uses scripts.
 */
export declare function normalizeCliProviderForRuntime(raw: any): {
    patterns: {
        approval: RegExp[];
    };
};
export declare class ProviderCliAdapter implements CliAdapter {
    private extraArgs;
    readonly cliType: string;
    readonly cliName: string;
    workingDir: string;
    private provider;
    private ptyProcess;
    private transportFactory;
    private messages;
    private committedMessages;
    private structuredMessages;
    private currentStatus;
    private onStatusChange;
    private responseBuffer;
    private recentOutputBuffer;
    private isWaitingForResponse;
    private activeModal;
    private responseTimeout;
    private idleTimeout;
    private ready;
    private startupBuffer;
    private startupParseGate;
    private spawnAt;
    private onPtyDataCallback;
    private pendingOutputParseBuffer;
    private pendingOutputParseTimer;
    private ptyOutputBuffer;
    private ptyOutputFlushTimer;
    private pendingTerminalQueryTail;
    private lastOutputAt;
    private lastNonEmptyOutputAt;
    private lastScreenChangeAt;
    private lastScreenSnapshot;
    private serverConn;
    private logBuffer;
    private lastApprovalResolvedAt;
    private approvalTransitionBuffer;
    private approvalExitTimeout;
    private pendingScriptStatus;
    private pendingScriptStatusSince;
    private pendingScriptStatusTimer;
    private settleTimer;
    private settledBuffer;
    private submitPendingUntil;
    private responseSettleIgnoreUntil;
    private responseEpoch;
    private submitRetryTimer;
    private submitRetryUsed;
    private submitRetryPromptSnippet;
    private idleFinishCandidate;
    private resizeSuppressUntil;
    private statusHistory;
    private cliScripts;
    /** Full accumulated ANSI-stripped PTY output */
    private accumulatedBuffer;
    /** Full accumulated raw PTY output (with ANSI) */
    private accumulatedRawBuffer;
    /** Current visible terminal screen snapshot */
    private terminalScreen;
    /** Max accumulated buffer size (last 50KB) */
    private static readonly MAX_ACCUMULATED_BUFFER;
    private currentTurnScope;
    private traceEntries;
    private traceSeq;
    private traceSessionId;
    private static readonly MAX_TRACE_ENTRIES;
    private readonly providerResolutionMeta;
    private static readonly IDLE_FINISH_CONFIRM_MS;
    private syncMessageViews;
    private normalizeParsedMessages;
    private sliceFromOffset;
    private buildParseInput;
    private setStatus;
    private clearIdleFinishCandidate;
    private armIdleFinishCandidate;
    private summarizeTraceText;
    private summarizeTraceMessages;
    private buildTraceParseSnapshot;
    private recordTrace;
    private resetTraceSession;
    private readonly timeouts;
    private readonly approvalKeys;
    private readonly sendDelayMs;
    private readonly sendKey;
    private readonly submitStrategy;
    private static readonly SCRIPT_STATUS_DEBOUNCE_MS;
    constructor(provider: CliProviderModule, workingDir: string, extraArgs?: string[], transportFactory?: PtyTransportFactory);
    /** Inject CLI scripts after construction (e.g. when resolved by ProviderLoader) */
    setCliScripts(scripts: CliScripts): void;
    setServerConn(serverConn: any): void;
    setOnStatusChange(callback: () => void): void;
    setOnPtyData(callback: (data: string) => void): void;
    private flushPendingOutputParse;
    spawn(): Promise<void>;
    private handleOutput;
    private scheduleSettle;
    private armApprovalExitTimeout;
    private looksLikeVisibleIdlePrompt;
    private waitForInteractivePrompt;
    private evaluateSettled;
    private finishResponse;
    private commitCurrentTranscript;
    private runDetectStatus;
    private runParseApproval;
    getStatus(): CliSessionStatus;
    /**
     * Script-based full parse — returns ReadChatResult.
     * Called by command handler / dashboard for rich content rendering.
     */
    getScriptParsedStatus(): any;
    private parseCurrentTranscript;
    /** Whether this adapter has CLI scripts loaded */
    hasCliScripts(): boolean;
    /**
     * Resolves an action (like 'fix' lint error) from the dashboard.
     * Uses resolveAction script if available, otherwise falls back to standard text.
     */
    resolveAction(data: any): Promise<void>;
    sendMessage(text: string): Promise<void>;
    getPartialResponse(): string;
    getRuntimeMetadata(): PtyRuntimeMetadata | null;
    updateRuntimeMeta(meta: Record<string, unknown>, replace?: boolean): void;
    cancel(): void;
    saveAndStop(): Promise<void>;
    private waitForStopped;
    shutdown(): void;
    detach(): void;
    clearHistory(): void;
    isProcessing(): boolean;
    isReady(): boolean;
    writeRaw(data: string): void;
    resolveModal(buttonIndex: number): void;
    resize(cols: number, rows: number): void;
    getDebugState(): Record<string, any>;
    getTraceState(limit?: number): Record<string, any>;
    getProviderResolutionMeta(): Record<string, any>;
    private respondToTerminalQueries;
}
