/**
 * StdioServer — JSON-RPC 2.0 protocol handler.
 *
 * Receives JSON-RPC messages from a Transport, dispatches to handlers,
 * writes JSON-RPC responses/notifications back through the Transport.
 * All log output goes to stderr.
 *
 * Protocol: each message is a single JSON-RPC 2.0 object.
 * The physical I/O layer is abstracted via the Transport interface.
 */
import type { Transport } from "./transport.js";
import type { Agent } from "../agent/agent.js";
import type { TurnConfig } from "../agent/types.js";
import type { LLMTransport } from "./provider-core-facade.js";
import { type MemoryPrefetchState } from "../runtime/hooks/memory-hooks.js";
import { SessionState } from "../runtime/session/session-state.js";
import { TaskStore } from "../runtime/infra/task-runtime.js";
import { BackgroundTaskManager } from "../runtime/infra/background-tasks.js";
import { type AgentRpcError } from "../protocol/wire/index.js";
import type { AcpServer } from "../transport/acp-server.js";
import type { NotificationMethod, NotificationMethodMap } from "../protocol/notifications.js";
import type { SessionLlmConfig } from "./acp-session-host.js";
import { AgentRuntimeSessionState } from "./agent-runtime-session-state.js";
import { type MultiAgentHandlerHost } from "./multi-agent-handler-host.js";
import type { WorkflowHandlerHost } from "./handlers/workflow-handler.js";
import { SessionHistoryCoordinator } from "./session-history-coordinator.js";
import { PetConfirmCoordinator } from "./pet-confirm-coordinator.js";
import type { MemoryDreamRuntimeProvider, MemoryHandlerProvider, ProjectMemoryStore } from "../runtime/ports/index.js";
export interface StdioServerConfig {
    verbose: boolean;
    transport?: Transport;
}
export declare class StdioServer {
    running: boolean;
    readonly startedAt: number;
    readonly packageVersion: string;
    /** JSON-RPC request lifecycle: gateway contract, in-flight ledger, deadlines. */
    private rpc;
    /** Gateway contract — exposed for control-handler metrics/cancel. */
    get rpcContract(): import("../protocol/wire/gateway-contract.js").GatewayRpcContract;
    activeTurn: AbortController | null;
    /** Resolves when the active turn fully completes (including post-abort flush). */
    private turnDone;
    verbose: boolean;
    private transport;
    private readonly runtimeServices;
    private readonly runtimeSession;
    /**
     * DERIVED resolved-agent cache (Agent + LLM client snapshot). The invalidation
     * invariant (full wipe on registry change vs forget-agent on session dispose)
     * is localized in ResolvedAgentCache. Host-pinned sessionLlmConfig is separate
     * and never touched by it.
     */
    private readonly resolvedAgent;
    /** Active session/turn identity + lifecycle (id/turn/state/taskDomain/llmConfig/acpMeta). */
    private readonly session;
    private currentMediaApiKeys;
    taskStore: TaskStore;
    /** Unified background execution registry (agent forks + backgrounded shell commands). */
    backgroundTasks: BackgroundTaskManager;
    /** Settled-task notifications queued for injection into the next turn's context. */
    private pendingTaskNotifications;
    /** Session-scoped memory prefetch state (LRU dedup + byte limit). */
    memoryPrefetchState: MemoryPrefetchState;
    /** Last user message text for auto-extract hook (set at turn start, cleared at turn end).
     * Public: the turn pipeline writes it through the ACP host adapter. */
    lastUserMessageForAutoExtract: string | undefined;
    /** Last assistant message text for implicit extraction hook (set at turn end).
     * Public: the turn pipeline writes it through the ACP host adapter. */
    lastAssistantMessageForExtract: string | undefined;
    /** MEMDIR file-based memory (CC memdir parity). */
    memdir: ProjectMemoryStore | null;
    readonly projectMemoryStoreFactory: import("../runtime/ports/project-memory-store.js").ProjectMemoryStoreFactory;
    /** Memory write gate state (P2+P3: category gate + supersedes). */
    /** Pending ask_user requests waiting for host response */
    pendingAskUser: Map<string, {
        resolve: (answers: Record<string, string> | null) => void;
    }>;
    /** Agents/solo/product handler facade. */
    readonly multiAgentHandlerHost: MultiAgentHandlerHost;
    /** Workflow handler host — carries toolCatalog + the lazy engine slots the multi-agent host lacks. */
    readonly workflowHandlerHost: WorkflowHandlerHost;
    /** ACP protocol coordinator — owns AcpServer lifecycle and ACP event mapping. */
    private readonly acp;
    sessionHistory: SessionHistoryCoordinator;
    private idleDreamCoordinator;
    private readonly sessionRuntime;
    readonly petConfirmCoordinator: PetConfirmCoordinator;
    private modelRegistryHydration;
    private get registry();
    get mediaClient(): import("@xiaozhiclaw/provider-core/media-client").MediaClient;
    get mediaPersistence(): import("../runtime/infra/media-persistence.js").MediaPersistence;
    private get pathService();
    get toolCatalog(): import("../runtime/ports/tool-contracts.js").ToolCatalog;
    /** Turn pipeline awaits this before tool dispatch (MCP servers connected). */
    get mcpReady(): Promise<void>;
    get petRuntime(): import("./pet-runtime.js").PetRuntime;
    private get agent();
    /** Cached LLM transport for sub-agent forks (dream). */
    get currentTransport(): LLMTransport | null;
    get currentApiKey(): string;
    get currentModel(): string;
    private get currentProvider();
    private get currentBaseUrl();
    get currentSessionId(): string;
    set currentSessionId(v: string);
    get currentTurnId(): string;
    set currentTurnId(v: string);
    get sessionState(): SessionState | null;
    set sessionState(v: SessionState | null);
    get sessionLlmConfig(): SessionLlmConfig;
    set sessionLlmConfig(v: SessionLlmConfig);
    get acpSessionMeta(): Record<string, unknown> | null;
    set acpSessionMeta(v: Record<string, unknown> | null);
    get currentHooks(): import("../contracts/hooks.js").HookRegistry | null;
    get permissionChecker(): AgentRuntimeSessionState["permissionChecker"];
    private set permissionChecker(value);
    private set mcpManager(value);
    get memoryProvider(): MemoryHandlerProvider | null;
    set memoryProvider(value: MemoryHandlerProvider | null);
    get memoryDreamProvider(): MemoryDreamRuntimeProvider | null;
    set memoryDreamProvider(value: MemoryDreamRuntimeProvider | null);
    get memoryUserId(): string;
    set memoryUserId(value: string);
    constructor(config: StdioServerConfig);
    /**
     * Get the active project workspace directory.
     * Reads from projectStore (single source of truth).
     */
    getActiveProjectRoot(): string;
    /**
     * Drain queued background-task completion notifications.
     * Called by the turn pipeline at turn start — settled tasks are injected
     * into the model's context as <task_notification> blocks.
     */
    drainPendingTaskNotifications(): string[];
    ensureModelRegistryHydrated(): Promise<void>;
    syncToolListMediaConfig(): void;
    configureTurnMedia(config: Record<string, unknown> | undefined, turnId: string): void;
    /**
     * Single entry point for updating the active workdir.
     * Centralizes all side-effects (bootstrap workdir, media persistence, etc.).
     * Uses projectStore as the source of truth — no private field cache.
     */
    setActiveWorkdir(dir: string): void;
    start(): void;
    stop(): Promise<void>;
    private readonly methodHandlers;
    private handleMessage;
    /**
     * Ensure a default project exists on first start.
     * Called from both legacy handleInitialize and ACP acpHandleInitialize.
     */
    ensureDefaultProject(): void;
    /**
     * Atomically resolve transport + model + apiKey for a given ModelPurpose.
     * If the resolved provider matches `this.currentProvider`, reuses cached transport.
     * Otherwise creates a one-shot client. Returns null if purpose is unresolvable.
     * This ensures side-ops always use fresh model from registry.
     */
    resolveClientForPurpose(purpose: import("../runtime/infra/model-registry.js").ModelPurpose): {
        transport: LLMTransport;
        apiKey: string;
        model: string;
    } | null;
    /**
     * Ensure the L2 SQLite memory provider exists for read-only RPCs
     * (memory.atlas / memory.activity). These can be called before any turn has
     * run, so they cannot rely on resolveAgent() having initialized the provider.
     * Opening the DB is cheap and side-effect-free (list() does not embed).
     */
    ensureMemoryProvider(): void;
    resolveAgent(config: TurnConfig): Agent | null;
    private invalidateResolvedLlmCache;
    /** Emit an `agents.status` notification when a child process state changes. */
    private emitAgentStatus;
    createDreamHandlerHost(): import("./handlers/dream-handler.js").DreamHandlerHost;
    private createAcpExtendedHandlerHost;
    /**
     * Handle an MCP tool call proxied from an external ACP agent via the
     * named-pipe bridge.  Dispatches the tool through the host's own tool
     * system and returns the text result.
     */
    private handleMcpToolCall;
    sendResponse(id: string | number, result?: unknown, error?: AgentRpcError): void;
    /**
     * Send a JSON-RPC error response by (code, message, data) — convenience over
     * sendResponse for handlers that build the error inline (e.g. session.moveToProject
     * error paths call `this.sendError`).
     */
    sendError(id: string | number, code: AgentRpcError["code"], message: string, data?: unknown): void;
    sendNotification<M extends NotificationMethod>(method: M, params: NotificationMethodMap[M]): void;
    private writeStdout;
    log(message: string): void;
    /**
     * Enable idle dream scheduling. Called after session setup when LLM config is available.
     */
    enableIdleDream(minutes?: number): void;
    cancelIdleDreamTimer(): void;
    disposeSessionRuntime(): void;
    /**
     * Initialize the ACP server alongside the legacy protocol.
     * Called once when the host is an ACP-compliant client.
     */
    initAcpServer(): void;
    /** Get the ACP server instance (for external wiring, e.g., main.ts). */
    getAcpServer(): AcpServer | null;
}
