/**
 * Context Window Monitor Service
 *
 * Monitors PTY session output for context window usage percentages and triggers
 * proactive warnings and runtime-native compaction when thresholds are exceeded.
 *
 * When an agent's session reports context usage (e.g., "85% context"),
 * this service detects the percentage, evaluates it against configured thresholds,
 * and takes action:
 * - Yellow (70%): Publishes a warning event
 * - Red (85%): Publishes a warning + triggers runtime compact (/compact or /compress)
 * - Critical (95%): Retries compact with cooldown; auto-recovery disabled by default
 *
 * Strategy: prefer runtime-native compact/compress commands which preserve session
 * state over session kill + restart which loses all context. Auto-recovery is
 * available as a last resort via AUTO_RECOVERY_ENABLED constant.
 *
 * Follows the PTY subscription pattern from RuntimeExitMonitorService and the
 * lifecycle/restart pattern from AgentHeartbeatMonitorService.
 *
 * @module services/agent/context-window-monitor
 */
import { StorageService } from '../core/storage.service.js';
import type { RuntimeType } from '../../constants.js';
import type { AgentRegistrationService } from './agent-registration.service.js';
import type { ISessionBackend } from '../session/session-backend.interface.js';
import type { EventBusService } from '../event-bus/event-bus.service.js';
/**
 * Context usage severity level.
 */
export type ContextLevel = 'normal' | 'yellow' | 'red' | 'critical';
/**
 * Per-session context window monitoring state.
 */
export interface ContextWindowState {
    /** PTY session name */
    sessionName: string;
    /** Team member ID */
    memberId: string;
    /** Team ID */
    teamId: string;
    /** Agent role */
    role: string;
    /** Runtime type for this session (determines compact command) */
    runtimeType: RuntimeType;
    /** Last detected context usage percentage (0-100) */
    contextPercent: number;
    /** Current severity level */
    level: ContextLevel;
    /** Timestamp of last context % detection */
    lastDetectedAt: number;
    /** Whether auto-recovery has been triggered for this session */
    recoveryTriggered: boolean;
    /** Total recovery count for this session */
    recoveryCount: number;
    /** Timestamps of recent recoveries for cooldown tracking */
    recoveryTimestamps: number[];
    /** Number of compact attempts for current high-usage episode */
    compactAttempts: number;
    /** Whether a compact is currently in progress */
    compactInProgress: boolean;
    /** Timestamp of the last compact attempt */
    lastCompactAt: number;
    /** Context percent recorded when compact was triggered (for post-compact verification) */
    preCompactPercent: number;
    /** Handle for the compact wait timeout (cleared on session stop) */
    compactWaitTimer: ReturnType<typeof setTimeout> | null;
}
/**
 * Monitors agent PTY sessions for context window usage and triggers
 * threshold-based warnings and auto-recovery.
 *
 * @example
 * ```typescript
 * const monitor = ContextWindowMonitorService.getInstance();
 * monitor.setDependencies(backend, regService, storageService, taskService, eventBus);
 * monitor.start();
 * monitor.startSessionMonitoring('agent-dev', 'member-1', 'team-1', 'developer');
 * ```
 */
export declare class ContextWindowMonitorService {
    private static instance;
    private logger;
    /** Per-session context window state */
    private contextStates;
    /** Per-session PTY data subscriptions + rolling buffers */
    private sessionSubscriptions;
    /** Periodic check interval timer */
    private checkTimer;
    /** Dependencies (injected via setDependencies) */
    private sessionBackend;
    private agentRegistrationService;
    private storageService;
    private eventBusService;
    private constructor();
    /**
     * Get the singleton instance.
     *
     * @returns The ContextWindowMonitorService singleton
     */
    static getInstance(): ContextWindowMonitorService;
    /**
     * Reset the singleton (for testing).
     */
    static resetInstance(): void;
    /**
     * Inject required dependencies.
     *
     * V3-only as of spec 2026-05-06-task-management-v1-deprecation.md.
     * The legacy `taskTrackingService` parameter has been removed; task
     * re-delivery now reads directly from TaskPoolService.
     *
     * @param sessionBackend - Session backend for PTY access
     * @param agentRegistrationService - For recreating agent sessions on recovery
     * @param storageService - For querying agent status
     * @param eventBusService - For publishing context warning/critical events
     */
    setDependencies(sessionBackend: ISessionBackend, agentRegistrationService: AgentRegistrationService, storageService: StorageService, eventBusService: EventBusService): void;
    /**
     * Start the periodic check loop for stale detection and cleanup.
     */
    start(): void;
    /**
     * Stop the periodic check loop.
     */
    stop(): void;
    /**
     * Check if the monitor is currently running.
     *
     * @returns True if the periodic check loop is active
     */
    isRunning(): boolean;
    /**
     * Start monitoring a specific session for context window usage.
     *
     * Subscribes to the session's PTY onData events and parses output
     * for context usage percentages.
     *
     * @param sessionName - PTY session name
     * @param memberId - Team member ID
     * @param teamId - Team ID
     * @param role - Agent role
     * @param runtimeType - Runtime type (defaults to 'claude-code')
     */
    startSessionMonitoring(sessionName: string, memberId: string, teamId: string, role: string, runtimeType?: RuntimeType): void;
    /**
     * Stop monitoring a specific session.
     *
     * @param sessionName - PTY session name
     */
    stopSessionMonitoring(sessionName: string): void;
    /**
     * Get the context window state for a specific session.
     *
     * @param sessionName - PTY session name
     * @returns The context window state or undefined if not monitored
     */
    getContextState(sessionName: string): ContextWindowState | undefined;
    /**
     * Get all monitored context window states.
     *
     * @returns Map of session name to context window state
     */
    getAllContextStates(): Map<string, ContextWindowState>;
    /**
     * Handle incoming PTY data for a monitored session.
     * Strips ANSI codes, appends to rolling buffer, and checks for context % patterns.
     *
     * @param sessionName - PTY session name
     * @param data - Raw PTY output data
     */
    private handleData;
    /**
     * Extract context usage percentage from terminal output.
     *
     * Tries percentage-based patterns first (Claude Code, generic), then
     * Gemini CLI token-count patterns. Token counts are converted to an
     * estimated usage percentage using GEMINI_DEFAULT_MAX_CONTEXT_TOKENS.
     *
     * @param text - Cleaned terminal output text
     * @param runtimeType - Optional runtime type for runtime-specific parsing
     * @returns The extracted percentage (0-100) or null if not found
     */
    private extractContextPercent;
    /**
     * Update context usage for a session and evaluate thresholds.
     *
     * @param sessionName - PTY session name
     * @param percent - New context usage percentage
     */
    updateContextUsage(sessionName: string, percent: number): void;
    /**
     * Evaluate threshold transitions and take appropriate actions.
     *
     * Strategy (compact-first):
     * 1. Yellow (70%): Publish warning event only
     * 2. Red (85%): Publish warning + trigger runtime-native compact/compress
     * 3. Critical (95%): Retry compact; periodic checks will continue retrying
     *    with cooldown. Auto-recovery (kill + restart) only if enabled.
     *
     * @param state - Current context window state
     * @param previousLevel - The level before this update
     */
    private evaluateThresholds;
    /**
     * Publish a context event via the event bus.
     *
     * @param state - Context window state
     * @param eventType - Event type to publish
     */
    private publishContextEvent;
    /**
     * Broadcast context window status to frontend via WebSocket.
     *
     * @param state - Context window state to broadcast
     */
    private broadcastContextWarning;
    /**
     * #166: Pre-compaction memory flush — send a message to the agent asking it to
     * save critical context (current task, progress, findings) before compaction
     * clears conversation history. The agent responds with record-learning or
     * remember calls, then replies NO_REPLY to avoid generating visible output.
     *
     * This is fire-and-forget: if delivery fails, compaction still proceeds.
     *
     * @param state - Context window state for the session
     */
    private triggerPreCompactionFlush;
    /**
     * Trigger context compaction by sending the runtime's native compact command.
     *
     * Writes the appropriate slash command (e.g., `/compact` for Claude Code,
     * `/compress` for Gemini CLI) to the PTY session stdin. The runtime handles
     * the actual compression — typically via LLM-based summarization.
     *
     * @param state - Context window state for the session to compact
     */
    private triggerCompact;
    /**
     * Returns true when a session is currently marked as in-progress.
     * Falls back to false on lookup errors so monitoring can continue.
     */
    private isSessionBusyForCompact;
    /**
     * Trigger auto-recovery for a session at critical context usage.
     *
     * Mirrors the restart pattern from AgentHeartbeatMonitorService:
     * 1. Check cooldown
     * 2. Save Claude session ID
     * 3. Stop exit monitoring
     * 4. Kill PTY session
     * 5. Clear activity tracker
     * 6. Pre-set session ID for resume
     * 7. Recreate agent session
     * 8. Broadcast status
     * 9. Re-deliver tasks
     *
     * @param state - Context window state for the session to recover
     */
    private triggerAutoRecovery;
    /**
     * Re-deliver in-progress tasks to a recovered agent.
     *
     * @param state - Context window state for the recovered session
     */
    private redeliverTasks;
    /**
     * Periodic check for stale states, cleanup, compact retries, and proactive compaction.
     *
     * For stale sessions (no context % detected recently), resets to normal.
     * For critical sessions with exhausted compacts, retries compact after
     * COMPACT_RETRY_COOLDOWN_MS has elapsed since the last attempt.
     * For all monitored sessions, checks cumulative output bytes and triggers
     * proactive compact when threshold is exceeded.
     */
    private performCheck;
    /** Timestamp of last proactive compact per session for cooldown tracking */
    private proactiveCompactLastTriggered;
    /**
     * Cached toggle for proactive compact behavior (loaded from settings).
     *
     * Default: `false` (fail-safe CLOSED). Per spec 2026-05-05-compact-fix-AB-followup §A.2 —
     * before the first refresh from settings, the wrapper does NOT proactively compact.
     * The runtime (Claude Code) handles its own compaction internally.
     */
    private proactiveCompactEnabled;
    /**
     * Cached toggle for threshold-driven compact at RED (85%) / CRITICAL (95%).
     *
     * Default: `false` (fail-safe CLOSED). Per spec 2026-05-05-compact-fix-AB-followup §B —
     * threshold-driven external compaction is opt-in. Auto-recovery (kill+restart) still
     * runs at CRITICAL when AUTO_RECOVERY_ENABLED, regardless of this flag.
     */
    private thresholdCompactEnabled;
    /**
     * Refresh the cached proactive compact toggle from persisted settings.
     * Non-fatal: any read failure keeps the previous cached value.
     *
     * Fail-safe semantics: when the persisted setting is undefined, default to
     * `false` so an absent configuration cannot enable external compaction.
     */
    private refreshProactiveCompactSetting;
    /**
     * Refresh the cached threshold compact toggle from persisted settings.
     * Non-fatal: any read failure keeps the previous cached value.
     *
     * Fail-safe semantics: when the persisted setting is undefined, default to
     * `false` so an absent configuration cannot enable threshold-driven compaction.
     */
    private refreshThresholdCompactSetting;
    /**
     * Check all monitored sessions for cumulative output volume and trigger
     * proactive compact when the threshold is exceeded.
     *
     * @param now - Current timestamp in epoch ms
     */
    private checkProactiveCompact;
    /**
     * Destroy all PTY subscriptions. Used during resetInstance.
     */
    private destroyAllSubscriptions;
}
//# sourceMappingURL=context-window-monitor.service.d.ts.map