/**
 * Shared Adapter Types
 *
 * Type definitions used by the adapter interface and shared across
 * pty-manager, tmux-manager, and coding-agent-adapters.
 */
/**
 * Message types for session communication
 */
type MessageType = 'task' | 'response' | 'question' | 'answer' | 'status' | 'error';
/**
 * Configuration for spawning a session
 */
interface SpawnConfig {
    /** Optional unique ID (auto-generated if not provided) */
    id?: string;
    /** Human-readable name */
    name: string;
    /** Adapter type to use */
    type: string;
    /** Working directory */
    workdir?: string;
    /** Environment variables */
    env?: Record<string, string>;
    /** Initial terminal columns (default: 120) */
    cols?: number;
    /** Initial terminal rows (default: 40) */
    rows?: number;
    /** Session timeout in ms */
    timeout?: number;
    /** Custom adapter configuration */
    adapterConfig?: Record<string, unknown>;
    /** Per-session stall timeout in ms. Overrides manager config. */
    stallTimeoutMs?: number;
    /** Override adapter's readySettleMs for this session.
     *  Ms of output silence after detectReady match before emitting session_ready. */
    readySettleMs?: number;
    /** Enable verbose task-completion trace logs.
     *  Disabled by default; set true to enable. */
    traceTaskCompletion?: boolean;
    /** Override or disable specific adapter auto-response rules for this session.
     *  Keys are regex source strings (from rule.pattern.source).
     *  - null value disables that rule entirely
     *  - Object value merges fields into the matching adapter rule */
    ruleOverrides?: Record<string, Partial<Omit<AutoResponseRule, 'pattern'>> | null>;
    /** When true, adapter detectBlockingPrompt() results with suggestedResponse
     *  are emitted as autoResponded=false instead of being auto-responded.
     *  Auto-response rules (ruleOverrides) are unaffected. */
    skipAdapterAutoResponse?: boolean;
    /**
     * Whether to inherit the parent process environment variables.
     * When `true` (default), `process.env` is spread as the base of the spawned
     * process environment. When `false`, only `adapter.getEnv()` output and
     * `config.env` are used — the caller is responsible for providing any
     * necessary system vars (PATH, HOME, etc.) via `config.env`.
     *
     * Set to `false` for security-sensitive contexts where the host process has
     * secrets that spawned agents should not access.
     */
    inheritProcessEnv?: boolean;
}
/**
 * Parsed output from a CLI
 */
interface ParsedOutput {
    type: MessageType;
    content: string;
    isComplete: boolean;
    isQuestion: boolean;
    metadata?: Record<string, unknown>;
}
/**
 * Login/auth detection result
 */
interface LoginDetection {
    required: boolean;
    type?: 'api_key' | 'oauth' | 'browser' | 'device_code' | 'cli_auth';
    url?: string;
    deviceCode?: string;
    instructions?: string;
}
/**
 * Types of blocking prompts that can occur
 */
type BlockingPromptType = 'login' | 'update' | 'config' | 'tos' | 'model_select' | 'project_select' | 'permission' | 'tool_wait' | 'unknown';
/**
 * Blocking prompt detection result
 */
interface BlockingPromptDetection {
    /** Whether a blocking prompt was detected */
    detected: boolean;
    /** Type of blocking prompt */
    type?: BlockingPromptType;
    /** The prompt text shown to the user */
    prompt?: string;
    /** Available options/choices if detected */
    options?: string[];
    /** Suggested auto-response (if safe to auto-respond) */
    suggestedResponse?: string;
    /** Whether it's safe to auto-respond without user confirmation */
    canAutoRespond?: boolean;
    /** Instructions for the user if manual intervention needed */
    instructions?: string;
    /** URL to open if browser action needed */
    url?: string;
}
/**
 * Auto-response rule for handling known blocking prompts
 */
interface AutoResponseRule {
    /** Pattern to match in output */
    pattern: RegExp;
    /** Type of prompt this handles */
    type: BlockingPromptType;
    /** Response to send automatically */
    response: string;
    /** How to deliver the response: 'text' writes raw text + CR, 'keys' sends key sequences (default: 'text') */
    responseType?: 'text' | 'keys';
    /** Key names to send when responseType is 'keys' (e.g. ['down', 'enter']) */
    keys?: string[];
    /** Human-readable description of what this does */
    description: string;
    /** Whether this is safe to auto-respond (default: true) */
    safe?: boolean;
    /** Fire this rule at most once per session (prevents thrashing on TUI re-renders) */
    once?: boolean;
}
/**
 * Information about an external tool/process running within a session.
 * Emitted when the adapter detects a tool is actively executing (e.g. browser,
 * bash command, Node process). Suppresses stall detection while active.
 */
interface ToolRunningInfo {
    /** Name of the tool (e.g. "Chrome", "bash", "node", "python") */
    toolName: string;
    /** Optional description of what the tool is doing */
    description?: string;
}
/**
 * Configuration for creating an adapter via factory
 */
interface AdapterFactoryConfig {
    /** Command to execute */
    command: string;
    /** Default arguments */
    args?: string[] | ((config: SpawnConfig) => string[]);
    /** Environment variables */
    env?: Record<string, string> | ((config: SpawnConfig) => Record<string, string>);
    /** Login detection configuration */
    loginDetection?: {
        patterns: RegExp[];
        extractUrl?: (output: string) => string | null;
        extractInstructions?: (output: string) => string | null;
    };
    /** Blocking prompt configuration */
    blockingPrompts?: Array<{
        pattern: RegExp;
        type: BlockingPromptType;
        autoResponse?: string;
        safe?: boolean;
        description?: string;
    }>;
    /** Ready state indicators */
    readyIndicators?: RegExp[];
    /** Exit indicators */
    exitIndicators?: Array<{
        pattern: RegExp;
        codeExtractor?: (match: RegExpMatchArray) => number;
    }>;
    /** Output parser */
    parseOutput?: (output: string) => ParsedOutput | null;
    /** Input formatter */
    formatInput?: (message: string) => string;
    /** Prompt pattern for detecting input readiness */
    promptPattern?: RegExp;
}

/**
 * CLI Adapter Interface
 *
 * Defines how to interact with different CLI tools via a session manager.
 */

/**
 * Interface that CLI adapters must implement
 */
interface CLIAdapter {
    /** Adapter type identifier */
    readonly adapterType: string;
    /** Display name for the CLI */
    readonly displayName: string;
    /**
     * Auto-response rules for handling known blocking prompts.
     * These are applied automatically during startup and execution.
     */
    readonly autoResponseRules?: AutoResponseRule[];
    /**
     * Whether this CLI uses TUI menus that require arrow-key navigation.
     * When true, auto-response rules without an explicit responseType
     * default to sending Enter via sendKeys instead of writeRaw.
     */
    readonly usesTuiMenus?: boolean;
    /**
     * Get the CLI command to execute
     */
    getCommand(): string;
    /**
     * Get command arguments
     */
    getArgs(config: SpawnConfig): string[];
    /**
     * Get environment variables needed
     */
    getEnv(config: SpawnConfig): Record<string, string>;
    /**
     * Detect if output indicates login is required
     * @deprecated Use detectBlockingPrompt() instead for comprehensive detection
     */
    detectLogin(output: string): LoginDetection;
    /**
     * Detect any blocking prompt that requires user input or auto-response.
     */
    detectBlockingPrompt?(output: string): BlockingPromptDetection;
    /**
     * Detect if CLI is ready to receive input
     */
    detectReady(output: string): boolean;
    /**
     * Detect if CLI has exited or crashed
     */
    detectExit(output: string): {
        exited: boolean;
        code?: number;
        error?: string;
    };
    /**
     * Parse structured response from output buffer
     * Returns null if output is incomplete
     */
    parseOutput(output: string): ParsedOutput | null;
    /**
     * Format a message/task for this CLI
     */
    formatInput(message: string): string;
    /**
     * Get prompt pattern to detect when CLI is waiting for input
     */
    getPromptPattern(): RegExp;
    /**
     * Optional: Detect if the CLI has completed a task and returned to its idle prompt.
     * More specific than detectReady — matches high-confidence completion indicators
     * (e.g. duration summaries, explicit "done" messages) alongside the idle prompt.
     *
     * Used as a fast-path in stall detection to avoid expensive LLM classifier calls.
     * If not implemented, the stall classifier is used as the fallback.
     */
    detectTaskComplete?(output: string): boolean;
    /**
     * Optional: Validate that the CLI is installed and accessible
     */
    validateInstallation?(): Promise<{
        installed: boolean;
        version?: string;
        error?: string;
    }>;
    /** Ms of output silence after detectReady match before emitting session_ready (default: 100) */
    readonly readySettleMs?: number;
    /**
     * Optional: Detect if the CLI is actively loading/processing (thinking spinner,
     * file reading, model streaming, etc.). When true, stall detection is suppressed
     * because the agent is provably working — just not producing new visible text.
     */
    detectLoading?(output: string): boolean;
    /**
     * Optional: Detect if an external tool/process is currently running within
     * the session (e.g. browser, bash command, Node server, Python script).
     *
     * When a tool is detected, stall detection is suppressed and a `tool_running`
     * event is emitted so the UI can display the active tool.
     *
     * Return null when no tool is detected.
     */
    detectToolRunning?(output: string): ToolRunningInfo | null;
    /**
     * Optional: Get health check command
     */
    getHealthCheckCommand?(): string;
}

/**
 * Adapter Factory
 *
 * Factory function for creating CLI adapters from configuration.
 */

/**
 * Creates a CLI adapter from configuration
 */
declare function createAdapter(config: AdapterFactoryConfig): CLIAdapter;

/**
 * Adapter Registry
 *
 * Registry for managing CLI adapters.
 */

/**
 * Registry of available CLI adapters
 */
declare class AdapterRegistry {
    private adapters;
    /**
     * Register an adapter
     */
    register(adapter: CLIAdapter): void;
    /**
     * Get adapter for type
     */
    get(adapterType: string): CLIAdapter | undefined;
    /**
     * Check if adapter exists for type
     */
    has(adapterType: string): boolean;
    /**
     * Unregister an adapter
     */
    unregister(adapterType: string): boolean;
    /**
     * List all registered adapter types
     */
    list(): string[];
    /**
     * Get all adapters
     */
    all(): CLIAdapter[];
    /**
     * Clear all adapters
     */
    clear(): void;
}

/**
 * Base CLI Adapter
 *
 * Abstract base class with common functionality for CLI adapters.
 */

/**
 * Abstract base class for CLI adapters with common functionality
 */
declare abstract class BaseCLIAdapter implements CLIAdapter {
    abstract readonly adapterType: string;
    abstract readonly displayName: string;
    /**
     * Auto-response rules for handling known blocking prompts.
     * Subclasses should override this to add CLI-specific rules.
     */
    readonly autoResponseRules: AutoResponseRule[];
    /**
     * Whether this CLI uses TUI menus requiring arrow-key navigation.
     * Defaults to false; coding agent adapters override to true.
     */
    readonly usesTuiMenus: boolean;
    abstract getCommand(): string;
    abstract getArgs(config: SpawnConfig): string[];
    abstract getEnv(config: SpawnConfig): Record<string, string>;
    abstract detectLogin(output: string): LoginDetection;
    abstract detectReady(output: string): boolean;
    abstract parseOutput(output: string): ParsedOutput | null;
    abstract getPromptPattern(): RegExp;
    /**
     * Default exit detection - look for common exit patterns
     */
    detectExit(output: string): {
        exited: boolean;
        code?: number;
        error?: string;
    };
    /**
     * Default blocking prompt detection - looks for common prompt patterns.
     * Subclasses should override for CLI-specific detection.
     */
    detectBlockingPrompt(output: string): BlockingPromptDetection;
    /**
     * Default task completion detection — delegates to detectReady().
     */
    detectTaskComplete(output: string): boolean;
    /**
     * Default input formatting — strip ANSI escape codes from input text.
     * Newlines are preserved (pty-manager handles them natively).
     * Transport-specific formatting (e.g., tmux newline collapsing) is
     * handled by the transport layer, not the adapter.
     */
    formatInput(message: string): string;
    /**
     * Validate CLI installation by running --version or --help
     */
    validateInstallation(): Promise<{
        installed: boolean;
        version?: string;
        error?: string;
    }>;
    /**
     * Helper to check if output contains a question
     */
    protected containsQuestion(output: string): boolean;
    /**
     * Helper to strip ANSI escape codes from output
     */
    protected stripAnsi(str: string): string;
}

/**
 * Output Sanitizer
 *
 * Utilities for cleaning terminal output — stripping ANSI escape codes,
 * TUI chrome, box-drawing characters, and other noise that interferes
 * with text processing.
 *
 * Used by both pty-manager and tmux-manager for stall detection, task
 * completion detection, and output capture. Also used by the workflow
 * executor to clean step results before interpolating into subsequent tasks.
 */
interface SanitizeOptions {
    /** Strip ANSI escape codes (SGR, cursor, etc). Default: true */
    stripAnsi?: boolean;
    /** Strip TUI box-drawing and decorative Unicode. Default: true */
    stripTuiChrome?: boolean;
    /** Strip OSC/DCS sequences (hyperlinks, window titles). Default: true */
    stripOsc?: boolean;
    /** Collapse multiple blank lines to at most 2. Default: true */
    collapseBlankLines?: boolean;
    /** Truncate to last N characters. 0 = no limit. Default: 0 */
    maxLength?: number;
}
/**
 * Sanitize terminal output for text processing.
 */
declare function sanitizeOutput(raw: string, options?: SanitizeOptions): string;

export { type AdapterFactoryConfig, AdapterRegistry, type AutoResponseRule, BaseCLIAdapter, type BlockingPromptDetection, type BlockingPromptType, type CLIAdapter, type LoginDetection, type MessageType, type ParsedOutput, type SanitizeOptions, type SpawnConfig, type ToolRunningInfo, createAdapter, sanitizeOutput };
