import { type SQL } from "drizzle-orm"; import type { ConnectionKind, ProviderId, SubscriptionConnection, SubscriptionQuota, SubscriptionSettingValues } from "@opengeni/subscriptions"; import { type Database } from "./database.js"; export type EffectiveSubscriptionSettingsRow = { values: SubscriptionSettingValues; sources: { rotation: Record; providers: Record; fallbackOrder: Record; crossProviderFailover: "organization" | "workspace"; personalConnectionsAllowed: "organization" | "workspace"; personalFallbackAllowed: "organization" | "workspace"; }; }; /** Typed M2 persistence seam; no production selector calls this repository yet. */ export declare function readSubscriptionEffectiveSettings(db: Database, accountId: string, workspaceId: string): Promise; /** * The resolver still reports the retired per-workspace source keys * (`useOrganizationAccounts`, `inferenceSource`) for binaries that straddle * 0907. Every account that reaches a workspace serves it now (D-50), so a * provider carries only its switch. Null (no settings row yet) stays null. */ export declare function withoutRetiredProviderKeys(effective: T): T; /** * The status of `alias`'s connection row as an availability read sees it at * `now`. A timed 403 quarantine is `error` with `health_retry_at` (only the * quarantine writer sets it; any other status or error write drops it). * From that time on the connection reads * `active`, without waiting for a turn to run the recovery routine, which * stores the same transition for the connections that turn may lease. * A quarantine without a deadline remains an error until reconnect. */ export declare function subscriptionConnectionEffectiveStatus(alias: string, now?: SQL): SQL; /** The row's last error as availability reads see it: none once its quarantine ended. */ export declare function subscriptionConnectionEffectiveLastError(alias: string, now?: SQL): SQL; /** * Read the provider/workspace-visible connection world for the pure placement * policy. Account and workspace are mandatory; provider and connection kind * may narrow the result (the shared core passes both: a row of another kind * is never placed for a provider, rather than placed and refused at * credential load). * Callers cannot accidentally turn this into a viewer-derived or cross-account pool read. * Credential ciphertext is deliberately never selected here. * * `health` says how an ended quarantine reads. `effective`: healthy, for a * reader that only decides availability (admission, the catalog), which * cannot run the recovery routine. `stored`: still `error`, for placement of * an accepted turn, whose lease and credential reads enforce the stored * status; the turn recovers ended quarantines before it places, and one that * ends after that recovery waits for the turn's next check rather than being * leased and refused at credential load. */ export declare function listSubscriptionConnectionsForPlacement(db: Database, input: { accountId: string; workspaceId: string; provider?: ProviderId; kind?: ConnectionKind; now?: Date; health: "effective" | "stored"; }): Promise; export declare function decodeSubscriptionQuota(row: { quota: unknown; quota_revision: number | string | null; quota_observed_refresh_generation: number | string | null; quota_updated_at: Date | string | null; }): SubscriptionQuota | null; /** * Record, inside the caller's transaction, that the provider reset a * connection's rate limits at `resetAt` (`quotaAfterRateLimitReset`): the * stored windows and exhaustion deadline are invalidated, so placement no * longer waits on readings taken before the reset. Only a quota observed with * the connection's current refresh generation is rewritten (an observation of * an older credential is left for the generation fence to discard). Returns * whether the stored quota changed. */ export declare function recordSubscriptionCoreRateLimitResetInTransaction(tx: Database, input: { accountId: string; provider: ProviderId; connectionId: string; resetAt: Date; }): Promise; /** Canonical IDs win; otherwise resolve one visible provider-scoped alias. */ export declare function resolveSubscriptionConnectionId(db: Database, input: { accountId: string; provider: ProviderId; connectionId: string; }): Promise; export type SubscriptionSessionBinding = { accountId: string; workspaceId: string; sessionId: string; provider: ProviderId; connectionId: string | null; modelId: string; choice: "automatic" | "explicit"; onlyThisModel: boolean; lastModelCallAt: Date | null; lastSwitchReason: "initial" | "reselected_cold" | "failover_same_provider" | "failover_cross_provider" | "return_to_preferred" | "explicit_choice" | "revoked" | null; version: number; }; /** * The session's binding for one provider (0733, D-32): a session keeps one * binding per provider, and a provider reads and writes only its own. */ export declare function readSubscriptionSessionBinding(db: Database, input: { workspaceId: string; sessionId: string; provider: ProviderId; /** * Lock the row until the transaction ends, so a placement compares and * writes the binding it decided from while parallel placements of the * same session wait (SUB-STICK-02). */ forUpdate?: boolean; }): Promise; /** * Whether an error is a concurrent first binding of the session meeting 0733's * rolling `(workspace_id, session_id)` index. That index is not the conflict * target of `writeSubscriptionSessionBinding`, so two first bindings of one * session can race on it as a unique violation instead of a lost * compare-and-swap. Callers treat it as the lost compare-and-swap; the * transaction (or savepoint) is aborted and must be retried in a new one. */ export declare function isSubscriptionSessionBindingRollingConflict(error: unknown): boolean; /** * Inserts the provider's binding once or compare-and-swaps its version. A * binding never changes provider (the 0733 trigger refuses it). While 0733's * rolling index exists a racing first binding can fail with * `isSubscriptionSessionBindingRollingConflict`. */ export declare function writeSubscriptionSessionBinding(db: Database, input: Omit & { expectedVersion?: number | null; }): Promise; /** * Record a use of the bound account's prompt cache on the session binding * (SUB-STICK-04): the clock placement measures warmth from. It moves only * forward and only while the binding still names this provider's connection, * so a use on an account the session has already left never warms the new * one. The clock is not part of the binding's version: the version guards the * account, model and choice, and a clock-only advance must not make a * concurrent placement or pin lose its compare-and-swap. * * A cleared clock (a pin change, or a switch by a writer that stated none) * means the next turn re-runs selection (SUB-STICK-05, D-31). Only a * placement restarts it (`restart: true`); a request or completed call of the * turn already running never does, so removing a pin mid-turn still takes * effect at the next turn. */ export declare function advanceSubscriptionBindingCacheClock(db: Database, input: { workspaceId: string; sessionId: string; provider: ProviderId; connectionId: string; at: Date; /** A placement on the account: may start a cleared clock. */ restart?: boolean; }): Promise; export declare function createSubscriptionConnection(db: Database, input: { accountId: string; provider: ProviderId; kind: "subscription" | "api_key"; credentialEncrypted: string; providerAccountId?: string | null; }): Promise; export type SubscriptionTurnLeaseIdentity = { accountId: string; workspaceId: string; sessionId: string; turnId: string; provider: ProviderId; connectionId: string; holderId: string; generation: number; }; export type SubscriptionTurnLease = SubscriptionTurnLeaseIdentity & { leasedUntil: Date; }; /** * Whether a turn lease row still holds its turn: unexpired, and its holder * generation's attempt has neither written its quiescence receipt nor been * closed for worker death (`lease_lost_recoverable`: the activity stopped * heartbeating for its whole heartbeat timeout and the turn was redispatched). * Either way that attempt has lost inference authority for good, so a crashed * or force-stopped worker that never ran its own release must not keep a newer * generation of the same turn waiting for the TTL. Renew, assert and usage * finalization keep the plain expiry fence: the holder may still finish usage * accounting after its receipt, but a newer generation can take the turn over * meanwhile, and a holder that was only partitioned loses its lease at its next * renewal once the newer generation replaced the row. */ export declare function subscriptionTurnLeaseHeldSql(table?: string): SQL; /** * Acquire the chat-turn lease after core placement and immediately rechecking * current eligibility. Replays by the same holder/connection/generation are * idempotent. A stale holder can be replaced only by a strictly newer * generation for the same turn and session, and only after the lease expired * or the holder generation's attempt wrote its quiescence receipt or was closed * for worker death. */ export declare function acquireSubscriptionTurnLease(db: Database, input: SubscriptionTurnLeaseIdentity & { ttlMs: number; }): Promise; /** * Persist one successful token refresh through the private database seam. * Call only inside withSubscriptionCoreRefreshLock for the same provider, * immediately after the provider returns. SQL consumes the one-shot * authorization that begin_subscription_core_refresh minted in the same * transaction and writes * under the refresh lock and refresh-generation compare-and-swap, so a caller * cannot turn the helper into a general credential update API, and a rotated * token is not discarded because the lease or visibility changed meanwhile. */ export declare function persistSubscriptionCoreRefresh(db: Database, input: { provider: ProviderId; accountId: string; workspaceId: string; sessionId: string; turnId: string; connectionId: string; expectedRefreshGeneration: number; credentialEncrypted: string; expiresAt: Date | null; lastRefreshAt: Date; }): Promise; /** * persistSubscriptionCoreRefresh plus the plan the rotated credential reports * (M3 PR 2a). Same one-shot authorization, advisory lock and * refresh-generation compare-and-swap; a NULL plan keeps the recorded plan, * and a changed plan clears the connection's model cooldowns. * * Every refresh path persists through it (migration 1367): a chat turn's * refresh names its session and turn and consumes the authorization * begin_subscription_core_refresh minted; a refresh outside a turn * (operations, usage reads, administered connections) passes null for both * and consumes the one begin_subscription_core_connection_refresh or * begin_subscription_core_owned_connection_refresh minted. */ export declare function persistSubscriptionCoreRefreshWithPlan(db: Database, input: Omit[1], "sessionId" | "turnId"> & { /** The chat turn's session and turn; both null for a refresh outside a turn. */ sessionId: string | null; turnId: string | null; planType: string | null; }): Promise; /** * An organization administrator's refresh of an organization-managed * connection (an organization usage read). The same refresh write as * persistSubscriptionCoreRefreshWithPlan (migration 1515): the rotated * credential, the plan it reports (null keeps the recorded plan), the * refresh-generation compare-and-swap and the model-cooldown reset on a plan * change. The routine runs with the caller's rights, so the organization * update policy decides whether the write is admitted; the caller holds the * per-connection refresh lock and has locked the row it may refresh. */ export declare function persistSubscriptionCoreAdministratorRefresh(db: Database, input: { provider: ProviderId; accountId: string; connectionId: string; expectedRefreshGeneration: number; credentialEncrypted: string; expiresAt: Date | null; lastRefreshAt: Date; planType: string | null; }): Promise; /** Renew only the exact, still-live chat-turn lease generation. */ export declare function renewSubscriptionTurnLease(db: Database, input: SubscriptionTurnLeaseIdentity & { ttlMs: number; }): Promise; /** Pre-dispatch fence; placement and current eligibility are separate checks. */ export declare function assertSubscriptionTurnLeaseCurrent(db: Database, input: SubscriptionTurnLeaseIdentity): Promise; /** Release is fenced by turn, connection, holder and generation. */ export declare function releaseSubscriptionTurnLease(db: Database, input: SubscriptionTurnLeaseIdentity): Promise; export type SubscriptionOperationKind = "session_title" | "image" | "video" | "realtime" | "transcription" | "completion"; export type SubscriptionOperationLeaseIdentity = { accountId: string; workspaceId: string; operationId: string; attemptId: string; operationKind: SubscriptionOperationKind; sessionId?: string | null; turnId?: string | null; provider: ProviderId; connectionId: string; holderId: string; generation: number; }; export type SubscriptionOperationLease = SubscriptionOperationLeaseIdentity & { leasedUntil: Date; }; /** * Acquire a lease for one durable operation. Replays of the same exact * generation are idempotent; a later generation can replace only an expired * lease. A caller must first own the corresponding operation-ledger claim. */ export declare function acquireSubscriptionOperationLease(db: Database, input: SubscriptionOperationLeaseIdentity & { ttlMs: number; }): Promise; /** Renew only the exact, still-live operation lease generation. */ export declare function renewSubscriptionOperationLease(db: Database, input: SubscriptionOperationLeaseIdentity & { ttlMs: number; }): Promise; /** Pre-dispatch fence; the caller must separately recheck current eligibility. */ export declare function assertSubscriptionOperationLeaseCurrent(db: Database, input: SubscriptionOperationLeaseIdentity): Promise; /** Release is fenced by operation, attempt, holder and generation. */ export declare function releaseSubscriptionOperationLease(db: Database, input: SubscriptionOperationLeaseIdentity): Promise; export type SubscriptionCapacityWaiter = { accountId: string; workspaceId: string; sessionId: string; turnId: string; waiterId: string; provider: ProviderId; waitReason: string; policyHash?: string | null; resetKind?: string | null; refreshAttempt?: number; resumedUpdateId?: string | null; earliestResetAt?: Date | null; generation: number; wakeRevision: number; observedWakeRevision: number; nextCheckAt?: Date | null; blockedTurnGeneration?: number | null; }; /** Upsert is monotonic: stale generations cannot replace the current waiter. */ export declare function upsertSubscriptionCapacityWaiter(db: Database, input: SubscriptionCapacityWaiter): Promise; /** Bump one exact waiter's revision; workflow signalling remains outbox-owned. */ export declare function wakeSubscriptionCapacityWaiter(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; nextCheckAt?: Date | null; }): Promise; export type SubscriptionCapacityWakeDelivery = { id: string; accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; wakeRevision: number; claimGeneration: number; /** Delivery attempts including this claim. */ attemptCount: number; }; /** * Claims due wake obligations under the trusted empty-subject worker scope. * Claim generations fence a delayed Temporal signaler from a later retry. */ export declare function claimSubscriptionCapacityWakeDeliveries(db: Database, input: { limit: number; claimTtlMs: number; }): Promise; export declare function markSubscriptionCapacityWakeDelivered(db: Database, input: { id: string; claimGeneration: number; }): Promise; /** Failure codes are deliberately bounded identifiers, never exception text. */ export declare function retrySubscriptionCapacityWakeDelivery(db: Database, input: { id: string; claimGeneration: number; retryInMs: number; failureCode: string; }): Promise; /** * Stop retrying one typed wake signal after its bounded attempts. The waiter's * wake revision stays unobserved, and the same commit also queued the generic * session workflow wake, so the workflow still re-evaluates the waiter; only * the typed fast path is given up. */ export declare function abandonSubscriptionCapacityWakeDelivery(db: Database, input: { id: string; claimGeneration: number; failureCode: string; }): Promise; export type DueSubscriptionCapacityWaiter = { accountId: string; workspaceId: string; sessionId: string; turnId: string; waiterId: string; provider: ProviderId; generation: number; wakeRevision: number; observedWakeRevision: number; nextCheckAt: Date | null; }; /** Lists due or newly-woken waiters inside the caller's authorized workspace scope. */ export declare function listDueSubscriptionCapacityWaiters(db: Database, input: { provider?: ProviderId; limit: number; }): Promise; /** Acknowledges only the revision actually observed by the workflow. */ export declare function observeSubscriptionCapacityWaiterWake(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; waiterId: string; generation: number; wakeRevision: number; }): Promise;