import type { DwnConfig, EncryptionKeyDeriver, EventLog, GenericMessage, MessageStore, ProtocolDefinition, ReplicationApplyResult } from '@enbox/dwn-sdk-js';
import { Dwn } from '@enbox/dwn-sdk-js';
import type { EnboxPlatformAgent } from './types/agent.js';
import type { LocalDwnStrategy } from './local-dwn.js';
import type { DwnResponse, ProcessDwnRequest, SendDwnRequest } from './types/dwn.js';
import { DwnInterface } from './types/dwn.js';
export { isDwnMessage, isDwnRequest, isMessagesPermissionScope, isRecordPermissionScope, isRecordsType } from './dwn-type-guards.js';
type DwnApiParams = {
    agent?: EnboxPlatformAgent;
    localDwnStrategy?: LocalDwnStrategy;
} & ({
    dwn: Dwn;
    localDwnEndpoint?: never;
} | {
    dwn?: never;
    localDwnEndpoint: string;
});
type MessageLog = {
    eventLog: EventLog;
    messageStore: MessageStore;
};
type DwnApiCreateDwnParams = Omit<Partial<DwnConfig>, 'eventLog' | 'messageStore'> & {
    dataPath?: string;
    /**
     * Inject a platform-specific message store together with its durable event log.
     * They are coupled because the event log reads the store's replication feed and must
     * share its wake publisher, so they are provided as a pair or omitted for defaults.
     */
    messageLog?: MessageLog;
};
export declare class AgentDwnApi {
    /**
     * Holds the instance of a `EnboxPlatformAgent` that represents the current execution context for
     * the `AgentDwnApi`. 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?;
    /**
     * The DWN instance to use for this API.
     * `undefined` in remote mode — all operations route through RPC to
     * the local DWN server endpoint.
     */
    private readonly _dwn?;
    /**
     * The local DWN server endpoint for remote mode.
     * When set, `_dwn` is `undefined` and `processRequest()` routes
     * through `sendDwnRpcRequest()`.
     */
    private readonly _localDwnEndpoint?;
    /**
     * Protocol definition cache — TTL 30 minutes. Protocols rarely change.
     * Keyed by `${tenantDid}~${protocolUri}`.
     */
    private readonly _protocolDefinitionCache;
    /**
     * Delegate decryption key cache — stores scope-aware decryption keys
     * delivered to delegates during the connect flow. These keys enable
     * delegates to decrypt encrypted records without possessing the owner's
     * root X25519 private key.
     *
     * Keyed by `ddk~${delegateDid}`. Each entry is an array covering all
     * granted read scopes for that delegate session.
     * TTL 24 hours (keys are re-populated on session restore).
     */
    private readonly _delegateDecryptionKeyCache;
    /**
     * Role-audience private keys hydrated from durable audience seals or delivery records.
     * This is a memory-only session cache; the records remain the durable source of truth.
     */
    private readonly _audienceDecryptionKeyCache;
    /**
     * Cache of locally-managed DIDs (agent DID + identities). Used to decide
     * whether a target DID should be routed through the local DWN server.
     */
    private readonly _localManagedDidCache;
    /** Controls local DWN discovery behavior ('prefer' | 'only' | 'off'). */
    private _localDwnStrategy;
    /** Lazy-initialized local DWN discovery instance. */
    private _localDwnDiscovery?;
    constructor(params: DwnApiParams);
    /**
     * Whether the API is operating in remote mode (no in-process DWN).
     * In remote mode, all DWN operations are routed through RPC.
     */
    get isRemoteMode(): boolean;
    /**
     * 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 localDwnStrategy(): LocalDwnStrategy;
    setLocalDwnStrategy(strategy: LocalDwnStrategy): void;
    /**
     * Inject a cached local DWN endpoint (e.g. from a `dwn://connect`
     * browser redirect or from persisted storage). The endpoint is validated
     * via `GET /info` before being accepted.
     *
     * @param endpoint - The local DWN server base URL.
     * @returns `true` if the endpoint was validated and cached, `false` otherwise.
     * @see https://github.com/enboxorg/enbox/issues/589
     */
    setCachedLocalDwnEndpoint(endpoint: string): Promise<boolean>;
    /**
     * Resolves the DWN service endpoint URLs for the given target DID, optionally
     * prepending a local DWN server endpoint when local discovery is enabled and
     * the target is a locally-managed DID.
     *
     * @param targetDid - The DID whose DWN endpoints should be resolved.
     * @returns An array of endpoint URLs.
     * @throws When strategy is `'only'` and no local server is available.
     */
    getDwnEndpointUrlsForTarget(targetDid: string): Promise<string[]>;
    /**
     * Returns only the DWN service endpoints from the DID document (no local
     * discovery endpoint). Use this when you need to confirm that a message
     * reached the owner's actual remote DWN, not just the delegate's local server.
     */
    getRemoteDwnEndpointUrls(targetDid: string): Promise<string[]>;
    /** Lazily retrieves the local DWN server endpoint via discovery. */
    private getLocalDwnEndpoint;
    /**
     * Attempt to create a {@link DwnDiscoveryFile} for file-based local DWN
     * discovery. Returns `undefined` in environments where the filesystem
     * is not available (e.g. browsers).
     */
    private static _tryCreateDiscoveryFile;
    /**
     * Determines whether the given target DID should be routed through the
     * local DWN server. Returns `true` if the DID is the agent DID or one
     * of the locally-managed identity DIDs.
     */
    private shouldUseLocalDwnForTarget;
    /**
     * Public getter for the DWN instance used by this API.
     *
     * Notes:
     * - This getter is public to allow advanced developers to access the DWN instance directly.
     *   However, it is recommended to use the `processRequest` method to interact with the DWN
     *   instance to ensure that the DWN message is constructed correctly.
     * - The getter is named `node` to avoid confusion with the `dwn` property of the
     *   `EnboxPlatformAgent`. In other words, so that a developer can call `agent.dwn.node` to access
     *   the DWN instance and not `agent.dwn.dwn`.
     */
    get node(): Dwn;
    static createDwn({ dataPath, dataStore, didResolver, messageLog, tenantGate, resumableTaskStore }: DwnApiCreateDwnParams): Promise<Dwn>;
    private static createDefaultMessageLog;
    processRequest<T extends DwnInterface>(request: ProcessDwnRequest<T>): Promise<DwnResponse<T>>;
    /**
     * Process a pre-constructed DWN message against the local DWN (in-process
     * or remote server). Used by the sync engine to store messages that were
     * already fetched from a remote DWN.
     *
     * Unlike {@link processRequest}, this method does NOT construct a new
     * message — it takes an already-signed `GenericMessage` and routes it
     * to the appropriate backend.
     *
     * @param tenant - The DID of the DWN tenant (target).
     * @param message - The pre-constructed DWN message.
     * @param options - Optional data stream and subscription handler.
     * @returns The reply from processing the message.
     */
    processRawMessage(tenant: string, message: GenericMessage, options?: {
        dataStream?: ReadableStream<Uint8Array>;
    }): Promise<{
        status: {
            code: number;
            detail: string;
        };
    }>;
    /**
     * Applies a replicated message to the local DWN and returns a structured sync
     * outcome. In-process DWNs call the native entry point directly. Local DWN
     * server mode calls the server's matching replication RPC so duplicate replay
     * and replication-index repair stay server-side instead of falling back to the
     * normal authoring path.
     */
    applyReplicatedMessage(tenant: string, message: GenericMessage, options?: {
        dataStream?: ReadableStream<Uint8Array>;
    }): Promise<ReplicationApplyResult>;
    sendRequest<T extends DwnInterface>(request: SendDwnRequest<T>): Promise<DwnResponse<T>>;
    private sendDwnRpcRequest;
    private provisionAudienceKeyForAcceptedRoleRecord;
    private getRoleAudienceKeyEncryptionInputs;
    private canPreparePendingAudienceRecord;
    private preparePendingAudienceRecord;
    private resolveRoleAudienceRule;
    private getRoleAudienceSourceContextId;
    private getOrCreateAudiencePublicKey;
    private getOrCreateAudienceKey;
    private assertAudienceSealCoverage;
    private resolveCurrentAudienceRecord;
    private readAudiencePayload;
    private processRequestWithRemoteFallback;
    private getRecipientRolePublicKey;
    private buildPendingAudienceRecordDescriptor;
    private constructDwnMessage;
    private populateDelegatedGrantForWrite;
    private hasGrantParams;
    private getSigner;
    /**
     * Constructs an EncryptionKeyDeriver callback for the SDK.
     * Delegates to the standalone function in `dwn-encryption.ts`.
     *
     * @param didUri - The DID URI to create the key deriver for
     * @returns An EncryptionKeyDeriver callback object
     */
    getEncryptionKeyDeriver(didUri: string): Promise<EncryptionKeyDeriver>;
    /**
     * Resolves the keyAgreement verification method for the given DID and returns
     * the key ID, key URI, and public key JWK.
     *
     * @param didUri - The DID URI to look up
     */
    private getEncryptionKeyInfo;
    /**
     * Constructs a ProtocolPath KeyDecrypter for the given DID.
     *
     * @param didUri - The DID URI to build a decrypter for
     */
    private getKeyDecrypter;
    /**
     * Analyses a record write to determine which DIDs join the readable audience.
     *
     * @param params - Parameters for participant detection
     * @returns Set of DIDs that join the readable audience
     */
    detectNewParticipants(params: {
        protocolDefinition: ProtocolDefinition;
        protocolPath: string;
        recipient?: string;
        tenantDid: string;
        authorDid?: string;
    }): Set<string>;
    /**
     * Fetches a protocol definition from the local DWN, with caching.
     * Returns undefined if the protocol is not installed.
     *
     * @param tenantDid - The tenant DID to query
     * @param protocolUri - The protocol URI to fetch
     * @returns The protocol definition, or undefined if not found
     */
    private getProtocolDefinition;
    /**
     * Fetches a protocol definition from a remote DWN.
     * Uses an unsigned ProtocolsQuery (public protocols can be queried anonymously).
     */
    private fetchRemoteProtocolDefinition;
    /**
     * Post-processes a DWN reply, auto-decrypting data if encryption is enabled.
     * Delegates to the standalone function in `dwn-encryption.ts`.
     */
    private maybeDecryptReply;
    private getDwnMessage;
    /**
     * Clears delegate decryption keys from the in-memory cache.
     *
     * @param delegateDid - If provided, clears keys for that delegate session only.
     *                      If omitted, clears all delegate keys.
     */
    clearDelegateDecryptionKeys(delegateDid?: string): void;
}
//# sourceMappingURL=dwn-api.d.ts.map