/**
 * OAuth Relogin Monitor Service
 *
 * Monitors PTY session output for OAuth token expiry errors and orchestrates
 * the full human-in-the-loop OAuth re-authentication flow:
 *
 * 1. **Detect**: Watch PTY output for authentication_error + expired token
 * 2. **Login**: Auto-send `/login` command to trigger OAuth flow
 * 3. **Capture**: Extract the OAuth URL from PTY output after /login
 * 4. **Notify**: Emit `agent:oauth_url` event so orchestrator/Slack can forward to user
 * 5. **Callback**: Accept auth code via API and write it to PTY to complete login
 *
 * Follows the PTY subscription pattern from ContextWindowMonitorService and
 * RuntimeExitMonitorService.
 *
 * @module services/agent/oauth-relogin-monitor
 */
import type { RuntimeType } from '../../constants.js';
import type { EventBusService } from '../event-bus/event-bus.service.js';
/**
 * URL capture mode — active after /login is sent, waiting for OAuth URL.
 */
type CaptureMode = 'idle' | 'capturing';
/**
 * Per-session OAuth relogin monitoring state.
 */
export interface OAuthMonitorState {
    /** PTY session name */
    sessionName: string;
    /** Runtime type (determines whether Escape key is safe) */
    runtimeType: RuntimeType;
    /** Function to unsubscribe from PTY data events */
    unsubscribe: () => void;
    /** Rolling buffer for terminal output */
    buffer: string;
    /** Timestamp when monitoring started */
    startedAt: number;
    /** Timestamp of last /login command sent */
    lastReloginAt: number;
    /** Whether a relogin is currently in progress (debounce guard) */
    reloginInProgress: boolean;
    /** Timestamps of recent relogin attempts for rate limiting */
    attemptTimestamps: number[];
    /** Debounce timer handle */
    debounceTimer: ReturnType<typeof setTimeout> | null;
    /** Current URL capture mode */
    captureMode: CaptureMode;
    /** Buffer specifically for URL capture (separate from error detection buffer) */
    captureBuffer: string;
    /** Timeout timer for URL capture — gives up after URL_CAPTURE_TIMEOUT_MS */
    captureTimeoutTimer: ReturnType<typeof setTimeout> | null;
    /** Last captured OAuth URL (for debugging/testing) */
    lastCapturedUrl: string | null;
}
/**
 * OAuth URL event payload emitted on the EventBus.
 */
export interface OAuthUrlEventPayload {
    /** PTY session name */
    sessionName: string;
    /** OAuth URL that the user needs to visit */
    url: string;
}
/**
 * Monitors PTY sessions for OAuth token expiry errors and orchestrates the
 * full OAuth re-authentication flow including URL capture and event notification.
 *
 * @example
 * ```typescript
 * const monitor = OAuthReloginMonitorService.getInstance();
 * monitor.setEventBusService(eventBus);
 * monitor.startMonitoring('agent-dev-001', 'claude-code');
 *
 * // User sends back auth code via API:
 * OAuthReloginMonitorService.submitOAuthCode('agent-dev-001', 'auth-code-123');
 * ```
 */
export declare class OAuthReloginMonitorService {
    private static instance;
    private logger;
    /** Per-session monitoring state */
    private sessions;
    /** EventBus for publishing oauth_url events */
    private eventBusService;
    /** Callback invoked when an OAuth URL is captured (for orchestrator/Slack integration) */
    private onOAuthUrlCallback;
    private constructor();
    /**
     * Get the singleton instance.
     *
     * @returns The OAuthReloginMonitorService singleton
     */
    static getInstance(): OAuthReloginMonitorService;
    /**
     * Reset the singleton (for testing).
     */
    static resetInstance(): void;
    /**
     * Set the EventBus dependency for publishing OAuth URL events.
     *
     * @param eventBus - The EventBusService instance
     */
    setEventBusService(eventBus: EventBusService): void;
    /**
     * Register a callback invoked when an OAuth URL is captured.
     * Used for direct notification (e.g., Slack) without going through EventBus subscriptions.
     *
     * @param callback - Called with (sessionName, oauthUrl)
     */
    setOnOAuthUrlCallback(callback: (sessionName: string, url: string) => void): void;
    /**
     * Submit an OAuth authorization code to a session's PTY.
     *
     * After the user visits the OAuth URL and gets an auth code, this method
     * writes the code into the agent's PTY session to complete authentication.
     *
     * @param sessionName - PTY session name
     * @param code - OAuth authorization code from the user
     * @returns True if the code was written successfully
     */
    static submitOAuthCode(sessionName: string, code: string): boolean;
    /**
     * Start monitoring a PTY session for OAuth token expiry errors.
     *
     * Subscribes to the session's PTY onData events and watches for
     * authentication error patterns in the output.
     *
     * @param sessionName - PTY session name
     * @param runtimeType - Agent runtime type (claude-code, gemini-cli, codex-cli)
     */
    startMonitoring(sessionName: string, runtimeType: RuntimeType): void;
    /**
     * Stop monitoring a PTY session.
     *
     * @param sessionName - PTY session name
     */
    stopMonitoring(sessionName: string): void;
    /**
     * Check if a session is being monitored.
     *
     * @param sessionName - PTY session name
     * @returns True if the session is being monitored
     */
    isMonitoring(sessionName: string): boolean;
    /**
     * Get the monitoring state for a session (for testing/debugging).
     *
     * @param sessionName - PTY session name
     * @returns The monitoring state or undefined
     */
    getState(sessionName: string): OAuthMonitorState | undefined;
    /**
     * Destroy all monitoring subscriptions.
     */
    destroy(): void;
    /**
     * Handle incoming PTY data for a monitored session.
     *
     * In normal mode: checks for OAuth error patterns.
     * In capture mode: looks for OAuth URL after /login was sent.
     *
     * @param sessionName - PTY session name
     * @param data - Raw PTY output data
     */
    private handleData;
    /**
     * Handle PTY data while in URL capture mode.
     *
     * Accumulates output and scans for an HTTPS URL that looks like an OAuth
     * authorization endpoint.
     *
     * @param state - Session monitoring state
     * @param data - Cleaned PTY output data
     */
    private handleCaptureData;
    /**
     * Extract an OAuth URL from terminal output.
     *
     * Looks for HTTPS URLs that appear to be OAuth authorization endpoints.
     * Matches URLs containing common OAuth path segments: /oauth, /authorize,
     * /login, /auth, /consent.
     *
     * @param buffer - Terminal output buffer
     * @returns The OAuth URL or null if not found
     */
    private extractOAuthUrl;
    /**
     * Emit an `agent:oauth_url` event via the EventBus and invoke the callback.
     *
     * @param sessionName - PTY session name
     * @param url - OAuth URL captured from PTY output
     */
    private emitOAuthUrlEvent;
    /**
     * Detect OAuth error patterns in the buffer using string matching.
     *
     * Uses plain string indexOf (case-insensitive via lowercasing) instead of
     * regex to prevent ReDoS vulnerabilities. Each pattern set requires ALL
     * strings in the set to be present (AND logic).
     *
     * @param buffer - Terminal output buffer to check
     * @returns True if an OAuth error pattern is detected
     */
    private detectOAuthError;
    /**
     * Send the /login command to a PTY session to re-authenticate.
     *
     * After sending /login, enters URL capture mode to extract the OAuth URL
     * from the subsequent PTY output.
     *
     * @param sessionName - PTY session name
     */
    private triggerRelogin;
}
export {};
//# sourceMappingURL=oauth-relogin-monitor.service.d.ts.map