import type { SubscriptionCoreOperationLeaseRef } from "./operations.js"; import { type Settings } from "@opengeni/config"; import { SubscriptionPersonalAuthorityV2 } from "@opengeni/contracts"; import { type Ineligibility, type ModelCooldownCause, type PlacementSwitch, type ReselectionPoint, type ReselectionReason, type SubscriptionQuota } from "@opengeni/subscriptions"; import { type Database } from "../database.js"; import { type SubscriptionCoreAcceptedTurnIdentity } from "../subscription-core-placement-world.js"; import { type SubscriptionCoreProvider } from "./provider.js"; import { type SubscriptionCoreWaitPresentation } from "./wait-reason.js"; /** The exact accepted turn plus its immutable v2 authority, read once per attempt. */ export type SubscriptionCoreTurnIdentity = SubscriptionCoreAcceptedTurnIdentity & { /** Parsed from `session_turns.subscription_authority`; NULL means no personal authority. */ acceptedAuthorityV2: SubscriptionPersonalAuthorityV2; }; /** The live chat-turn lease that authorizes credential reads and writes. */ export type SubscriptionCoreLeaseRef = { connectionId: string; holderId: string; generation: number; }; /** * Read the session owner tuple and the turn's immutable v2 authority. The * owner is the session's recorded owner and its membership, never a viewer, * creator or live-membership inference; NULL authority is no personal * authority. A malformed stored value fails closed. */ export declare function readSubscriptionCoreTurnIdentity(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; }): Promise; /** * The accepted model and reasoning level of a (waiting) turn, for evaluating * where it could run. The frozen execution policy wins; the turn columns are * the fallback for turns accepted without one. The resumed attempt re-verifies * its policy at claim, so this read never authorizes anything by itself. */ export declare function readSubscriptionCoreTurnModel(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; turnId: string; }): Promise<{ productModelId: string; reasoningLevel: string; } | null>; /** * The RLS actor that core lease and credential operations run as for this turn. * * For a service-initiated turn in an owned session the session owner stands in * as the actor's initiating human, as `withSubscriptionCoreAcceptedTurn` does, * only so the owner's session rows are visible. It grants no personal * authority: personal access is decided from the turn's stored * `initiating_human_subject_id`, which stays NULL for service turns. The v2 * placement helper refuses a NULL turn human, and the lease guard's * `authorize_subscription_personal_access` matches the stored turn human * exactly, so a service turn never leases, reads or refreshes a personal * connection. */ export declare function subscriptionCoreTurnActor(identity: SubscriptionCoreAcceptedTurnIdentity): { subjectId: string; initiatingHumanSubjectId: string | null; }; export type SubscriptionCorePlacementRequest = { identity: SubscriptionCoreTurnIdentity; attemptId: string; executionGeneration: number; holderId: string; /** The turn's accepted product model; placement is strict to this provider's models. */ productModelId: string; reasoningLevel: string; leaseTtlMs: number; now?: Date; }; export type SubscriptionCorePlacement = { kind: "not_visible"; } /** Another attempt owns the turn, or a newer lease generation exists. */ | { kind: "attempt_fenced"; } /** * An older attempt's lease of this turn is still live; it expires at * `leasedUntil`. With `cause: "binding_conflict"`, no attempt holds the * turn: the session's binding kept changing while this placement was * deciding (retried like a busy lease). */ | { kind: "lease_busy"; leasedUntil: Date | null; cause?: "binding_conflict"; } | (SubscriptionCoreWaitPresentation & { kind: "wait"; /** When a quarantined connection in this world returns, if any. */ healthRetryAt: Date | null; explicitConnectionId: string | null; }) | { kind: "run"; connectionId: string; personal: boolean; switch: PlacementSwitch; /** This exact attempt already held a live lease on the connection. */ reusedLease: boolean; explicit: boolean; previousConnectionId: string | null; rotationMode: "primary_first" | "spread"; refreshGeneration: number; leasedUntil: Date; eligibleCount: number; connectedCount: number; /** * Why an automatic binding's account was not simply kept * (SUB-STICK-03): a forced reason or a cold cache. Null when the warm * account was kept, for an explicit choice and for a reused lease. */ reselection: { reason: ReselectionReason; ineligibility: readonly Ineligibility[]; points: readonly ReselectionPoint[]; } | null; }; /** * How long before its settlement a refusal's response headers may have * claimed the cooldown the settlement records (`recordSubscriptionCoreModelCooldown`). */ export declare const SUBSCRIPTION_CORE_REFUSAL_CLAIM_MS: number; /** * Re-selection points since the binding's last model call (SUB-STICK-05). * * - `model_changed`: the turn's accepted model is not the bound model. * - `compaction_completed`: the session's durable `session.context.compacted` * or `session.context.cleared` event occurred after the binding's last * model call, so the cached prefix the binding kept warm was replaced. The * explicit event is the marker: an unknown input-token count (an aggregate * usage fallback, a provider that reports none) is not a compaction. * * Both only ever release an automatic binding; an explicit choice is kept. */ export declare function subscriptionCoreReselectionPoints(input: { binding: { modelId: string; lastModelCallAt: number; } | null; productModelId: string; /** When the session's context was last compacted or cleared (epoch ms). */ lastContextReplacedAt: number | null; }): ReselectionPoint[]; export type SubscriptionCorePlacementEvaluation = { kind: "not_visible"; } | { kind: "run"; connectionId: string; switch: PlacementSwitch; } | (SubscriptionCoreWaitPresentation & { kind: "wait"; /** When a quarantined connection in this world returns, if sooner than any reset. */ healthRetryAt: Date | null; explicitConnectionId: string | null; }); export type SubscriptionCoreCredential = { connectionId: string; ownership: "shared" | "personal"; refreshGeneration: number; /** The decoded secret (the adapter's credential codec). */ credential: Credential; /** The provider's account id for this sign-in (sent upstream by some providers). */ providerAccountId: string | null; /** Provider-owned connection facts; only the provider's adapter interprets them. */ providerState: Record; planType: string | null; expiresAt: Date | null; lastRefreshAt: Date | null; }; export type SubscriptionCoreCredentialLoad = { kind: "loaded"; credential: SubscriptionCoreCredential; } | { kind: "lease_lost"; } /** The turn, or the connection under its authority, is not visible. */ | { kind: "not_visible"; } | { kind: "needs_relogin"; } | { kind: "unavailable"; }; export type SubscriptionCoreRefreshOutcome = { kind: "refreshed"; /** The rotated credential, already persisted. */ credential: unknown; refreshGeneration: number; planType: string | null; } /** Another refresh or credential writer already advanced the generation. */ | { kind: "superseded"; } | { kind: "relogin"; message: string; marked: boolean; } | { kind: "lease_lost"; } | { kind: "not_visible"; } | { kind: "refused"; } | { kind: "error"; error: unknown; }; export type SubscriptionCoreRefreshDeps = { now?: () => Date; /** * Called after a persisted refresh whose id_token reports a plan different * from the recorded one. The database already cleared the connection's * model cooldowns; the caller wakes waiters that may now place. */ onPlanChanged?: (connectionId: string) => void; }; /** * The chat-turn runtime bound to one provider: placement and lease, credential * load and refresh, health and quota observations, and settlement facts. One * instance per provider (memoized); the functions are identical for every * provider and take every provider fact from `provider`. */ export declare const subscriptionCoreTurns: (provider: SubscriptionCoreProvider) => { placeSubscriptionCoreTurn: (db: Database, request: SubscriptionCorePlacementRequest) => Promise; canSpendSubscriptionCoreExtraCredits: (db: Database, request: SubscriptionCorePlacementRequest & { connectionId: string; operationRef?: SubscriptionCoreOperationLeaseRef; }) => Promise; subscriptionCoreAcceptedTurnIsFunded: (db: Database, request: { accountId: string; workspaceId: string; sessionId: string; turnId: string; productModelId: string; }) => Promise; evaluateSubscriptionCorePlacement: (db: Database, request: { identity: SubscriptionCoreTurnIdentity; productModelId: string; reasoningLevel: string; now?: Date; }) => Promise; recoverSubscriptionCoreConnectionHealth: (db: Database, identity: SubscriptionCoreTurnIdentity) => Promise; quarantineSubscriptionCoreConnection: (db: Database, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, input: { kind: "sign_in" | "forbidden"; refreshGeneration: number; now?: Date; }) => Promise; recordSubscriptionCoreModelCooldown: (db: Database, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, input: { modelId: string; until: Date; refreshGeneration: number; refusedAt?: number; cause?: ModelCooldownCause; }) => Promise; authorizeSubscriptionCoreFrozenPersonal: (tx: Database, identity: SubscriptionCoreTurnIdentity) => Promise; loadSubscriptionCoreCredential: (db: Database, settings: Settings, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef) => Promise; refreshSubscriptionCoreCredential: (db: Database, settings: Settings, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, observedRefreshGeneration: number, deps?: SubscriptionCoreRefreshDeps) => Promise; recordSubscriptionCoreQuotaObservation: (db: Database, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, observation: SubscriptionQuota) => Promise; recordSubscriptionCoreTurnUsageReading: (db: Database, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, observation: SubscriptionQuota) => Promise; applySubscriptionCoreQuotaObservation: (db: Database, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, observation: SubscriptionQuota) => Promise<{ applied: boolean; recovered: boolean; }>; recordSubscriptionCoreTurnFailure: (db: Database, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, failure: { kind: string; evidence?: Record; }) => Promise; countSubscriptionCoreTurnRefusals: (db: Database, identity: SubscriptionCoreTurnIdentity) => Promise; touchSubscriptionCoreBinding: (db: Database, identity: SubscriptionCoreTurnIdentity, lease: SubscriptionCoreLeaseRef, lastModelCallAt: Date) => Promise; };