/**
 * @fileoverview Respawn Controller for autonomous Claude Code session cycling.
 *
 * Manages automatic respawning of Claude Code sessions. When Claude finishes
 * working (detected by completion message + output silence), it cycles through
 * update → clear → init steps to keep the session productive.
 *
 * ## State Machine
 *
 * ```
 * WATCHING → CONFIRMING_IDLE → SENDING_UPDATE → WAITING_UPDATE → SENDING_CLEAR → WAITING_CLEAR
 *    ↑          │                                                                      │
 *    │          │ (new output)                                                         ▼
 *    │          └─────────────► SENDING_INIT → WAITING_INIT → MONITORING_INIT ────────┘
 *    │                                                             │
 *    │                                                             ▼ (if no work triggered)
 *    └──────────────────────── SENDING_KICKSTART → WAITING_KICKSTART ──┘
 * ```
 *
 * ## Idle Detection (multi-layer)
 * - Layer 0: Stop hook / idle_prompt notification (definitive)
 * - Layer 1: Completion message pattern "for Xm Xs"
 * - Layer 2: AI idle check via `AiIdleChecker` (optional)
 * - Layer 3: No-output timeout fallback
 *
 * Key exports:
 * - `RespawnController` class — state machine, extends EventEmitter
 * - `RespawnConfig` interface — all configuration options
 * - `RespawnState` type — union of all state machine states
 * - `DetectionStatus`, `ActiveTimerInfo` — status types
 *
 * Key methods: `start()`, `stop()`, `getStatus()`, `getConfig()`,
 * `getDetectionStatus()`, `getActiveTimers()`, `getAggregateMetrics()`,
 * `getTimingHistory()`, `getHealthScore()`
 *
 * @dependencies session (PTY output), ai-idle-checker, ai-plan-checker,
 *   respawn-patterns, respawn-adaptive-timing, respawn-metrics, respawn-health,
 *   team-watcher (blocks respawn if teammates active)
 * @consumedby web/server (respawn routes, SSE), ralph-loop
 * @emits respawn:stateChanged, respawn:started, respawn:stopped, respawn:cycleStarted,
 *   respawn:cycleCompleted, respawn:detectionUpdate, respawn:aiCheck*, respawn:log
 *
 * @module respawn-controller
 */
import { EventEmitter } from 'node:events';
import { Session } from './session.js';
import { type AiCheckState } from './ai-idle-checker.js';
import type { TeamWatcher } from './team-watcher.js';
import { type RespawnCycleMetrics, type RespawnAggregateMetrics, type RalphLoopHealthScore, type TimingHistory } from './types.js';
/**
 * Detection layers for multi-signal idle detection.
 * Each layer provides a confidence signal that Claude has finished working.
 */
/** Active timer info for UI display */
interface ActiveTimerInfo {
    name: string;
    remainingMs: number;
    totalMs: number;
}
interface DetectionStatus {
    /** Layer 0: Stop hook received (highest priority - definitive signal) */
    stopHookReceived: boolean;
    /** Timestamp when Stop hook was received */
    stopHookTime: number | null;
    /** Layer 0: idle_prompt notification received (definitive signal) */
    idlePromptReceived: boolean;
    /** Timestamp when idle_prompt was received */
    idlePromptTime: number | null;
    /** Layer 1: Completion message detected ("for Xm Xs") */
    completionMessageDetected: boolean;
    /** Timestamp when completion message was last seen */
    completionMessageTime: number | null;
    /** Layer 2: Output silence - no new output for threshold duration */
    outputSilent: boolean;
    /** Milliseconds since last output */
    msSinceLastOutput: number;
    /** Layer 3: Token count stability - tokens haven't changed */
    tokensStable: boolean;
    /** Last observed token count */
    lastTokenCount: number;
    /** Milliseconds since token count changed */
    msSinceTokenChange: number;
    /** Layer 4: Working patterns absent - no spinners/activity words */
    workingPatternsAbsent: boolean;
    /** Milliseconds since last working pattern */
    msSinceLastWorking: number;
    /** Layer 5: AI idle check status */
    aiCheck: AiCheckState | null;
    /** Overall confidence level (0-100) */
    confidenceLevel: number;
    /** Human-readable status for UI */
    statusText: string;
    /** What the controller is currently waiting for */
    waitingFor: string;
    /** Active countdown timers */
    activeTimers: ActiveTimerInfo[];
    /** Recent action log entries (last 10) */
    recentActions: ActionLogEntry[];
    /** Current phase description */
    currentPhase: string;
    /** Next expected action */
    nextAction: string;
    /** Stuck-state detection metrics */
    stuckState: {
        /** How long the controller has been in the current state (ms) */
        currentStateDurationMs: number;
        /** Warning threshold (ms) */
        warningThresholdMs: number;
        /** Recovery threshold (ms) */
        recoveryThresholdMs: number;
        /** Number of recovery attempts made */
        recoveryAttempts: number;
        /** Maximum allowed recoveries */
        maxRecoveries: number;
        /** Whether a warning has been emitted for current state */
        isWarned: boolean;
    };
}
/**
 * Respawn sequence states.
 *
 * The controller cycles through these states:
 * ```
 * WATCHING → SENDING_UPDATE → WAITING_UPDATE →
 *   SENDING_CLEAR → WAITING_CLEAR →
 *   SENDING_INIT → WAITING_INIT →
 *   MONITORING_INIT → (maybe SENDING_KICKSTART → WAITING_KICKSTART) →
 *   WATCHING (repeat)
 * ```
 *
 * Steps can be skipped via config (`sendClear: false`, `sendInit: false`).
 */
export type RespawnState = 
/** Watching for idle, ready to start respawn sequence */
'watching'
/** Completion message detected, waiting for output silence to confirm */
 | 'confirming_idle'
/** AI checker is analyzing terminal output for IDLE/WORKING verdict */
 | 'ai_checking'
/** About to send the update docs prompt */
 | 'sending_update'
/** Waiting for update to complete */
 | 'waiting_update'
/** About to send /clear command */
 | 'sending_clear'
/** Waiting for clear to complete */
 | 'waiting_clear'
/** About to send /init command */
 | 'sending_init'
/** Waiting for init to complete */
 | 'waiting_init'
/** Monitoring if /init triggered work */
 | 'monitoring_init'
/** About to send kickstart prompt */
 | 'sending_kickstart'
/** Waiting for kickstart to complete */
 | 'waiting_kickstart'
/** Controller stopped (not running) */
 | 'stopped';
/**
 * Configuration options for the RespawnController.
 */
export interface RespawnConfig {
    /**
     * How long to wait after seeing prompt before considering truly idle.
     * Prevents premature cycling when user is about to type.
     * @default 10000 (10 seconds)
     */
    idleTimeoutMs: number;
    /**
     * The prompt to send when updating docs.
     * Sent at the start of each respawn cycle.
     * @default 'write a brief progress summary to CLAUDE.md noting what you accomplished, then continue working.'
     */
    updatePrompt: string;
    /**
     * Delay between sending steps (ms).
     * Gives Claude time to process each command.
     * @default 1000 (1 second)
     */
    interStepDelayMs: number;
    /**
     * Whether the respawn loop is enabled.
     * When false, start() will be a no-op.
     * @default true
     */
    enabled: boolean;
    /**
     * Whether to send /clear after update prompt completes.
     * Resets Claude's context for fresh start.
     * @default true
     */
    sendClear: boolean;
    /**
     * Whether to send /init after /clear completes.
     * Re-initializes Claude with CLAUDE.md context.
     * @default true
     */
    sendInit: boolean;
    /**
     * Optional prompt to send if /init doesn't trigger work.
     * Used as a fallback when /init completes but Claude doesn't start working.
     * @default undefined
     */
    kickstartPrompt?: string;
    /**
     * Time to wait after completion message before confirming idle (ms).
     * After seeing "for Xm Xs" pattern, waits this long with no new output.
     * @default 10000 (10 seconds)
     */
    completionConfirmMs: number;
    /**
     * Fallback timeout when no output received at all (ms).
     * If no terminal output for this duration, assumes idle even without completion message.
     * @default 30000 (30 seconds)
     */
    noOutputTimeoutMs: number;
    /**
     * Whether to auto-accept plan mode prompts by pressing Enter.
     * When Claude enters plan mode and presents a plan for approval, output stops
     * without a completion message. This feature detects that state and sends Enter
     * to accept the plan. Does NOT auto-accept AskUserQuestion prompts (those are
     * blocked via the elicitation_dialog hook signal).
     * @default true
     */
    autoAcceptPrompts: boolean;
    /**
     * Delay before auto-accepting plan mode prompts (ms).
     * After no output for this duration AND no completion message detected
     * AND no elicitation dialog signaled, sends Enter to accept the plan.
     * Must be shorter than noOutputTimeoutMs.
     * @default 8000 (8 seconds)
     */
    autoAcceptDelayMs: number;
    /**
     * Whether AI idle check is enabled.
     * When enabled, spawns a fresh Claude CLI to analyze terminal output
     * and provide a definitive IDLE/WORKING verdict before starting respawn.
     * @default true
     */
    aiIdleCheckEnabled: boolean;
    /**
     * Model to use for AI idle check.
     * @default 'claude-opus-4-5-20251101'
     */
    aiIdleCheckModel: string;
    /**
     * Maximum characters of terminal buffer to send to AI checker.
     * @default 16000
     */
    aiIdleCheckMaxContext: number;
    /**
     * Timeout for the AI check in ms.
     * @default 90000 (90 seconds)
     */
    aiIdleCheckTimeoutMs: number;
    /**
     * Cooldown after WORKING verdict in ms.
     * @default 180000 (3 minutes)
     */
    aiIdleCheckCooldownMs: number;
    /**
     * Whether AI plan mode check is enabled for auto-accept.
     * When enabled, spawns a fresh Claude CLI to confirm the terminal is
     * showing a plan mode approval prompt before auto-accepting.
     * @default true
     */
    aiPlanCheckEnabled: boolean;
    /**
     * Model to use for AI plan mode check.
     * @default 'claude-opus-4-5-20251101' (thinking enabled by default)
     */
    aiPlanCheckModel: string;
    /**
     * Maximum characters of terminal buffer to send to plan checker.
     * @default 8000
     */
    aiPlanCheckMaxContext: number;
    /**
     * Timeout for the AI plan check in ms.
     * @default 60000 (60 seconds, allows time for thinking)
     */
    aiPlanCheckTimeoutMs: number;
    /**
     * Cooldown after NOT_PLAN_MODE verdict in ms.
     * @default 30000 (30 seconds)
     */
    aiPlanCheckCooldownMs: number;
    /**
     * Enable stuck-state detection.
     * Detects when the controller stays in the same state for too long.
     * @default true
     */
    stuckStateDetectionEnabled: boolean;
    /**
     * Threshold for stuck-state warning in ms.
     * If state doesn't change for this duration, emits a warning.
     * @default 300000 (5 minutes)
     */
    stuckStateWarningMs: number;
    /**
     * Threshold for stuck-state recovery in ms.
     * If state doesn't change for this duration, triggers recovery action.
     * @default 600000 (10 minutes)
     */
    stuckStateRecoveryMs: number;
    /**
     * Maximum consecutive stuck-state recoveries before giving up.
     * @default 3
     */
    maxStuckRecoveries: number;
    /**
     * Enable adaptive timing based on historical patterns.
     * Adjusts completion confirm timeout dynamically.
     * @default true
     */
    adaptiveTimingEnabled?: boolean;
    /**
     * Minimum adaptive completion confirm timeout (ms).
     * @default 5000
     */
    adaptiveMinConfirmMs?: number;
    /**
     * Maximum adaptive completion confirm timeout (ms).
     * @default 30000
     */
    adaptiveMaxConfirmMs?: number;
    /**
     * Skip /clear when context usage is low.
     * @default true
     */
    skipClearWhenLowContext?: boolean;
    /**
     * Context threshold percentage below which to skip /clear.
     * @default 30
     */
    skipClearThresholdPercent?: number;
    /**
     * Enable tracking of respawn cycle metrics.
     * @default true
     */
    trackCycleMetrics?: boolean;
    /**
     * Minimum confidence level required to trigger idle detection.
     * Below this threshold, the controller waits for more signals.
     * @default 65
     */
    minIdleConfidence?: number;
    /**
     * Confidence weight for completion message detection.
     * @default 40
     */
    confidenceWeightCompletion?: number;
    /**
     * Confidence weight for output silence.
     * @default 25
     */
    confidenceWeightSilence?: number;
    /**
     * Confidence weight for token stability.
     * @default 20
     */
    confidenceWeightTokens?: number;
    /**
     * Confidence weight for working pattern absence.
     * @default 15
     */
    confidenceWeightNoWorking?: number;
}
/**
 * Events emitted by RespawnController.
 *
 * @event stateChanged - Fired when state machine transitions
 * @event respawnCycleStarted - Fired when a new cycle begins
 * @event respawnCycleCompleted - Fired when a cycle finishes
 * @event stepSent - Fired when a command is sent to the session
 * @event stepCompleted - Fired when a step finishes (ready indicator detected)
 * @event detectionUpdate - Fired when detection status changes (for UI)
 * @event error - Fired on errors
 * @event log - Fired for debug logging
 */
/** Action log entry for detailed UI feedback */
interface ActionLogEntry {
    type: string;
    detail: string;
    timestamp: number;
}
/**
 * RespawnController - Automatic session cycling for continuous Claude work.
 *
 * Monitors a Claude Code session for idle state and automatically cycles
 * through update → clear → init steps to keep the session productive.
 *
 * ## How It Works
 *
 * 1. **Idle Detection**: Watches for completion message ("for Xm Xs" pattern)
 * 2. **Confirmation**: Waits for output silence (no new tokens for 5s)
 * 3. **Update**: Sends configured prompt (e.g., "update all docs")
 * 4. **Clear**: Sends `/clear` to reset context (optional)
 * 5. **Init**: Sends `/init` to re-initialize with CLAUDE.md (optional)
 * 6. **Kickstart**: If /init doesn't trigger work, sends fallback prompt (optional)
 * 7. **Repeat**: Returns to watching state for next cycle
 *
 * ## Idle Detection (Updated for Claude Code 2024+)
 *
 * Primary: Completion message with time duration (e.g., "✻ Worked for 2m 46s")
 * The pattern "for Xm Xs" indicates Claude finished work and reports duration.
 *
 * Confirmation: After seeing completion message, waits for output silence.
 * If no new output for `completionConfirmMs` (default 10s), confirms idle.
 *
 * Fallback: If no output at all for `noOutputTimeoutMs` (default 30s), assumes idle.
 *
 * Working indicators: Thinking, Writing, spinner characters, etc. reset detection.
 *
 * ## Events
 *
 * - `stateChanged`: State machine transition
 * - `respawnCycleStarted`: New cycle began
 * - `respawnCycleCompleted`: Cycle finished
 * - `stepSent`: Command sent to session
 * - `stepCompleted`: Step finished
 * - `log`: Debug messages
 *
 * @extends EventEmitter
 * @example
 * ```typescript
 * const respawn = new RespawnController(session, {
 *   updatePrompt: 'continue working on the task',
 *   completionConfirmMs: 10000,  // Wait 10s after completion message
 * });
 *
 * respawn.on('respawnCycleCompleted', (cycle) => {
 *   console.log(`Completed cycle ${cycle}`);
 * });
 *
 * respawn.start();
 * ```
 */
export declare class RespawnController extends EventEmitter {
    /** The session being controlled */
    private session;
    /** Optional team watcher for team-aware idle detection */
    private teamWatcher;
    /** Current configuration */
    private config;
    /** Current state machine state */
    private _state;
    /** Centralized timer lifecycle manager — disposed and recreated on clearTimers() */
    private cleanup;
    /** Maps timer names to CleanupManager registration IDs (for individual cancel) */
    private timerIds;
    /** Cached key fields from last emitted detection status (for dedup) */
    private lastEmittedDetectionKey;
    /** Whether any terminal output has been received since start/last-auto-accept */
    private hasReceivedOutput;
    /** Whether a Stop hook was received (definitive idle signal from Claude Code) */
    private stopHookReceived;
    /** Timestamp when Stop hook was received */
    private stopHookTime;
    /** Whether an idle_prompt notification was received (60s+ idle signal) */
    private idlePromptReceived;
    /** Timestamp when idle_prompt was received */
    private idlePromptTime;
    /** Confirmation delay after hook signal before confirming idle (ms) */
    private static readonly HOOK_CONFIRM_DELAY_MS;
    /** Number of completed respawn cycles */
    private cycleCount;
    /** Timestamp of last terminal activity */
    private lastActivityTime;
    /** Buffer for recent terminal output (uses BufferAccumulator to reduce GC pressure) */
    private terminalBuffer;
    /** Whether a prompt indicator was detected */
    private promptDetected;
    /** Whether a working indicator was detected */
    private workingDetected;
    /** Reference to terminal event handler (for cleanup) */
    private terminalHandler;
    /** AI idle checker instance */
    private aiChecker;
    /** AI plan mode checker instance */
    private planChecker;
    /** Timestamp when plan check was started (to detect stale results) */
    private planCheckStartTime;
    /** Unique ID for current AI check request (to detect stale results) */
    private _currentAiCheckId;
    /** Fallback timeout for /clear step (ms) - sends /init without waiting for prompt */
    private static readonly CLEAR_FALLBACK_TIMEOUT_MS;
    /** Active timers being tracked for UI display */
    private activeTimers;
    /** Recent action log entries (for UI display, max 20) */
    private recentActions;
    /** Timestamp when the current state was entered */
    private stateEnteredAt;
    /** Whether a stuck-state warning has been emitted for current state */
    private stuckStateWarned;
    /** Number of stuck-state recovery attempts */
    private stuckRecoveryCount;
    /** Adaptive timing controller */
    private adaptiveTiming;
    /** Cycle metrics tracker */
    private cycleMetrics;
    /** Timestamp when idle detection started for current cycle */
    private idleDetectionStartTime;
    /** Layer 1: Timestamp when completion message was detected */
    private completionMessageTime;
    /** Layer 2: Timestamp of last terminal output received */
    private lastOutputTime;
    /** Layer 3: Last observed token count */
    private lastTokenCount;
    /** Layer 3: Timestamp when token count last changed */
    private lastTokenChangeTime;
    /** Layer 4: Timestamp when last working pattern was seen */
    private lastWorkingPatternTime;
    /**
     * Rolling window buffer for working pattern detection.
     * Prevents split-chunk issues where "Thinking" arrives as "Thin" + "king".
     * Size: 300 chars should be enough to catch any split pattern.
     */
    private workingPatternWindow;
    private static readonly WORKING_PATTERN_WINDOW_SIZE;
    /**
     * Minimum time without working patterns before considering idle (ms).
     * Increased from 3s to 8s to avoid false positives during tool execution gaps.
     */
    private static readonly MIN_WORKING_PATTERN_ABSENCE_MS;
    /**
     * Creates a new RespawnController.
     *
     * @param session - The Session instance to control
     * @param config - Partial configuration (merged with defaults)
     */
    constructor(session: Session, config?: Partial<RespawnConfig>);
    /**
     * Validate configuration values and reset invalid ones to defaults.
     * Ensures timeouts are positive and logically consistent.
     */
    private validateConfig;
    /** Wire up AI checker events to controller events (removes existing listeners first to prevent duplicates) */
    private setupAiCheckerListeners;
    /** Wire up plan checker events to controller events (removes existing listeners first to prevent duplicates) */
    private setupPlanCheckerListeners;
    /**
     * Get the current state machine state.
     * @returns Current RespawnState
     */
    get state(): RespawnState;
    /**
     * Get the current respawn cycle count.
     * Increments each time a new cycle starts.
     * @returns Number of cycles started
     */
    get currentCycle(): number;
    /**
     * Check if the controller is currently running.
     * @returns True if state is not 'stopped'
     */
    get isRunning(): boolean;
    /**
     * Get current detection status for UI display.
     * Shows all detection layers and their current state.
     * @returns DetectionStatus object
     */
    getDetectionStatus(): DetectionStatus;
    /**
     * Start periodic detection status updates for UI.
     * Emits 'detectionUpdate' event every 2s while running.
     */
    private startDetectionUpdates;
    /**
     * Stop periodic detection status updates.
     */
    private stopDetectionUpdates;
    /**
     * Transition to a new state.
     * Emits 'stateChanged' event with old and new states.
     * No-op if already in the target state.
     *
     * @param newState - State to transition to
     * @fires stateChanged
     */
    private setState;
    /**
     * Emit a timestamped log message.
     * @param message - Log message content
     * @fires log
     */
    private log;
    /** Set team watcher for team-aware idle detection */
    setTeamWatcher(watcher: TeamWatcher): void;
    /**
     * Start watching the session for idle state.
     *
     * Begins monitoring terminal output for idle indicators.
     * When idle is detected, starts the respawn cycle.
     *
     * No-op if:
     * - `config.enabled` is false
     * - Already running (state !== 'stopped')
     *
     * @fires stateChanged - Transitions to 'watching'
     */
    start(): void;
    /**
     * Stop the respawn controller.
     *
     * Clears all timers, removes terminal listener, and sets state to 'stopped'.
     * Safe to call multiple times.
     *
     * @fires stateChanged - Transitions to 'stopped'
     */
    stop(): void;
    /**
     * Pause respawn without stopping.
     *
     * Clears timers but keeps listening to terminal.
     * State is preserved; won't trigger idle detection while paused.
     * Use resume() to continue.
     */
    pause(): void;
    /**
     * Resume respawn after pause.
     *
     * If in 'watching' state, immediately checks for idle condition.
     * Otherwise, continues from current state.
     * Re-setups terminal listener if it was removed (e.g., after stop()).
     */
    resume(): void;
    /**
     * Set up terminal output listener on the session.
     * Removes any previous listener first to avoid duplicates.
     */
    private setupTerminalListener;
    /**
     * Process terminal data for idle/working detection using multi-layer approach.
     *
     * Detection Layers:
     * 1. Completion message ("for Xm Xs") - PRIMARY signal
     * 2. Output silence - confirms completion
     * 3. Token stability - additional confirmation
     * 4. Working pattern absence - supports idle detection
     * 5. No-output fallback - catches edge cases
     *
     * @param data - Raw terminal output data
     */
    private handleTerminalData;
    private _detectCompletionMessage;
    private _detectWorkingPattern;
    private _detectPrompt;
    /**
     * Handle update step completion.
     * Called when ready indicator detected in waiting_update state.
     * Proceeds to clear, init, or completes cycle based on config.
     * @fires stepCompleted - With step 'update'
     */
    private checkUpdateComplete;
    /**
     * Handle /clear step completion.
     * Proceeds to init or completes cycle based on config.
     * @fires stepCompleted - With step 'clear'
     */
    private checkClearComplete;
    /**
     * Handle /init step completion.
     * If kickstart is configured, monitors for work.
     * Otherwise completes cycle.
     * @fires stepCompleted - With step 'init' (if no kickstart)
     */
    private checkInitComplete;
    /**
     * Start monitoring to see if /init triggered work.
     * Enters 'monitoring_init' state and waits 3s grace period.
     * If no work detected, sends kickstart prompt.
     */
    private startMonitoringInit;
    /**
     * Handle monitoring timeout when /init didn't trigger work.
     * Sends kickstart prompt as fallback.
     * @fires stepCompleted - With step 'init'
     */
    private checkMonitoringInitIdle;
    /**
     * Send the kickstart prompt to get Claude working.
     * @fires stepSent - With step 'kickstart'
     */
    private sendKickstart;
    /**
     * Handle kickstart step completion.
     * @fires stepCompleted - With step 'kickstart'
     */
    private checkKickstartComplete;
    /** Clear all timers (step, completion confirm, no-output, pre-filter, step confirm, auto-accept, hook confirm, and clear fallback) */
    private clearTimers;
    /**
     * Start or restart the stuck-state detection timer.
     * Emits warning after stuckStateWarningMs, triggers recovery after stuckStateRecoveryMs.
     */
    private startStuckStateTimer;
    /**
     * Check if the controller is stuck in the current state.
     * Emits warnings and triggers recovery actions as appropriate.
     */
    private checkStuckState;
    /**
     * Handle stuck-state recovery by resetting to a known good state.
     * Uses escalating recovery strategies based on current state.
     */
    private handleStuckStateRecovery;
    /**
     * Reset the controller to watching state during stuck-state recovery.
     * Sets state to watching and restarts all detection timers.
     *
     * @param reason - Human-readable reason for the reset (logged)
     */
    private recoveryResetToWatching;
    /**
     * Get stuck-state metrics for UI display.
     */
    getStuckStateMetrics(): {
        currentStateDurationMs: number;
        warningThresholdMs: number;
        recoveryThresholdMs: number;
        recoveryAttempts: number;
        maxRecoveries: number;
        isWarned: boolean;
    };
    /**
     * Start a tracked timer with UI countdown support.
     * Emits timerStarted event and tracks the timer for UI display.
     */
    private startTrackedTimer;
    /**
     * Cancel a tracked timer and emit cancellation event.
     */
    private cancelTrackedTimer;
    /**
     * Get all active timers with remaining time for UI display.
     */
    getActiveTimers(): ActiveTimerInfo[];
    /**
     * Log an action for detailed UI feedback.
     * Keeps the last 20 entries.
     */
    private logAction;
    /**
     * Get recent action log entries.
     */
    getRecentActions(): ActionLogEntry[];
    /**
     * Check if data contains working patterns using the rolling window.
     * Updates the window and delegates to the pure function from respawn-patterns.
     */
    private checkWorkingPattern;
    /**
     * Clear the working pattern rolling window.
     * Called when starting a new detection cycle.
     */
    private clearWorkingPatternWindow;
    /**
     * Start the no-output fallback timer.
     * If no output for noOutputTimeoutMs, triggers idle detection as safety net
     * (used when AI check is disabled or has too many errors).
     */
    private startNoOutputTimer;
    /**
     * Reset the no-output fallback timer.
     * Called whenever output is received.
     */
    private resetNoOutputTimer;
    /**
     * Start the pre-filter timer.
     * Fires after completionConfirmMs of silence. When it fires, checks if
     * all pre-filter conditions are met and starts the AI check if so.
     * This provides an additional path to AI check even without a completion message.
     */
    private startPreFilterTimer;
    /**
     * Reset the pre-filter timer.
     * Called whenever output is received.
     */
    private resetPreFilterTimer;
    /**
     * Attempt to start an AI idle check.
     * Checks if AI check is enabled, not on cooldown, and not already checking.
     * Falls back to direct idle confirmation if AI check is unavailable.
     *
     * @param reason - What triggered this attempt (for logging)
     */
    private tryStartAiCheck;
    /**
     * Start the AI idle check.
     * Transitions to 'ai_checking' state and runs the check asynchronously.
     *
     * @param reason - What triggered this check (for logging)
     */
    private startAiCheck;
    /**
     * Reset the auto-accept timer.
     * Called whenever output is received. After autoAcceptDelayMs of silence
     * (without a completion message), sends Enter to accept prompts.
     */
    private resetAutoAcceptTimer;
    /**
     * Start the auto-accept timer.
     * Fires after autoAcceptDelayMs of no output when no completion message
     * and no elicitation dialog was detected. Only handles plan mode approvals.
     */
    private startAutoAcceptTimer;
    /**
     * Cancel the auto-accept timer.
     * Called when a completion message is detected (normal idle flow handles it).
     */
    private cancelAutoAcceptTimer;
    /**
     * Attempt to auto-accept a plan mode prompt by sending Enter.
     * Two-stage gate:
     * 1. Strict regex pre-filter — check if terminal buffer contains plan mode UI elements
     * 2. AI confirmation — spawn Opus to classify buffer as PLAN_MODE or NOT_PLAN_MODE
     *
     * Only sends Enter if both stages confirm (or pre-filter only if AI disabled).
     *
     * @fires autoAcceptSent
     * @fires planCheckStarted
     */
    private tryAutoAccept;
    /**
     * Check whether all preconditions for auto-accept are met.
     * Validates state, config, and pre-filter conditions before attempting auto-accept.
     *
     * @returns True if auto-accept should proceed to the AI confirmation stage
     */
    private canAutoAccept;
    /**
     * Check if the terminal buffer matches plan mode pre-filter patterns.
     * Only checks the last 2000 chars (plan mode UI appears at the bottom).
     *
     * Must find:
     * - Numbered option pattern (e.g., "1. Yes", "2. No")
     * - Selection indicator (❯ or > followed by number)
     * Must NOT find:
     * - Recent working patterns (spinners, "Thinking", etc.) in the tail
     */
    private isPlanModePreFilterMatch;
    /**
     * Start an AI plan check to confirm plan mode before auto-accepting.
     * Async — result handled by then/catch.
     *
     * @param buffer - Terminal buffer to analyze
     * @fires planCheckStarted
     * @fires planCheckCompleted
     * @fires planCheckFailed
     */
    private startPlanCheck;
    /**
     * Send the actual Enter keystroke for auto-accept.
     * Factored out so both pre-filter-only and AI-confirmed paths can call it.
     * @fires autoAcceptSent
     */
    private sendAutoAcceptEnter;
    /**
     * Signal that an elicitation dialog (AskUserQuestion) was detected via hook.
     * Used as a positive hint that a numbered selection menu is about to render —
     * we restart the auto-accept timer so the pre-filter gets a fresh shot at it
     * once the menu finishes drawing. The actual gate is `isPlanModePreFilterMatch()`
     * plus (optionally) the AI plan check; this hook just primes the timer.
     * No-op if respawn isn't `'watching'`/`'confirming_idle'` or `autoAcceptPrompts`
     * is off, so this can never fire Enter when the user has disabled auto-accept.
     */
    signalElicitation(): void;
    /**
     * Signal that a Stop hook was received from Claude Code.
     * This is a DEFINITIVE signal that Claude has finished responding.
     * Skips AI idle check and uses a short confirmation period to handle race conditions.
     *
     * @fires log
     */
    signalStopHook(): void;
    /**
     * Signal that an idle_prompt notification was received from Claude Code.
     * This fires after 60+ seconds of Claude waiting for user input.
     * This is a DEFINITIVE signal that Claude is idle.
     *
     * @fires log
     */
    signalIdlePrompt(): void;
    /**
     * Start a short confirmation timer after receiving a hook signal.
     * This handles race conditions where a hook arrives but Claude immediately starts new work.
     *
     * @param hookType - Which hook triggered this ('stop' or 'idle_prompt')
     */
    private startHookConfirmTimer;
    /**
     * Reset hook-based detection state.
     * Called when hooks are cancelled due to new activity.
     */
    private resetHookState;
    /**
     * Signal that the transcript indicates completion.
     * This is a supporting signal from transcript file monitoring.
     * Unlike hooks, this doesn't immediately trigger idle - it boosts confidence.
     */
    signalTranscriptComplete(): void;
    /**
     * Signal that the transcript indicates plan mode.
     * This helps prevent auto-accept from triggering on AskUserQuestion.
     */
    signalTranscriptPlanMode(): void;
    /**
     * Start completion confirmation timer.
     * After completion message, waits for output silence then triggers AI check.
     */
    private startCompletionConfirmTimer;
    /**
     * Cancel completion confirmation if new activity detected.
     */
    private cancelCompletionConfirm;
    /**
     * Start step confirmation timer for waiting states.
     * Waits for output silence before proceeding to next step.
     * This ensures Claude has finished processing before we send the next command.
     */
    private startStepConfirmTimer;
    /**
     * Cancel step confirmation if working patterns detected.
     */
    private cancelStepConfirm;
    /**
     * Called when idle is confirmed through any detection layer.
     * @param reason - What triggered the confirmation
     */
    private onIdleConfirmed;
    /**
     * Handle confirmed idle detection.
     * Starts a new respawn cycle.
     * @fires respawnCycleStarted
     */
    private onIdleDetected;
    /**
     * Send the update docs prompt (first step of cycle).
     * Uses RALPH_STATUS RECOMMENDATION if available, otherwise falls back to configured prompt.
     * @fires stepSent - With step 'update'
     */
    private sendUpdateDocs;
    /**
     * Send /clear command.
     * Starts a 10-second fallback timer - if no prompt is detected after /clear,
     * proceeds to /init anyway (workaround for when Claude doesn't show prompt after /clear).
     * @fires stepSent - With step 'clear'
     */
    private sendClear;
    /**
     * Send /init command.
     * @fires stepSent - With step 'init'
     */
    private sendInit;
    /**
     * Complete the current respawn cycle.
     * Returns to watching state for next cycle.
     * @fires respawnCycleCompleted
     */
    private completeCycle;
    /**
     * Check if already idle and start cycle if so.
     * Used when resuming from pause.
     */
    private checkIdleAndMaybeStart;
    /**
     * Update configuration at runtime.
     *
     * Merges provided config with existing config.
     * Takes effect immediately for new operations.
     *
     * @param config - Partial configuration to merge
     * @fires log - With updated config details
     */
    updateConfig(config: Partial<RespawnConfig>): void;
    /**
     * Get current configuration.
     * @returns Copy of current config (safe to modify)
     */
    getConfig(): RespawnConfig;
    /**
     * Get comprehensive status information.
     *
     * Useful for debugging and monitoring.
     *
     * @returns Status object with:
     *   - state: Current state machine state
     *   - cycleCount: Number of cycles started
     *   - lastActivityTime: Timestamp of last activity
     *   - timeSinceActivity: Milliseconds since last activity
     *   - promptDetected: Whether prompt indicator seen
     *   - workingDetected: Whether working indicator seen
     *   - detection: Multi-layer detection status
     *   - config: Current configuration
     */
    getStatus(): {
        state: RespawnState;
        cycleCount: number;
        lastActivityTime: number;
        timeSinceActivity: number;
        promptDetected: boolean;
        workingDetected: boolean;
        detection: DetectionStatus;
        config: RespawnConfig;
    };
    /**
     * Get the current completion confirm timeout, potentially adjusted by adaptive timing.
     * Uses historical idle detection durations to calculate an optimal timeout.
     *
     * @returns Completion confirm timeout in milliseconds
     */
    getAdaptiveCompletionConfirmMs(): number;
    /**
     * Get the current timing history for monitoring.
     * @returns Copy of timing history
     */
    getTimingHistory(): TimingHistory;
    /**
     * Determine whether to skip the /clear step based on current context usage.
     * Skips if token count is below the configured threshold percentage.
     *
     * @returns True if /clear should be skipped
     */
    private checkShouldSkipClear;
    /**
     * Start tracking metrics for a new cycle.
     * Called when a respawn cycle begins.
     */
    private startCycleMetrics;
    /**
     * Record a completed step in the current cycle.
     * @param step - Name of the step (e.g., 'update', 'clear', 'init')
     */
    private recordCycleStep;
    /**
     * Complete the current cycle metrics with outcome.
     * Adds to recent metrics and updates aggregates.
     *
     * @param outcome - Outcome of the cycle
     * @param errorMessage - Optional error message if outcome is 'error'
     */
    private completeCycleMetrics;
    /**
     * Get aggregate metrics for monitoring.
     * @returns Copy of aggregate metrics
     */
    getAggregateMetrics(): RespawnAggregateMetrics;
    /**
     * Get recent cycle metrics for analysis.
     * @param limit - Maximum number of metrics to return (default: 20)
     * @returns Recent cycle metrics, newest first
     */
    getRecentCycleMetrics(limit?: number): RespawnCycleMetrics[];
    /**
     * Calculate a comprehensive health score for the Ralph Loop system.
     * Aggregates multiple health signals into a single score (0-100).
     *
     * @returns Health score with component breakdown
     */
    calculateHealthScore(): RalphLoopHealthScore;
}
export {};
//# sourceMappingURL=respawn-controller.d.ts.map