import { sql } from "drizzle-orm"; import { rawRows, setSubjectRlsContext, withRlsContext, type Database } from "./database"; import { currentCreditDebitAttribution } from "./credit-debit-attribution"; /** All amounts are integer USD micros, never dollars or floating-point credits. */ export type MemberAllowanceRule = { share: number } | { credits: number } | null; /** * How model calls that spend no Opengeni credits (subscription connections, * workspace keys, deployments without credit billing) count. "ignore" (the * default) keeps the allowance credit-only; "list_price" counts them at the * configured list-price estimate and admits their turns against it. */ export type UnbilledUsageMetering = "ignore" | "list_price"; export type WorkspaceAllowanceConfig = { includedCredits: number; period: "monthly" | "none"; anchorDay?: number; memberDefault?: "none" | "equal_share" | Exclude; thresholds?: { workspace?: number[]; member?: number[] }; unbilledUsage?: UnbilledUsageMetering; }; export type WorkspaceAllowance = WorkspaceAllowanceConfig & { version: number }; export type WorkspaceAllowanceState = { version: number; config: WorkspaceAllowance | null }; export type AllowanceStatus = "ok" | "warning" | "exhausted"; export type AllowanceUsage = { limit: number | null; used: number; remaining: number | null; fraction: number | null; status: AllowanceStatus; resetsAt: string | null; }; export type MemberAllowance = { subjectId: string; rule: MemberAllowanceRule; version: number; }; export type WorkspaceUsage = { /** Every amount is an integer USD micro: 1 USD = 1,000,000. */ unit: "usd_micros"; /** The window the counters cover, configured or not; null when unknown or lifetime. */ period: { start: string | null; end: string | null }; workspace: AllowanceUsage & { includedCredits: number; grantsRemaining: number }; members: (AllowanceUsage & MemberAllowance & { externalIdentity: { source: string; externalId: string } | null; })[]; nextCursor: string | null; }; export type AllowanceExhausted = { code: "allowance_exhausted"; scope: "workspace" | "member"; resetsAt: string | null; subjectId?: string; message: string; }; type Scope = { accountId: string; workspaceId: string }; type Actor = { actorSubjectId: string; actorType?: string | undefined }; export class UsageAllowanceVersionConflictError extends Error { constructor() { super("Usage allowance version conflict"); this.name = "UsageAllowanceVersionConflictError"; } } function amount(value: number, name: string, positive = false): void { if (!Number.isSafeInteger(value) || value < (positive ? 1 : 0)) { throw new Error( `${name} must be ${positive ? "a positive" : "a non-negative"} safe integer in USD micros`, ); } } export function validateMemberAllowanceRule(rule: MemberAllowanceRule): void { if (rule === null) return; if ("credits" in rule) { if (Object.keys(rule).length !== 1) throw new Error("Member rule must have only credits or share"); amount(rule.credits, "credits"); } else if ("share" in rule) { if (Object.keys(rule).length !== 1 || !Number.isFinite(rule.share) || rule.share < 0) { throw new Error("share must be a finite non-negative number"); } } else { throw new Error("Member rule must have credits or share"); } } export function validateWorkspaceAllowanceConfig(config: WorkspaceAllowanceConfig): void { amount(config.includedCredits, "includedCredits"); if (config.period !== "monthly" && config.period !== "none") throw new Error("Invalid allowance period"); if ( config.anchorDay !== undefined && (!Number.isInteger(config.anchorDay) || config.anchorDay < 1 || config.anchorDay > 31) ) { throw new Error("anchorDay must be an integer from 1 to 31"); } if ( config.unbilledUsage !== undefined && config.unbilledUsage !== "ignore" && config.unbilledUsage !== "list_price" ) { throw new Error('unbilledUsage must be "ignore" or "list_price"'); } if ( config.memberDefault !== undefined && config.memberDefault !== "none" && config.memberDefault !== "equal_share" ) { validateMemberAllowanceRule(config.memberDefault); } for (const list of [config.thresholds?.workspace, config.thresholds?.member]) { if ( list !== undefined && (list.length > 16 || list.some((threshold) => !Number.isFinite(threshold) || threshold <= 0 || threshold > 1)) ) { throw new Error( "thresholds must contain at most 16 fractions greater than zero and at most one", ); } } } async function command(db: Database, input: Scope & Record): Promise { if ( ["set", "clear", "member", "grant"].includes(String(input.action)) && currentCreditDebitAttribution().kind === "turn" ) { // This context is installed by the authenticated request boundary, not // supplied in the allowance command. Agent attempts cannot substitute // human-looking actor labels to author allowance policy. throw new Error("Agent attempts cannot change usage allowances"); } try { const mutation = ["set", "clear", "member", "grant"].includes(String(input.action)); const read = input.action === "usage" || input.action === "check"; return await withRlsContext( db, input, async (scoped) => { if (mutation) { // The organization lifecycle can hold this fence while waiting for // exclusive tenancy. Never acquire shared tenancy ahead of it. await scoped.execute(sql`select pg_advisory_xact_lock( hashtextextended(${`organization-membership:${input.accountId}`},0))`); await scoped.execute(sql`select pg_advisory_xact_lock_shared( hashtextextended(${`session-tenancy:${input.workspaceId}`},0))`); } if (typeof input.actorSubjectId === "string") await setSubjectRlsContext(scoped, input.actorSubjectId); const commandCall = sql`usage_allowance_command(${JSON.stringify(input)}::jsonb)`; // Reads also take the organization's per-person limit for Personal // workspaces, in the same statement (see personalWorkspaceConfig). const [row] = await rawRows<{ result: T; personal_monthly_credits?: string | null }>( scoped, read ? sql`select ${commandCall} as result, ( select preferences.personal_workspace_monthly_credits from organization_privacy_preferences preferences where preferences.account_id = ${input.accountId}::uuid and preferences.personal_workspace_monthly_credits is not null and get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid) = 'personal' ) as personal_monthly_credits` : sql`select ${commandCall} as result`, ); if (!row) throw new Error("Usage allowance command returned no result"); if (!read) return row.result; const credits = row.personal_monthly_credits; return { ...(row.result as object), personalMonthlyCredits: credits === null || credits === undefined ? null : Number(credits), } as T; }, undefined, mutation ? "none" : "shared", ); } catch (error) { const cause = error as { code?: string; cause?: { code?: string } }; if ((cause.code ?? cause.cause?.code) === "40001") throw new UsageAllowanceVersionConflictError(); throw error; } } function actor(input: Actor): Actor & { actorType: string } { return { actorSubjectId: input.actorSubjectId, actorType: input.actorType ?? "subject" }; } function version(value: number): void { amount(value, "expectedVersion"); } export async function getWorkspaceAllowance( db: Database, input: Scope, ): Promise { return await command(db, { ...input, action: "get" }); } /** Includes the lifecycle revision even when no configuration exists. */ export async function getWorkspaceAllowanceState( db: Database, input: Scope, ): Promise { return await command(db, { ...input, action: "state" }); } export async function setWorkspaceAllowance( db: Database, input: Scope & Actor & WorkspaceAllowanceConfig & { expectedVersion: number }, ): Promise { const { accountId, workspaceId, expectedVersion, actorSubjectId, actorType } = input; const config: WorkspaceAllowanceConfig = { includedCredits: input.includedCredits, period: input.period, ...(input.anchorDay === undefined ? {} : { anchorDay: input.anchorDay }), ...(input.memberDefault === undefined ? {} : { memberDefault: input.memberDefault }), ...(input.thresholds === undefined ? {} : { thresholds: input.thresholds }), ...(input.unbilledUsage === undefined ? {} : { unbilledUsage: input.unbilledUsage }), }; version(expectedVersion); validateWorkspaceAllowanceConfig(config); return await command(db, { accountId, workspaceId, expectedVersion, ...actor({ actorSubjectId, actorType }), action: "set", config, }); } export async function clearWorkspaceAllowance( db: Database, input: Scope & Actor & { expectedVersion: number; operationId?: string }, ): Promise<{ version: number }> { version(input.expectedVersion); if (input.expectedVersion === 0) throw new UsageAllowanceVersionConflictError(); if ( input.operationId !== undefined && (!input.operationId.trim() || new TextEncoder().encode(input.operationId).length > 256) ) throw new Error("operationId must be non-empty and at most 256 bytes"); return await command(db, { ...input, ...actor(input), action: "clear" }); } export async function grantWorkspaceCredits( db: Database, input: Scope & Actor & { operationId: string; credits: number; expiresAt?: string | null }, ): Promise<{ operationId: string; credits: number; remaining: number; expiresAt: string | null }> { amount(input.credits, "credits", true); if (!input.operationId.trim() || new TextEncoder().encode(input.operationId).length > 256) { throw new Error("operationId must be non-empty and at most 256 bytes"); } if (input.expiresAt != null && !Number.isFinite(Date.parse(input.expiresAt))) throw new Error("Invalid grant expiresAt"); return await command(db, { ...input, ...actor(input), expiresAt: input.expiresAt ?? null, action: "grant", }); } export async function setMemberAllowance( db: Database, input: Scope & Actor & { rule: MemberAllowanceRule; expectedVersion: number } & ( | { subjectId: string; externalIdentity?: never } | { externalIdentity: { source: string; externalId: string }; subjectId?: never } ), ): Promise { version(input.expectedVersion); validateMemberAllowanceRule(input.rule); return await command(db, { ...input, ...actor(input), action: "member" }); } type RawUsage = { config: WorkspaceAllowanceConfig | null; period: WorkspaceUsage["period"]; used: number; includedUsed: number; grantsUsed: number; grantsRemaining: number; memberCount: number; members: (MemberAllowance & { used: number; externalIdentity: { source: string; externalId: string } | null; })[]; /** The organization's per-person limit when this is a Personal workspace. */ personalMonthlyCredits?: number | null; }; /** * A Personal workspace without a budget of its own takes its organization's * per-person monthly limit, metered by the calendar-month counters every * workspace keeps. The limit applies to the running month only: a past month * without a budget of its own has no recorded window (`end` is null), and the * organization keeps no history of the limit. */ function personalWorkspaceConfig(raw: RawUsage): WorkspaceAllowanceConfig | null { const credits = raw.personalMonthlyCredits; if (credits === null || credits === undefined || raw.period.end === null) return null; return { includedCredits: credits, period: "monthly" }; } export function allowanceUsage( limit: number | null, used: number, resetsAt: string | null, thresholds = [0.8, 1], ): AllowanceUsage { const fraction = limit === null ? null : limit === 0 ? 1 : used / limit; const remaining = limit === null ? null : Math.max(0, limit - used); return { limit, used, remaining, fraction, status: remaining === 0 ? "exhausted" : fraction !== null && thresholds.some((t) => fraction >= t) ? "warning" : "ok", resetsAt, }; } export async function getWorkspaceUsage( db: Database, input: Scope & { period?: "current" | string; limit?: number; cursor?: string | null; subjectId?: string; }, ): Promise { if ( input.period !== undefined && input.period !== "current" && !/^\d{4}-(0[1-9]|1[0-2])$/.test(input.period) ) { throw new Error("period must be current or YYYY-MM"); } const pageSize = Math.min(500, Math.max(1, Math.trunc(input.limit ?? 100))); const raw = await command(db, { ...input, limit: pageSize, action: "usage" }); return projectUsage(raw, pageSize); } function projectUsage(raw: RawUsage, pageSize: number): WorkspaceUsage { const config = raw.config ?? personalWorkspaceConfig(raw); // The period's whole pool: included credits plus the grants spent this // period and those still left. Usage counts the whole period, so its // ceilings must too: against what is left, every credit spent would shrink // every member's share. const pool = config ? config.includedCredits + Number(raw.grantsUsed) + Number(raw.grantsRemaining) : null; const resetsAt = config ? raw.period.end : null; const members = raw.members.slice(0, pageSize).map((member) => { let rule = member.rule; if (rule === null) { const fallback = config?.memberDefault ?? "none"; rule = fallback === "none" ? null : fallback === "equal_share" ? { share: raw.memberCount > 0 ? 1 / Number(raw.memberCount) : 0 } : fallback; } const limit = rule === null ? null : "credits" in rule ? rule.credits : pool === null ? null : Math.min(Number.MAX_SAFE_INTEGER, Math.floor(pool * rule.share)); return { ...member, rule: member.rule, ...allowanceUsage(limit, Number(member.used), resetsAt, config?.thresholds?.member), }; }); return { unit: "usd_micros", // The window these counters were read for. Without a budget, usage still // counts per calendar month, so the month is still the answer. period: raw.period, workspace: { ...allowanceUsage(pool, Number(raw.used), resetsAt, config?.thresholds?.workspace), includedCredits: config?.includedCredits ?? 0, grantsRemaining: Number(raw.grantsRemaining), }, members, nextCursor: raw.members.length > pageSize ? members.at(-1)!.subjectId : null, }; } export async function checkWorkspaceAllowance( db: Database, input: Scope & { subjectId?: string | null; /** * The work spends no Opengeni credits. It is admitted against the allowance * only when the allowance opts into `unbilledUsage: "list_price"`. */ fundedWithoutCredits?: boolean; }, ): Promise { const raw = await command(db, { accountId: input.accountId, workspaceId: input.workspaceId, ...(input.subjectId ? { subjectId: input.subjectId } : {}), limit: 1, action: "check", }); if (input.fundedWithoutCredits && raw.config?.unbilledUsage !== "list_price") return null; const usage = projectUsage(raw, 1); if (usage.workspace.status === "exhausted") { return { code: "allowance_exhausted", scope: "workspace", resetsAt: usage.workspace.resetsAt, message: "The workspace usage allowance is exhausted.", }; } const member = input.subjectId ? usage.members.find((row) => row.subjectId === input.subjectId) : null; if (member?.status === "exhausted") { return { code: "allowance_exhausted", scope: "member", subjectId: member.subjectId, resetsAt: member.resetsAt, message: "The member usage allowance is exhausted.", }; } return null; } /** Bounded periodic work, independent of reads/admission and webhook delivery. */ export async function maintainWorkspaceAllowances( db: Database, input: { limit?: number; memberLimit?: number } = {}, ): Promise { const [row] = await rawRows<{ processed: number }>( db, sql`select maintain_usage_allowances(${input.limit ?? 20}::integer,${input.memberLimit ?? 100}::integer) as processed`, ); return Number(row?.processed ?? 0); }