/** * @hanzo/commerce/metering * * The ONE way every Hanzo product meters usage to commerce — the single * billing source of truth — so that everything (not only the LLM/cloud path) * can be paid for. This is the TypeScript counterpart of * github.com/hanzoai/go-sdk/metering; the two share an identical wire contract. * * It provides two operations against commerce's canonical billing API: * * - authorize(): a pre-request balance gate. Fail-closed by default — if the * balance cannot be determined the request is denied, exactly like the * gateway's prepaid-balance gate. With tierAware it consults the effective * balance (prepaid + included plan allotment, e.g. the free-tier daily * credit) so included usage is honored before prepaid funds. * * - record(): a post-request usage write that debits the user's balance. * * Composition over duplication: this wraps the existing {@link Commerce} * client (GET /v1/billing/balance, GET /v1/billing/tier, POST /v1/billing/usage) * rather than re-implementing the HTTP layer. * * Auth is the commerce service token (admin-scoped S2S), sent as * `Authorization: Bearer ` plus the tenant org as `X-Org-Id`. The * token is a secret and MUST come from KMS (the operator wires it into * COMMERCE_SERVICE_TOKEN); this module never reads it from disk. * * @example * ```ts * import { Metering } from '@hanzo/commerce/metering' * * const meter = Metering.fromEnv() // COMMERCE_URL + COMMERCE_SERVICE_TOKEN (KMS) + COMMERCE_SERVICE_ORG * * // Pre-request gate (fail-closed). * const gate = await meter.authorize({ user: 'hanzo/alice' }) * if (!gate.allowed) { * res.status(gate.reason === 'insufficient_balance' ? 402 : 503).end() * return * } * * // ... do the work, compute cost ... * * // Post-request record (best-effort). * await meter.record({ user: 'hanzo/alice', amount: 5, provider: 'search' }) * ``` */ /** The public API origin; a deployment inside the cluster sets COMMERCE_URL. */ export declare const DEFAULT_COMMERCE_URL = "https://api.hanzo.ai"; export type MeteringConfig = { /** * Commerce base URL (no /v1 suffix). When empty the meter is in * "not configured" mode: authorize allows and record is a no-op. */ baseUrl?: string; /** Commerce service token (admin-scoped S2S). MUST be KMS-sourced. */ token?: string; /** Default tenant org slug sent as X-Org-Id (default "hanzo"). */ org?: string; /** * Gate on the tier-aware effective balance (prepaid + included plan * allotment) instead of the bare prepaid balance. Default false. */ tierAware?: boolean; /** * Allow-on-error. Default false (fail-closed, like the gateway). Set true * only where availability outranks billing. */ failOpen?: boolean; /** Request timeout in ms. Default 5000 (the gateway's value). */ timeoutMs?: number; /** * Send every call to commerce's TEST ledger (org.Live=false), so balances and * debits hit the sandbox books rather than real money. The Go meter spells * this the same way; a product opts in with METERING_TEST. */ test?: boolean; }; /** Who to authorize / charge. user is the IAM "org/sub" identity. */ export type MeteringIdentity = { user: string; org?: string; currency?: string; }; /** One usage event to record. Mirrors commerce's usageRequest one-for-one. */ export type UsageEvent = { user: string; org?: string; /** Cost to debit, in cents. */ amount: number; currency?: string; model?: string; provider?: string; promptTokens?: number; completionTokens?: number; totalTokens?: number; requestId?: string; premium?: boolean; stream?: boolean; status?: string; clientIp?: string; }; /** Result of a usage write. */ export type RecordResult = { transactionId: string; user: string; amount: number; currency: string; type: string; }; /** Outcome of an authorize() gate. */ export type AuthDecision = { allowed: boolean; /** 'insufficient_balance' -> 402 ; 'balance_unavailable' -> 503 (fail-closed). */ reason?: 'insufficient_balance' | 'balance_unavailable'; /** Spendable balance in cents that the decision was based on (when known). */ available?: number; }; /** * Metering is the server-side hook a product uses to charge for usage. It is * safe to share a single instance across requests. */ export declare class Metering { private readonly commerce; private readonly org; private readonly tierAware; private readonly failOpen; private readonly test; constructor(config?: MeteringConfig); /** * Build a Metering instance from the canonical environment variables. This * is the one-liner products use at startup. Honors METERING_DISABLED for * local dev. */ static fromEnv(env?: Record): Metering; /** Whether a commerce base URL is configured. */ get enabled(): boolean; /** The headers every call carries: which org, and which ledger. */ private wire; /** * Pre-request balance gate. Never throws — returns a decision so callers map * it to a status code. When not configured it always allows. * * Outcomes (matching the gateway): * { allowed: true } -> allow. * { allowed: false, reason: 'insufficient_balance' } -> 402 (out of funds). * { allowed: false, reason: 'balance_unavailable' } -> 503 (fail-closed). */ authorize(id: MeteringIdentity): Promise; /** * Record a usage event, debiting the user's balance. No-op when not * configured or amount <= 0 (commerce treats zero-cost usage as skipped). * Decoupled from gating: the work already happened, so balance is not * re-checked here. Returns null on no-op. */ record(usage: UsageEvent): Promise; /** * Convenience for products that prefer to throw on denial. Throws a * {@link CommerceApiError} with status 402 (insufficient) or 503 (unknown). */ authorizeOrThrow(id: MeteringIdentity): Promise; } /** Gateway-minted identity headers. */ export declare const HEADER_USER_ID = "x-user-id"; export declare const HEADER_ORG_ID = "x-org-id"; /** * Build a {@link MeteringIdentity} from gateway-minted identity headers. The * user is "{org}/{sub}" (commerce's iam-user form) when both are present. * Accepts a header bag with string | string[] | undefined values (Node http, * Next.js, fetch Headers via Object.fromEntries). */ export declare function identityFromHeaders(headers: Record | Headers): MeteringIdentity;