import { S as StatusResponse, D as DaemonEvent, C as CommandResult$2, a as SessionEntry, P as ProviderCategory, b as ProviderModule, R as ResolvedProvider, c as ProviderSettingSchema, d as CdpTargetFilter, e as ProviderInstance, I as InstanceContext, f as ProviderState, g as ProviderEvent, h as SessionTransport, i as StatusReportPayload, A as AvailableProviderInfo, j as ProviderResumeCapability, k as AcpProviderState, l as ContentBlock } from './normalize-auJAPmKy.js';
export { m as AcpConfigOption, n as AcpMode, o as ActiveChatData, p as AgentEntry, q as AgentSessionStream, r as ChatMessage, s as CliProviderState, t as DetectedIde, u as DetectedIdeInfo, E as ExtensionInfo, v as ExtensionProviderState, w as IdeProviderState, M as MachineInfo, x as ManagedStatus, y as ProviderConfig, z as ProviderErrorReason, B as ProviderInfo, F as ProviderStatus, G as SessionCapability, H as SessionKind, J as SystemInfo, W as WorkspaceActivity, K as WorkspaceEntry, L as addCliHistory, N as getWorkspaceActivity, O as getWorkspaceState, Q as isManagedStatusWaiting, T as isManagedStatusWorking, U as isSetupComplete, V as loadConfig, X as markSetupComplete, Y as normalizeActiveChatData, Z as normalizeManagedStatus, _ as resetConfig, $ as saveConfig, a0 as updateConfig } from './normalize-auJAPmKy.js';
import * as child_process from 'child_process';
import { ChildProcess } from 'child_process';
import * as http from 'http';
import { SessionHostEndpoint, SessionHostCategory } from '@adhdev/session-host-core';
export { SessionHostEndpoint } from '@adhdev/session-host-core';

/**
 * DaemonCore — Core daemon orchestrator interface
 *
 * Provides the core daemon orchestrator interface consumed by daemon-standalone.
 * Actual implementation extracted from launcher and placed in this package.
 */

interface DaemonCoreOptions {
    /** Data directory for config, logs */
    dataDir?: string;
    /** Custom provider directories */
    providerDirs?: string[];
    /** Enable/disable specific detectors */
    enableIdeDetection?: boolean;
    enableCliDetection?: boolean;
    enableAcpDetection?: boolean;
    /** Status report interval (ms) */
    statusInterval?: number;
}
interface IDaemonCore {
    /** Initialize and start the daemon core */
    start(): Promise<void>;
    /** Gracefully stop the daemon */
    stop(): Promise<void>;
    /** Get current daemon status snapshot */
    getStatus(): StatusResponse;
    /** Subscribe to status changes. Returns unsubscribe function. */
    onStatusChange(callback: (status: StatusResponse) => void): () => void;
    /** Subscribe to all daemon events. Returns unsubscribe function. */
    onEvent(callback: (event: DaemonEvent) => void): () => void;
    /** Execute a command (send_chat, new_session, etc.) */
    executeCommand(type: string, payload: any, target?: string): Promise<CommandResult$2>;
    /** Get current canonical runtime sessions */
    getSessions(): SessionEntry[];
}

/**
 * ADHDev — IDE Detector (canonical implementation)
 *
 * Detects installed IDEs on the user's local machine.
 * Supports macOS, Windows, and Linux.
 *
 * Migrated from @adhdev/core — this is now the single source of truth.
 */
interface IDEInfo {
    id: string;
    name: string;
    displayName: string;
    installed: boolean;
    path: string | null;
    cliCommand: string | null;
    version: string | null;
    icon: string;
    notes?: string;
}
declare function detectIDEs(): Promise<IDEInfo[]>;

/**
 * Provider Version Detection & Archiving
 *
 * Detects installed versions for all provider categories (IDE, CLI, ACP, Extension).
 * Archives version history to ~/.adhdev/version-history.json for compatibility tracking.
 *
 * Usage:
 *   const archive = new VersionArchive();
 *   const results = await detectAllVersions(providerLoader, archive);
 */

interface ProviderVersionInfo {
    type: string;
    name: string;
    category: string;
    installed: boolean;
    version: string | null;
    path: string | null;
    binary: string | null;
    detectedAt: string;
    /**
     * Set when the detected version is NOT listed in provider.json testedVersions.
     * Means scripts may not work correctly with this version.
     */
    warning?: string;
}
interface VersionHistoryEntry {
    version: string;
    detectedAt: string;
    os: string;
}
interface VersionHistory {
    [providerType: string]: VersionHistoryEntry[];
}
declare class VersionArchive {
    private history;
    constructor();
    private load;
    /** Record a detected version (deduplicates same version) */
    record(type: string, version: string): void;
    /** Get version history for a provider */
    getHistory(type: string): VersionHistoryEntry[];
    /** Get latest known version for a provider */
    getLatest(type: string): string | null;
    /** Get full archive */
    getAll(): VersionHistory;
    private save;
}
/**
 * Detect versions for all loaded providers
 */
declare function detectAllVersions(loader: ProviderLoader, archive?: VersionArchive): Promise<ProviderVersionInfo[]>;

/**
 * ProviderLoader — Provider discovery + OS/version override resolution
 *
 * Role:
 * 1. Load providers from upstream auto-download (~/.adhdev/providers/.upstream/)
 * 2. Load user custom from ~/.adhdev/providers/ (overrides)
 * 3. Apply OS/version overrides (process.platform + detected IDE version)
 * 4. Hot-reload support (fs.watch)
 *
 * Design principles:
 * - Load JS files via require() (CJS compatible)
 * - User custom can override builtin
 * - provider.js files are independent, so load order doesn't matter
 */

declare class ProviderLoader {
    private providers;
    private userDir;
    private upstreamDir;
    private disableUpstream;
    private watchers;
    private logFn;
    private versionArchive;
    private scriptsCache;
    /** Inject VersionArchive so resolve() can auto-detect installed versions */
    setVersionArchive(archive: VersionArchive): void;
    private static readonly GITHUB_TARBALL_URL;
    private static readonly META_FILE;
    constructor(options?: {
        userDir?: string;
        logFn?: (msg: string) => void;
        /** Disable upstream auto-download (for dev/testing/OSS) */
        disableUpstream?: boolean;
    });
    private log;
    /**
     * User override root (~/.adhdev/providers by default).
     */
    getUserDir(): string;
    /**
    * Auto-updated upstream root (~/.adhdev/providers/.upstream by default).
    */
    getUpstreamDir(): string;
    /**
     * Provider search order for on-disk lookups.
     * Highest-priority editable overrides come first.
     */
    getProviderRoots(): string[];
    /**
    * Canonical provider directory shape for a given root.
    */
    getProviderDir(root: string, category: ProviderCategory, type: string): string;
    /**
    * Canonical user override directory for a provider.
    */
    getUserProviderDir(category: ProviderCategory, type: string): string;
    /**
    * Canonical upstream directory for a provider.
    */
    getUpstreamProviderDir(category: ProviderCategory, type: string): string;
    /**
     * Find the on-disk directory for a provider by type.
     * Search order: user override → upstream.
     */
    findProviderDir(type: string): string | null;
    /**
    * Resolve a file within a provider directory.
    */
    resolveProviderFile(type: string, ...segments: string[]): string | null;
    /**
    * Load all providers (3-tier priority)
    * 1. .upstream/ (GitHub auto-download — primary source)
    * 2. User custom (~/.adhdev/providers/ excluding .upstream)
    * User custom always wins (highest priority).
    * If .upstream/ is empty, call fetchLatest() before loadAll().
    */
    loadAll(): void;
    /**
     * Check if upstream directory exists and has providers.
     */
    hasUpstream(): boolean;
    /**
    * Get raw provider metadata by type (NO scripts loaded).
    * Use resolve() when you need scripts (readChat, listModels, etc).
    * @deprecated Use getMeta() for metadata or resolve() for scripts.
    */
    get(type: string): ProviderModule | undefined;
    /**
    * Get raw provider metadata by type (NO scripts loaded).
    * Safe for: category checks, icon, displayName, targetFilter, cdpPorts.
    * NOT safe for: script execution (readChat, listModels, sendMessage).
    * Use resolve() when scripts are needed.
    */
    getMeta(type: string): ProviderModule | undefined;
    /**
    * Resolve provider type by alias
    * 'claude' → 'claude-cli', 'codex' → 'codex-cli' etc
    * Returns input as-is if no match found.
    */
    resolveAlias(input: string): string;
    /**
    * Get provider with alias resolution (get + alias fallback)
    */
    getByAlias(input: string): ProviderModule | undefined;
    /**
    * Build CLI/ACP detection list (replaces cli-detector)
    * Dynamically generated from provider.js spawn.command.
    */
    getCliDetectionList(): {
        id: string;
        displayName: string;
        icon: string;
        command: string;
        category: string;
        versionCommand?: string;
    }[];
    /**
    * List providers by category
    */
    getByCategory(cat: ProviderCategory): ProviderModule[];
    /**
    * Extension Extension providers with extensionIdPattern only
    * (used by discoverAgentWebviews in daemon-cdp.ts)
    */
    getExtensionProviders(): ProviderModule[];
    /**
    * All loaded providers
    */
    getAll(): ProviderModule[];
    /**
    * Check if a provider is enabled (per-IDE)
    * Checks ideSettings[ideType].extensions[type].enabled.
    * Default false (disabled) — user must explicitly enable.
    * Always returns true when called without ideType.
    */
    isEnabled(type: string, ideType?: string): boolean;
    /**
    * Save IDE extension enabled setting
    */
    setIdeExtensionEnabled(ideType: string, extensionType: string, enabled: boolean): boolean;
    /**
    * Return only enabled providers by category (per-IDE)
    */
    getEnabledByCategory(cat: ProviderCategory, ideType?: string): ProviderModule[];
    /**
    * Extension Enabled extension providers with extensionIdPattern only (per-IDE)
    */
    getEnabledExtensionProviders(ideType?: string): ProviderModule[];
    /**
    * Return CDP port map for IDE providers
    * Used by launch.ts, adhdev-daemon.ts
    */
    getCdpPortMap(): Record<string, [number, number]>;
    /**
    * Return IDE process name map (macOS)
    */
    getMacAppIdentifiers(): Record<string, string>;
    /**
    * Return IDE process name map (Windows)
    */
    getWinProcessNames(): Record<string, string[]>;
    /**
    * Available IDE types (only those with cdpPorts)
    */
    getAvailableIdeTypes(): string[];
    /**
    * Register IDE providers to core/detector registry
    * → Enables detectIDEs() to detect provider.js-based IDEs
    */
    registerToDetector(): number;
    /**
    * Return final provider with OS/version overrides applied.
    *
    * Script resolution order:
    *   1. compatibility array (new format — preferred)
    *      Provider.json defines: "compatibility": [{ "ideVersion": ">=1.107.0", "scriptDir": "scripts/1.107" }]
    *      First matching range wins. Fallback: defaultScriptDir.
    *   2. versions field (legacy format — backward compat)
    *      "versions": { "< 1.107.0": { "__dir": "scripts/legacy" } }
    *   3. Root scripts.js (original format — no versioning)
    *
    * Version source: context.version → VersionArchive → undefined
    */
    resolve(type: string, context?: {
        os?: string;
        version?: string;
    }): ResolvedProvider | undefined;
    /**
     * Load scripts from a scriptDir within a provider directory.
     * Tries scripts.js first, then individual .js files.
     */
    private loadScriptsFromDir;
    /**
     * Hot-reload: start watching for file changes
     */
    watch(): void;
    /**
    * Stop hot-reload
    */
    stopWatch(): void;
    /**
    * Full reload
    */
    reload(): void;
    /**
    * Download latest providers tarball from GitHub → extract to .upstream/
    * - ETag-based change detection (skip if unchanged)
    * - Never touches user custom files in ~/.adhdev/providers/
    * - Runs in background; existing providers are kept on failure
    *
    * @returns Whether an update occurred
    */
    fetchLatest(): Promise<{
        updated: boolean;
        error?: string;
    }>;
    /** HTTP(S) file download (follows redirects) */
    private downloadFile;
    /** Recursive directory copy */
    private copyDirRecursive;
    /** .meta.json save */
    private writeMeta;
    /** Count provider files (provider.js or provider.json) */
    private countProviders;
    /**
    * Get public settings schema for a provider (for dashboard UI rendering)
    */
    getPublicSettings(type: string): ProviderSettingSchema[];
    /**
    * Get public settings schema for all providers
    */
    getAllPublicSettings(): Record<string, ProviderSettingSchema[]>;
    /**
    * Resolved setting value for a provider (default + user override)
    */
    getSettingValue(type: string, key: string): any;
    /**
    * All resolved settings for a provider (default + user override)
    */
    getSettings(type: string): Record<string, any>;
    /**
    * Save provider setting value (writes to config.json)
    */
    setSetting(type: string, key: string, value: any): boolean;
    /**
     * Find the on-disk directory for a provider by type.
     * Canonical shape: root/category/type.
     */
    private findProviderDirInternal;
    /**
     * Build a scripts function map from individual .js files in a directory.
     * Each file is wrapped as: (params?) => fs.readFileSync(filePath, 'utf-8')
     * (template substitution is NOT applied here — scripts.js handles that)
     */
    private buildScriptWrappersFromDir;
    /**
     * Recursively scan directory to load provider files
     * Supports two formats:
     *   1. provider.json (metadata) + scripts.js (optional CDP scripts)
     *   2. provider.js (legacy — everything in one file)
     * Structure: dir/category/agent-name/provider.{json,js}
     */
    private loadDir;
    /**
    * Simple semver range matching
    * Supported formats: '>=4.0.0', '<3.0.0', '>=2.1.0'
    */
    private matchesVersion;
    private compareVersions;
}

/**
 * CLI AI Agent Detector
 *
 * Dynamic CLI detection based on Provider.
 * Reads spawn.command from cli/acp categories via ProviderLoader to check installation.
 *
 * Uses parallel execution for fast detection across many providers.
 */

interface CLIInfo {
    id: string;
    displayName: string;
    icon: string;
    command: string;
    versionCommand?: string;
    installed: boolean;
    version?: string;
    path?: string;
    category?: string;
}
/**
 * Detect all CLI/ACP agents (parallel)
 * @param providerLoader ProviderLoader instance (dynamic list creation)
 */
declare function detectCLIs(providerLoader?: ProviderLoader): Promise<CLIInfo[]>;

/**
 * Host memory metrics — macOS-aware "available" memory.
 *
 * Node's os.freemem() on darwin reports only the tiny truly-free pool; most RAM
 * sits in inactive/file-backed cache that the OS can reclaim. Dashboard "used %"
 * based on (total - freemem) looks ~99% almost always — misleading.
 *
 * On macOS we parse `vm_stat` and approximate available bytes as:
 *   (free + inactive + speculative + purgeable [+ file_backed]) × page size
 * (aligned with common Activity Monitor–style interpretations.)
 */
interface HostMemorySnapshot {
    totalMem: number;
    /** Raw kernel "free" — small on macOS; kept for debugging / API compat */
    freeMem: number;
    /** Use this for UI "used %" — on darwin from vm_stat; else equals freeMem */
    availableMem: number;
}
declare function getHostMemorySnapshot(): HostMemorySnapshot;

/**
 * CDP Manager for ADHDev Daemon
 *
 * Ported cdp.ts from Extension for Daemon use.
 * vscode dependencies removed — works in pure Node.js environment.
 *
 * Connects to IDE CDP port (9222, 9333 etc) to:
 * - Execute JS via Runtime.evaluate
 * - Agent webview iframe search & session connection
 * - DOM query
 */

interface CdpTarget {
    id: string;
    type: string;
    title: string;
    url: string;
    webSocketDebuggerUrl: string;
}
interface AgentWebviewTarget {
    targetId: string;
    extensionId: string;
    agentType: string;
    url: string;
}
declare class DaemonCdpManager {
    private ws;
    private browserWs;
    private browserMsgId;
    private browserPending;
    private msgId;
    private pending;
    private port;
    private _connected;
    private _browserConnected;
    private targetUrl;
    private reconnectTimer;
    private contexts;
    private connectPromise;
    private failureCount;
    private readonly MAX_FAILURES;
    private agentSessions;
    private logFn;
    private extensionProviders;
    private _lastDiscoverSig;
    private _targetId;
    private _pageTitle;
    private _targetFilter;
    private _lastDiscoveredTargets?;
    constructor(port?: number, logFn?: (msg: string) => void, targetId?: string, targetFilter?: CdpTargetFilter);
    /** Set target filter (can be updated after construction) */
    setTargetFilter(filter: CdpTargetFilter): void;
    /**
     * Check if a page title should be excluded (non-main page).
     * Uses provider-configured titleExcludes, falls back to default pattern.
     */
    private isNonMainTitle;
    /**
     * Check if a page URL matches the main window criteria.
     * Uses provider-configured urlIncludes/urlExcludes.
     */
    private isMainPageUrl;
    /** Connected page title (includes workspace name) */
    get pageTitle(): string;
    /** Connected target ID */
    get targetId(): string | null;
    /**
    * Query all workbench pages on port (static)
    * Returns multiple entries if multiple IDE windows are open on same port
    */
    static listAllTargets(port: number): Promise<CdpTarget[]>;
    setPort(port: number): void;
    getPort(): number;
    private log;
    connect(): Promise<boolean>;
    private doConnect;
    private findTargetOnPort;
    private findTarget;
    setExtensionProviders(providers: {
        agentType: string;
        extensionId: string;
        extensionIdPattern: RegExp;
    }[]): void;
    private connectToTarget;
    /** Browser-level CDP connection — needed for Target discovery */
    private connectBrowserWs;
    private getBrowserWsUrl;
    private sendBrowser;
    private scheduleReconnect;
    disconnect(): void;
    get isConnected(): boolean;
    private sendInternal;
    send(method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<any>;
    sendCdpCommand(method: string, params?: Record<string, unknown>): Promise<any>;
    evaluate(expression: string, timeoutMs?: number): Promise<unknown>;
    querySelector(selector: string): Promise<string | null>;
    /**
    * Input text via CDP protocol then send Enter
    * Used for editors where execCommand does not work (e.g. Lexical).
    *
    * 1. Find editor by selector, focus + click
    * 2. Insert text via Input.insertText
    * 3. Send Enter via Input.dispatchKeyEvent
    */
    typeAndSend(selector: string, text: string): Promise<boolean>;
    /**
    * Coordinate-based typeAndSend — for input fields inside webview iframe
    * Receives coordinates directly instead of selector for click+input+Enter
    */
    typeAndSendAt(x: number, y: number, text: string): Promise<boolean>;
    /**
    * Evaluate JS from inside Webview iframe
    * Kiro, PearAI etc Used for IDEs where chat UI is inside webview iframe.
    *
    * 1. Query Target.getTargets via browser WS → find vscode-webview iframes
    * 2. Target.attachToTarget → session acquire
    * 3. Page.getFrameTree → nested iframe find
    * 4. Page.createIsolatedWorld → contextId acquire
    * 5. Runtime.evaluate → result return
    *
    * @param expression JS expression to execute
    * @param matchFn webview iframe URL match function (optional, all webview attempt)
    * @returns evaluate result or null
    */
    evaluateInWebviewFrame(expression: string, matchFn?: (bodyPreview: string) => boolean): Promise<string | null>;
    discoverAgentWebviews(): Promise<AgentWebviewTarget[]>;
    attachToAgent(target: AgentWebviewTarget): Promise<string | null>;
    evaluateInSession(sessionId: string, expression: string, timeoutMs?: number): Promise<unknown>;
    /**
     * Evaluate inside the child frame of an attached session.
     * Extension webviews have a nested iframe structure:
     *   outer (vscode-webview://) → inner (extension React app)
     * This method navigates into the inner frame using CDP Page.getFrameTree.
     * Falls back to evaluateInSession if no child frame is found.
     */
    evaluateInSessionFrame(sessionId: string, expression: string, timeoutMs?: number): Promise<unknown>;
    detachAgent(sessionId: string): Promise<void>;
    detachAllAgents(): Promise<void>;
    getAgentSessions(): Map<string, AgentWebviewTarget>;
    private getCurrentPageWebviewUrls;
    captureScreenshot(opts?: {
        quality?: number;
    }): Promise<Buffer | null>;
}

/**
 * ProviderInstanceManager — lifecycle management for all ProviderInstances
 *
 * Role:
 * 1. Instance create/delete
 * 2. Tick engine (periodic onTick calls)
 * 3. Collect overall state
 * 4. Event collection and propagation
 */

declare class ProviderInstanceManager {
    private instances;
    private tickTimer;
    private tickInterval;
    private eventListeners;
    /**
    * Instance add and initialize
    */
    addInstance(id: string, instance: ProviderInstance, context: InstanceContext): Promise<void>;
    /**
    * Instance remove
    */
    removeInstance(id: string): void;
    removeByCategory(category: 'cli' | 'ide' | 'extension' | 'acp', options?: {
        dispose?: boolean;
    }): number;
    /**
    * Import by Instance ID
    */
    getInstance(id: string): ProviderInstance | undefined;
    /**
    * Per-category Instance list
    */
    getByCategory(category: 'cli' | 'ide' | 'extension' | 'acp'): ProviderInstance[];
    /**
    * All Instance count
    */
    get size(): number;
    /**
    * all Instance's current status collect
    * + Propagate pending events to event listeners
    */
    collectAllStates(): ProviderState[];
    /**
    * Per-category status collect
    */
    collectStatesByCategory(category: 'cli' | 'ide' | 'extension' | 'acp'): ProviderState[];
    /**
    * Start tick — periodically call all Instance.onTick() call
    */
    startTicking(intervalMs?: number): void;
    /**
    * Stop tick
    */
    stopTicking(): void;
    /**
    * Register event listener (used for daemon status_event transmission)
    */
    onEvent(listener: (event: ProviderEvent & {
        providerType: string;
    }) => void): void;
    private emitPendingEvents;
    /**
    * Forward event to specific Instance
    */
    sendEvent(id: string, event: string, data?: any): void;
    /**
    * Broadcast event to all Instances
    */
    broadcast(event: string, data?: any): void;
    /**
     * Update settings for all instances of a given provider type.
     * Called when user changes settings from dashboard.
     */
    updateInstanceSettings(providerType: string, settings: Record<string, any>): number;
    /**
    * All terminate
    */
    disposeAll(): void;
}

interface SessionRuntimeTarget {
    sessionId: string;
    parentSessionId: string | null;
    providerType: string;
    providerCategory: 'ide' | 'extension' | 'cli' | 'acp';
    transport: SessionTransport;
    cdpManagerKey?: string;
    adapterKey?: string;
    instanceKey?: string;
}
declare class SessionRegistry {
    private readonly bySessionId;
    private readonly byManagerKey;
    private readonly byInstanceKey;
    private readonly byParentSessionId;
    register(target: SessionRuntimeTarget): void;
    get(sessionId: string | undefined | null): SessionRuntimeTarget | undefined;
    unregister(sessionId: string | undefined | null): void;
    unregisterByManagerKey(managerKey: string): void;
    unregisterByInstanceKey(instanceKey: string): void;
    listChildren(parentSessionId: string): SessionRuntimeTarget[];
    private addIndex;
    private removeIndex;
}

/**
 * Agent Stream Types — ported for Daemon (identical to original)
 *
 * Agent stream types.
 * No vscode dependency — can be used as-is.
 */
/** Agent chat message */
interface AgentChatMessage {
    role: 'user' | 'assistant' | 'system';
    content: string;
    timestamp?: number;
}
/** Agent chat history item */
interface AgentChatListItem {
    title: string;
    id: string;
    status?: string;
    time?: string;
    cost?: string;
}
/** Agent stream status */
interface AgentStreamState {
    agentType: string;
    agentName: string;
    extensionId: string;
    status: 'idle' | 'streaming' | 'waiting_approval' | 'error' | 'disconnected' | 'panel_hidden' | 'not_monitored';
    messages: AgentChatMessage[];
    inputContent: string;
    model?: string;
    mode?: string;
    activeModal?: {
        message: string;
        buttons: string[];
    };
}
/** Agent stream adapter interface */
interface IAgentStreamAdapter {
    readonly agentType: string;
    readonly agentName: string;
    readonly extensionId: string;
    readonly extensionIdPattern: RegExp;
    readChat(evaluate: AgentEvaluateFn): Promise<AgentStreamState>;
    sendMessage(evaluate: AgentEvaluateFn, text: string): Promise<void>;
    resolveAction(evaluate: AgentEvaluateFn, action: string, button?: string): Promise<boolean>;
    newSession(evaluate: AgentEvaluateFn): Promise<void>;
    listChats?(evaluate: AgentEvaluateFn): Promise<AgentChatListItem[]>;
    switchSession?(evaluate: AgentEvaluateFn, sessionId: string): Promise<boolean>;
    focusEditor?(evaluate: AgentEvaluateFn): Promise<void>;
    setProvider?(provider: any): void;
}
type AgentEvaluateFn = (expression: string, timeoutMs?: number) => Promise<unknown>;

/**
 * DaemonAgentStreamManager — manage agent streams (ported for Daemon)
 *
 * Agent stream manager for extension data collection.
 * All vscode dependencies removed — pure Node.js environment.
 *
 * Panel focus is delegated to Extension via IPC.
 * CDP session management uses DaemonCdpManager directly.
 */

interface ManagedAgent {
    adapter: IAgentStreamAdapter;
    runtimeSessionId: string;
    parentSessionId: string;
    cdpSessionId: string;
    target: AgentWebviewTarget;
    lastState: AgentStreamState | null;
    lastError: string | null;
    lastHiddenCheckTime: number;
}
declare class DaemonAgentStreamManager {
    private readonly sessionRegistry?;
    private adaptersByType;
    private managedBySessionId;
    private enabled;
    private logFn;
    private lastDiscoveryTimeByParent;
    private discoveryIntervalMsByParent;
    private activeSessionIdByParent;
    constructor(logFn?: (msg: string) => void, providerLoader?: ProviderLoader, sessionRegistry?: SessionRegistry | undefined);
    setEnabled(enabled: boolean): void;
    get isEnabled(): boolean;
    getActiveSessionId(parentSessionId: string): string | null;
    private getSessionTarget;
    resetParentSession(parentSessionId: string): void;
    /** Panel focus based on provider.js focusPanel or extensionId (currently no-op) */
    ensureSessionPanelOpen(_sessionId: string): Promise<void>;
    setActiveSession(cdp: DaemonCdpManager, parentSessionId: string, sessionId: string | null): Promise<void>;
    private resolveSessionIdForTarget;
    private connectManagedSession;
    /** Agent webview discovery + session connection */
    syncActiveSession(cdp: DaemonCdpManager, parentSessionId: string): Promise<void>;
    /** Collect active extension session state */
    collectActiveSession(cdp: DaemonCdpManager, parentSessionId: string): Promise<AgentStreamState | null>;
    sendToSession(cdp: DaemonCdpManager, sessionId: string, text: string): Promise<boolean>;
    resolveSessionAction(cdp: DaemonCdpManager, sessionId: string, action: 'approve' | 'reject'): Promise<boolean>;
    newSession(cdp: DaemonCdpManager, sessionId: string): Promise<boolean>;
    listSessionChats(cdp: DaemonCdpManager, sessionId: string): Promise<AgentChatListItem[]>;
    switchConversation(cdp: DaemonCdpManager, sessionId: string, conversationId: string): Promise<boolean>;
    focusSession(cdp: DaemonCdpManager, sessionId: string): Promise<boolean>;
    getConnectedSessions(parentSessionId?: string): string[];
    getManagedSession(sessionId: string): ManagedAgent | undefined;
    dispose(cdpManagers: Map<string, DaemonCdpManager>): Promise<void>;
    resolveSessionForAgent(parentSessionId: string, agentType: string): string | null;
}

/**
 * AgentStreamPoller — Periodic agent stream polling + extension dynamic management
 *
 * Handles periodic agent stream polling and extension dynamic management.
 *
 * Responsibilities:
 *   1. Refresh extension providers in CDP managers (config changes take effect immediately)
 *   2. Dynamically add/remove IDE instance extensions based on enabled state
 *   3. Sync agent sessions + collect agent streams
 *   4. Auto-discover agents in connected IDEs
 */

interface AgentStreamPollerDeps {
    agentStreamManager: DaemonAgentStreamManager;
    providerLoader: ProviderLoader;
    instanceManager: ProviderInstanceManager;
    cdpManagers: Map<string, DaemonCdpManager>;
    sessionRegistry: SessionRegistry;
    /** Callback when agent streams are updated */
    onStreamsUpdated?: (ideType: string, streams: AgentStreamState[]) => void;
}
declare class AgentStreamPoller {
    private deps;
    private timer;
    constructor(deps: AgentStreamPollerDeps);
    /** Currently active IDE type for agent streaming */
    get activeIde(): string | null;
    /** Reset active IDE tracking (e.g., when IDE is stopped) */
    resetActiveIde(parentSessionId: string): void;
    /** Start polling (idempotent — ignored if already started) */
    start(intervalMs?: number): void;
    /** Stop polling */
    stop(): void;
    /** Single poll tick — can also be called manually */
    private tick;
}

/**
 * Chat History Persistence — Persist completed chat messages to local disk
 *
 * Design:
 * - ~/.adhdev/history/{agentType}/YYYY-MM-DD.jsonl
 * - JSONL format (one line = one message, append-friendly)
 * - Track only new messages (hash comparison with previous)
 * - Auto-rotation (delete files older than 30 days)
 * - Async/non-blocking (no impact on chat collection)
 */
interface HistoryMessage {
    ts: string;
    receivedAt: number;
    role: 'user' | 'assistant' | 'system';
    content: string;
    agent: string;
    instanceId?: string;
    sessionTitle?: string;
}
declare class ChatHistoryWriter {
    /** Last seen message count per agent (deduplication) */
    private lastSeenCounts;
    /** Last seen message hash per agent (deduplication) */
    private lastSeenHashes;
    /** Last seen append-only terminal transcript per agent */
    private lastSeenTerminal;
    private rotated;
    /**
    * Append new messages to history
    *
    * @param agentType agent type (e.g. 'antigravity', 'cursor')
    * @param messages Message array received from readChat
    * @param sessionTitle Current session title
    * @param instanceId IDE instance UUID (distinguishes windows of the same agent)
    */
    appendNewMessages(agentType: string, messages: Array<{
        role: string;
        content: string;
        receivedAt?: number;
    }>, sessionTitle?: string, instanceId?: string): void;
    appendTerminalHistory(agentType: string, terminalHistory: string, sessionTitle?: string, instanceId?: string): void;
    /** Called when agent session is explicitly changed */
    onSessionChange(agentType: string): void;
    /** Delete history files older than 30 days */
    private rotateOldFiles;
    /** Allow only filename-safe characters */
    private sanitize;
}
/**
 * Read history (static — called from P2P commands)
 *
 * Read JSONL files in reverse order, returning most recent messages first.
 * When instanceId is specified, reads only that instance file.
 * Offset/limit-based paging.
 */
declare function readChatHistory(agentType: string, offset?: number, limit?: number, instanceId?: string): {
    messages: HistoryMessage[];
    hasMore: boolean;
};

/**
 * DaemonCommandHandler — unified command routing for CDP & CLI
 *
 * Routes incoming commands (from server WS, P2P, or local WS) to
 * the correct CDP manager or CLI adapter.
 *
 * Key concepts:
 *   - extractIdeType(): determines target IDE from targetSessionId or ideType
 *   - getCdp(): returns the DaemonCdpManager for current command
 *   - getProvider(): returns the ProviderModule for current command
 *   - handle(): main entry point, sets context then dispatches
 */

interface CommandResult$1 {
    success: boolean;
    [key: string]: unknown;
}
interface CommandContext {
    cdpManagers: Map<string, DaemonCdpManager>;
    ideType: string;
    adapters: Map<string, any>;
    providerLoader?: ProviderLoader;
    /** ProviderInstanceManager — for runtime settings propagation */
    instanceManager?: ProviderInstanceManager;
    sessionRegistry?: SessionRegistry;
}
/**
 * Shared helpers interface — passed to sub-module command functions
 * for accessing CDP, providers, agent streams, and other handler-owned state.
 */
interface CommandHelpers {
    getCdp(ideType?: string): DaemonCdpManager | null;
    getProvider(overrideType?: string): ProviderModule | undefined;
    getProviderScript(scriptName: string, params?: Record<string, string>, ideType?: string): string | null;
    evaluateProviderScript(scriptName: string, params?: Record<string, string>, timeout?: number): Promise<{
        result: any;
        category: string;
    } | null>;
    getCliAdapter(type?: string): any | null;
    readonly currentManagerKey: string | undefined;
    readonly currentIdeType: string | undefined;
    readonly currentProviderType: string | undefined;
    readonly currentSession: SessionRuntimeTarget | undefined;
    readonly agentStream: DaemonAgentStreamManager | null;
    readonly ctx: CommandContext;
    readonly historyWriter: ChatHistoryWriter;
}
declare class DaemonCommandHandler implements CommandHelpers {
    private _ctx;
    private _agentStream;
    private domHandlers;
    private _historyWriter;
    /** Current request route context */
    private _currentRoute;
    constructor(ctx: CommandContext);
    get ctx(): CommandContext;
    get agentStream(): DaemonAgentStreamManager | null;
    get historyWriter(): ChatHistoryWriter;
    get currentManagerKey(): string | undefined;
    get currentIdeType(): string | undefined;
    get currentProviderType(): string | undefined;
    get currentSession(): SessionRuntimeTarget | undefined;
    /** Get CDP manager for a specific session or manager key. */
    getCdp(ideType?: string): DaemonCdpManager | null;
    /**
     * Get provider module — _currentProviderType (agentType priority) use.
     */
    getProvider(overrideType?: string): ProviderModule | undefined;
    /** Get a provider script by name from ProviderLoader. */
    getProviderScript(scriptName: string, params?: Record<string, string>, ideType?: string): string | null;
    /**
     * per-category CDP script execute:
     * IDE → cdp.evaluate(script) (main window)
     * Extension → cdp.evaluateInSession(sessionId, script) (webview)
     */
    evaluateProviderScript(scriptName: string, params?: Record<string, string>, timeout?: number): Promise<{
        result: any;
        category: string;
    } | null>;
    /** CLI adapter search */
    getCliAdapter(type?: string): any | null;
    private inferProviderType;
    private resolveRoute;
    /** Extract CDP scope key from target session or explicit ideType */
    private extractIdeType;
    private logCommandStart;
    private logCommandEnd;
    setAgentStreamManager(manager: DaemonAgentStreamManager): void;
    handle(cmd: string, args: any): Promise<CommandResult$1>;
    private dispatch;
    private handleGetRecentWorkspaces;
    private handleRefreshScripts;
    private proxyDevServerPost;
    private proxyDevServerGet;
    private proxyDevServerScaffold;
}

/**
 * CDP DOM Analysis Tools — DOM dump, query, debug
 *
 * Separated from daemon-commands.ts.
 * Tools for analyzing DOM structure when developing new IDE scripts.
 */

type CdpGetter = (ideType?: string) => DaemonCdpManager | null;
/**
 * CDP DOM analysis handler
 *
 * Uses getCdp from DaemonCommandHandler.
 */
declare class CdpDomHandlers {
    private getCdp;
    constructor(getCdp: CdpGetter);
    /**
    * CDP DOM Dump — IDE's DOM tree retrieve
    *
    * args:
    * selector?: string — CSS selector to dump specific area only (default: All)
    * depth?: number — Dump depth limit (default: 10)
    * attrs?: boolean — Whether to include properties (default: true)
    * maxLength?: number — Max character count (default: 200000)
    * format?: 'html' | 'tree' | 'summary' — Output format (default: 'html')
    * sessionId?: string — Agent webview session ID (if provided, match webview DOM)
    */
    handleDomDump(args: any): Promise<CommandResult$1>;
    /**
    * CDP DOM Query — CSS Test selector
    * Check how many elements match selector and what elements they are
    *
    * args:
    * selector: string — CSS selector
    * limit?: number — Max element count to return (default: 20)
    * content?: boolean — Whether to include text content (default: true)
    * sessionId?: string — agent webview session ID
    */
    handleDomQuery(args: any): Promise<CommandResult$1>;
    /**
    * CDP DOM Debug — IDE AI panel specialized analysis
    * Collect all essential info at once when supporting new IDE
    *
    * args:
    * ideType?: string — IDE type hint
    * sessionId?: string — agent webview session ID
    */
    handleDomDebug(args: any): Promise<CommandResult$1>;
}

/**
 * ExtensionProviderInstance — Runtime instance for Extension Provider
 *
 * Manages IDE extensions (Cline, Roo Code, etc).
 * CDP webview discovery + agent stream collection moved here.
 */

declare class ExtensionProviderInstance implements ProviderInstance {
    readonly type: string;
    readonly category: "extension";
    private provider;
    private context;
    private settings;
    private events;
    private currentStatus;
    private agentStreams;
    private messages;
    private activeModal;
    private currentModel;
    private currentMode;
    private lastAgentStatus;
    private generatingStartedAt;
    private monitor;
    private instanceId;
    private ideType;
    private chatId;
    private chatTitle;
    private agentName;
    private extensionId;
    constructor(provider: ProviderModule);
    init(context: InstanceContext): Promise<void>;
    onTick(): Promise<void>;
    getState(): ProviderState;
    onEvent(event: string, data?: any): void;
    dispose(): void;
    /** Query UUID instanceId */
    getInstanceId(): string;
    private detectTransition;
    private pushEvent;
    private flushEvents;
    private resolveChatTitle;
}

/**
 * IdeProviderInstance — Runtime instance for IDE Provider
 *
 * Within a single IDE:
 * 1. Native chat (readChat via CDP)
 * 2. Extension agents (Cline, Roo Code etc)
 *
 * IDE Instance manages child Extension Instances.
 * Daemon collects all via a single IDE Instance.getState() call.
 */

declare class IdeProviderInstance implements ProviderInstance {
    readonly type: string;
    readonly category: "ide";
    private provider;
    private context;
    private settings;
    private events;
    private tickErrorCount;
    private cachedChat;
    private currentStatus;
    private lastAgentStatuses;
    private generatingStartedAt;
    private tickBusy;
    private monitor;
    private historyWriter;
    private autoApproveBusy;
    private ideVersion;
    private instanceId;
    private workspace;
    private extensions;
    constructor(provider: ProviderModule, instanceKey?: string);
    init(context: InstanceContext): Promise<void>;
    onTick(): Promise<void>;
    getState(): ProviderState;
    onEvent(event: string, data?: any): void;
    dispose(): void;
    /** Extension Instance add */
    addExtension(provider: ProviderModule, settings?: Record<string, any>): Promise<void>;
    /** Extension Instance remove */
    removeExtension(type: string): void;
    /** Extension Instance Import */
    getExtension(type: string): ExtensionProviderInstance | undefined;
    /** Child Extension list */
    getExtensionTypes(): string[];
    /** Query UUID instanceId */
    getInstanceId(): string;
    /** all Extension Instance list */
    getExtensionInstances(): ExtensionProviderInstance[];
    /** Set workspace from daemon launch context */
    setWorkspace(workspace: string): void;
    private readChat;
    private getReadChatScript;
    private detectAgentTransitions;
    private pushEvent;
    private flushEvents;
    updateCdp(cdp: InstanceContext['cdp']): void;
    private autoApproveViaScript;
}

/**
 * DaemonCdpSetup — Shared CDP initialization helpers
 *
 * Common CDP setup logic for consistent
 * CDP → ProviderInstance registration.
 */

interface CdpSetupContext {
    providerLoader: ProviderLoader;
    instanceManager: ProviderInstanceManager;
    cdpManagers: Map<string, DaemonCdpManager>;
    sessionRegistry: SessionRegistry;
    /** Server connection (optional) */
    serverConn?: any;
}
interface SetupIdeInstanceOptions {
    /** Provider-based IDE type (e.g., 'antigravity', 'cursor') */
    ideType: string;
    /** Connected CDP manager */
    manager: DaemonCdpManager;
    /** CDP manager key (for multi-window: 'antigravity_remote_vs', single: 'antigravity') */
    managerKey?: string;
    /** Provider settings override */
    settings?: Record<string, any>;
}
/**
 * Register extension providers on a CDP manager.
 * Common pattern used during CDP init and periodic scans.
 */
declare function registerExtensionProviders(providerLoader: ProviderLoader, manager: DaemonCdpManager, ideType: string): void;
/**
 * Setup a CDP-connected IDE as a ProviderInstance.
 *
 * Performs:
 * 1. providerLoader.resolve() to get scripts
 * 2. Create IdeProviderInstance
 * 3. Register in InstanceManager
 * 4. Register enabled extensions
 * 5. Register runtime sessions (workspace + extension children)
 *
 * @returns The created IdeProviderInstance, or null if provider not found
 */
declare function setupIdeInstance(ctx: CdpSetupContext, opts: SetupIdeInstanceOptions): Promise<IdeProviderInstance | null>;
/**
 * Create and connect a DaemonCdpManager for a given port.
 *
 * @returns Connected manager or null if connection failed
 */
declare function connectCdpManager(port: number, ideType: string, logFn: (msg: string) => void, providerLoader: ProviderLoader, targetId?: string): Promise<DaemonCdpManager | null>;
/**
 * Probe a CDP port to check if it's listening.
 * @returns true if CDP is available on this port
 */
declare function probeCdpPort(port: number, timeoutMs?: number): Promise<boolean>;

/**
 * DaemonCdpScanner — Periodic CDP port scanning & auto-connect
 *
 * Periodic CDP port scanning and auto-connect for IDE discovery.
 * Provides a unified approach to:
 * 1. Initial CDP port discovery
 * 2. Periodic scanning for newly launched IDEs
 * 3. Multi-window support (multiple pages on same port)
 */

interface CdpScannerOptions {
    /** Context for setup operations */
    ctx: CdpSetupContext;
    /** Log function for per-IDE CDP logs */
    logFn?: (ideType: string) => (msg: string) => void;
    /** Whether to support multi-window (multiple pages per port) */
    multiWindow?: boolean;
    /** Scan interval in ms (default: 30000) */
    scanIntervalMs?: number;
    /** Callback when a new CDP connection is established */
    onConnected?: (ideType: string, managerKey: string, manager: DaemonCdpManager) => void;
}
declare class DaemonCdpScanner {
    private ctx;
    private opts;
    private scanTimer;
    private discoveryTimer;
    constructor(opts: CdpScannerOptions);
    /**
     * Initial CDP discovery — connect to all available IDEs.
     * Supports both single-window and multi-window modes.
     */
    initialScan(enabledIdes?: string[]): Promise<void>;
    /**
     * Start periodic scanning for newly launched IDEs.
     */
    startPeriodicScan(): void;
    /**
     * Start periodic agent webview discovery on all connected CDPs.
     */
    startWebviewDiscovery(intervalMs?: number): void;
    /**
     * Stop all timers.
     */
    stop(): void;
    private getLogFn;
    /**
     * Single-window connection (standalone mode).
     * One CDP manager per IDE, first working port wins.
     */
    private connectSingleWindow;
    /**
     * Multi-window connection.
     * Multiple CDP managers per IDE — one per workbench page.
     */
    private connectMultiWindow;
}

/**
 * DaemonCdpInitializer — Unified CDP initialization + periodic scanning
 *
 * Unified CDP initialization + periodic scanning.
 *
 * Features:
 *   1. Initial connection: connectAll() — multi-window aware
 *   2. Periodic scan: startPeriodicScan() — auto-detect newly opened IDEs
 *   3. Discovery: startDiscovery() — periodic agent webview discovery
 */

interface CdpInitializerConfig {
    providerLoader: ProviderLoader;
    cdpManagers: Map<string, DaemonCdpManager>;
    /** Filter: only connect these IDEs (empty/undefined = all) */
    enabledIdes?: string[];
    /** Callback when a new CDP manager is connected */
    onConnected?: (ideType: string, manager: DaemonCdpManager, managerKey: string) => void | Promise<void>;
    /** Callback when a stale/disconnected CDP manager is removed */
    onDisconnected?: (ideType: string, manager: DaemonCdpManager, managerKey: string, reason: 'ide_closed' | 'target_closed' | 'target_rekeyed') => void | Promise<void>;
}
declare class DaemonCdpInitializer {
    private config;
    private scanTimer;
    private discoveryTimer;
    constructor(config: CdpInitializerConfig);
    /**
     * Connect to all detected IDEs.
     * Multi-window aware: creates separate CdpManager per workbench page.
     */
    connectAll(detectedIdes: any[]): Promise<void>;
    /**
     * Connect to a single IDE port.
     * Tries multi-window first (listAllTargets), falls back to direct connect.
     */
    private connectIdePort;
    private pruneStaleManagers;
    /**
     * Start periodic scanning for newly opened IDEs.
     * Idempotent — ignored if already started.
     */
    startPeriodicScan(intervalMs?: number): void;
    /**
     * Start periodic agent webview discovery.
     */
    startDiscovery(intervalMs?: number): void;
    /** Stop all timers */
    stop(): void;
}

/**
 * CliAdapter — common interface for CLI agents
 *
 * Contract implemented by all CLI adapters (ProviderCliAdapter etc).
 */
interface CliAdapter {
    cliType: string;
    cliName: string;
    workingDir: string;
    spawn(): Promise<void>;
    sendMessage(text: string): Promise<void>;
    getStatus(): any;
    getPartialResponse(): string;
    saveAndStop?(): Promise<void>;
    shutdown(): void;
    detach?(): void;
    cancel(): void;
    isProcessing(): boolean;
    isReady(): boolean;
    setOnStatusChange(callback: () => void): void;
    setServerConn?(serverConn: any): void;
    setOnPtyData?(callback: (data: string) => void): void;
    writeRaw?(data: string): void;
    resize?(cols: number, rows: number): void;
}

interface PtySpawnOptions {
    cwd: string;
    env: Record<string, string>;
    cols: number;
    rows: number;
}
interface PtyRuntimeWriteOwner {
    clientId: string;
    ownerType: 'agent' | 'user';
}
interface PtyRuntimeClientInfo {
    clientId: string;
    type: 'daemon' | 'web' | 'local-terminal';
    readOnly: boolean;
}
interface PtyRuntimeMetadata {
    runtimeId: string;
    runtimeKey?: string;
    displayName?: string;
    workspaceLabel?: string;
    writeOwner?: PtyRuntimeWriteOwner | null;
    attachedClients?: PtyRuntimeClientInfo[];
}
interface PtyRuntimeTransport {
    readonly pid: number;
    readonly ready: Promise<void>;
    write(data: string): void;
    resize(cols: number, rows: number): void;
    kill(): void;
    clearBuffer?(): void;
    detach?(): void;
    getMetadata?(): PtyRuntimeMetadata | null;
    onData(callback: (data: string) => void): void;
    onExit(callback: (info: {
        exitCode: number;
    }) => void): void;
}
interface PtyTransportFactory {
    spawn(command: string, args: string[], options: PtySpawnOptions): PtyRuntimeTransport;
}
declare class NodePtyTransportFactory implements PtyTransportFactory {
    spawn(command: string, args: string[], options: PtySpawnOptions): PtyRuntimeTransport;
}

/**
 * DaemonCliManager — CLI session creation, management, and command handling
 *
 * Separated from adhdev-daemon.ts.
 * CLI cases of createAdapter, startCliSession, stopCliSession, executeDaemonCommand extracted to independent module extract.
 */

interface CliManagerDeps {
    /** Server connection — injected into adapter */
    getServerConn(): any | null;
    /** P2P — PTY output transmit */
    getP2p(): {
        broadcastPtyOutput(key: string, data: string): void;
    } | null;
    /** StatusReporter callback */
    onStatusChange(): void;
    removeAgentTracking(key: string): void;
    /** InstanceManager — register in CLI unified status */
    getInstanceManager(): ProviderInstanceManager | null;
    getSessionRegistry?(): SessionRegistry | null;
    createPtyTransportFactory?: (params: CliTransportFactoryParams) => PtyTransportFactory | null;
    listHostedCliRuntimes?: () => Promise<HostedCliRuntimeDescriptor[]>;
}
type CommandResult = {
    success: boolean;
    [key: string]: unknown;
};
interface CliTransportFactoryParams {
    runtimeId: string;
    providerType: string;
    workspace: string;
    cliArgs?: string[];
    attachExisting?: boolean;
}
interface HostedCliRuntimeDescriptor {
    runtimeId: string;
    runtimeKey?: string;
    displayName?: string;
    workspaceLabel?: string;
    lifecycle?: 'starting' | 'running' | 'stopping' | 'stopped' | 'failed' | 'interrupted';
    recoveryState?: string | null;
    cliType: string;
    workspace: string;
    cliArgs?: string[];
}
declare class DaemonCliManager {
    readonly adapters: Map<string, CliAdapter>;
    private deps;
    private providerLoader;
    constructor(deps: CliManagerDeps, providerLoader: ProviderLoader);
    getCliKey(cliType: string, dir: string): string;
    private persistRecentDir;
    private getTransportFactory;
    private createAdapter;
    private startCliExitMonitor;
    private registerCliInstance;
    startSession(cliType: string, workingDir: string, cliArgs?: string[], initialModel?: string): Promise<void>;
    stopSession(key: string): Promise<void>;
    stopSessionWithMode(key: string, mode: 'hard' | 'save'): Promise<void>;
    shutdownAll(): void;
    detachAll(): void;
    restoreHostedSessions(records?: HostedCliRuntimeDescriptor[]): Promise<number>;
    /**
    * Search for CLI adapter. Priority order:
    * 0. sessionId (UUID direct match)
    * 1. agentType + dir (iteration match)
    * 2. agentType fuzzy match (⚠ returns first match when multiple sessions exist)
    */
    findAdapter(agentType: string, opts?: {
        dir?: string;
        instanceKey?: string;
    }): {
        adapter: CliAdapter;
        key: string;
    } | null;
    handleCliCommand(cmd: string, args: any): Promise<CommandResult | null>;
}

/**
 * DaemonCommandRouter — Unified command routing for daemon-level commands
 *
 * Unified command routing for daemon-level commands.
 *
 * Routing flow:
 *   1. Daemon-level commands (launch_ide, stop_ide, restart_ide, etc.) → handled here
 *   2. CLI/ACP commands → delegated to cliManager
 *   3. Everything else → delegated to commandHandler.handle()
 */

interface CommandRouterDeps {
    commandHandler: DaemonCommandHandler;
    cliManager: DaemonCliManager;
    cdpManagers: Map<string, DaemonCdpManager>;
    providerLoader: ProviderLoader;
    instanceManager: ProviderInstanceManager;
    /** Reference to detected IDEs array (mutable — router updates it) */
    detectedIdes: {
        value: any[];
    };
    sessionRegistry: SessionRegistry;
    /** Callback for CDP manager creation after launch_ide */
    onCdpManagerCreated?: (ideType: string, manager: DaemonCdpManager) => void;
    /** Callback after IDE connected (e.g., startAgentStreamPolling) */
    onIdeConnected?: () => void;
    /** Callback after status change (stop_ide, restart) */
    onStatusChange?: () => void;
    /** Callback after chat-related commands */
    onPostChatCommand?: () => void;
    /** Get a connected CDP manager (for agent stream reset check) */
    getCdpLogFn?: (ideType: string) => (msg: string) => void;
    /** Package name for upgrade detection ('adhdev' or '@adhdev/daemon-standalone') */
    packageName?: string;
}
interface CommandRouterResult {
    success: boolean;
    [key: string]: unknown;
}
declare class DaemonCommandRouter {
    private deps;
    constructor(deps: CommandRouterDeps);
    /**
     * Unified command routing.
     * Returns result for all commands:
     *   1. Daemon-level commands (launch_ide, stop_ide, etc.)
     *   2. CLI commands (launch_cli, stop_cli, agent_command)
     *   3. DaemonCommandHandler delegation (CDP/agent-stream/file commands)
     *
     * @param cmd Command name
     * @param args Command arguments
     * @param source Log source ('ws' | 'p2p' | 'standalone' | etc.)
     */
    execute(cmd: string, args: any, source?: string): Promise<CommandRouterResult>;
    /**
     * Daemon-level command execution (IDE start/stop/restart, CLI, detect, logs).
     * Returns null if not handled at this level → caller delegates to CommandHandler.
     */
    private executeDaemonCommand;
    /**
     * IDE stop: CDP disconnect + InstanceManager cleanup + optionally kill OS process
     */
    private stopIde;
}

/**
 * DaemonStatusReporter — status collect & transmit (StatusReport / P2P / StatusEvent)
 *
 * Collect status from ProviderInstanceManager → assemble payload → transmit
 * Each Instance manages its own status/transition. This module only assembles + transmits.
 */

interface StatusReporterDeps {
    serverConn: {
        isConnected(): boolean;
        sendMessage(type: string, data: any): void;
        getUserPlan(): string;
    } | null;
    cdpManagers: Map<string, {
        isConnected: boolean;
    }>;
    p2p: {
        isConnected: boolean;
        isAvailable: boolean;
        connectionState: string;
        connectedPeerCount: number;
        screenshotActive: boolean;
        sendStatus(data: any): void;
    } | null;
    providerLoader: {
        resolve(type: string): any;
        getAll(): any[];
    };
    detectedIdes: any[];
    instanceId: string;
    daemonVersion?: string;
    instanceManager: {
        collectAllStates(): ProviderState[];
        collectStatesByCategory(cat: string): ProviderState[];
    };
    getScreenshotUsage?: () => {
        dailyUsedMinutes: number;
        dailyBudgetMinutes: number;
        budgetExhausted: boolean;
    } | null;
}
declare class DaemonStatusReporter {
    private deps;
    private log;
    private lastStatusSentAt;
    private statusPendingThrottle;
    private lastP2PStatusHash;
    private lastStatusSummary;
    private statusTimer;
    private p2pTimer;
    constructor(deps: StatusReporterDeps, opts?: {
        logFn?: (msg: string) => void;
    });
    startReporting(): void;
    stopReporting(): void;
    onStatusChange(): void;
    throttledReport(): void;
    emitStatusEvent(event: Record<string, unknown>): void;
    removeAgentTracking(_key: string): void;
    updateAgentStreams(_ideType: string, _streams: any[]): void;
    /** Reset P2P dedup hash — forces next send to transmit even if content unchanged */
    resetP2PHash(): void;
    private ts;
    sendUnifiedStatusReport(opts?: {
        p2pOnly?: boolean;
    }): Promise<void>;
    private sendP2PPayload;
    private simpleHash;
}

/**
 * Status Builders — shared conversion functions for ProviderState → ManagedEntry
 *
 * Used by:
 *   - daemon-standalone (StandaloneServer.getStatus)
 *   - DaemonStatusReporter
 *
 * Consolidates ProviderState→ManagedEntry mapping logic.
 */

/**
 * Find a CDP manager by key, with prefix matching for multi-window support.
 *
 * Lookup order:
 *   1. Exact match: cdpManagers.get(key)
 *   2. Prefix match: key starts with `${ideType}_` (multi-window: "cursor_remote_vs")
 *   3. null
 *
 * This replaces raw `cdpManagers.get(ideType)` calls that broke when
 * multi-window keys like "cursor_remote_vs" were used.
 */
declare function findCdpManager(cdpManagers: Map<string, DaemonCdpManager>, key: string): DaemonCdpManager | null;
/**
 * Check if any CDP manager matches the given key (exact or prefix).
 */
declare function hasCdpManager(cdpManagers: Map<string, DaemonCdpManager>, key: string): boolean;
/**
 * Check if any CDP manager matching the key is connected.
 */
declare function isCdpConnected(cdpManagers: Map<string, DaemonCdpManager>, key: string): boolean;
declare function buildSessionEntries(allStates: ProviderState[], cdpManagers: Map<string, DaemonCdpManager>): SessionEntry[];

/**
 * Shared status snapshot builders.
 *
 * Used by:
 * - DaemonStatusReporter (cloud)
 * - daemon-standalone HTTP/WS status responses
 */

interface StatusSnapshotOptions {
    allStates: ProviderState[];
    cdpManagers: Map<string, unknown>;
    providerLoader: {
        getAll(): Array<{
            type: string;
            icon?: string;
            displayName?: string;
            category: 'ide' | 'extension' | 'cli' | 'acp';
        }>;
    };
    detectedIdes: Array<{
        id: string;
        name?: string;
        displayName?: string;
        installed?: boolean;
        path?: string;
    }>;
    instanceId: string;
    version: string;
    daemonMode: boolean;
    timestamp?: number;
    p2p?: StatusReportPayload['p2p'];
    machineNickname?: string | null;
}
interface StatusSnapshot extends StatusReportPayload {
    availableProviders: AvailableProviderInfo[];
}
declare function buildStatusSnapshot(options: StatusSnapshotOptions): StatusSnapshot;

/**
 * ADHDev Daemon — unified logger (v2)
 *
 * log level: DEBUG < INFO < WARN < ERROR
 *
 * Features:
 * 1. daemonLog(category, msg, level) — explicit per-category logging
 * 2. installGlobalInterceptor() — Auto-intercept console.log (once on daemon start)
 * 3. Recent log ring buffer — for remote transmission via P2P/WS
 * 4. File logging — ~/Library/Logs/adhdev/daemon.log (10MB rolling)
 *
 * use:
 * import { daemonLog, LOG } from './daemon-logger';
 * LOG.info('CDP', 'Connected to cursor on port 9333');
 * LOG.debug('StatusReport', 'P2P heartbeat sent');
 * LOG.warn('IdeInstance', 'onTick error: ...');
 * LOG.error('Server', 'WebSocket disconnected');
 */
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
declare function setLogLevel(level: LogLevel): void;
declare function getLogLevel(): LogLevel;
interface LogEntry {
    ts: number;
    level: LogLevel;
    category: string;
    message: string;
}
/** Get recent N logs (for remote transmission) */
declare function getRecentLogs(count?: number, minLevel?: LogLevel): LogEntry[];
/**
 * Scoped logger instance for a specific component.
 * Created via LOG.forComponent('CDP:cursor').
 */
interface ScopedLogger {
    debug: (msg: string) => void;
    info: (msg: string) => void;
    warn: (msg: string) => void;
    error: (msg: string) => void;
    /** Returns a plain (msg: string) => void function at the given level.
     *  Useful as logFn callback for ProviderLoader, DaemonStatusReporter, etc. */
    asLogFn: (level?: LogLevel) => (msg: string) => void;
}
/**
 * LOG — unified logging API
 *
 * Usage:
 *   LOG.info('CDP', 'Connected to cursor on port 9333');
 *   LOG.debug('StatusReport', 'P2P heartbeat sent');
 *
 * Component-scoped logger:
 *   const log = LOG.forComponent('ACP:cursor');
 *   log.info('Session created');
 *   log.debug('Heartbeat');
 *
 * As callback for external components:
 *   new ProviderLoader({ logFn: LOG.forComponent('Provider').asLogFn() });
 *   new DaemonStatusReporter({ logFn: LOG.forComponent('Status').asLogFn() });
 */
declare const LOG: {
    debug: (category: string, msg: string) => void;
    info: (category: string, msg: string) => void;
    warn: (category: string, msg: string) => void;
    error: (category: string, msg: string) => void;
    /**
     * Create a scoped logger for a specific component.
     * Category is baked in so callers only pass the message.
     */
    forComponent(category: string): ScopedLogger;
};
/**
 * console.log/warn/error global interceptor install
 * Prevent recording in places not using daemonLog.
 * daemon start when 1time call.
 */
declare function installGlobalInterceptor(): void;

/**
 * ADHDev Daemon — Command History Logger
 *
 * Record all commands from dashboard/WS/P2P/Extension/API to local file.
 * Per-date JSONL file, 7-day retention, 5MB limit.
 *
 * Purpose:
 * - Debugging: track what command came and when
 * - Audit: record all commands executed from remote
 * - Stats: identify frequently used features
 */
interface CommandLogEntry {
    ts: string;
    cmd: string;
    source: 'ws' | 'p2p' | 'ext' | 'api' | 'standalone' | 'unknown';
    args?: Record<string, unknown>;
    success?: boolean;
    error?: string;
    durationMs?: number;
}
/**
 * Log a command received from the dashboard/WS/P2P/extension/API.
 * Call this at the entry point of command handling.
 */
declare function logCommand(entry: CommandLogEntry): void;
/**
 * Read recent command history (for dashboard display / debugging)
 */
declare function getRecentCommands(count?: number): CommandLogEntry[];

/**
 * ADHDev Launcher — IDE Launch/Relaunch with CDP
 *
 * Launches IDE with Chrome DevTools Protocol (remote-debugging-port).
 * If IDE is already running, terminates it and restarts with CDP option.
 *
 * Pipeline:
 * 1. IDE process detection (already running?)
 * 2. If already running with CDP → reuse as-is
 * 3. If running without CDP → kill process → wait → restart with CDP
 * 4. Not running → start fresh with CDP
 *
 * Usage:
 * adhdev launch — Launch configured IDE with CDP port
 * adhdev launch cursor — Launch Cursor with CDP port
 * adhdev launch --workspace /path — Open specific workspace
 */
/** Kill IDE process (graceful → force) */
declare function killIdeProcess(ideId: string): Promise<boolean>;
/** Check if IDE process is running */
declare function isIdeRunning(ideId: string): boolean;
interface LaunchOptions {
    ideId?: string;
    workspace?: string;
    newWindow?: boolean;
}
interface LaunchResult {
    success: boolean;
    ideId: string;
    ideName: string;
    port: number;
    action: 'started' | 'restarted' | 'reused' | 'failed';
    message: string;
    error?: string;
}
/**
 * Execute IDE with CDP port (relaunch pipeline)
 *
 * 1. IDE detect
 * 2. per-fixed IDE CDP port determine
 * 3. CDP not active → reuse
 * 4. IDE execute during but CDP none → terminate → restart with CDP
 * 5. IDE not running → start fresh with CDP
 */
declare function launchWithCdp(options?: LaunchOptions): Promise<LaunchResult>;
declare function getAvailableIdeIds(): string[];

declare const DEFAULT_DAEMON_PORT = 19222;
declare const DAEMON_WS_PATH = "/ipc";

/**
 * Shared helper for forwarding agent stream snapshots into the IDE instance.
 *
 * Both cloud and standalone daemons use the same InstanceManager wiring.
 */
declare function forwardAgentStreamsToIdeInstance(instanceManager: {
    getInstance: (key: string) => any;
}, ideType: string, streams: any[]): void;

/**
 * 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
 */

interface CliChatMessage {
    role: 'user' | 'assistant';
    content: string;
    timestamp?: number;
}
interface CliSessionStatus {
    status: 'idle' | 'generating' | 'waiting_approval' | 'error' | 'stopped' | 'starting';
    messages: CliChatMessage[];
    workingDir: string;
    activeModal: {
        message: string;
        buttons: string[];
    } | null;
    terminalHistory?: string;
}
/**
 * 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.
 */
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;
}
interface CliScriptInput {
    buffer: string;
    rawBuffer: string;
    recentBuffer: string;
    screenText: string;
    terminalHistory?: string;
    messages: CliChatMessage[];
    partialResponse: string;
}
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;
}
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 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 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;
    /** Rolling append-only terminal transcript built from screen snapshots */
    private terminalHistory;
    /** Max accumulated buffer size (last 50KB) */
    private static readonly MAX_ACCUMULATED_BUFFER;
    private currentTurnScope;
    private syncMessageViews;
    private sliceFromOffset;
    private buildParseInput;
    private setStatus;
    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 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;
    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>;
}

/**
 * CliProviderInstance — Runtime instance for CLI Provider
 *
 * Lifecycle layer on top of ProviderCliAdapter.
 * collectCliData() + status transition logic from daemon-status.ts moved here.
 */

declare class CliProviderInstance implements ProviderInstance {
    private provider;
    private workingDir;
    private cliArgs;
    readonly type: string;
    readonly category: "cli";
    private adapter;
    private context;
    private events;
    private lastStatus;
    private generatingStartedAt;
    private settings;
    private monitor;
    private generatingDebounceTimer;
    private generatingDebouncePending;
    private lastApprovalEventAt;
    private historyWriter;
    readonly instanceId: string;
    constructor(provider: ProviderModule, workingDir: string, cliArgs?: string[], instanceId?: string, transportFactory?: PtyTransportFactory);
    init(context: InstanceContext): Promise<void>;
    onTick(): Promise<void>;
    getState(): ProviderState;
    onEvent(event: string, data?: any): void;
    dispose(): void;
    private completedDebounceTimer;
    private completedDebouncePending;
    private detectStatusTransition;
    private pushEvent;
    private flushEvents;
    getAdapter(): ProviderCliAdapter;
    get cliType(): string;
    get cliName(): string;
}

/**
 * AcpProviderInstance — ACP (Agent Client Protocol) Provider runtime instance
 *
 * Spawns ACP agent process and communicates via the official ACP SDK.
 * Uses ClientSideConnection + ndJsonStream for structured protocol communication.
 *
 * ACP spec: https://agentclientprotocol.com
 * ACP SDK: @agentclientprotocol/sdk@0.16.1
 *
 * lifecycle:
 * 1. init() → Spawn agent process + ACP initialize handshake
 * 2. onTick() → no-op (ACP event based)
 * 3. getState() → ProviderState return (dashboard for display)
 * 4. onEvent('send_message') → session/prompt transmit
 * 5. dispose() → kill process
 */

declare class AcpProviderInstance implements ProviderInstance {
    private cliArgs;
    readonly type: string;
    readonly category: "acp";
    private readonly log;
    private provider;
    private context;
    private settings;
    private events;
    private monitor;
    private process;
    private connection;
    private sessionId;
    private messages;
    private currentStatus;
    private lastStatus;
    private generatingStartedAt;
    private agentCapabilities;
    private currentModel;
    private currentMode;
    private activeToolCalls;
    private stopReason;
    private partialContent;
    /** Rich content blocks accumulated during streaming */
    private partialBlocks;
    /** Tool calls collected during current turn */
    private turnToolCalls;
    private errorMessage;
    private errorReason;
    private stderrBuffer;
    private spawnedAt;
    private configOptions;
    private availableModes;
    /** Static config mode — agent doesn't support config/* methods */
    private useStaticConfig;
    /** Current config selections (for spawnArgBuilder) */
    private selectedConfig;
    private workingDir;
    private instanceId;
    constructor(provider: ProviderModule, workingDir: string, cliArgs?: string[]);
    init(context: InstanceContext): Promise<void>;
    onTick(): Promise<void>;
    getState(): AcpProviderState;
    onEvent(event: string, data?: any): void;
    getInstanceId(): string;
    private parseConfigOptions;
    private parseModes;
    setConfigOption(category: string, value: string): Promise<void>;
    setMode(modeId: string): Promise<void>;
    /** Static config: kill process and restart with new args */
    private restartWithNewConfig;
    /** Update settings at runtime (called when user changes settings from dashboard) */
    updateSettings(newSettings: Record<string, any>): void;
    dispose(): void;
    private spawnAgent;
    private createClient;
    private initialize;
    private createSession;
    sendPrompt(text: string, contentBlocks?: ContentBlock[]): Promise<void>;
    private cancelSession;
    private permissionResolvers;
    private resolvePermission;
    private handleSessionUpdate;
    /** Handle legacy session/update formats (pre-standardization compat) */
    private handleLegacyUpdate;
    /** Map SDK ToolCallStatus to internal status */
    private mapToolCallStatus;
    /** Truncate content for transport (text: 2000 chars, images preserved) */
    private truncateContent;
    /** Build ContentBlock[] from current partial state */
    private buildPartialBlocks;
    /** Finalize streaming content into an assistant message */
    private finalizeAssistantMessage;
    /** Convert ACP ToolCallContent[] to our ToolCallContent[] */
    private convertToolCallContent;
    private detectStatusTransition;
    private pushEvent;
    private flushEvents;
    get cliType(): string;
    get cliName(): string;
    /** ACP Agent capabilities (available after initialize) */
    getCapabilities(): Record<string, any>;
}

/**
 * Context passed from the main DevServer to handler modules.
 * Provides access to shared dependencies and utility methods.
 */
interface DevServerContext {
    readonly providerLoader: ProviderLoader;
    readonly cdpManagers: Map<string, DaemonCdpManager>;
    readonly instanceManager: ProviderInstanceManager | null;
    readonly cliManager: DaemonCliManager | null;
    getCdp(ideType?: string): DaemonCdpManager | null;
    json(res: http.ServerResponse, status: number, data: any): void;
    readBody(req: http.IncomingMessage): Promise<any>;
    log(msg: string): void;
    autoImplSSEClients: http.ServerResponse[];
    sendAutoImplSSE(msg: {
        event: string;
        data: any;
    }): void;
    autoImplStatus: {
        running: boolean;
        type: string | null;
        progress: any[];
    };
    autoImplProcess: child_process.ChildProcess | null;
    sendCliSSE(data: any): void;
    handleRunScript(type: string, req: http.IncomingMessage, res: http.ServerResponse, parsedBody?: any): Promise<void>;
    findProviderDir(type: string): string | null;
    getLatestScriptVersionDir(scriptsDir: string): string | null;
}

declare class DevServer implements DevServerContext {
    private server;
    providerLoader: ProviderLoader;
    cdpManagers: Map<string, DaemonCdpManager>;
    instanceManager: ProviderInstanceManager | null;
    cliManager: DaemonCliManager | null;
    private logFn;
    private sseClients;
    private watchScriptPath;
    private watchScriptName;
    private watchTimer;
    autoImplProcess: ChildProcess | null;
    autoImplSSEClients: http.ServerResponse[];
    autoImplStatus: {
        running: boolean;
        type: string | null;
        progress: any[];
    };
    private cliSSEClients;
    constructor(options: {
        providerLoader: ProviderLoader;
        cdpManagers: Map<string, DaemonCdpManager>;
        instanceManager?: ProviderInstanceManager;
        cliManager?: DaemonCliManager;
        logFn?: (msg: string) => void;
    });
    log(msg: string): void;
    private readonly routes;
    private matchRoute;
    private getEndpointList;
    start(port?: number): Promise<void>;
    stop(): void;
    private handleListProviders;
    private handleProviderConfig;
    private handleSpawnTest;
    handleRunScript(type: string, req: http.IncomingMessage, res: http.ServerResponse, parsedBody?: any): Promise<void>;
    private handleCdpEvaluate;
    private handleCdpClick;
    private handleCdpDomQuery;
    private handleScreenshot;
    private handleScriptsRun;
    private handleStatus;
    private handleReload;
    private getConsoleDistDir;
    private serveConsole;
    private static MIME_MAP;
    private serveStaticAsset;
    private handleSSE;
    private sendSSE;
    private handleWatchStart;
    private handleWatchStop;
    /** Find the provider directory on disk */
    findProviderDir(type: string): string | null;
    /** GET /api/providers/:type/files — list all files in provider directory */
    private handleListFiles;
    /** GET /api/providers/:type/file?path=scripts.js — read a file */
    private handleReadFile;
    /** POST /api/providers/:type/file — write a file { path, content } */
    private handleWriteFile;
    private handleSource;
    private handleSave;
    private handleTypeAndSend;
    private handleTypeAndSendAt;
    private handleScriptHints;
    private handleValidate;
    private handleAcpChat;
    private handleCdpTargets;
    private handleScaffold;
    private handleDetectVersions;
    private handleDomInspect;
    private handleDomChildren;
    private handleDomAnalyze;
    private handleFindCommon;
    private handleFindByText;
    private handleDomContext;
    getLatestScriptVersionDir(scriptsDir: string): string | null;
    private resolveAutoImplWritableProviderDir;
    private handleAutoImplement;
    private buildAutoImplPrompt;
    private buildCliAutoImplPrompt;
    private handleAutoImplSSE;
    private handleAutoImplCancel;
    sendAutoImplSSE(msg: {
        event: string;
        data: any;
    }): void;
    /** Get CDP manager — matching IDE when ideType specified, first connected one otherwise.
     *  DevServer is a debugging tool so first-connected fallback is acceptable,
     *  but callers should pass ideType when possible. */
    getCdp(ideType?: string): DaemonCdpManager | null;
    json(res: http.ServerResponse, status: number, data: any): void;
    readBody(req: http.IncomingMessage): Promise<any>;
    /** GET /api/cli/status — list all running CLI/ACP instances with state */
    private handleCliStatus;
    /** POST /api/cli/launch — launch a CLI agent { type, workingDir?, args? } */
    private handleCliLaunch;
    /** POST /api/cli/send — send message to a running CLI { type, text } */
    private handleCliSend;
    /** POST /api/cli/stop — stop a running CLI { type } */
    private handleCliStop;
    /** GET /api/cli/events — SSE stream of CLI status events */
    private handleCliSSE;
    sendCliSSE(data: any): void;
    /** GET /api/cli/debug/:type — full internal debug state of a CLI adapter */
    private handleCliDebug;
    /** POST /api/cli/resolve — resolve an approval modal { type, buttonIndex } */
    private handleCliResolve;
    /** POST /api/cli/raw — send raw keystrokes to PTY { type, keys } */
    private handleCliRaw;
}

interface SessionHostPtyTransportFactoryOptions {
    endpoint?: SessionHostEndpoint;
    appName?: string;
    clientId: string;
    runtimeId: string;
    providerType: string;
    category?: SessionHostCategory;
    workspace: string;
    meta?: Record<string, unknown>;
    attachExisting?: boolean;
}
declare class SessionHostPtyTransportFactory implements PtyTransportFactory {
    private readonly options;
    constructor(options: SessionHostPtyTransportFactoryOptions);
    spawn(command: string, args: string[], spawnOptions: PtySpawnOptions): PtyRuntimeTransport;
}

declare function ensureSessionHostReady(options: {
    appName?: string;
    spawnHost: () => void;
    timeoutMs?: number;
}): Promise<SessionHostEndpoint>;
declare function listHostedCliRuntimes(endpoint: SessionHostEndpoint): Promise<HostedCliRuntimeDescriptor[]>;

/**
 * ADHDev Launcher — Extension Installer
 *
 * Installs VS Code extensions via CLI commands.
 * Supports installing user-selected AI extensions.
 */

interface ExtensionInfo {
    id: string;
    name: string;
    displayName: string;
    marketplaceId: string;
    description: string;
    category: 'ai-agent' | 'utility';
    icon: string;
    recommended: boolean;
    requiresApiKey?: boolean;
    apiKeyName?: string;
    website?: string;
    vsixUrl?: string;
}
interface InstallResult {
    extensionId: string;
    marketplaceId: string;
    success: boolean;
    alreadyInstalled: boolean;
    error?: string;
}
/**
 * Check if an extension is already installed
 */
declare function isExtensionInstalled(ide: IDEInfo, marketplaceId: string): boolean;
/**
 * Install multiple extensions sequentially
 */
declare function installExtensions(ide: IDEInfo, extensions: ExtensionInfo[], onProgress?: (current: number, total: number, ext: ExtensionInfo, result: InstallResult) => void): Promise<InstallResult[]>;
/**
 * Get AI agent extensions
 */
declare function getAIExtensions(): ExtensionInfo[];
/**
 * Launch IDE after installation
 */
declare function launchIDE(ide: IDEInfo, workspacePath?: string): boolean;

/**
 * Daemon Lifecycle — Shared init + shutdown logic
 *
 * initDaemonComponents(): Creates all core daemon components in correct order.
 * shutdownDaemonComponents(): Graceful shutdown of all components.
 *
 * Transport-specific setup (ServerConnection, P2P, HTTP/WS) remains in each daemon.
 */

interface DaemonInitConfig {
    /** ProviderLoader log function */
    providerLogFn?: (msg: string) => void;
    /** CLI Manager deps (transport-specific) */
    cliManagerDeps: {
        getServerConn: () => any;
        getP2p: () => any;
        onStatusChange: () => void;
        removeAgentTracking: (key: string) => void;
        createPtyTransportFactory?: (params: CliTransportFactoryParams) => PtyTransportFactory | null;
        listHostedCliRuntimes?: () => Promise<HostedCliRuntimeDescriptor[]>;
    };
    /** CDP config */
    enabledIdes?: string[];
    /** Router transport-specific callbacks */
    onStatusChange?: () => void;
    onPostChatCommand?: () => void;
    getCdpLogFn?: (ideType: string) => (msg: string) => void;
    /** Additional callback after CDP manager created (transport-specific extras) */
    onCdpManagerSetup?: (ideType: string, manager: DaemonCdpManager, managerKey: string) => void | Promise<void>;
    /** Poller callback (transport-specific) */
    onStreamsUpdated?: (ideType: string, streams: any[]) => void;
    /** Instance ticking interval (ms), default 5000 */
    tickIntervalMs?: number;
    /** CDP scan interval (ms), default 30000 */
    cdpScanIntervalMs?: number;
}
interface DaemonComponents {
    providerLoader: ProviderLoader;
    instanceManager: ProviderInstanceManager;
    cliManager: DaemonCliManager;
    commandHandler: DaemonCommandHandler;
    agentStreamManager: DaemonAgentStreamManager;
    router: DaemonCommandRouter;
    poller: AgentStreamPoller;
    cdpInitializer: DaemonCdpInitializer;
    cdpManagers: Map<string, DaemonCdpManager>;
    sessionRegistry: SessionRegistry;
    detectedIdes: {
        value: any[];
    };
}
interface DaemonDevSupportOptions {
    components: DaemonComponents;
    logFn?: (msg: string) => void;
}
/**
 * Initialize all daemon core components.
 *
 * Order:
 *   1. Global log interceptor
 *   2. ProviderLoader
 *   3. InstanceManager + CliManager
 *   4. Detect IDEs
 *   5. CdpInitializer → connectAll + periodic scan + discovery
 *   6. CommandHandler + AgentStreamManager
 *   7. Router + Poller
 *   8. Start instance ticking
 */
declare function initDaemonComponents(config: DaemonInitConfig): Promise<DaemonComponents>;
/**
 * Start shared dev-only helpers:
 * - DevServer on port 19280
 * - Provider hot-reload watcher
 */
declare function startDaemonDevSupport(options: DaemonDevSupportOptions): Promise<DevServer>;
/**
 * Graceful shutdown of all daemon components.
 *
 * Order:
 *   1. Stop timers (poller, cdpInitializer)
 *   2. Dispose agent stream
 *   3. Shutdown CLIs
 *   4. Dispose instances
 *   5. Disconnect CDPs
 */
declare function shutdownDaemonComponents(components: DaemonComponents): Promise<void>;

export { AcpProviderInstance, AcpProviderState, AgentStreamPoller, type AgentStreamPollerDeps, AvailableProviderInfo, CdpDomHandlers, type CdpInitializerConfig, type CdpScannerOptions, type CdpSetupContext, CdpTargetFilter, type CliAdapter, CliProviderInstance, type CliTransportFactoryParams, type CommandContext, type CommandResult$1 as CommandResult, type CommandRouterDeps, type CommandRouterResult, CommandResult$2 as CoreCommandResult, DAEMON_WS_PATH, DEFAULT_DAEMON_PORT, DaemonAgentStreamManager, DaemonCdpInitializer, DaemonCdpManager, DaemonCdpScanner, DaemonCliManager, DaemonCommandHandler, DaemonCommandRouter, type DaemonComponents, type DaemonCoreOptions, type DaemonDevSupportOptions, DaemonEvent, type DaemonInitConfig, DaemonStatusReporter, DevServer, type HostMemorySnapshot, type HostedCliRuntimeDescriptor, type IDEInfo, type IDaemonCore, IdeProviderInstance, type ExtensionInfo as InstallerExtensionInfo, LOG, type LogEntry, type LogLevel, NodePtyTransportFactory, ProviderCliAdapter, ProviderInstanceManager, ProviderLoader, ProviderModule, ProviderResumeCapability, type ProviderVersionInfo, type PtyRuntimeTransport, type PtySpawnOptions, type PtyTransportFactory, type ScopedLogger, SessionEntry, SessionHostPtyTransportFactory, SessionTransport, type SetupIdeInstanceOptions, StatusReportPayload, StatusResponse, type StatusSnapshot, type StatusSnapshotOptions, VersionArchive, type VersionHistory, buildSessionEntries, buildStatusSnapshot, connectCdpManager, detectAllVersions, detectCLIs, detectIDEs, ensureSessionHostReady, findCdpManager, forwardAgentStreamsToIdeInstance, getAIExtensions, getAvailableIdeIds, getHostMemorySnapshot, getLogLevel, getRecentCommands, getRecentLogs, hasCdpManager, initDaemonComponents, installExtensions, installGlobalInterceptor, isCdpConnected, isExtensionInstalled, isIdeRunning, killIdeProcess, launchIDE, launchWithCdp, listHostedCliRuntimes, logCommand, probeCdpPort, readChatHistory, registerExtensionProviders, setLogLevel, setupIdeInstance, shutdownDaemonComponents, startDaemonDevSupport };
