import { type SessionUsageLimit, type SessionUsageLimitReachedRefusal } from "@opengeni/contracts"; import { type Database, type SessionActivityDatabase } from "./database.js"; /** * Per-task (root session) API-equivalent usage limits. * * All state lives in owner-only FORCE-RLS private tables reached through one * SECURITY DEFINER command routine. Settlement is synchronous and exactly-once * per canonical producer identity; admission reads one indexed counter row and * probes the partial index of open single-call custody markers. * Limits are admission policy, never reservations: already admitted requests * may finish above the limit. */ type Scope = { accountId: string; workspaceId: string; }; /** The state could not be read or written. Callers must block new model requests, never assume unlimited. */ export declare class SessionUsageLimitUnavailableError extends Error { readonly code = "session_usage_limit_unavailable"; /** * `custody_pending`: an earlier single model call in the task tree still * owes its receipt (a fenced marker, or an open one past the overdue * window). Not a database outage: the owner fills it or maintenance * discloses it as unpriced, after which admission proceeds. * `not_found`: the task for a runtime request could not be resolved. */ readonly reason: "unavailable" | "custody_pending" | "not_found"; constructor(message?: string, options?: { cause?: unknown; reason?: "unavailable" | "custody_pending" | "not_found"; }); } /** Agents (including delegated-human or admin-access agents) can never change a limit. */ export declare class SessionUsageLimitForbiddenError extends Error { readonly code = "session_usage_limit_forbidden"; constructor(message?: string); } export type SessionUsageLimitReadResult = { outcome: "ok"; state: SessionUsageLimit; } | { outcome: "not_found"; }; export type SessionUsageLimitSetOutcome = "ok" | "replayed" | "conflict" | "operation_conflict" | "not_root" | "preparing" | "disabled" | "not_found"; export type SessionUsageLimitSetResult = { outcome: SessionUsageLimitSetOutcome; state: SessionUsageLimit | null; rootSessionId: string | null; /** Set when `outcome === "ok"`: the appended `session.usage_limit.updated` event id. */ eventId?: string; }; export type SessionUsageReceiptOutcome = "recorded" | "duplicate" | "filled" | "conflict" | "source_gone"; /** Strip internal diagnostics and normalize bigint-as-number JSON to the public projection. */ export declare function projectSessionUsageLimitState(raw: unknown): SessionUsageLimit; /** Diagnostic-only count of rejected conflicting receipts (never in the public projection). */ export declare function sessionUsageLimitConflictCount(raw: unknown): number; /** * Read a session's task usage state (through a descendant, the root's state * with `inherited: true`). `subjectId` applies private-session visibility; a * hidden session is reported as `not_found`. `prepare` advances one bounded * page of a pending historical import inline. * * `runtime` is for server-internal admission on behalf of an already * authorized task attempt: the session is resolved tenant-bounded with private * visibility cleared, so a private root is enforced rather than read as * missing. `openSourceId` (runtime only) opens a pending custody marker for a * single call in the same statement, only when the call is admitted. */ export declare function readSessionUsageLimit(db: Database, input: Scope & { sessionId: string; subjectId?: string | null; prepare?: boolean; runtime?: boolean; openSourceId?: string; }): Promise; export type SessionUsageLimitAdmission = { allowed: true; state: SessionUsageLimit | null; } | { allowed: false; refusal: SessionUsageLimitReachedRefusal; state: SessionUsageLimit; }; /** Build the typed refusal for a reached state. */ export declare function sessionUsageLimitRefusal(state: SessionUsageLimit): SessionUsageLimitReachedRefusal | null; /** * Admission check for one new model request, message or goal resume. Reads * the latest durable root counter (one indexed row, no event scan). * * People-facing checks admit a missing or hidden session as unlimited only * because no session exists to account against. Runtime checks fail closed: * the attempt already owns the session, so a missing tree, a read failure or a * fenced custody marker (an earlier single call whose usage could not be * recorded) throws `SessionUsageLimitUnavailableError`. */ export declare function checkSessionUsageLimitAdmission(db: Database, input: Scope & { sessionId: string; subjectId?: string | null; runtime?: boolean; openSourceId?: string; }): Promise; /** * Mark an open custody marker as fenced after its owner failed to fill it, so * the task blocks new model requests at once instead of after the overdue * window. Best effort: callers keep the unrecorded receipt for retry. */ export declare function fenceSessionUsageReceipt(db: Database, input: Scope & { sessionId: string; sourceId: string; }): Promise<"fenced" | "not_pending" | "source_gone">; /** * Remove an unfenced custody marker whose single call returned no response * (the provider request failed before any usage was reported). */ export declare function releaseSessionUsageReceipt(db: Database, input: Scope & { sessionId: string; sourceId: string; }): Promise<"released" | "not_pending" | "source_gone">; /** * Record one settled model response against its task root, synchronously and * exactly once per `sourceId` (the canonical producer identity). `amountMicros` * is the pre-margin `estimatedProviderCostMicros`; null with no pricing source * records an unpriced call (excluded from the total and disclosed). Failures * throw: the caller must not dispatch another model request until a later * settlement or admission read succeeds. */ export declare function settleSessionUsageReceipt(db: Database, input: Scope & { sessionId: string; sourceId: string; turnId?: string | null; amountMicros: number | null; pricingSource: "configured_list_price" | "gateway_reported" | null; model?: string | null; }): Promise<{ outcome: SessionUsageReceiptOutcome; state: SessionUsageLimit | null; }>; export type SessionUsageLimitWriteActor = { /** Verified human subject or trusted host identity; never an agent attempt. */ subjectId: string; type: "human" | "host"; }; /** * Compare-and-set a root task's limit inside the caller's session-activity * transaction, appending `session.usage_limit.updated` on change. Takes the * canonical workspace/session event-write prefix before the private counter * row. Never wakes, resumes or interrupts a turn. */ type SessionUsageLimitSetInput = Scope & { sessionId: string; limitMicros: number | null; /** Recurring window: omitted keeps the current one, null removes it. */ window?: { period: "day"; timeZone: string; } | null; expectedVersion: number; operationId: string; actor: SessionUsageLimitWriteActor; /** Producer flag; when false only clearing (null) is accepted. */ producerEnabled: boolean; }; /** * The limit a person or trusted host requested on create, applied inside the * session-creating transaction (which already owns the new row) before the * initial turn can be claimed. No event: the create response carries the * state. Version 0 and a create-scoped operation make it exactly once. */ export declare function setInitialSessionUsageLimitInTransaction(db: Database, input: Omit): Promise; /** * A later change to a root's limit: CAS on `expectedVersion`, idempotent on * `operationId`, and a durable `session.usage_limit.updated` event under the * canonical session event-write locks. */ export declare function setSessionUsageLimitInTransaction(db: SessionActivityDatabase, input: SessionUsageLimitSetInput): Promise; export type SessionUsageLimitMaintenanceResult = { /** Roots whose import advanced a page. */ processed: number; /** Roots whose import page failed and was backed off. */ failed: number; /** Content-free failure diagnostics: SQLSTATE to count. */ errors: Record; /** Custody markers left unfilled past the lost window, now disclosed as unpriced. */ resolvedLost: number; }; /** * One bounded, resumable maintenance pass: advance the historical import for * roots created before this feature (failed pages back off exponentially and * keep their SQLSTATE) and resolve lost single-call custody markers. Safe to * call from any periodic maintenance loop. */ export declare function maintainSessionUsageLimits(db: Database, input?: { limit?: number; budget?: number; }): Promise; export {};