import { PhantomClient } from '@phantom/client';
export { PhantomClient } from '@phantom/client';
import { PhantomApiClient } from '@phantom/phantom-api-client';

/**
 * Complete session data stored on disk
 *
 * Note: SSO flow uses stamper keys for API authentication, not OAuth tokens
 */
interface SessionData {
    walletId: string;
    organizationId: string;
    authUserId: string;
    /** App/client ID used during authentication (for quote API key headers) */
    appId?: string;
    /** Auth flow used to create this session */
    authFlow?: "sso" | "device-code";
    /** SSO flow uses API key stamper keys; device-code uses separate auth2 stamper storage */
    stamperKeys?: {
        publicKey: string;
        secretKey: string;
    };
    createdAt: number;
    updatedAt: number;
}

/**
 * SessionManager orchestrates the complete session lifecycle:
 * - Loads existing sessions from storage
 * - Handles authentication when needed
 * - Creates and manages PhantomClient instances
 * - Provides session data access
 */

/**
 * Configuration options for SessionManager
 */
interface SessionManagerOptions {
    /** Base URL for OAuth authorization server (overrides PHANTOM_AUTH_BASE_URL and env-based default) */
    authBaseUrl?: string;
    /** Base URL for Phantom Connect (overrides PHANTOM_CONNECT_BASE_URL and env-based default) */
    connectBaseUrl?: string;
    /** Base URL for Phantom wallets API (default: https://api.phantom.app/v1/wallets or PHANTOM_WALLETS_API_BASE_URL env var) */
    walletsApiBaseUrl?: string;
    /** Port for local OAuth callback server (default: 8080 or PHANTOM_CALLBACK_PORT env var) */
    callbackPort?: number;
    /** Path for OAuth callback (default: /callback or PHANTOM_CALLBACK_PATH env var) */
    callbackPath?: string;
    /** Application identifier prefix (default: phantom-mcp) */
    appId?: string;
    /** Directory to store session data (default: ~/.phantom-mcp) */
    sessionDir?: string;
    /**
     * Authentication flow to use (default: "device-code" or PHANTOM_AUTH_FLOW env var).
     * - "sso": Browser redirect + localhost callback
     * - "device-code": RFC 8628 device authorization — terminal display + polling
     */
    authFlow?: "sso" | "device-code";
}
/**
 * SessionManager handles session lifecycle, auto-authentication, and PhantomClient creation
 *
 * Usage:
 * ```typescript
 * const manager = new SessionManager();
 * await manager.initialize(); // Loads session or authenticates
 * const client = manager.getClient();
 * const session = manager.getSession();
 * ```
 */
declare class SessionManager {
    private readonly authBaseUrl;
    private readonly connectBaseUrl;
    private readonly walletsApiBaseUrl;
    private readonly callbackPort;
    private readonly callbackPath;
    private readonly appId;
    private readonly authFlow;
    private readonly storage;
    private readonly logger;
    private session;
    private client;
    private stamper;
    private createMcpAnalyticsHeaders;
    private resolveAppId;
    /**
     * Creates a new SessionManager
     *
     * @param options - Configuration options
     */
    constructor(options?: SessionManagerOptions);
    /**
     * Initializes the session manager
     * Loads existing session or authenticates if needed
     *
     * @throws Error if authentication fails
     */
    initialize(): Promise<void>;
    /**
     * Returns whether the session manager has an active, loaded session.
     *
     * This is a synchronous local check — it does NOT make a network call and
     * cannot detect server-side session revocation. A truthy result means a
     * session file was loaded; it does not guarantee the server will accept it.
     *
     * On startup, initialize() proactively validates a loaded session via a
     * lightweight API call and re-authenticates immediately if it returns 401/403.
     * During normal operation, any tool call that receives 401/403 automatically
     * calls resetSession(), opens the browser for re-auth, and returns AUTH_EXPIRED
     * so the agent can retry.
     *
     * @returns true if a session is loaded in memory
     */
    isInitialized(): boolean;
    /**
     * Returns the initialized PhantomClient
     *
     * @returns PhantomClient instance
     * @throws Error if not initialized
     */
    getClient(): PhantomClient;
    /**
     * Returns the current session data
     *
     * @returns Current session data
     * @throws Error if not initialized
     */
    getSession(): SessionData;
    /**
     * Attempts to refresh the OAuth tokens for the current device-code session.
     * Used to recover from a 401 before falling back to full re-authentication.
     *
     * @returns true if tokens were refreshed successfully, false otherwise
     */
    tryRefreshSession(): Promise<boolean>;
    /**
     * Resets the session by clearing stored data and re-authenticating
     *
     * @throws Error if authentication fails
     */
    resetSession(): Promise<void>;
    /**
     * Authenticates using the configured auth flow and creates a new session.
     * Delegates to SSO (browser + callback) or device-code (terminal + poll) flow.
     *
     * @throws Error if authentication fails
     */
    private authenticate;
    /**
     * Executes the SSO flow (browser redirect + localhost callback) and creates a new session.
     *
     * @throws Error if SSO flow fails
     */
    private authenticateWithSso;
    /**
     * Executes the RFC 8628 device authorization flow (terminal display + polling) and creates a new session.
     *
     * @throws Error if device flow fails
     */
    private authenticateWithDeviceFlow;
    /**
     * Creates a PhantomClient instance from the current session.
     *
     * - SSO sessions: PKI stamper (Ed25519 ApiKeyStamper)
     * - Device-code sessions: storage-backed Auth2Stamper (P-256 OIDC) with session metadata
     */
    private createClient;
    /**
     * SSO flow: PKI stamper using the Ed25519 keypair from the session.
     */
    private createClientForSso;
    /**
     * Device-code flow:
     * 1. Rehydrate the storage-backed Auth2Stamper from the local auth2 file.
     * 2. Require the session to already contain org/wallet metadata from the explicit auth step.
     * 3. Create PhantomClient with the OIDC stamper.
     */
    private createClientForDeviceFlow;
    /**
     * Returns dynamic OAuth headers for the current device-code session.
     * Called on every request so the bearer token is always fresh (handles refresh).
     * Returns an empty object for SSO sessions or when no stamper is available.
     */
    getOAuthHeaders(): Record<string, string | undefined>;
    private clearDeviceCodeAuthState;
}

declare class Logger {
    private context;
    constructor(context?: string);
    /**
     * Private method to write to stderr with proper formatting
     */
    private log;
    /**
     * Log info message
     */
    info(message: string): void;
    /**
     * Log error message
     */
    error(message: string): void;
    /**
     * Log warning message
     */
    warn(message: string): void;
    /**
     * Log debug message (only if DEBUG or PHANTOM_MCP_DEBUG env var is set)
     */
    debug(message: string): void;
    /**
     * Create a child logger with combined context
     * Example: parent context "MCP" + child "Transport" = "MCP:Transport"
     */
    child(childContext: string): Logger;
}

/**
 * MCP Tool types and interfaces
 */

/**
 * Context provided to tool handlers
 */
interface ToolContext {
    /** Authenticated PhantomClient instance */
    client: PhantomClient;
    /** Current session data */
    session: SessionData;
    /** Logger instance for this tool */
    logger: Logger;
    /** Shared HTTP client for api.phantom.app (or proxy). Handles 402/429 automatically. */
    apiClient: PhantomApiClient;
}
/**
 * JSON Schema for MCP tool input validation
 */
interface ToolInputSchema {
    type: "object";
    properties: Record<string, unknown>;
    required?: string[];
}
/**
 * MCP Tool annotations describing safety and behavior characteristics.
 * See: https://modelcontextprotocol.io/docs/concepts/tools#tool-annotations
 */
interface ToolAnnotations {
    /** If true, the tool only reads data and has no side effects */
    readOnlyHint?: boolean;
    /** If true, the tool may perform destructive or irreversible actions (e.g. sending transactions) */
    destructiveHint?: boolean;
    /** If true, calling the tool repeatedly with the same inputs has the same effect as calling it once */
    idempotentHint?: boolean;
    /** If true, the tool may interact with external systems outside the local environment */
    openWorldHint?: boolean;
}
/**
 * MCP Tool definition
 */
interface ToolHandler {
    /** Tool name (used in tool calls) */
    name: string;
    /** Tool description (shown to LLM) */
    description: string;
    /** JSON schema for input validation */
    inputSchema: ToolInputSchema;
    /** Safety and behavior annotations */
    annotations?: ToolAnnotations;
    /** Tool handler function */
    handler: (params: Record<string, unknown>, context: ToolContext) => Promise<unknown>;
}

/**
 * MCP Tools Registry
 *
 * Chain-specific tools for Solana and EVM chains.
 * Tools mirror the browser-sdk's chain-specific API pattern (sdk.solana.*, sdk.ethereum.*).
 */

/**
 * Array of all available tools
 */
declare const tools: ToolHandler[];

export { SessionData, SessionManager, ToolContext, ToolHandler, tools };
