import { AgentService } from '../agent/service.js';
import { MessageBus } from '../infra/bus/index.js';
import { CronService } from '../cron/index.js';
import { ExtensionLoader } from '../extensions/index.js';
import { SessionIndex } from '../session/index.js';
import type { Config } from '../config/schema.js';
import { type ResolvedGatewayAuth } from './auth.js';
import { AgentRunRelay } from './agent-run-relay.js';
import { GatewaySessionsApi } from './service/sessions-api.js';
import { GatewayMarketplaceService } from './service/marketplace-service.js';
import { GatewayAgentRunner } from './service/agent-runner.js';
import type { GatewayServiceConfig, ServiceEvent } from './service/types.js';
import { type GatewayReadinessSnapshot } from './startup-readiness.js';
export type { GatewayChannelStartupPhase1Metrics, GatewayChannelStartupPhase2Metrics, GatewayServiceConfig, ServiceEvent, } from './service/types.js';
export declare class GatewayService {
    private serviceConfig;
    private bus;
    private config;
    private configPath;
    private _agentService;
    private channelManager;
    private cronService;
    private extensionLoader;
    private extensionMetadataSnapshot;
    private browserExtensionProvider;
    private browserExtensionRelease;
    /** `${host}:${port}` when the gateway holds the extension bridge listener. */
    private browserExtensionBindKey;
    private heartbeatService;
    private sessionIndex;
    private running;
    private startTime;
    private workspacePath;
    private readonly configCoordinator;
    private auth;
    private readonly sse;
    private stopGatewayUpdateCheck;
    /** When set (e.g. by `GatewayServer`), `triggerGatewayProcessRestart` can stop HTTP then exit. */
    private gatewayShutdownForRestart;
    /** Snapshot for phase-2 metrics / logs (ids deferred at phase-1 `start()`). */
    private lastDeferredChannelConnectIds;
    private lastChannelConnectDeferMode;
    private lastChannelConnectDeferSource;
    private readonly readiness;
    private startupTrace;
    /**
     * Webchat agent invocation surface (`runAgent`, `abortAgentRun`, `steer*`,
     * `submitClarifyResponse`, clarify-bridge dispatch). Owns the
     * `activeWebchatRunBySession` + `runAbortControllers` maps.
     */
    readonly agentRunner: GatewayAgentRunner;
    /** Read-only alias re-exported from `agentRunner.runRelay` for legacy callers. */
    get runRelay(): AgentRunRelay;
    /**
     * Session CRUD / search / compaction / tag-archive-pin / stats — the gateway
     * REST surface for sessions. Routes should depend on this narrow service
     * rather than the full GatewayService composition root.
     */
    readonly sessions: GatewaySessionsApi;
    /**
     * Skills + extensions marketplace surface (browse / install / uninstall) plus
     * local-only managed-skill ops. Routes depend on this narrow service.
     */
    readonly marketplace: GatewayMarketplaceService;
    constructor(serviceConfig?: GatewayServiceConfig);
    /** Lazy AgentService — constructed on first use or during `start()`. */
    get agentService(): AgentService;
    private ensureAgentService;
    private ensureHeartbeatService;
    enqueueWebchatPersistentGoalKickoff(sessionKey: string, goalText: string): void;
    runAgent(...args: Parameters<GatewayAgentRunner['runAgent']>): ReturnType<GatewayAgentRunner['runAgent']>;
    abortAgentRun(runId: string): boolean;
    steerWebchatAgent(chatId: string, message: string): ReturnType<GatewayAgentRunner['steerWebchatAgent']>;
    submitClarifyResponse(requestId: string, answer: string): boolean;
    private initializeExtensionLoader;
    private registerExtensionChannelPlugins;
    /**
     * Load extensions and register SDK / full ChannelPlugin instances with ChannelManager.
     */
    private loadExtensionsAndRegisterChannels;
    private loadDeferredExtensions;
    private schedulePostReadySidecars;
    private runPostReadySidecars;
    start(): Promise<void>;
    /** Called when the HTTP listener is bound (before deferred channel work). */
    markHttpListening(): void;
    isGatewayReady(): boolean;
    getGatewayReadiness(): GatewayReadinessSnapshot;
    private applyStartupReadyDelayForTesting;
    private markGatewayReady;
    /** After HTTP is listening: exposure auto-start (Tailscale, then FRP tunnel). */
    private runExposureAutoStartIfConfigured;
    /**
     * Called by `GatewayServer` when the HTTP listener is bound. Starts channels that
     * opted into `meta.deferConnectUntilAfterListen`, then replays outbound queue.
     */
    onHttpListening(): Promise<void>;
    stop(): Promise<void>;
    /** Start the browser extension WS server when backend is 'extension'. */
    private startBrowserExtensionServerIfNeeded;
    /** Release the gateway's hold on the shared extension bridge (does not restart). */
    releaseBrowserExtensionBridge(): Promise<void>;
    /**
     * Start/stop/rebind the Chrome extension bridge when `agents.defaults.browser` changes.
     * PATCH saves update config in memory without re-running gateway startup, so this must run on save too.
     */
    reconcileBrowserExtensionServer(): Promise<void>;
    /**
     * Start processing outbound messages and send through channels
     */
    private startOutboundProcessor;
    reloadHeartbeatFromCurrentConfig(): void;
    reloadConfig(): Promise<{
        reloaded: boolean;
        error?: string;
    }>;
    afterWeixinCredentialsPersisted(): Promise<void>;
    afterFeishuCredentialsPersisted(): Promise<void>;
    saveConfig(config: Config): Promise<{
        saved: boolean;
        error?: string;
    }>;
    setBundledExtensionActivationTarget(extensionId: string, wanted: boolean): Promise<{
        ok: boolean;
        error?: string;
        requiresGatewayRestart: boolean;
    }>;
    updateConfig(updates: Partial<Config>): Promise<{
        updated: boolean;
        error?: string;
    }>;
    /**
     * Send message through a channel
     */
    sendMessage(channel: string, chatId: string, content: string): Promise<{
        sent: boolean;
        messageId?: string;
    }>;
    /**
     * Get channel statuses
     */
    getChannelsStatus(): Array<{
        name: string;
        enabled: boolean;
        connected: boolean;
    }>;
    /**
     * Hub metadata for gateway console (built-in registry + registered channel plugins).
     */
    getChannelsHubMeta(): Array<{
        id: string;
        label: string;
        description: string;
        manageable: boolean;
        order: number;
    }>;
    /**
     * Request an immediate heartbeat run (coalesced like interval/cron wakes).
     */
    requestHeartbeatNow(opts?: {
        reason?: string;
    }): void;
    /**
     * Register graceful shutdown used after spawning a replacement gateway process (foreground CLI server).
     */
    registerGatewayShutdownForRestart(handler: () => Promise<void>): void;
    /**
     * Respawn the gateway process when supported (spawn + exit, supervisor exit, or disabled when XOPC_NO_RESPAWN).
     */
    triggerGatewayProcessRestart(): {
        ok: boolean;
        mode: string;
        message?: string;
    };
    /**
     * Get health status
     */
    getHealth(): {
        status: string;
        service: string;
        version: string;
        uptime: number;
        ready: boolean;
        httpListening: boolean;
        startupDurationMs: number | null;
        channels: {
            running: number;
            total: number;
        };
        configPath: string;
        logs?: {
            dir: string;
            errors24h: number;
            stats: Record<string, number>;
        };
    };
    get isRunning(): boolean;
    /**
     * Get extension registry for external access (HTTP routes, gateway methods)
     */
    getExtensionRegistry(): import("../extensions/extension-registry-impl.js").ExtensionRegistryImpl;
    /** Extension loader for discovery and frontend asset APIs (may be null if extensions failed to init). */
    getExtensionLoader(): ExtensionLoader | null;
    /**
     * Get model registry for external access (HTTP routes)
     */
    getModelRegistry(): any;
    /**
     * Invoke a gateway method registered by extensions
     */
    invokeGatewayMethod(method: string, params: Record<string, unknown>): Promise<unknown>;
    get currentConfig(): Config;
    get currentWorkspacePath(): string;
    get messageBusInstance(): MessageBus;
    /** Effective HTTP listen port (CLI `--port` override or config default). */
    getEffectiveListenPort(): number;
    get cronServiceInstance(): CronService;
    get sessionIndexInstance(): SessionIndex;
    /** Process a message directly through the agent (for CLI mode). */
    processDirect(content: string, sessionKey?: string): Promise<string>;
    subscribe(sessionId: string, listener: (event: ServiceEvent) => Promise<void> | void): () => void;
    emit(type: string, payload: unknown): void;
    /** Replay events since `lastEventId` for SSE reconnection. */
    getEventsSince(sessionId: string, lastEventId: string): ServiceEvent[];
    /**
     * Validate authentication token from request headers.
     * Returns true if auth is disabled (mode: 'none') or token is valid.
     */
    validateAuth(headers?: Record<string, string | string[] | undefined>): boolean;
    /**
     * Get current auth mode.
     */
    getAuthMode(): 'none' | 'token' | 'password' | 'trusted-proxy';
    /** Resolved gateway auth (mode, credentials, trusted-proxy config). */
    getResolvedAuth(): ResolvedGatewayAuth;
    /**
     * Get current auth token (for CLI server integration).
     * Returns undefined if mode is not token.
     */
    getAuthToken(): string | undefined;
    /**
     * Refresh (regenerate) the gateway auth token.
     * Returns the new token.
     */
    refreshAuthToken(): Promise<string>;
}
