import { type OrchestratorToPlatformMessage, type WebhookRelay, type WebhookRelayResult, type TrustPolicyUpdate, type StaleCheckrunCleanup, type DashboardRunDetailRequest, type DashboardRunsListRequest, type DashboardRunsFiltersRequest, type DashboardSourcesListRequest, type DashboardStepLogsRequest, type DashboardOrchLogsRequest, type RunRerunRequest, type ManualScheduleRequest, type RunCancelRequest, type DashboardPayloadRequest, type DashboardPlatformToOrchMessage, type DashboardDiagnosticsRequest, type DashboardScalerCapacityRequest, type DashboardScalerAgentsRequest, type JoinRequest, type JoinResponse, type OrchCapabilities, type OrchRole } from '@kici-dev/engine';
import { RelayBufferRegistry, type RelayStartMeta } from '../webhook/relay-buffer.js';
/**
 * Verification + processing outcome returned by the chunked relay path's
 * `onVerifyInbound` callback. Mirrors the shape exported by
 * `webhook/verify-inbound.ts` so wiring is a single hand-off without an
 * adapter layer.
 */
export interface InboundVerifyOutcome {
    result: WebhookRelayResult;
    reason?: string;
}
export type ConnectionState = 'disconnected' | 'connecting' | 'authenticating' | 'authenticated';
/**
 * A webhook source that this orchestrator manages.
 * Sent to Platform after auth.success so the Platform knows which
 * routing keys this orchestrator handles.
 *
 * Note: webhookSecret is no longer included. Secrets are pushed separately
 * via source.secrets after loading from PgSecretStore.
 *
 * Single source of truth lives in `../entry-helpers.ts`. Re-exported here
 * so existing imports of `ProviderSource` from `./platform-client.js` keep
 * working without churn.
 */
export type { ProviderSource } from '../entry-helpers.js';
import type { ProviderSource } from '../entry-helpers.js';
export interface PlatformClientOptions {
    /** WebSocket URL of the Platform relay. */
    url: string;
    /** API key for authentication. */
    token: string;
    /** Callback invoked when a webhook relay is received from Platform. */
    onWebhookRelay: (relay: WebhookRelay) => Promise<void>;
    /** Provider sources to register after authentication. */
    providerSources?: ProviderSource[];
    /** Orchestrator cluster instance ID (sent in source.register for peer correlation). */
    instanceId?: string;
    /**
     * Human-friendly cluster name resolved on orch boot
     * (`cluster_meta.cluster_name`). Sent in source.register so Platform
     * can route per-orch dashboard requests by this identifier.
     */
    clusterName?: string;
    /**
     * Orchestrator DB identifier (UUID, seeded by migration 001 in
     * `cluster_meta` key `'cluster_id'`). Sent in source.register so
     * Platform can warn when two unrelated clusters in the same org
     * accidentally share a `clusterName`. HA siblings share the same orch
     * DB and therefore the same `clusterId`.
     */
    clusterId?: string;
    /** Reachable address for peer-to-peer connections (from KICI_CLUSTER_ADDRESS env var). Null if not configured. */
    address?: string | null;
    /** Orchestrator version string (e.g. "0.0.1"). Sent in source.register for diagnostics. */
    version?: string;
    /** Orchestrator config mode. Sent in source.register for diagnostics. */
    mode?: string;
    /** Scaler backends configured (e.g. ["container", "firecracker"]). Sent in source.register for diagnostics. */
    scalerBackends?: string[];
    /** Whether this orchestrator has S3 log storage configured. Sent in source.register for pool validation. */
    s3LogAccess?: boolean;
    /** Queue timeout in ms. Sent in source.register for Platform safety-net GC. */
    queueTimeoutMs?: number;
    /** Heartbeat interval in ms. Default: 30000 (30s). */
    heartbeatIntervalMs?: number;
    /** Maximum reconnect delay in ms. Default: 60000 (60s). */
    maxReconnectDelayMs?: number;
    /** Maximum event buffer size. Default: 10000. */
    maxBufferSize?: number;
    /** Optional callback for log pull requests from Platform. */
    onLogPullRequest?: (msg: {
        messageId: string;
        executionId: string;
        jobName?: string;
        stepIndex?: number;
        cursor?: number;
        limit?: number;
    }) => void;
    /** Optional callback for peer discovery (from Platform matchmaker). */
    onPeerDiscover?: (peer: {
        connectionId: string;
        instanceId?: string;
        address: string | null;
        routingKeys: string[];
        orchRole?: OrchRole;
    }) => void;
    /** Optional callback invoked after successful authentication and source registration. */
    onAuthenticated?: () => void;
    /** Optional callback for dashboard run detail requests from Platform. */
    onDashboardRunDetail?: (msg: DashboardRunDetailRequest) => void;
    /** Optional callback for dashboard runs.list (operator console) requests from Platform. */
    onDashboardRunsList?: (msg: DashboardRunsListRequest) => void;
    /** Optional callback for dashboard runs.filters (operator console) requests from Platform. */
    onDashboardRunsFilters?: (msg: DashboardRunsFiltersRequest) => void;
    /** Optional callback for dashboard sources.list (operator console) requests from Platform. */
    onDashboardSourcesList?: (msg: DashboardSourcesListRequest) => void;
    /** Optional callback for dashboard step logs requests from Platform. */
    onDashboardStepLogs?: (msg: DashboardStepLogsRequest) => void;
    /** Optional callback for run re-run requests from Platform (dashboard action). */
    onRunRerun?: (msg: RunRerunRequest) => void;
    /** Optional callback for manual schedule trigger requests from Platform (dashboard action). */
    onManualSchedule?: (msg: ManualScheduleRequest) => void;
    /** Optional callback for run cancel requests from Platform (dashboard action). */
    onRunCancel?: (msg: RunCancelRequest) => void;
    /** Optional callback for dashboard payload requests from Platform. */
    onDashboardPayload?: (msg: DashboardPayloadRequest) => void;
    /** Optional callback for dashboard orchestration logs requests from Platform. */
    onDashboardOrchLogs?: (msg: DashboardOrchLogsRequest) => void;
    /** Optional callback for dashboard environment/held-run messages from Platform. */
    onDashboardEnvMessage?: (msg: DashboardPlatformToOrchMessage) => void;
    /** Optional callback for dashboard diagnostics requests from Platform. */
    onDashboardDiagnostics?: (msg: DashboardDiagnosticsRequest) => void;
    /** Optional callback for dashboard scaler capacity requests from Platform. */
    onDashboardScalerCapacity?: (msg: DashboardScalerCapacityRequest) => void;
    /** Optional callback for dashboard scaler agents requests from Platform. */
    onDashboardScalerAgents?: (msg: DashboardScalerAgentsRequest) => void;
    /** Optional callback for trust policy updates pushed from Platform. */
    onTrustPolicyUpdate?: (msg: TrustPolicyUpdate) => void;
    /** Optional callback for stale check run cleanup requests from Platform. */
    onStaleCheckrunCleanup?: (msg: StaleCheckrunCleanup) => void;
    /** Optional callback for join requests relayed via Platform. */
    onJoinRequest?: (msg: JoinRequest) => Promise<JoinResponse>;
    /** Custom orchestrator capabilities to merge with ORCH_CAPABILITIES in auth.request. */
    orchCapabilities?: Partial<OrchCapabilities>;
    /**
     * Verify a reassembled inbound webhook from the chunked relay path.
     *
     * Wired to `verifyInboundWebhook(deps, ...)` in production. Required when
     * Platform sends `webhook.relay.start`/`webhook.relay.chunk` (chunked path);
     * if absent, the orchestrator ACKs `rejected_misconfigured` because it
     * cannot perform the trust check the new design requires.
     */
    onVerifyInbound?: (meta: RelayStartMeta, body: Buffer) => Promise<InboundVerifyOutcome> | InboundVerifyOutcome;
    /**
     * Optional injected reassembly registry. Tests pass a registry with a short
     * TTL; production constructs a default one per PlatformClient.
     */
    relayBuffer?: RelayBufferRegistry;
}
/**
 * WebSocket client that connects the orchestrator to the Platform relay.
 *
 * Handles:
 * - Authentication handshake (auth.request -> auth.success/failure)
 * - Periodic heartbeat messages to keep the connection alive
 * - Auto-reconnect with exponential backoff (1s initial, 1.5x, jitter, 60s max)
 * - Webhook relay reception and ACK responses
 * - Event buffering during disconnection with flush on reconnect
 */
export declare class PlatformClient {
    private ws;
    private _state;
    private readonly eventBuffer;
    private heartbeatTimer;
    private reconnectTimer;
    private reconnectAttempts;
    private intentionalDisconnect;
    private readonly url;
    private readonly token;
    private readonly onWebhookRelay;
    private providerSources;
    /**
     * Pending `registerSourceAndAwait()` callers, keyed by routing key. Resolved
     * with the Platform-computed webhook URL when the matching
     * `source.register.ack` arrives, or rejected on timeout / disconnect.
     */
    private readonly pendingSourceRegistrations;
    private readonly instanceId?;
    private readonly clusterName?;
    private readonly clusterId?;
    private readonly address?;
    private readonly version?;
    private readonly mode?;
    private readonly scalerBackends?;
    private readonly s3LogAccess?;
    private readonly queueTimeoutMs?;
    private readonly heartbeatIntervalMs;
    private readonly maxReconnectDelayMs;
    private readonly onLogPullRequest?;
    private readonly onPeerDiscover?;
    private readonly onAuthenticated?;
    private readonly onDashboardRunDetail?;
    private readonly onDashboardRunsList?;
    private readonly onDashboardRunsFilters?;
    private readonly onDashboardSourcesList?;
    private readonly onDashboardStepLogs?;
    private readonly onRunRerun?;
    private readonly onManualSchedule?;
    private readonly onRunCancel?;
    private readonly onDashboardPayload?;
    private readonly onDashboardOrchLogs?;
    private readonly onDashboardEnvMessage?;
    private readonly onDashboardDiagnostics?;
    private readonly onDashboardScalerCapacity?;
    private readonly onDashboardScalerAgents?;
    private readonly onTrustPolicyUpdate?;
    private readonly onStaleCheckrunCleanup?;
    private readonly onJoinRequest?;
    private orchCapabilities;
    private readonly onVerifyInbound?;
    private readonly relayBuffer;
    /**
     * Public alias of the orchestrator's owning org as supplied by
     * Platform on `auth.success`. Used by the check-run emitter to build
     * outbound `details_url`s that hide the canonical `org_<12-char>` id.
     * `undefined` when the orchestrator runs against a Platform that
     * predates the alias plumbing, or before the first successful auth.
     */
    private _orgPublicAlias?;
    /**
     * Returns the cached public alias of the orchestrator's owning org,
     * or `undefined` if Platform has not supplied one yet. Read by
     * `check-run-reporter.ts` when building `details_url`.
     */
    getOrgPublicAlias(): string | undefined;
    constructor(options: PlatformClientOptions);
    /**
     * Merge `updates` into the stored orch capabilities and broadcast the
     * full set to Platform via `orch.capabilities.update`. Buffers via
     * `send()` when not yet authenticated. The next `auth.request` will
     * also carry the merged capabilities, so a reconnect-followed-by-
     * runtime-broadcast still ends Platform in the correct cache state.
     */
    broadcastCapabilities(updates: Partial<OrchCapabilities>): void;
    /**
     * Current merged orchestrator capabilities. Read-only view used by
     * tests and diagnostics; mutate via `broadcastCapabilities`.
     */
    getCapabilities(): OrchCapabilities;
    /** Current connection state. */
    get state(): ConnectionState;
    /** Number of messages currently buffered. */
    getBufferedCount(): number;
    /**
     * Complete a chunked webhook relay: verify, process if accepted, ACK.
     *
     * Called from the `webhook.relay.chunk` handler once `relayBuffer.chunk(...)`
     * returns `{ status: 'completed' }`. This sequence is intentionally single-pass
     * and inside `requestContext.run` so trace propagation works end-to-end.
     */
    private completeChunkedRelay;
    /**
     * Initiate connection to the Platform relay.
     * Starts the connect -> authenticate -> ready lifecycle.
     */
    connect(): void;
    /**
     * Gracefully disconnect from Platform. Does not trigger reconnection.
     */
    disconnect(): void;
    /**
     * Send a message to Platform. If authenticated, sends immediately.
     * If not authenticated, buffers the message for later delivery.
     */
    send(message: OrchestratorToPlatformMessage): void;
    /**
     * Send a raw message directly on the WebSocket, bypassing typed validation.
     * Used for log pull response messages (log.response) which are
     * NOT in the OrchestratorToPlatformMessage union (they are in the separate log pull schema).
     */
    sendRaw(data: unknown): void;
    /**
     * Register a new source at runtime (e.g., after config reload adds a new GitHub app).
     * Separate from the post-auth registration which sends all sources at once.
     */
    sendSourceRegister(source: ProviderSource): void;
    /**
     * Deregister sources at runtime (e.g., after config reload removes a GitHub app).
     * Tells Platform to stop routing webhooks for these routing keys to this orchestrator.
     */
    sendSourceDeregister(source: {
        routingKey: string;
    }): void;
    /**
     * Diff current provider sources with new ones and send register/deregister as needed.
     * Convenience method for config reload that atomically updates routing.
     */
    updateSources(newSources: ProviderSource[]): void;
    /**
     * Push the full source list to the Platform and resolve with the webhook URL
     * the Platform computed for `routingKey` (from the `source.register.ack`), or
     * `null` if the Platform has no public webhook base configured.
     *
     * Used by `kici-admin source add` (platform/hybrid mode) to print the URL
     * synchronously. Passing the **full** source list keeps this on the single
     * `updateSources` push path — the routing key being newly added means
     * `updateSources` emits a `source.register` whose ack carries the URL; the
     * later NOTIFY-driven republish then diffs to a no-op.
     *
     * Rejects on timeout or disconnect; the caller degrades to a "(unavailable)"
     * note rather than fabricating a URL.
     */
    registerSourceAndAwait(fullSources: ProviderSource[], routingKey: string, timeoutMs?: number): Promise<string | null>;
    /**
     * Reject every pending `registerSourceAndAwait()` — called on disconnect so a
     * `source add` issued while the link drops fails fast instead of hanging.
     */
    private rejectPendingSourceRegistrations;
    getReconnectDelay(): number;
    private doConnect;
    private handleMessage;
    /**
     * Try the two non-mainline schemas (log-pull, cluster join.request) when
     * the primary `platformToOrchestratorMessageSchema` failed to parse. Falls
     * back to a structured warning if neither schema matches.
     */
    private handleNonStandardMessage;
    /**
     * Dispatch a parsed platform message to the appropriate per-area
     * handler. Each `case` either inlines a tiny dispatch (for one-line
     * forwards to a callback) or delegates to a private method when the
     * branch carries non-trivial logic.
     */
    private dispatchPlatformMessage;
    private handleAuthSuccess;
    private handleAuthFailure;
    private handleWebhookRelayStart;
    private handleWebhookRelayChunk;
    private handleSourceRegisterAck;
    private handlePeerDiscover;
    private handlePeerUpdate;
    /**
     * Send a message directly on the WebSocket without buffering.
     * Used for ACK responses that must go immediately.
     */
    private sendDirect;
    private flushBuffer;
    private startHeartbeat;
    private stopHeartbeat;
    private scheduleReconnect;
    private cancelReconnect;
}
//# sourceMappingURL=platform-client.d.ts.map