/**
 * @amigo-ai/platform-sdk
 *
 * Official TypeScript SDK for the Amigo Platform API.
 *
 * @example
 * ```typescript
 * import { AmigoClient } from '@amigo-ai/platform-sdk'
 *
 * const client = new AmigoClient({
 *   apiKey: 'your-api-key',
 *   workspaceId: 'your-workspace-id',
 * })
 *
 * const agents = await client.agents.list()
 * console.log(agents.items)
 * ```
 */
import { ConfigurationError } from './core/errors.js';
import { applyPlatformRequestOptions, createPlatformClient, } from './core/openapi-client.js';
import { mergeRequestOptions, } from './core/request-options.js';
import { MeResource } from './resources/me.js';
import { WorkspacesResource } from './resources/workspaces.js';
import { ApiKeysResource } from './resources/api-keys.js';
import { TokensResource } from './resources/tokens.js';
import { AgentsResource } from './resources/agents.js';
import { SkillsResource } from './resources/skills.js';
import { ActionsResource } from './resources/actions.js';
import { OperatorsResource } from './resources/operators.js';
import { PromptLogsResource } from './resources/prompt-logs.js';
import { TriggersResource } from './resources/triggers.js';
import { ServicesResource } from './resources/services.js';
import { ContextGraphsResource } from './resources/context-graphs.js';
import { DataSourcesResource } from './resources/data-sources.js';
import { WorldResource } from './resources/world.js';
import { CallsResource } from './resources/calls.js';
import { ConversationsResource } from './resources/conversations.js';
import { IntegrationsResource } from './resources/integrations.js';
import { ExternalIntegrationsResource } from './resources/external-integrations.js';
import { AnalyticsResource } from './resources/analytics.js';
import { SimulationsResource } from './resources/simulations.js';
import { MetricsResource } from './resources/metrics.js';
import { SettingsResource } from './resources/settings.js';
import { BillingResource } from './resources/billing.js';
import { ReviewQueueResource } from './resources/review-queue.js';
import { RecordingsResource } from './resources/recordings.js';
import { AuditResource } from './resources/audit.js';
import { ComplianceResource } from './resources/compliance.js';
import { EventsResource } from './resources/events.js';
import { FunctionsResource } from './resources/functions.js';
import { ObserversResource } from './resources/observers.js';
import { FhirResource } from './resources/fhir.js';
import { InsightsResource } from './resources/insights.js';
import { CommandCenterResource } from './resources/command-center.js';
import { SensoriumResource } from './resources/sensorium.js';
import { DataQueryResource } from './resources/data-query.js';
import { BriefsResource } from './resources/briefs.js';
import { DesktopSessionsResource } from './resources/desktop-sessions.js';
import { IntakeResource } from './resources/intake.js';
import { NetworkResource } from './resources/network.js';
import { PipelineResource } from './resources/pipeline.js';
import { TasksResource } from './resources/tasks.js';
import { ToolsResource } from './resources/tools.js';
import { SurfacesResource } from './resources/surfaces.js';
import { SessionsResource } from './resources/sessions.js';
import { WorkspaceDatabaseResource } from './resources/workspace-database.js';
import { WorkspaceDataQueriesResource } from './resources/workspace-data-queries.js';
import { resolveScopedPlatformClient, scopePlatformClient } from './resources/base.js';
import { withResponse } from './core/utils.js';
export const DEFAULT_BASE_URL = 'https://api.platform.amigo.ai';
export class AmigoClient {
    workspaceId;
    baseUrl;
    agentBaseUrl;
    workspaces;
    me;
    apiKeys;
    tokens;
    agents;
    /** @deprecated Use `actions` instead */
    skills;
    actions;
    operators;
    promptLogs;
    triggers;
    services;
    contextGraphs;
    dataSources;
    world;
    calls;
    conversations;
    integrations;
    externalIntegrations;
    analytics;
    simulations;
    metrics;
    settings;
    billing;
    reviewQueue;
    recordings;
    audit;
    compliance;
    events;
    functions;
    /**
     * Voice-call observer real-time stream. Subscribe with
     * ``client.observers.subscribe({ callSid, token, onEvent })``. See
     * {@link ObserversResource}.
     */
    observers;
    /** FHIR / EHR data interop — sync status, imports, resources, patient views */
    fhir;
    /** Natural-language insights — schema, suggestions, SQL, chat sessions */
    insights;
    /** Command Center — rolled-up workspace homepage snapshot */
    commandCenter;
    /** Sensorium — operator-facing live agent loop observability */
    sensorium;
    /** Generic data query against whitelisted workspace datasets */
    dataQuery;
    /** AI-generated entity briefs (workspace-level + per-entity) */
    briefs;
    /** Remote-controlled desktop sessions for driving GUI-only third-party apps */
    desktopSessions;
    /** Patient intake — signed upload links + uploads */
    intake;
    /** Workspace network metadata (egress IP allowlist) */
    network;
    /** Data ingestion pipeline observability (sources, throughput, review backlog) */
    pipeline;
    /** Long-running async tasks (poll by id or list by call) */
    tasks;
    /** Manual tool execution + per-service tool resolution */
    tools;
    /** Surfaces — short-lived form/intake experiences (lifecycle: create→deliver→review→approve) */
    surfaces;
    /** Live agent sessions — list active calls + inject mid-call directives */
    sessions;
    /** Workspace database — Lakebase fork lifecycle, SQL query execution, query tool CRUD */
    workspaceDatabase;
    /** Workspace data queries — Lakebase-backed query tool registry */
    workspaceDataQueries;
    /** @internal — exposed for path-level type inference in GET/POST/PUT/etc. */
    api;
    constructor(config) {
        if (!config.apiKey || typeof config.apiKey !== 'string') {
            throw new ConfigurationError('apiKey is required and must be a non-empty string');
        }
        if (!config.workspaceId || typeof config.workspaceId !== 'string') {
            throw new ConfigurationError('workspaceId is required and must be a non-empty string');
        }
        const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, '');
        const client = createPlatformClient({
            apiKey: config.apiKey,
            baseUrl,
            retry: config.retry,
            maxRetries: config.maxRetries,
            timeout: config.timeout,
            headers: config.headers,
            hooks: config.hooks,
            fetch: config.fetch,
        });
        AmigoClient.hydrate(this, client, config.workspaceId, baseUrl, config.agentBaseUrl);
    }
    withOptions(options) {
        return AmigoClient.fromPlatformClient(scopePlatformClient(this.api, options), this.workspaceId, this.baseUrl, this.agentBaseUrl);
    }
    async GET(path, ...[init]) {
        return withResponse(await this.resolveApiRequest(path, 'GET', init));
    }
    async POST(path, ...[init]) {
        return withResponse(await this.resolveApiRequest(path, 'POST', init));
    }
    async PUT(path, ...[init]) {
        return withResponse(await this.resolveApiRequest(path, 'PUT', init));
    }
    async PATCH(path, ...[init]) {
        return withResponse(await this.resolveApiRequest(path, 'PATCH', init));
    }
    async DELETE(path, ...[init]) {
        return withResponse(await this.resolveApiRequest(path, 'DELETE', init));
    }
    async HEAD(path, ...[init]) {
        return withResponse(await this.resolveApiRequest(path, 'HEAD', init), {
            allowEmptyBody: true,
        });
    }
    async OPTIONS(path, ...[init]) {
        return withResponse(await this.resolveApiRequest(path, 'OPTIONS', init), {
            allowEmptyBody: true,
        });
    }
    defineRoute(method, path) {
        const dispatcher = this[method];
        return (init) => dispatcher.call(this, path, init);
    }
    static fromPlatformClient(client, workspaceId, baseUrl, agentBaseUrl) {
        const instance = Object.create(AmigoClient.prototype);
        AmigoClient.hydrate(instance, client, workspaceId, baseUrl, agentBaseUrl);
        return instance;
    }
    static hydrate(target, client, workspaceId, baseUrl, agentBaseUrl) {
        const mutable = target;
        mutable.workspaceId = workspaceId;
        mutable.baseUrl = baseUrl;
        mutable.agentBaseUrl = agentBaseUrl;
        target.api = client;
        mutable.workspaces = new WorkspacesResource(client, workspaceId);
        // ``MeResource`` operates on /v1/me/... — account-scoped, not
        // workspace-scoped. Pass a sentinel literal instead of forwarding
        // the bound ``workspaceId`` so any accidental future use of
        // ``this.workspaceId`` inside ``MeResource`` (or its base) is
        // visibly wrong rather than silently picking up the caller's
        // workspace context. Pinned by the exact-URL test in
        // ``tests/resources/me.test.ts``.
        mutable.me = new MeResource(client, '_account');
        mutable.apiKeys = new ApiKeysResource(client, workspaceId);
        mutable.tokens = new TokensResource(client, workspaceId);
        mutable.agents = new AgentsResource(client, workspaceId);
        mutable.skills = new SkillsResource(client, workspaceId);
        mutable.actions = new ActionsResource(client, workspaceId);
        mutable.operators = new OperatorsResource(client, workspaceId);
        mutable.promptLogs = new PromptLogsResource(client, workspaceId);
        mutable.triggers = new TriggersResource(client, workspaceId);
        mutable.services = new ServicesResource(client, workspaceId);
        mutable.contextGraphs = new ContextGraphsResource(client, workspaceId);
        mutable.dataSources = new DataSourcesResource(client, workspaceId);
        mutable.world = new WorldResource(client, workspaceId);
        mutable.calls = new CallsResource(client, workspaceId);
        mutable.conversations = new ConversationsResource(client, workspaceId, agentBaseUrl);
        mutable.integrations = new IntegrationsResource(client, workspaceId);
        mutable.externalIntegrations = new ExternalIntegrationsResource(client, workspaceId);
        mutable.analytics = new AnalyticsResource(client, workspaceId);
        mutable.simulations = new SimulationsResource(client, workspaceId);
        mutable.metrics = new MetricsResource(client, workspaceId);
        mutable.settings = new SettingsResource(client, workspaceId);
        mutable.billing = new BillingResource(client, workspaceId);
        mutable.reviewQueue = new ReviewQueueResource(client, workspaceId);
        mutable.recordings = new RecordingsResource(client, workspaceId);
        mutable.audit = new AuditResource(client, workspaceId);
        mutable.compliance = new ComplianceResource(client, workspaceId);
        mutable.events = new EventsResource(client, workspaceId);
        mutable.functions = new FunctionsResource(client, workspaceId);
        mutable.observers = new ObserversResource(client, workspaceId, agentBaseUrl);
        mutable.fhir = new FhirResource(client, workspaceId);
        mutable.insights = new InsightsResource(client, workspaceId);
        mutable.commandCenter = new CommandCenterResource(client, workspaceId);
        mutable.sensorium = new SensoriumResource(client, workspaceId);
        mutable.dataQuery = new DataQueryResource(client, workspaceId);
        mutable.briefs = new BriefsResource(client, workspaceId);
        mutable.desktopSessions = new DesktopSessionsResource(client, workspaceId);
        mutable.intake = new IntakeResource(client, workspaceId);
        mutable.network = new NetworkResource(client, workspaceId);
        mutable.pipeline = new PipelineResource(client, workspaceId);
        mutable.tasks = new TasksResource(client, workspaceId);
        mutable.tools = new ToolsResource(client, workspaceId);
        mutable.surfaces = new SurfacesResource(client, workspaceId);
        mutable.sessions = new SessionsResource(client, workspaceId);
        mutable.workspaceDatabase = new WorkspaceDatabaseResource(client, workspaceId);
        mutable.workspaceDataQueries = new WorkspaceDataQueriesResource(client, workspaceId);
    }
    async resolveApiRequest(path, method, init) {
        const { baseClient, options } = resolveScopedPlatformClient(this.api);
        const mergedInit = mergeRequestOptions(options, withWorkspaceId(path, init, this.workspaceId));
        const requestInit = applyPlatformRequestOptions(baseClient, mergedInit);
        switch (method) {
            case 'GET':
                return await baseClient.GET(path, requestInit);
            case 'POST':
                return await baseClient.POST(path, requestInit);
            case 'PUT':
                return await baseClient.PUT(path, requestInit);
            case 'PATCH':
                return await baseClient.PATCH(path, requestInit);
            case 'DELETE':
                return await baseClient.DELETE(path, requestInit);
            case 'HEAD':
                return await baseClient.HEAD(path, requestInit);
            case 'OPTIONS':
                return await baseClient.OPTIONS(path, requestInit);
        }
    }
}
export { AmigoError, BadRequestError, AuthenticationError, PermissionError, NotFoundError, ConflictError, ValidationError, RateLimitError, ServerError, ServiceUnavailableError, NetworkError, RequestTimeoutError, ParseError, ConfigurationError, isAmigoError, isNotFoundError, isRateLimitError, isAuthenticationError, isRequestTimeoutError, isPermissionError, isConflictError, isValidationError, isServerError, isNetworkError, isHttpException, isHttpValidationError, isUnparseableErrorBody, } from './core/errors.js';
export { workspaceId, apiKeyId, agentId, skillId, actionId, serviceId, contextGraphId, callId, phoneNumberId, integrationId, integrationEndpointId, entityId, eventId, simulationRunId, simulationSessionId, functionId, dataSourceId, } from './core/branded-types.js';
export { paginate } from './core/utils.js';
export { buildLastResponse, extractRequestId } from './core/utils.js';
export { parseRateLimitHeaders } from './core/rate-limit.js';
export { verifyWebhookSignature, parseWebhookEvent, WebhookVerificationError, } from './core/webhooks.js';
export { TokensResource } from './resources/tokens.js';
export { EXTERNAL_USER_SESSION_CREATE_SCOPE } from './resources/tokens.js';
export { ExternalIntegrationsResource } from './resources/external-integrations.js';
export { IntegrationsResource } from './resources/integrations.js';
/** Voice provider constants and types. */
export { STT_PROVIDERS, TTS_PROVIDERS, VOICE_SESSION_PROVIDERS } from './resources/voice.js';
export { WorkspaceEventStreamError, isWorkspaceEventStreamError } from './resources/events.js';
export { sessionConnectAuthProtocols, textStreamAuthProtocols } from './resources/conversations.js';
// Voice-call observer real-time stream
export { ObserversResource, observerAuthProtocols } from './resources/observers.js';
// Reconnecting WebSocket primitive (compose for custom realtime surfaces)
export { createReconnectingWebSocket, ReconnectingWebSocketError, } from './core/reconnecting-websocket.js';
// Device code auth (desktop / CLI login)
export { loginWithDeviceCode, TokenManager, FileTokenStorage, MemoryTokenStorage, DeviceCodeExpiredError, DeviceCodeDeniedError, RefreshTokenExpiredError, LoginCancelledError, formatDeviceCodeInstructions, formatDeviceCodeLink, formatWorkspaceList, openBrowser, } from './core/device-code.js';
function withWorkspaceId(path, init, workspaceId) {
    if (!path.includes('{workspace_id}')) {
        return (init ?? {});
    }
    const current = (init ?? {});
    return {
        ...current,
        params: {
            ...(current.params ?? {}),
            path: {
                ...(current.params?.path ?? {}),
                workspace_id: workspaceId,
            },
        },
    };
}
//# sourceMappingURL=index.js.map