import { IncomingMessage } from 'node:http';
import { E as EngramAccessService } from './access-service-_AEUMVyX.js';
import './storage.js';
import './page-versioning.js';
import './consolidation-operator.js';
import './types.js';
import './memory-projection-store-D3vBHS4J.js';
import 'better-sqlite3';
import './recall-xray.js';
import './recall-explain-renderer.js';
import './recall-state.js';
import './recall-audit-anomaly.js';
import './recall-audit.js';
import './explicit-capture.js';
import './orchestrator-ChkesB8U.js';
import './buffer.js';
import './port-hqGnoStS.js';
import './transcript.js';
import './session-integrity.js';
import './summarizer.js';
import './model-registry.js';
import './local-llm.js';
import './fallback-llm.js';
import './live-connectors-runner.js';
import './framework-CyHYDcri.js';
import './relevance.js';
import './negative.js';
import './session-observer-state.js';
import './embedding-fallback.js';
import './semantic-consolidation-ByBXb-sf.js';
import './codex-materialize-CQlLTzke.js';
import './logger.js';
import 'zod';
import './policy-runtime.js';
import './profiling.js';
import './cross-namespace-budget.js';
import './graph-snapshot.js';
import './graph.js';
import './trust-zones.js';
import './memory-worth-outcomes.js';
import './capsule-cli.js';

/**
 * Adapter interface for external system identity resolution.
 *
 * Each adapter maps an external system's session/identity conventions
 * to Engram's namespace + principal model. Adapters are stateless and
 * lightweight — they don't manage lifecycles or load plugins.
 */
interface AdapterContext {
    /** Raw HTTP headers from the incoming request */
    headers: Record<string, string | string[] | undefined>;
    /** MCP client info (from initialize handshake, if available) */
    clientInfo?: {
        name: string;
        version?: string;
    };
    /** Explicit session key from request args */
    sessionKey?: string;
}
interface ResolvedIdentity {
    /** Engram namespace (scopes memory access) */
    namespace: string;
    /** Engram principal (authorization subject) */
    principal: string;
    /** Session key for continuity tracking */
    sessionKey?: string;
    /** Which adapter resolved this identity */
    adapterId: string;
}
interface EngramAdapter {
    /** Adapter identifier (e.g., "claude-code", "codex", "hermes", "replit") */
    readonly id: string;
    /** Whether this adapter recognizes the given request context */
    matches(context: AdapterContext): boolean;
    /** Map external session/identity to Engram namespace + principal */
    resolveIdentity(context: AdapterContext): ResolvedIdentity;
}

/**
 * Adapter registry. Attempts to identify which external system is
 * connecting by checking each registered adapter in order. Falls back
 * to explicit namespace/principal from the request args.
 */
declare class AdapterRegistry {
    private readonly adapters;
    constructor(adapters?: EngramAdapter[]);
    /**
     * Try each adapter in order. Return the first match, or null if
     * no adapter recognizes the request context.
     */
    resolve(context: AdapterContext): ResolvedIdentity | null;
    /** List registered adapter IDs */
    list(): string[];
}

interface EngramAccessHttpServerOptions {
    service: EngramAccessService;
    host?: string;
    port?: number;
    authToken?: string;
    /** Additional valid tokens (for multi-connector auth). Checked alongside authToken. */
    authTokens?: string[];
    /** Dynamic token loader — called on each auth check so new/revoked tokens take effect without restart. */
    authTokensGetter?: () => string[];
    principal?: string;
    maxBodyBytes?: number;
    adminConsoleEnabled?: boolean;
    adminConsolePublicDir?: string;
    trustPrincipalHeader?: boolean;
    /** Enable adapter-based identity resolution from request headers */
    enableAdapters?: boolean;
    /** Custom adapter registry (defaults to built-in adapters) */
    adapterRegistry?: AdapterRegistry;
    /** Enable oai-mem-citation blocks in recall responses (issue #379). */
    citationsEnabled?: boolean;
    /** Auto-enable citations for Codex adapter connections (issue #379). */
    citationsAutoDetect?: boolean;
}
interface EngramAccessHttpServerStatus {
    running: boolean;
    host: string;
    port: number;
    maxBodyBytes: number;
}
declare class EngramAccessHttpServer {
    private readonly service;
    private readonly host;
    private readonly requestedPort;
    private readonly authToken?;
    private readonly authTokens;
    private readonly authTokensGetter?;
    private readonly authenticatedPrincipal?;
    private readonly maxBodyBytes;
    private readonly adminConsoleEnabled;
    private readonly adminConsolePublicDir;
    private readonly trustPrincipalHeader;
    private readonly adapterRegistry;
    private readonly writeRequestTimestamps;
    private readonly mcpServer;
    private server;
    private boundPort;
    /** Active SSE response objects for /engram/v1/graph/events. */
    private readonly sseClients;
    /** Throttle batch: pending SSE event batches per client. */
    private readonly sseBatchTimers;
    private readonly ssePendingBatches;
    /**
     * Per-client cleanup callbacks: clear heartbeat interval, flush timer,
     * unsubscribe from bus, and end the response.  Stored here so `stop()`
     * can invoke them even when the client hasn't disconnected yet
     * (Cursor review thread `access-http.ts:232`).
     */
    private readonly sseCleanupFns;
    constructor(options: EngramAccessHttpServerOptions);
    start(): Promise<EngramAccessHttpServerStatus>;
    stop(): Promise<void>;
    status(): EngramAccessHttpServerStatus;
    /**
     * Resolve the adapter identity for the incoming request.
     * Includes MCP clientInfo from the last initialize handshake if available.
     * Returns null if no adapter matches or adapters are disabled.
     */
    resolveAdapterIdentity(req: IncomingMessage): ResolvedIdentity | null;
    /** Cache for per-request identity resolution (avoids double adapter resolution) */
    private identityCache;
    /** Resolve principal and namespace from request headers and adapter identity */
    private resolveRequestIdentity;
    private resolveRequestPrincipal;
    /** Resolve namespace: only use the explicit body value. Adapter-inferred namespace
     *  is intentionally NOT used as a fallback for REST requests — omitting namespace
     *  should default to the server's global namespace, not silently scope to an adapter. */
    private resolveNamespace;
    /**
     * Resolve the recall disclosure depth from the request (issue #677 PR
     * 2/4).  Explicit body value wins; otherwise we accept a
     * `?disclosure=...` query parameter so curl/browser tooling can use the
     * three-tier surface without rewriting JSON.  Invalid query values
     * throw `EngramAccessInputError` (CLAUDE.md rule 51 — no silent
     * fallback).  An absent body field AND an absent query param yields
     * `undefined`, which the service maps to `DEFAULT_RECALL_DISCLOSURE`.
     */
    private resolveRecallDisclosure;
    private handle;
    /**
     * SSE handler for /engram/v1/graph/events.
     *
     * Lifecycle:
     *  1. Write SSE headers (Content-Type: text/event-stream).
     *  2. Register this response in `sseClients`.
     *  3. Resolve the namespace from the request and subscribe to THAT
     *     namespace's graph event bus (Codex P1: in multi-namespace
     *     deployments each namespace has its own bus keyed by its storage
     *     dir — subscribing to the global root leaks events across tenants).
     *  4. On each event, add to a 200 ms batch; flush batch as a single SSE frame.
     *  5. Send heartbeat every 25 s.
     *  6. On client disconnect (req "close"), clean up timers and unsubscribe.
     *  7. Register the cleanup callback in `sseCleanupFns` so `stop()` can
     *     release the heartbeat interval and bus subscription even when the
     *     client never disconnects (Cursor review thread `access-http.ts:232`).
     */
    private handleGraphEventsSSE;
    private handleMcpRequest;
    private respondJson;
    private handleAdminConsole;
    private respondStatic;
    private readJsonBody;
    private readValidatedBody;
    private isAuthorized;
    private timingSafeStringEqual;
    private encodeSecret;
    private writeResponseStatus;
    private ensureWriteRateLimitAvailable;
    private recordWriteRateLimitHit;
    private shouldCountWriteRateLimit;
}

export { EngramAccessHttpServer, type EngramAccessHttpServerOptions, type EngramAccessHttpServerStatus };
