import type { AbstractLevel } from 'abstract-level';
import type { GenericMessage } from '@enbox/dwn-sdk-js';
import type { EnboxPlatformAgent } from './types/agent.js';
import type { StartSyncParams, SyncConnectivityState, SyncEngine, SyncIdentityOptions } from './types/sync.js';
export type SyncEngineLevelParams = {
    agent?: EnboxPlatformAgent;
    dataPath?: string;
    db?: AbstractLevel<string | Buffer | Uint8Array>;
};
export declare class SyncEngineLevel implements SyncEngine {
    /**
     * Holds the instance of a `EnboxPlatformAgent` that represents the current execution context for
     * the `SyncEngineLevel`. This agent is used to interact with other Enbox agent components. It's
     * vital to ensure this instance is set to correctly contextualize operations within the broader
     * Enbox Agent framework.
     */
    private _agent?;
    /**
     * An instance of the `AgentPermissionsApi` that is used to interact with permissions grants used during sync
     */
    private _permissionsApi;
    private _db;
    private _syncIntervalId?;
    private _syncLock;
    /**
     * Hex-encoded default hashes for empty subtrees at each depth, keyed by depth.
     * Lazily initialized on first use. Used by `walkTreeDiff` to detect empty subtrees
     * and short-circuit the recursive walk instead of descending all the way to MAX_DIFF_DEPTH.
     */
    private _defaultHashHex?;
    /** Current sync mode, set by `startSync`. */
    private _syncMode;
    /** Active live pull subscriptions (remote -> local via MessagesSubscribe). */
    private _liveSubscriptions;
    /** Active local EventLog subscriptions for push-on-write (local -> remote). */
    private _localSubscriptions;
    /** Connectivity state derived from subscription health. */
    private _connectivityState;
    /** Debounce timer for batched push-on-write. */
    private _pushDebounceTimer?;
    /** Pending message CIDs to push, accumulated during the debounce window. */
    private _pendingPushCids;
    /** Count of consecutive SMT sync failures (for backoff in poll mode). */
    private _consecutiveFailures;
    /** Maximum consecutive failures before entering backoff. */
    private static readonly MAX_CONSECUTIVE_FAILURES;
    /** Backoff multiplier for consecutive failures (caps at 4x the configured interval). */
    private static readonly MAX_BACKOFF_MULTIPLIER;
    constructor({ agent, dataPath, db }: SyncEngineLevelParams);
    /**
     * Retrieves the `EnboxPlatformAgent` execution context.
     *
     * @returns The `EnboxPlatformAgent` instance that represents the current execution context.
     * @throws Will throw an error if the `agent` instance property is undefined.
     */
    get agent(): EnboxPlatformAgent;
    set agent(agent: EnboxPlatformAgent);
    get connectivityState(): SyncConnectivityState;
    clear(): Promise<void>;
    close(): Promise<void>;
    registerIdentity({ did, options }: {
        did: string;
        options?: SyncIdentityOptions;
    }): Promise<void>;
    unregisterIdentity(did: string): Promise<void>;
    getIdentityOptions(did: string): Promise<SyncIdentityOptions | undefined>;
    updateIdentityOptions({ did, options }: {
        did: string;
        options: SyncIdentityOptions;
    }): Promise<void>;
    sync(direction?: 'push' | 'pull'): Promise<void>;
    startSync(params: StartSyncParams): Promise<void>;
    /**
     * stopSync awaits the completion of the current sync operation before stopping the sync interval
     * and tearing down any live subscriptions.
     */
    stopSync(timeout?: number): Promise<void>;
    private startPollSync;
    /**
     * Starts live sync:
     * 1. Performs an initial SMT reconciliation to catch up.
     * 2. Opens MessagesSubscribe subscriptions to each remote DWN for real-time pull.
     * 3. Subscribes to the local EventLog for push-on-write.
     * 4. Schedules an infrequent SMT integrity check at `interval`.
     */
    private startLiveSync;
    /**
     * Tears down all live subscriptions and push listeners.
     */
    private teardownLiveSync;
    /**
     * Opens a MessagesSubscribe WebSocket subscription to a remote DWN.
     * Incoming events are processed locally as they arrive.
     */
    private openLivePullSubscription;
    /**
     * Subscribes to the local DWN's EventLog so that writes by the user are
     * immediately pushed to the remote DWN instead of waiting for the next poll.
     */
    private openLocalPushSubscription;
    /**
     * Flushes accumulated push CIDs to remote DWNs.
     */
    private flushPendingPushes;
    private buildCursorKey;
    private getCursor;
    private setCursor;
    /**
     * Extracts a ReadableStream from a MessageEvent if it contains a RecordsWrite with data.
     */
    private extractDataStream;
    /**
     * Synchronously attempts to get a message CID. Returns undefined on failure.
     * This is used in the synchronous EventLog callback; the actual CID computation
     * is fast for already-constructed messages.
     */
    private tryGetCidSync;
    /**
     * Returns the hex-encoded default (empty-subtree) hash for a given depth.
     * Lazily initializes the cache on first call.
     */
    private getDefaultHashHex;
    /**
     * Parse a bit prefix string (e.g. "0110101") into a boolean array
     * for the StateIndex API. Each '1' maps to `true` (right child),
     * each '0' maps to `false` (left child).
     */
    private static parseBitPrefix;
    /**
     * Access the local DWN's StateIndex directly, bypassing the `processMessage`
     * pipeline. The sync engine runs in the same process as the local DWN, so
     * there is no need for message signing, schema validation, or authentication
     * when querying our own state.
     *
     * Returns `undefined` in remote mode (no in-process DWN). The local methods
     * fall back to `processRequest` in that case, routing through RPC to the
     * local DWN server.
     */
    private get stateIndex();
    /**
     * Get the SMT root hash from the local DWN.
     *
     * In local mode: queries the StateIndex directly (fast, no processMessage overhead).
     * In remote mode: constructs a signed MessagesSync message and routes through RPC.
     *
     * Returns a hex-encoded root hash string.
     */
    private getLocalRoot;
    /**
     * Get the SMT root hash from a remote DWN via a MessagesSync 'root' action.
     * Returns a hex-encoded root hash string.
     */
    private getRemoteRoot;
    /**
     * Walks the local and remote SMTs in parallel, recursing into subtrees whose
     * hashes differ, until reaching `MAX_DIFF_DEPTH` where leaves are enumerated.
     *
     * Returns the sets of messageCids that exist only locally or only remotely.
     */
    private walkTreeDiff;
    /**
     * Compute the diff between local and remote in a single HTTP round-trip.
     *
     * 1. Walk the local SMT directly (no processMessage) to collect subtree
     *    hashes at `MAX_DIFF_DEPTH`.
     * 2. Send a single `MessagesSync action:'diff'` to the remote with all
     *    non-empty subtree hashes.
     * 3. The remote compares and returns `onlyRemote` (with inline messages)
     *    and `onlyLocal` prefixes.
     * 4. Enumerate local leaves for the `onlyLocal` prefixes directly.
     *
     * This replaces `walkTreeDiff()` which required one HTTP call per tree node.
     */
    private diffWithRemote;
    /**
     * Walk the local SMT to a given depth and collect non-empty subtree hashes.
     * Returns a `{ prefix: hexHash }` map. Empty subtrees (matching the default
     * hash) are omitted.
     *
     * Uses direct StateIndex access in local mode. In remote mode, falls back
     * to `getLocalSubtreeHash` which routes through RPC.
     */
    private collectLocalSubtreeHashes;
    /**
     * Get the subtree hash at a given bit prefix from the local DWN.
     *
     * In local mode: queries the StateIndex directly.
     * In remote mode: constructs a signed MessagesSync message and routes through RPC.
     */
    private getLocalSubtreeHash;
    private getRemoteSubtreeHash;
    /**
     * Get all leaf messageCids under a given prefix from the local DWN.
     *
     * In local mode: queries the StateIndex directly.
     * In remote mode: constructs a signed MessagesSync message and routes through RPC.
     */
    private getLocalLeaves;
    private getRemoteLeaves;
    /**
     * Fetches missing messages from the remote DWN and processes them locally
     * in dependency order (topological sort).
     *
     * When prefetched entries are provided (from the batched diff response),
     * they are processed directly without additional HTTP round-trips.
     * Only `messageCids` that were NOT prefetched are fetched individually.
     */
    private pullMessages;
    /**
     * Reads missing messages from the local DWN and pushes them to the remote DWN
     * in dependency order (topological sort).
     */
    private pushMessages;
    /**
     * Delegate to the standalone `topologicalSort` function.
     * Tests call `SyncEngineLevel.topologicalSort(...)` so this static method must remain.
     */
    static topologicalSort<T extends {
        message: GenericMessage;
    }>(messages: T[]): T[];
    /**
     * Returns the list of sync targets: (did, dwnUrl, delegateDid?, protocol?) tuples.
     */
    private getSyncTargets;
    /**
     * Gets the permission grant ID for MessagesSync if a delegateDid is provided.
     * Returns undefined if no delegate is in use (owner access).
     */
    private getSyncPermissionGrantId;
}
//# sourceMappingURL=sync-engine-level.d.ts.map