import { V as Vendor } from './Vendor-DYh_bzwo.js';

/**
 * Connector - Represents authenticated connection to ANY API
 *
 * Connectors handle authentication for:
 * - AI providers (OpenAI, Anthropic, Google, etc.)
 * - External APIs (GitHub, Microsoft, Salesforce, etc.)
 *
 * This is the SINGLE source of truth for authentication.
 */

/**
 * No authentication (for testing/mock providers and local services like Ollama)
 */
interface NoneConnectorAuth {
    type: 'none';
}
/**
 * Connector authentication configuration
 * Supports OAuth 2.0, API keys, JWT bearer tokens, and none (for testing)
 */
type ConnectorAuth = OAuthConnectorAuth | APIKeyConnectorAuth | JWTConnectorAuth | NoneConnectorAuth;
/**
 * OAuth 2.0 authentication for connectors
 * Supports multiple OAuth flows
 */
interface OAuthConnectorAuth {
    type: 'oauth';
    flow: 'authorization_code' | 'client_credentials' | 'jwt_bearer';
    clientId: string;
    clientSecret?: string;
    tokenUrl: string;
    authorizationUrl?: string;
    redirectUri?: string;
    scope?: string;
    usePKCE?: boolean;
    /**
     * Vendor-mandated scope token that must appear in every authorize URL for
     * refresh-token issuance (e.g. `offline_access` for Microsoft / Atlassian,
     * `refresh_token` for Salesforce, `offline.access` for Twitter/X). Stamped
     * by `buildAuthConfig` from the template's `RefreshStrategy`. Force-merged
     * into `scope` at URL-build time so operator scope overrides
     * (e.g. Microsoft `.default`) can't drop it. Idempotent.
     */
    requiredScope?: string;
    privateKey?: string;
    privateKeyPath?: string;
    issuer?: string;
    subject?: string;
    audience?: string;
    /**
     * How the JWT assertion is delivered to the token endpoint.
     * - `'form'` (default, RFC 7523): POST with grant_type + assertion body.
     * - `'bearer'` (GitHub App installation tokens): POST with
     *   `Authorization: Bearer <JWT>` header and no body.
     */
    tokenRequestStyle?: 'form' | 'bearer';
    /** JWT `exp` lifetime in seconds (default 3600; GitHub caps at 600). */
    tokenLifetimeSeconds?: number;
    refreshBeforeExpiry?: number;
    storageKey?: string;
    /** Extra query parameters appended to the authorization URL.
     *  Used for vendor-specific requirements, e.g. Google's `access_type: 'offline'`. */
    authorizationParams?: Record<string, string>;
    /** Vendor-specific extra credentials */
    extra?: Record<string, string>;
}
/**
 * Static API key authentication
 * For services like OpenAI, Anthropic, many SaaS APIs
 */
interface APIKeyConnectorAuth {
    type: 'api_key';
    apiKey: string;
    headerName?: string;
    headerPrefix?: string;
    /**
     * Send the API key as a URL query parameter instead of an HTTP header.
     * When set, `connector.fetch()` injects `?<queryParamName>=<apiKey>` into
     * the request URL and does NOT add an auth header. `headerName` and
     * `headerPrefix` are ignored in that case. Used by vendors like ipapi.co
     * that authenticate via `?key=...`.
     */
    queryParamName?: string;
    /**
     * Vendor-specific extra credentials beyond the primary API key.
     * E.g., Slack Socket Mode needs { appToken: 'xapp-...', signingSecret: '...' }
     */
    extra?: Record<string, string>;
}
/**
 * JWT Bearer token authentication
 * For service accounts (Google, Salesforce)
 */
interface JWTConnectorAuth {
    type: 'jwt';
    privateKey: string;
    privateKeyPath?: string;
    tokenUrl: string;
    clientId: string;
    scope?: string;
    issuer?: string;
    subject?: string;
    audience?: string;
    /** Vendor-specific extra credentials */
    extra?: Record<string, string>;
}
/**
 * Complete connector configuration
 * Used for BOTH AI providers AND external APIs
 */
interface ConnectorConfig {
    id?: string;
    name?: string;
    vendor?: Vendor;
    serviceType?: string;
    auth: ConnectorAuth;
    displayName?: string;
    description?: string;
    baseURL?: string;
    defaultModel?: string;
    apiVersion?: string;
    rateLimit?: {
        requestsPerMinute?: number;
        requestsPerDay?: number;
    };
    documentation?: string;
    tags?: string[];
    options?: {
        organization?: string;
        project?: string;
        anthropicVersion?: string;
        location?: string;
        projectId?: string;
        [key: string]: unknown;
    };
    /**
     * Request timeout in milliseconds
     * @default 30000 (30 seconds)
     */
    timeout?: number;
    /**
     * Retry configuration for transient failures
     */
    retry?: {
        /** Maximum number of retry attempts @default 3 */
        maxRetries?: number;
        /** HTTP status codes that trigger retry @default [429, 500, 502, 503, 504] */
        retryableStatuses?: number[];
        /** Base delay in ms for exponential backoff @default 1000 */
        baseDelayMs?: number;
        /** Maximum delay in ms @default 30000 */
        maxDelayMs?: number;
    };
    /**
     * Circuit breaker configuration for failing services
     */
    circuitBreaker?: {
        /** Enable circuit breaker @default true */
        enabled?: boolean;
        /** Number of failures before opening circuit @default 5 */
        failureThreshold?: number;
        /** Number of successes to close circuit @default 2 */
        successThreshold?: number;
        /** Time in ms before attempting to close circuit @default 30000 */
        resetTimeoutMs?: number;
    };
    /**
     * Logging configuration for requests/responses
     */
    logging?: {
        /** Enable request/response logging @default false */
        enabled?: boolean;
        /** Log request/response bodies (security risk) @default false */
        logBody?: boolean;
        /** Log request/response headers (security risk) @default false */
        logHeaders?: boolean;
    };
}
/**
 * Result from ProviderConfigAgent
 * Includes setup instructions and environment variables
 */
interface ConnectorConfigResult {
    name: string;
    config: ConnectorConfig;
    setupInstructions: string;
    envVariables: string[];
    setupUrl?: string;
}

/**
 * Token storage interface (Clean Architecture - Domain Layer)
 * All implementations must encrypt tokens at rest
 */
interface StoredToken {
    access_token: string;
    refresh_token?: string;
    expires_in: number;
    token_type: string;
    scope?: string;
    obtained_at: number;
}
/**
 * Token storage interface
 * All implementations MUST encrypt tokens before storing
 */
interface ITokenStorage {
    /**
     * Store token (must be encrypted by implementation)
     *
     * @param key - Unique identifier for this token
     * @param token - Token data to store
     */
    storeToken(key: string, token: StoredToken): Promise<void>;
    /**
     * Retrieve token (must be decrypted by implementation)
     *
     * @param key - Unique identifier for the token
     * @returns Decrypted token or null if not found
     */
    getToken(key: string): Promise<StoredToken | null>;
    /**
     * Delete token
     *
     * @param key - Unique identifier for the token
     */
    deleteToken(key: string): Promise<void>;
    /**
     * Check if token exists
     *
     * @param key - Unique identifier for the token
     * @returns True if token exists
     */
    hasToken(key: string): Promise<boolean>;
    /**
     * List all storage keys (for account enumeration).
     * Optional — implementations that support it enable multi-account listing.
     *
     * @returns Array of all stored token keys
     */
    listKeys?(): Promise<string[]>;
}

/**
 * IConnectorRegistry - Read-only interface for connector lookup
 *
 * Covers the read-only subset of Connector static methods.
 * Used by ScopedConnectorRegistry to provide filtered views
 * and by consumers that only need to read from the registry.
 */

interface IConnectorRegistry {
    /** Get a connector by name. Throws if not found (or not accessible). */
    get(name: string): Connector;
    /** Check if a connector exists (and is accessible) */
    has(name: string): boolean;
    /** List all accessible connector names */
    list(): string[];
    /** List all accessible connector instances */
    listAll(): Connector[];
    /** Get number of accessible connectors */
    size(): number;
    /** Get connector descriptions formatted for tool parameters */
    getDescriptionsForTools(): string;
    /** Get connector info map */
    getInfo(): Record<string, {
        displayName: string;
        description: string;
        baseURL: string;
    }>;
    /** Get a connector by ID. Optional — not all registries support ID-based lookup. */
    getById?(id: string): Connector;
    /**
     * Optional async warmup — called before sync reads to ensure connectors are loaded.
     *
     * Multi-tenant registries can implement this to lazily load connectors for the
     * current request context (e.g., tenant/group). Entry points call Connector.warmup()
     * which delegates here. After warmup completes, all sync read methods (get, has,
     * list, listAll) must return correct results without further async work.
     */
    warmup?(): Promise<void>;
}

/**
 * IConnectorAccessPolicy - Pluggable access control for connector registry
 *
 * Policies are sync-only for performance — access checks must be fast
 * and policy data should be in-memory.
 */

/**
 * Opaque context passed to access policy checks.
 * Library imposes no structure — consumers define their own shape
 * (e.g., { userId, tenantId, roles }).
 */
type ConnectorAccessContext = Record<string, unknown>;
interface IConnectorAccessPolicy {
    /**
     * Check if a connector is accessible in the given context.
     * Receives the full Connector instance so it can inspect
     * config.tags, vendor, serviceType, etc.
     */
    canAccess(connector: Connector, context: ConnectorAccessContext): boolean;
}

/**
 * Connector - The single source of truth for authentication
 *
 * Manages authenticated connections to:
 * - AI providers (OpenAI, Anthropic, Google, etc.)
 * - External APIs (GitHub, Salesforce, etc.)
 *
 * Enterprise features:
 * - Request timeout with AbortController
 * - Circuit breaker for failing services
 * - Retry with exponential backoff
 * - Request/response logging
 */

/**
 * Default configuration values for resilience features
 */
declare const DEFAULT_CONNECTOR_TIMEOUT = 30000;
declare const DEFAULT_MAX_RETRIES = 3;
declare const DEFAULT_RETRYABLE_STATUSES: number[];
declare const DEFAULT_BASE_DELAY_MS = 1000;
declare const DEFAULT_MAX_DELAY_MS = 30000;
/**
 * Fetch options with additional connector-specific settings
 */
interface ConnectorFetchOptions extends RequestInit {
    /** Override timeout for this request */
    timeout?: number;
    /** Skip retry for this request */
    skipRetry?: boolean;
    /** Skip circuit breaker for this request */
    skipCircuitBreaker?: boolean;
}
/**
 * Connector class - represents a single authenticated connection
 */
declare class Connector {
    private static _customRegistry;
    /**
     * Set a custom connector registry implementation.
     * When set, all static read methods (get, has, list, listAll, size, etc.)
     * delegate to this registry instead of the internal Map.
     *
     * Use this to plug in multi-tenant, lazy-loading, or any custom connector
     * resolution strategy. Pass null to revert to the built-in Map-based registry.
     *
     * @example
     * ```typescript
     * // Multi-tenant app — set per-request in middleware
     * Connector.setRegistry(new TenantConnectorRegistry(tenantId));
     *
     * // Now Connector.get('microsoft') resolves via TenantConnectorRegistry
     * ```
     */
    static setRegistry(registry: IConnectorRegistry | null): void;
    /**
     * Get the current custom registry (or null if using the built-in registry).
     */
    static getRegistry(): IConnectorRegistry | null;
    private static registry;
    /**
     * Create and register a new connector
     * @param config - Must include `name` field
     */
    static create(config: ConnectorConfig & {
        name: string;
    }): Connector;
    /**
     * Get a connector by name
     */
    static get(name: string): Connector;
    /**
     * Check if a connector exists
     */
    static has(name: string): boolean;
    /**
     * List all registered connector names
     */
    static list(): string[];
    /**
     * Remove a connector
     */
    static remove(name: string): boolean;
    /**
     * Clear all connectors (useful for testing)
     */
    static clear(): void;
    /**
     * Get a connector from the internal Map, bypassing the custom registry.
     * Returns undefined if not found (does not throw).
     */
    static getFromMap(name: string): Connector | undefined;
    /**
     * Check if a connector exists in the internal Map, bypassing the custom registry.
     */
    static hasInMap(name: string): boolean;
    /**
     * List all connector instances from the internal Map, bypassing the custom registry.
     */
    static listAllFromMap(): Connector[];
    /**
     * Call the custom registry's warmup() if available.
     * Entry points (middleware, request handlers) should call this before
     * using sync read methods to ensure connectors are loaded for the
     * current context (e.g., tenant/group).
     *
     * No-op if no custom registry or no warmup method.
     */
    static warmup(): Promise<void>;
    /**
     * Get the default token storage for OAuth connectors.
     * Resolves from StorageRegistry, falling back to MemoryStorage.
     */
    private static get defaultStorage();
    /**
     * Set default token storage for OAuth connectors
     */
    static setDefaultStorage(storage: ITokenStorage): void;
    /**
     * Get all registered connectors
     */
    static listAll(): Connector[];
    /**
     * Get number of registered connectors
     */
    static size(): number;
    /**
     * Get a connector by ID
     */
    static getById(id: string): Connector;
    private static _accessPolicy;
    /**
     * Set a global access policy for connector scoping.
     * Pass null to clear the policy.
     */
    static setAccessPolicy(policy: IConnectorAccessPolicy | null): void;
    /**
     * Get the current global access policy (or null if none set).
     */
    static getAccessPolicy(): IConnectorAccessPolicy | null;
    /**
     * Create a scoped (filtered) view of the connector registry.
     * Requires a global access policy to be set via setAccessPolicy().
     *
     * @param context - Opaque context passed to the policy (e.g., { userId, tenantId })
     * @returns IConnectorRegistry that only exposes accessible connectors
     * @throws Error if no access policy is set
     */
    static scoped(context: ConnectorAccessContext): IConnectorRegistry;
    /**
     * Return the static Connector methods as an IConnectorRegistry object (unfiltered).
     * Useful when code accepts the interface but you want the full admin view.
     */
    static asRegistry(): IConnectorRegistry;
    /**
     * Get connector descriptions formatted for tool parameters
     * Useful for generating dynamic tool descriptions
     */
    static getDescriptionsForTools(): string;
    /**
     * Get connector info (for tools and documentation)
     */
    static getInfo(): Record<string, {
        displayName: string;
        description: string;
        baseURL: string;
    }>;
    /**
     * Backfill resolver for OAuth `authorization_code` connectors loaded from
     * persisted configs that pre-date the `RefreshStrategy` annotation. Given a
     * `serviceType` (e.g. `'microsoft'`), returns a patch that re-applies the
     * vendor template's strategy: stamps `requiredScope` and merges the
     * scope/authorizationParams. Returns `undefined` if no template is found
     * or the strategy is a no-op (`automatic`/`never_expires`/`manual_setup`).
     *
     * Registered by `vendors/index.ts` at module-load time, so the lookup
     * works for any host that imports `@everworker/oneringai`. Hosts that
     * bypass `buildAuthConfig` (e.g. v25's GroupScopedConnectorRegistry, which
     * reconstructs Connectors from decrypted DB configs) still get the right
     * refresh-grant tokens on every authorize URL — no migration required.
     */
    private static refreshStrategyBackfill?;
    /**
     * Register the refresh-strategy backfill resolver. Called by
     * `vendors/index.ts` once at boot. Idempotent (a second call replaces).
     */
    static setRefreshStrategyBackfill(fn: NonNullable<typeof Connector.refreshStrategyBackfill>): void;
    readonly id: string;
    readonly name: string;
    readonly vendor?: Vendor;
    readonly config: ConnectorConfig;
    private oauthManager?;
    private circuitBreaker?;
    private disposed;
    private requestCount;
    private successCount;
    private failureCount;
    private totalLatencyMs;
    private constructor();
    /**
     * Initialize circuit breaker with config or defaults
     */
    private initCircuitBreaker;
    /**
     * Human-readable display name
     */
    get displayName(): string;
    /**
     * API base URL for this connector
     */
    get baseURL(): string;
    /**
     * Get the API key (for api_key auth type)
     */
    getApiKey(): string;
    /**
     * Get the current access token (for OAuth, JWT, or API key)
     * Handles automatic refresh if needed
     *
     * @param userId - Optional user identifier for multi-user support
     * @param accountId - Optional account alias for multi-account support (e.g., 'work', 'personal')
     */
    getToken(userId?: string, accountId?: string): Promise<string>;
    /**
     * Start OAuth authorization flow
     * Returns the URL to redirect the user to
     *
     * @param userId - Optional user identifier for multi-user support
     * @param accountId - Optional account alias for multi-account support (e.g., 'work', 'personal')
     */
    startAuth(userId?: string, accountId?: string): Promise<string>;
    /**
     * Handle OAuth callback
     * Call this after user is redirected back from OAuth provider
     *
     * @param callbackUrl - Full callback URL with code and state parameters
     * @param userId - Optional user identifier (can be extracted from state if embedded)
     * @param accountId - Optional account alias (can be extracted from state if embedded)
     */
    handleCallback(callbackUrl: string, userId?: string, accountId?: string): Promise<void>;
    /**
     * Check if the connector has a valid token
     *
     * @param userId - Optional user identifier for multi-user support
     * @param accountId - Optional account alias for multi-account support
     */
    hasValidToken(userId?: string, accountId?: string): Promise<boolean>;
    /**
     * List account aliases for a user on this connector.
     * Only applicable for OAuth connectors with multi-account support.
     *
     * @param userId - Optional user identifier
     * @returns Array of account aliases (e.g., ['work', 'personal'])
     */
    listAccounts(userId?: string): Promise<string[]>;
    /**
     * Re-key a token from one accountId to another.
     * Used to stabilize account IDs after OAuth — e.g., replacing a temporary
     * random ID with the actual email address discovered post-authorization.
     *
     * @param userId - User identifier
     * @param oldAccountId - Current account alias (temporary)
     * @param newAccountId - Stable account alias (e.g., email)
     * @returns true if re-keyed, false if no token found under oldAccountId
     */
    rekeyAccount(userId: string, oldAccountId: string, newAccountId: string): Promise<boolean>;
    /**
     * Remove a specific account's stored token.
     * Used when a user unlinks/disconnects one of their accounts.
     * Only applicable for OAuth connectors with multi-account support.
     *
     * @param userId - User identifier
     * @param accountId - Account alias to remove (e.g., 'work', 'personal')
     * @returns true if a token was deleted, false if no token existed
     */
    removeAccount(userId: string, accountId: string): Promise<boolean>;
    /**
     * Get vendor-specific options from config
     */
    getOptions(): Record<string, unknown>;
    /**
     * Get the service type (explicit or undefined)
     */
    get serviceType(): string | undefined;
    /**
     * Get connector metrics
     */
    getMetrics(): {
        requestCount: number;
        successCount: number;
        failureCount: number;
        avgLatencyMs: number;
        circuitBreakerState?: string;
    };
    /**
     * Reset circuit breaker (force close)
     */
    resetCircuitBreaker(): void;
    /**
     * Make an authenticated fetch request using this connector
     * This is the foundation for all vendor-dependent tools
     *
     * Features:
     * - Timeout with AbortController
     * - Circuit breaker protection
     * - Retry with exponential backoff
     * - Request/response logging
     *
     * @param endpoint - API endpoint (relative to baseURL) or full URL
     * @param options - Fetch options with connector-specific settings
     * @param userId - Optional user ID for multi-user OAuth
     * @param accountId - Optional account alias for multi-account OAuth
     * @returns Fetch Response
     */
    fetch(endpoint: string, options?: ConnectorFetchOptions, userId?: string, accountId?: string): Promise<Response>;
    /**
     * Make an authenticated fetch request and parse JSON response
     * Throws on non-OK responses
     *
     * @param endpoint - API endpoint (relative to baseURL) or full URL
     * @param options - Fetch options with connector-specific settings
     * @param userId - Optional user ID for multi-user OAuth
     * @param accountId - Optional account alias for multi-account OAuth
     * @returns Parsed JSON response
     */
    fetchJSON<T = unknown>(endpoint: string, options?: ConnectorFetchOptions, userId?: string, accountId?: string): Promise<T>;
    private sleep;
    /**
     * Strip the value of a known auth query parameter from a URL for logging.
     * Used when `auth.queryParamName` is in play so the API key never lands in
     * logs even if a caller passed a URL that already carried it, or a future
     * change switches `logRequest`/`logResponse` to log the post-injection URL.
     */
    private scrubAuthQueryParam;
    private logRequest;
    private logResponse;
    /**
     * Dispose of resources
     */
    dispose(): void;
    /**
     * Check if connector is disposed
     */
    isDisposed(): boolean;
    private initOAuthManager;
    private initJWTManager;
}

/**
 * Base provider interface
 */
interface ProviderCapabilities {
    text: boolean;
    images: boolean;
    videos: boolean;
    audio: boolean;
    embeddings?: boolean;
    /** Optional feature flags for specific capabilities */
    features?: Record<string, boolean>;
}
interface IProvider {
    readonly name: string;
    readonly vendor?: string;
    readonly capabilities: ProviderCapabilities;
    /**
     * Validate that the provider configuration is correct
     */
    validateConfig(): Promise<boolean>;
}

export { type APIKeyConnectorAuth as A, type ConnectorAccessContext as C, DEFAULT_BASE_DELAY_MS as D, type IConnectorRegistry as I, type JWTConnectorAuth as J, type OAuthConnectorAuth as O, type ProviderCapabilities as P, type StoredToken as S, type IConnectorAccessPolicy as a, Connector as b, type ConnectorConfig as c, type ITokenStorage as d, type IProvider as e, type ConnectorFetchOptions as f, type ConnectorAuth as g, type ConnectorConfigResult as h, DEFAULT_CONNECTOR_TIMEOUT as i, DEFAULT_MAX_DELAY_MS as j, DEFAULT_MAX_RETRIES as k, DEFAULT_RETRYABLE_STATUSES as l };
