/**
 * Real-time workspace event streaming via Server-Sent Events.
 *
 * Subscribes to ``GET /v1/{workspace_id}/events/stream`` and yields typed
 * {@link WorkspaceSSEEvent} values. The platform-api endpoint:
 *
 *   - Streams ``text/event-stream`` over HTTP/1.1
 *   - Sends ``retry: 3000`` directive as the first frame
 *   - Tags every event with ``id: <millisecond-timestamp>`` for replay
 *   - Buffers the last 5 minutes of events in Valkey for gapless reconnect
 *   - Pops the discriminator (``event_type``) out of the JSON ``data:``
 *     payload and into the SSE ``event:`` line — this helper reattaches
 *     it before yielding the typed union member
 *
 * Implementation choice: this helper uses the SDK's own fetch transport
 * (with auth + retry middleware applied) rather than the WHATWG
 * ``EventSource`` API or the ``eventsource`` polyfill. The reasons are:
 *
 *   1. ``EventSource`` cannot send ``Authorization`` headers — the polyfill
 *      can, but adds a runtime dep and bypasses the SDK's BFF-proxy /
 *      custom-fetch / mock-fetch composition.
 *   2. Reusing the existing ``createTurnStream`` pattern keeps a single
 *      SSE parser in the SDK and shares the auth middleware that already
 *      attaches the bearer token on every request.
 *   3. The SDK ships with two runtime deps (``openapi-fetch`` +
 *      ``openapi-typescript-helpers``); adding ``eventsource`` would inflate
 *      bundle size for a feature that fetch streaming handles cleanly.
 *
 * The trade-off is that we reimplement the reconnect loop. The platform-api
 * advertises ``retry: 3000`` and we honor that as the initial backoff,
 * doubling with full jitter on each successive failure up to ``maxDelayMs``.
 *
 * @see ConversationsResource.streamTurn for the analogous turn-stream helper.
 */
import type { components } from '../generated/api.js';
import { type PlatformFetch } from '../core/openapi-client.js';
import { WorkspaceScopedResource } from './base.js';
/**
 * Discriminated union of every workspace SSE event variant exposed by
 * platform-api. Members carry their own ``event_type`` literal — narrow
 * with ``switch (event.event_type)`` to access typed payload fields.
 */
export type WorkspaceSSEEvent = components['schemas']['WorkspaceSSEEvent'];
/** Discriminator literal for {@link WorkspaceSSEEvent} members. */
export type WorkspaceSSEEventType = WorkspaceSSEEvent['event_type'];
/**
 * Reason taxonomy for {@link WorkspaceEventStreamError}. The platform-api
 * stream encodes a stable ``code`` in every error / control frame so
 * consumers can branch deterministically without parsing free-form text.
 *
 *   * ``too_many_streams`` — workspace exceeded its concurrent-stream cap
 *     (``error`` frame with ``code=too_many_streams``). Do NOT auto-retry —
 *     close another tab first.
 *   * ``stream_unavailable`` — Valkey or downstream pubsub is unreachable.
 *     Retryable, but not until the platform recovers.
 *   * ``stream_error`` — generic server-side stream failure.
 *   * ``auth`` — 401/403 returned at connect time. Terminal.
 *   * ``transport_exhausted`` — reconnect budget exhausted.
 *   * ``aborted`` — caller aborted via signal / ``unsubscribe()``.
 *   * ``unknown`` — fallback when the server returns an error frame the SDK
 *     does not recognize.
 */
export type WorkspaceEventStreamErrorCode = 'too_many_streams' | 'stream_unavailable' | 'stream_error' | 'auth' | 'transport_exhausted' | 'aborted' | 'unknown';
/**
 * Structured error surfaced through {@link SubscribeToWorkspaceOptions.onError}.
 *
 * Subclasses ``Error`` so existing consumers using ``err.message`` continue
 * to work, while adding ``code`` + ``retryable`` + raw ``frame`` for
 * deterministic branching. Inspect with ``isWorkspaceEventStreamError``.
 */
export declare class WorkspaceEventStreamError extends Error {
    readonly code: WorkspaceEventStreamErrorCode;
    readonly retryable: boolean;
    /** Raw decoded ``error`` frame body (or ``undefined`` for transport errors). */
    readonly frame: Record<string, unknown> | undefined;
    constructor(message: string, code: WorkspaceEventStreamErrorCode, retryable: boolean, frame?: Record<string, unknown>);
}
export declare function isWorkspaceEventStreamError(value: unknown): value is WorkspaceEventStreamError;
/**
 * Options for {@link EventsResource.subscribeToWorkspace}.
 */
export interface SubscribeToWorkspaceOptions {
    /**
     * Resume from a previously seen event id. Forwarded as the
     * ``Last-Event-ID`` request header on the first connect; the server
     * replays buffered events with id > ``lastEventId`` before switching to
     * live pub/sub. The SDK automatically tracks the most recent id during
     * the stream and re-sends it on every reconnect.
     *
     * Event ids are millisecond Unix timestamps; pass them as raw numeric
     * strings.
     */
    lastEventId?: string;
    /**
     * Cancellation signal. Aborting the signal closes the underlying fetch
     * stream and stops the reconnect loop.
     */
    signal?: AbortSignal;
    /** Invoked once per parsed, typed event. */
    onEvent: (event: WorkspaceSSEEvent) => void;
    /**
     * Invoked on a terminal error (e.g., 401 / 403, abort, or reconnect
     * budget exhausted). Will not be called more than once per
     * ``subscribeToWorkspace`` invocation.
     */
    onError?: (error: Error) => void;
    /**
     * Invoked just before each reconnect attempt with the 1-based attempt
     * number. The first connection (attempt 0) does not fire this.
     */
    onReconnect?: (attempt: number) => void;
    /**
     * Initial reconnect delay in milliseconds. Defaults to 3000 to match
     * the platform-api ``retry:`` directive. The actual delay grows
     * exponentially (with jitter) up to ``maxDelayMs`` per failure.
     */
    initialDelayMs?: number;
    /** Cap on the reconnect backoff delay in milliseconds. Defaults to 30s. */
    maxDelayMs?: number;
    /**
     * Maximum number of reconnect attempts before giving up and calling
     * ``onError``. Defaults to 10. Set to ``Infinity`` to retry forever
     * (the consumer is then responsible for aborting via ``signal``).
     */
    maxReconnects?: number;
}
/**
 * Handle returned by {@link EventsResource.subscribeToWorkspace}.
 *
 * Resolves when the stream terminates — either because the consumer
 * aborted via ``signal``, an unrecoverable error fired ``onError``, or
 * the reconnect budget was exhausted. The promise never rejects; consume
 * errors via ``onError``.
 */
export interface SubscriptionHandle {
    /**
     * Returns a promise that resolves once the subscription has fully
     * stopped (post-abort cleanup complete, no further callbacks pending).
     */
    done: Promise<void>;
    /**
     * Stop the subscription. Equivalent to aborting the caller-supplied
     * ``AbortSignal``. Idempotent.
     */
    unsubscribe(): void;
}
/**
 * Real-time event stream resource.
 *
 * @example
 * ```ts
 * const handle = client.events.subscribeToWorkspace({
 *   onEvent: (event) => {
 *     switch (event.event_type) {
 *       case 'call.started':
 *         console.log('Call started:', event.call_sid)
 *         break
 *       case 'pipeline.error':
 *         console.error('Pipeline error:', event)
 *         break
 *     }
 *   },
 *   onError: (err) => console.error('Stream error:', err),
 *   onReconnect: (attempt) => console.warn(`Reconnect #${attempt}`),
 * })
 *
 * // Later, to stop:
 * handle.unsubscribe()
 * await handle.done
 * ```
 */
export declare class EventsResource extends WorkspaceScopedResource {
    constructor(client: PlatformFetch, workspaceId: string);
    /**
     * Subscribe to the workspace event stream.
     *
     * Establishes an SSE connection to ``/v1/{workspace_id}/events/stream``
     * and invokes ``onEvent`` once per typed {@link WorkspaceSSEEvent}.
     * Unrecoverable failures (auth errors, exhausted reconnect budget,
     * caller abort) surface through ``onError``.
     *
     * Reconnection is automatic: on a network drop or 5xx, the helper
     * backs off (initial delay derived from the ``retry:`` directive,
     * default 3s, doubling with full jitter up to ``maxDelayMs``) and
     * resumes with the most recently seen ``Last-Event-ID``. The platform
     * buffers 5 minutes of events for gapless replay.
     *
     * @returns a {@link SubscriptionHandle} for cleanup. Aborting the
     *   caller's ``signal`` is equivalent to calling ``unsubscribe()``.
     */
    subscribeToWorkspace(options: SubscribeToWorkspaceOptions): SubscriptionHandle;
}
//# sourceMappingURL=events.d.ts.map