import type { Result } from '@private.me/shared';
import { EventEmitter } from 'node:events';
import type { AgentIdentity } from './identity.js';
import { generateSharedKey } from './envelope.js';
import type { TransportEnvelopeV4, AnyTransportEnvelope } from './envelope.js';
import type { NonceStore } from './nonce-store.js';
import type { SplitChannelConfig } from './split-channel.js';
import type { XailTransportAdapter, TransportError } from './transport.js';
import type { TrustRegistry, TrustEvent } from './trust-registry.js';
import type { ProgressCallback } from '@private.me/ux-helpers';
import type { SecurityPolicy, SecurityLevel, SecurityDecision } from './security-policy.js';
/**
 * Simplified options for Agent constructor (agent-first API).
 *
 * For full control, use Agent.create() with AgentCreateOptions.
 */
export interface AgentOptions {
    /**
     * Identity mode:
     * - 'persistent': Long-lived DID, registered with trust registry
     * - 'ephemeral': Short-lived DID, auto-cleanup after TTL expires
     */
    readonly identity?: 'persistent' | 'ephemeral';
    /**
     * Time-to-live for ephemeral identities (milliseconds).
     *
     * After this duration, the identity is auto-deregistered and cleaned up.
     * Only applies when identity === 'ephemeral'.
     *
     * Default: 3600000 (1 hour)
     */
    readonly identityTTL?: number;
    /**
     * Trust registry (instance or URL for HttpTrustRegistry).
     *
     * Optional for ephemeral identities (uses MemoryTrustRegistry by default).
     * Required for persistent identities.
     */
    readonly registry?: TrustRegistry | string;
    /**
     * Transport adapter(s) for envelope delivery.
     *
     * Optional - uses HttpsTransportAdapter by default.
     */
    readonly transport?: XailTransportAdapter | XailTransportAdapter[];
    /**
     * Security policy for automatic risk-based Xorida activation.
     *
     * Uses DefaultSecurityPolicy if omitted.
     */
    readonly securityPolicy?: SecurityPolicy;
    /**
     * Enable post-quantum signatures (ML-DSA-65).
     *
     * Default: false
     */
    readonly postQuantumSig?: boolean;
    /**
     * XorIDA backup configuration for key splitting.
     *
     * Uses DEFAULT_BACKUP_CONFIG (k=2, n=3) if omitted.
     */
    readonly backupConfig?: import('./backup-config.js').BackupConfig;
}
/** Options for Agent.create() (full-featured API). */
export interface AgentCreateOptions {
    /** Display name for the agent. */
    readonly name: string;
    /** Trust registry (instance or URL for HttpTrustRegistry). */
    readonly registry: TrustRegistry;
    /**
     * Transport adapter(s) for envelope delivery.
     *
     * For split-channel security, provide one transport per share channel.
     * Each share routes to transports[shareIndex % transports.length].
     * With a single transport, all shares travel the same channel —
     * data is split but channel separation is not achieved.
     */
    readonly transport: XailTransportAdapter | XailTransportAdapter[];
    /** NonceStore for replay prevention. Uses MemoryNonceStore if omitted. */
    readonly nonceStore?: NonceStore;
    /** Scopes this agent requests. */
    readonly scopes?: string[];
    /** Timestamp validity window in ms. Default 30 000 (30 s). */
    readonly timestampWindowMs?: number;
    /** Enable ML-DSA-65 post-quantum signatures (v3 envelopes). Default: false. */
    readonly postQuantumSig?: boolean;
    /** Advertise Xchange mode support. Default: false. When true, peers MAY send Xchange envelopes (faster, single security layer). */
    readonly xchange?: boolean;
    /**
     * Security policy for automatic risk-based Xorida activation.
     *
     * Uses DefaultSecurityPolicy if omitted. Enterprise users can provide
     * EnterpriseSecurityPolicy with custom rules.
     */
    readonly securityPolicy?: SecurityPolicy;
}
/** Options for agent.send(). */
export interface AgentSendOptions {
    /** Recipient DID. */
    readonly to: string;
    /** Payload (serialized to JSON). */
    readonly payload: unknown;
    /** Permission scope. */
    readonly scope: string;
    /**
     * Action being performed (e.g., 'transfer', 'execute', 'send').
     *
     * Used by security policy to determine when to auto-apply XorIDA split-channel.
     * If omitted, defaults to 'send'.
     */
    readonly action?: string;
    /**
     * Security level override.
     *
     * - 'auto' (default): Let security policy decide based on action + params
     * - 'standard': Force standard encrypted transport (disable auto-upgrade)
     * - 'high': Force multi-party approval (3 shares, 2-of-3 threshold)
     * - 'critical': Force critical security (5 shares, 3-of-5 threshold)
     *
     * Most users should use 'auto' and let the system decide.
     */
    readonly security?: SecurityLevel;
    /**
     * Enable XorIDA split-channel.
     *
     * @deprecated Use `security: 'high'` instead. This field is maintained for
     * backward compatibility but will be removed in v3.0.
     */
    readonly splitChannel?: boolean;
    /**
     * Split-channel configuration (totalShares, threshold).
     *
     * @deprecated Security policy now determines share configuration automatically.
     * This field is maintained for backward compatibility but will be removed in v3.0.
     */
    readonly splitChannelConfig?: SplitChannelConfig;
    /**
     * Use Xchange mode (faster, single security layer instead of three).
     *
     * @deprecated Set `payload.xchange: true` instead. The security policy will
     * detect this and apply Xchange mode automatically.
     */
    readonly xchange?: boolean;
    /** Optional progress callback for long-running operations. */
    readonly onProgress?: ProgressCallback;
}
/** Verified message from receive/middleware. */
export interface AgentMessage {
    readonly sender: string;
    readonly payload: unknown;
    readonly scope: string;
    readonly timestamp: number;
    /** Protocol metadata for viral exposure */
    readonly metadata?: {
        readonly protocol: string;
        readonly documentationUrl: string;
    };
}
/** Options for agent.receive(). */
export interface AgentReceiveOptions {
    /**
     * When true, accept signed-but-unencrypted envelopes as cleartext.
     *
     * If decryption fails, the payload is parsed as plaintext JSON instead
     * of returning a decryption error. Useful for IoT gateways that accept
     * both encrypted and signed-only telemetry.
     */
    readonly allowCleartext?: boolean;
    /** Optional progress callback for long-running operations. */
    readonly onProgress?: ProgressCallback;
}
/** Parsed error detail with step context. */
export interface AgentErrorDetail {
    /** Base error code (e.g. 'TIMESTAMP_EXPIRED'). */
    readonly code: string;
    /** Sub-code if present (e.g. 'DECRYPTION' from 'DECRYPT_FAILED:DECRYPTION'). */
    readonly subCode?: string;
    /** Human-readable diagnostic detail from the verification step. */
    readonly step?: string;
}
/**
 * Parse an AgentError string into structured detail.
 *
 * Splits colon-separated error codes into base code and sub-code.
 *
 * @param error - An AgentError string (e.g. 'DECRYPT_FAILED:KEY_AGREEMENT').
 * @returns Parsed error detail.
 */
export declare function parseAgentError(error: string): AgentErrorDetail;
/** Agent-level error codes. Sub-codes give precise failure context. */
export type AgentError = TransportError | 'IDENTITY_FAILED' | 'IDENTITY_FAILED:KEYGEN' | 'IDENTITY_FAILED:VAULT_STORE' | 'REGISTRATION_FAILED' | 'REGISTRATION_FAILED:ALREADY_REGISTERED' | 'REGISTRATION_FAILED:NETWORK_ERROR' | 'RECIPIENT_NOT_FOUND' | 'RECIPIENT_REVOKED' | 'KEY_AGREEMENT_FAILED' | 'KEY_AGREEMENT_FAILED:RECIPIENT_HAS_NO_X25519_KEY' | 'ENVELOPE_FAILED' | 'ENVELOPE_FAILED:ENCRYPT' | 'ENVELOPE_FAILED:SIGN' | 'ENVELOPE_FAILED:SPLIT' | 'VERIFICATION_FAILED' | 'VERIFICATION_FAILED:UNSUPPORTED_VERSION' | 'VERIFICATION_FAILED:DID_NOT_IN_REGISTRY' | 'VERIFICATION_FAILED:KEY_IMPORT_FAILED' | 'VERIFICATION_FAILED:SIGNATURE_MISMATCH' | 'VERIFICATION_FAILED:PQ_KEY_MISSING' | 'VERIFICATION_FAILED:PQ_SIGNATURE_MISMATCH' | 'ENVELOPE_FAILED:PQ_KEY_MISSING' | 'REPLAY_DETECTED' | 'SCOPE_DENIED' | 'RECEIVER_SCOPE_DENIED' | 'TIMESTAMP_EXPIRED' | 'DECRYPT_FAILED' | 'DECRYPT_FAILED:KEY_AGREEMENT' | 'DECRYPT_FAILED:NO_EPHEMERAL_KEY' | 'DECRYPT_FAILED:DECRYPTION' | 'DECRYPT_FAILED:PARSE' | 'SEND_FAILED:BELOW_THRESHOLD' | 'QUOTA_EXCEEDED';
/**
 * Top-level Xail Agent SDK API.
 *
 * Provides cryptographically secure agent-to-agent messaging with:
 * - Ed25519 digital signatures
 * - X25519 ECDH forward secrecy
 * - ML-KEM-768 post-quantum encryption
 * - ML-DSA-65 post-quantum signatures (opt-in)
 * - XorIDA information-theoretic split-channel delivery
 *
 * @example Basic Agent Usage
 * ```typescript
 * import { Agent } from '@private.me/xbind';
 *
 * // Create an agent with auto-generated identity
 * const alice = await Agent.create({
 *   name: 'alice',
 *   registry: 'https://private.me/registry'
 * });
 * if (!alice.ok) throw new Error(alice.error);
 *
 * const bob = await Agent.create({
 *   name: 'bob',
 *   registry: 'https://private.me/registry'
 * });
 * if (!bob.ok) throw new Error(bob.error);
 *
 * // Send encrypted message
 * const result = await alice.value.send({
 *   to: bob.value.identity.did,
 *   payload: { message: 'Hello, Bob!' },
 *   scope: ['read:profile']
 * });
 *
 * // Receive and decrypt message
 * if (result.ok && result.value.envelope) {
 *   const message = await bob.value.receive(result.value.envelope);
 *   if (message.ok) {
 *     console.log('Received:', message.value.payload);
 *   }
 * }
 * ```
 *
 * @example Using Existing Identity
 * ```typescript
 * import { Agent, identityFromSeed } from '@private.me/xbind';
 *
 * // Restore identity from seed
 * const seed = process.env.XBIND_SEED;
 * const identity = await identityFromSeed(seed);
 * if (!identity.ok) throw new Error(identity.error);
 *
 * // Create agent from existing identity
 * const agent = new Agent(identity.value, {
 *   name: 'my-agent',
 *   registry: 'https://private.me/registry'
 * });
 * ```
 */
export declare class Agent extends EventEmitter {
    readonly identity: AgentIdentity;
    readonly name: string;
    private readonly registry;
    private readonly transports;
    private readonly nonceStore;
    private readonly timestampWindowMs;
    private readonly securityPolicy;
    private readonly backupConfig;
    /** Accumulates split-channel shares by groupId until threshold is met. */
    private readonly shareAccumulator;
    /** Diagnostic detail from the last failed verification step. */
    private lastDetail;
    /** Last security decision made by the policy (for debugging/logging). */
    private lastSecurityDecision?;
    /** Timer for ephemeral agent auto-cleanup. */
    private cleanupTimer?;
    /** Crypto package (XorIDA algorithms) loaded from Vault Store. */
    private cryptoModule;
    /**
     * Human-readable diagnostic from the last failed receive/verify call.
     *
     * Populated during verification with context like age vs max window.
     * Empty string if no error has occurred or after a successful call.
     */
    get lastErrorDetail(): string;
    /**
     * Last security decision made by the security policy.
     *
     * Shows which security mode was selected and why. Useful for debugging
     * and understanding when/why Xorida split-channel was activated.
     *
     * Returns undefined if no send() has been called yet.
     */
    get lastSecurity(): SecurityDecision | undefined;
    private constructor();
    /** The agent's DID. */
    get did(): string;
    /** The agent's trust registry. */
    get trustRegistry(): TrustRegistry;
    /**
     * Get the agent's transport adapters.
     * @internal Used by MessageStream for envelope handling.
     */
    getTransports(): XailTransportAdapter[];
    /**
     * Ensure crypto package is loaded from Vault Store.
     *
     * Loads XorIDA algorithms with:
     * - DID-based authentication
     * - Usage quota verification (Free: 100K/month, Pro: unlimited)
     * - 7-day memory cache
     *
     * @returns Crypto package or throws QuotaExceededError/VaultStoreError
     * @throws {QuotaExceededError} If Free tier quota exceeded (>120K hard cap)
     * @throws {VaultStoreError} If vault fetch/load fails
     * @private
     */
    private ensureCrypto;
    /**
     * Check whether the runtime supports the SDK's crypto requirements.
     *
     * Verifies that `crypto.subtle` is available and supports Ed25519 +
     * AES-256-GCM. Call this before lazy-loading the SDK in middleware
     * to avoid failing on the first `Agent.create()` call.
     *
     * @returns `true` if the runtime has the required Web Crypto APIs.
     */
    static isSupported(): boolean;
    /**
     * Create an Agent from a persisted identity (skips keygen + registration).
     *
     * Use this with importFromPKCS8 or importIdentity to restore a
     * previously created agent across process restarts.
     *
     * @param identity - A previously exported AgentIdentity.
     * @param opts - Agent options (registry, transport, etc.).
     * @returns Agent instance or error.
     */
    static fromIdentity(identity: AgentIdentity, opts: Omit<AgentCreateOptions, 'name'> & {
        name?: string;
        backupConfig?: import('./backup-config.js').BackupConfig;
    }): Promise<Result<Agent, AgentError>>;
    /**
     * Build an Agent from pre-constructed parts (synchronous).
     *
     * Unlike `create()` this does NOT generate keys or register with the
     * registry — the caller is responsible for both.  Useful when identity
     * is provisioned in a factory step, registration is handled by an
     * external system, or transport is wired up at runtime.
     *
     * @param identity  - A previously generated or imported AgentIdentity.
     * @param registry  - Trust registry the agent will query for peers.
     * @param transport - Transport adapter for envelope delivery.
     * @param opts      - Optional overrides (name, nonceStore, timestampWindowMs).
     * @returns A fully wired Agent instance.
     */
    static fromParts(identity: AgentIdentity, registry: TrustRegistry, transport: XailTransportAdapter | XailTransportAdapter[], opts?: {
        name?: string;
        nonceStore?: NonceStore;
        timestampWindowMs?: number;
        securityPolicy?: SecurityPolicy;
        backupConfig?: import('./backup-config.js').BackupConfig;
    }): Agent;
    /**
     * Create an Agent from a deterministic 32-byte seed.
     *
     * Uses HKDF-SHA256 to derive Ed25519 + X25519 keys from the seed.
     * The same seed always produces the same DID and keys.
     *
     * **Just-in-Time Registration (JITR):** Automatically registers identity
     * with the trust registry on first use. Follows industry standards (AWS IoT
     * JITR, OAuth DCR, MCP 2025 spec) for zero-config onboarding. Idempotent:
     * safe to call multiple times (ignores ALREADY_REGISTERED errors).
     *
     * Ideal for IoT, servers, AI agents: zero-config deployment with automatic
     * registration on first connection.
     *
     * @param seed - Exactly 32 bytes of high-entropy key material.
     * @param opts - Agent options (registry, transport, scopes, etc.).
     * @returns Agent instance or error.
     */
    static fromSeed(seed: Uint8Array, opts: Omit<AgentCreateOptions, 'name'> & {
        name?: string;
        backupConfig?: import('./backup-config.js').BackupConfig;
    }): Promise<Result<Agent, AgentError>>;
    /**
     * Create a lazy agent that initializes on first use (zero-click onboarding).
     *
     * Defers invite acceptance and identity generation until first send/receive.
     * Reads invite code from XBIND_INVITE_CODE environment variable.
     * Auto-accepts invite and configures registry/transport automatically.
     *
     * @param config - Lazy agent configuration (name required).
     * @returns Lazy agent wrapper (synchronous).
     *
     * @example
     * ```ts
     * // Environment: XBIND_INVITE_CODE=XBD-abc123, XBIND_AUTO_ACCEPT=true
     *
     * // Synchronous construction (no await):
     * const agent = Agent.lazy({ name: 'my-service' });
     *
     * // Auto-accept happens on first send/receive:
     * await agent.send({
     *   to: 'did:key:z6Mk...',
     *   payload: { action: 'test' },
     *   scope: 'test',
     * });
     * ```
     */
    static lazy(config: {
        name: string;
        inviteCode?: string;
        endpoint?: string;
        postQuantumSig?: boolean;
        xchange?: boolean;
    }): Promise<import('./lazy-init.js').LazyAgent>;
    /**
     * Check whether this agent is fully initialized and ready to send/receive.
     *
     * Returns `true` if identity, registry, and transport are all present.
     * Construction always produces a ready agent (invalid inputs cause the
     * factory to return an error instead), so this is primarily useful in
     * middleware that lazily initializes agents and needs a guard.
     *
     * @returns `true` if the agent can send and receive messages.
     */
    isReady(): boolean;
    /** Create a new agent, generate identity, register with trust registry. */
    static create(opts: AgentCreateOptions): Promise<Result<Agent, AgentError>>;
    /**
     * Quickstart: create an agent with zero configuration.
     *
     * Creates an ephemeral agent with auto-cleanup after 1 hour. No policy
     * restrictions by default (allow all operations). Ideal for getting
     * started, prototyping, and simple use cases.
     *
     * Uses in-memory registry and default transport. Identity auto-expires
     * and is deregistered after TTL.
     *
     * @param opts - Optional configuration
     * @returns Agent instance (throws on error for simpler API)
     *
     * @example
     * ```ts
     * // Zero config (ephemeral identity, 1-hour TTL):
     * const agent = await Agent.quickstart();
     *
     * // With custom name:
     * const agent = await Agent.quickstart({ name: 'my-service' });
     *
     * // Multi-agent with shared registry:
     * const registry = new MemoryTrustRegistry();
     * const transport = new LoopbackTransport();
     * const alice = await Agent.quickstart({ name: 'alice', registry, transport });
     * const bob = await Agent.quickstart({ name: 'bob', registry, transport });
     * // Alice and Bob can now communicate (shared registry)
     *
     * // Agent is ready to use immediately:
     * await agent.send({
     *   to: 'did:key:z6Mk...',
     *   payload: { action: 'test' },
     *   scope: 'test',
     * });
     * ```
     */
    static quickstart(opts?: {
        /** Agent name (default: auto-generated) */
        name?: string;
        /** Enable post-quantum signatures (ML-DSA-65) */
        postQuantumSig?: boolean;
        /** Trust registry (default: new MemoryTrustRegistry()) */
        registry?: TrustRegistry;
        /** Transport (default: new HttpsTransportAdapter()) */
        transport?: XailTransportAdapter;
        /** Relay URL (alternative to transport, default: https://private.me/relay) */
        relayUrl?: string;
    }): Promise<Agent>;
    /**
     * Create agent from simplified options (async factory).
     *
     * This is the async-safe way to construct agents with AgentOptions.
     *
     * @param options - Agent configuration
     * @returns Agent instance
     *
     * @example
     * ```typescript
     * import { Agent } from '@private.me/xbind';
     *
     * // Ephemeral agent (auto-cleanup after 1 hour)
     * const agent = await Agent.from({
     *   identity: 'ephemeral',
     *   identityTTL: 3600, // seconds
     * });
     *
     * // Use the agent
     * await agent.send({ to, payload, scope: 'read' });
     * ```
     */
    static from(options?: AgentOptions): Promise<Agent>;
    /** Send a message to a recipient. */
    send(opts: AgentSendOptions): Promise<Result<void, AgentError>>;
    /** Internal send implementation (without event emission). */
    private _sendInternal;
    /**
     * Verify and decrypt an incoming encrypted envelope (v1 or v2).
     *
     * ROT-1: Supports key rotation with fallback to old keys.
     * If decryption fails with current keys, tries old rotated keys.
     *
     * @param envelope - Incoming transport envelope.
     * @param opts - Optional receive options (e.g. allowCleartext).
     */
    receive(envelope: AnyTransportEnvelope, opts?: AgentReceiveOptions): Promise<Result<AgentMessage, AgentError>>;
    /** Internal receive implementation (without event emission). */
    private _receiveInternal;
    /**
     * Verify only the signature on an envelope without consuming the nonce.
     *
     * Does NOT check timestamp, nonce, or scope. Use this for pre-screening
     * or audit logging where you need to confirm the sender but don't want
     * to consume replay-prevention state.
     *
     * @param envelope - The envelope to verify.
     * @returns `{ sender, valid }` or error if the DID cannot be resolved.
     */
    verifySignature(envelope: AnyTransportEnvelope): Promise<Result<{
        sender: string;
        valid: boolean;
    }, AgentError>>;
    /**
     * Export the raw 32-byte private key seeds for both Ed25519 and X25519.
     *
     * These are the raw private key bytes extracted from PKCS8, NOT the
     * original HKDF seed (that derivation is one-way). Use these for
     * persistence or cross-device transfer.
     *
     * @returns Two 32-byte Uint8Arrays or error.
     */
    exportSeeds(): Promise<Result<{
        ed25519: Uint8Array;
        x25519: Uint8Array;
        mlKemSecretKey?: Uint8Array;
        mlKemPublicKey?: Uint8Array;
    }, AgentError>>;
    /**
     * Split a cryptographic key into backup shares using XorIDA.
     *
     * Uses the agent's backup configuration (default: k=2, n=3).
     * Any `threshold` shares can reconstruct the original key.
     * Each share reveals zero information (information-theoretic security).
     *
     * @param key - The key to split (32 or 64 bytes typical).
     * @returns Array of backup shares or error.
     *
     * @example
     * ```typescript
     * // Generate a key and split it
     * const key = crypto.getRandomValues(new Uint8Array(32));
     * const shares = await agent.splitKey(key);
     *
     * if (shares.ok) {
     *   // Store shares in separate locations
     *   shares.value.forEach((share, i) => {
     *     storeShare(`backup-${i}.json`, JSON.stringify(share));
     *   });
     * }
     * ```
     */
    splitKey(key: Uint8Array): Promise<Result<import('./backup-config.js').BackupShare[], AgentError>>;
    /**
     * Reconstruct a cryptographic key from backup shares.
     *
     * Requires at least `threshold` shares. Verifies HMAC before returning
     * the reconstructed key to prevent tampering.
     *
     * @param shares - Backup shares (must be >= threshold).
     * @returns Reconstructed key or error.
     *
     * @example
     * ```typescript
     * // Load shares from storage
     * const share0 = JSON.parse(loadShare('backup-0.json'));
     * const share1 = JSON.parse(loadShare('backup-1.json'));
     *
     * // Reconstruct from any 2 shares (threshold=2)
     * const key = await agent.reconstructKey([share0, share1]);
     *
     * if (key.ok) {
     *   // Use reconstructed key
     *   console.log('Key recovered:', key.value);
     * }
     * ```
     */
    reconstructKey(shares: import('./backup-config.js').BackupShare[]): Promise<Result<Uint8Array, AgentError>>;
    /**
     * Verify a signed (unencrypted) envelope and return the message.
     *
     * Use for envelopes created with createSignedEnvelope().
     * Verifies signature, timestamp, nonce, and scope — skips decryption.
     *
     * @param envelope - A signed (unencrypted) transport envelope.
     * @returns Verified message or error with sub-code.
     */
    receiveSigned(envelope: AnyTransportEnvelope): Promise<Result<AgentMessage, AgentError>>;
    /**
     * Discover available tools in the registry.
     *
     * Query xRegistry for tools matching the given service prefix or capability.
     * Returns tool metadata including name, description, schema, and trust level.
     *
     * @param service - Optional service prefix to filter by (e.g., "payments")
     * @returns Array of tool metadata or empty array if none found
     *
     * @example
     * ```typescript
     * import { Agent } from '@private.me/xbind';
     * import { ToolRegistry } from '@private.me/xregistry';
     * import { setToolRegistry } from '@private.me/xbind/agent-call';
     *
     * const registry = new ToolRegistry();
     * registry.register({
     *   name: 'payments:createCharge',
     *   description: 'Create a payment charge',
     *   schema: { type: 'object', properties: { amount: { type: 'number' } } },
     *   trustLevel: 'verified',
     *   endpoint: 'https://api.stripe.com/v1/charges',
     *   capabilities: ['payment', 'charge']
     * });
     *
     * setToolRegistry(registry);
     *
     * const agent = await Agent.quickstart();
     *
     * // Discover all payment tools
     * const tools = await agent.discover('payments');
     * console.log(tools); // [{ name: 'payments:createCharge', ... }]
     *
     * // Discover all tools
     * const allTools = await agent.discover();
     * ```
     */
    discover(service?: string): Promise<readonly import('@private.me/xregistry').ToolMetadata[]>;
    /**
     * Revoke this agent's DID in the trust registry.
     *
     * Once revoked, the DID can no longer be resolved and all future messages
     * will be rejected. This operation is irreversible.
     *
     * Requires proof-of-possession: the registry validates ownership using the
     * access token received during registration.
     *
     * @returns Result indicating success or error
     *
     * @example
     * ```typescript
     * const agent = await Agent.create({ ... });
     * const result = await agent.revoke();
     * if (!result.ok) {
     *   console.error('Revocation failed:', result.error);
     * }
     * ```
     */
    revoke(): Promise<Result<void, string>>;
    /**
     * Subscribe to trust events (revocations, key rotations) from the registry.
     *
     * Wraps the registry's subscribe() method and provides a callback for trust events.
     *
     * @param callback - Function called when trust events occur
     * @returns Unsubscribe function to stop watching
     *
     * @example
     * ```typescript
     * const unsubscribe = agent.subscribeTrustEvents((event) => {
     *   if (event.type === 'revocation') {
     *     console.log(`DID revoked: ${event.did}`);
     *   } else if (event.type === 'succession') {
     *     console.log(`Key rotated: ${event.did}`);
     *   }
     * });
     *
     * // Later, stop watching
     * unsubscribe();
     * ```
     */
    subscribeTrustEvents(callback: (event: TrustEvent) => void): () => void;
    /**
     * Rotate agent DID (key rotation with succession proof).
     *
     * Creates a new identity, generates succession announcement with dual signatures,
     * registers the new identity, and updates the agent's current identity.
     *
     * @param opts - Optional reason for rotation
     * @returns Result with void on success or error
     *
     * @example
     * ```typescript
     * const agent = await Agent.create({ ... });
     * const result = await agent.rotateDid({ reason: 'scheduled rotation' });
     * if (!result.ok) {
     *   console.error('Rotation failed:', result.error);
     * }
     * ```
     */
    rotateDid(_opts?: {
        reason?: string;
    }): Promise<Result<void, AgentError>>;
    /**
     * Verify a message receipt signature.
     *
     * Note: Receipt functionality is planned but not yet implemented.
     * This method validates a receipt's cryptographic signature.
     *
     * @param receipt - Receipt object with signature
     * @returns Result with true if valid, false otherwise
     *
     * @example
     * ```typescript
     * const result = await agent.verifyReceipt(receipt);
     * if (result.ok && result.value) {
     *   console.log('Receipt is valid');
     * }
     * ```
     */
    verifyReceipt(receipt: {
        senderDid: string;
        signature: string;
        payload: string;
    }): Promise<Result<boolean, AgentError>>;
    /** Generate an Express-compatible middleware handler. */
    middleware(): (req: {
        body?: unknown;
    }, res: {
        status: (code: number) => {
            json: (data: unknown) => void;
        };
    }, next: (err?: unknown) => void) => Promise<void>;
    /**
     * Cleanup resources (timers, handlers, etc.)
     *
     * Call this in tests or when disposing an agent to prevent timer leaks.
     * Clears the ephemeral identity auto-cleanup timer if present.
     */
    cleanup(): void;
    /**
     * Dispose of agent resources (alias for cleanup)
     *
     * Provided for compatibility with test cleanup patterns.
     */
    dispose(): void;
    /**
     * Attempt sender-side key agreement.
     *
     * If both sides support ML-KEM-768, uses hybrid (X25519 + ML-KEM-768).
     * Otherwise falls back to X25519-only ECDH.
     * Returns null if recipient has no X25519 key registered.
     * Also returns whether recipient supports ML-DSA-65 for v3 envelopes.
     */
    private trySenderECDH;
    /** Send with ECDH forward secrecy (ephemeral key in envelope). */
    private sendWithECDH;
    /** Send with hybrid KEM (X25519 + ML-KEM-768) via v2 envelope. */
    private sendWithHybrid;
    /** Send with hybrid KEM + dual signatures via v3 envelope. */
    private sendWithHybridV3;
    private sendDirect;
    /**
     * Check whether the recipient supports Xchange (XorIDA key transport).
     *
     * @param recipientDid - Recipient DID to check.
     * @returns True if recipient has xchange: true in registry.
     */
    private canUseXchange;
    /**
     * Send via Xchange mode: random key + AES-GCM encrypt, bundle, XorIDA split, v4 envelopes.
     *
     * Opt-in performance mode. No KEM, no key agreement — the random key is
     * embedded in the bundle and split across channels. Single security layer
     * (information-theoretic) + Ed25519 authentication. ~180x faster than V3.
     */
    private sendXchange;
    /**
     * Split plaintext via XorIDA and send each share as a separate V3 envelope.
     *
     * Default split-channel path with three independent cryptographic layers:
     * XorIDA payload split, hybrid PQ KEM, and dual signatures.
     * Returns ok() if at least threshold sends succeed.
     */
    private sendSplitChannel;
    /**
     * Create and send an envelope for each share independently.
     *
     * Routes share[i] to transports[i % transports.length] for channel separation.
     */
    private sendShareEnvelopes;
    /**
     * Receive and accumulate a split-channel share envelope.
     *
     * Verifies the envelope, extracts share metadata, accumulates shares.
     * When threshold is reached, reconstructs the original plaintext.
     *
     * @param envelope - A share envelope with split-channel metadata
     * @returns AgentMessage if threshold met, null if more shares needed
     */
    receiveSplitShare(envelope: AnyTransportEnvelope): Promise<Result<AgentMessage | null, AgentError>>;
    /**
     * Receive and accumulate a v4 Xchange share envelope.
     *
     * Verifies Ed25519 signature, extracts raw share data (no decryption —
     * the XorIDA share IS the payload). When threshold is reached,
     * reconstructs and decrypts via Xchange.
     *
     * @param envelope - A v4 Xchange envelope with share metadata.
     * @returns AgentMessage if threshold met, null if more shares needed.
     */
    receiveXchangeShare(envelope: TransportEnvelopeV4): Promise<Result<AgentMessage | null, AgentError>>;
    /**
     * Accumulate a Xchange share and attempt reconstruction + decryption.
     *
     * When threshold is met:
     * 1. Reconstruct padded bundle from XorIDA shares
     * 2. Verify HMAC (BEFORE decrypt — CRITICAL)
     * 3. Unpad → extract bundle → xchangeDecrypt → plaintext
     */
    private accumulateXchangeShare;
    /**
     * Accumulate a share and attempt reconstruction when threshold is met.
     */
    private accumulateShare;
    /**
     * Common envelope verification: version, timestamp, nonce, DID, signature, scope.
     *
     * Used by receive(), receiveSigned(), and receiveRaw() to avoid duplication.
     * Consumes the nonce on success (replay prevention).
     */
    private verifyEnvelope;
    /**
     * Verify and decrypt an envelope, returning raw text (no JSON parse).
     * Used by receiveSplitShare to get the raw decrypted share data.
     *
     * ROT-1: Supports key rotation with fallback to old keys.
     */
    private receiveRaw;
    /**
     * Create a test envelope for testing purposes.
     *
     * This is a helper method for tests to create properly signed and encrypted
     * envelopes without going through the full send() flow.
     *
     * @param recipientDid - Recipient DID
     * @param payload - Payload object (will be JSON serialized)
     * @param scope - Permission scope
     * @returns TransportEnvelope or null if creation failed
     * @internal
     */
    private createTestEnvelope;
    /**
     * Send email invitation to establish connection.
     *
     * Uses email transport to send branded invitation with one-click acceptance.
     * Requires EmailTransport to be configured in agent options.
     *
     * @param opts - Invitation options
     * @returns Result with success status
     *
     * @example
     * ```ts
     * await agent.invite({
     *   to: 'fulfillment@acme.com',
     *   message: 'Connect our payment systems'
     * });
     * ```
     */
    invite(opts: {
        to: string;
        message?: string;
        template?: string;
    }): Promise<Result<void, AgentError>>;
}
export { generateSharedKey };
