import type { ErrorSpec } from './derived-core.js'; /** Shortest window a declaration may claim. A sub-second window is a counter reset, not a budget. */ export declare const MIN_RATE_BUDGET_WINDOW_MS = 1000; /** Longest window a declaration may claim — beyond an hour the ledger stops being a rolling window. */ export declare const MAX_RATE_BUDGET_WINDOW_MS: number; /** * The most weighted units any pack may declare per window. Not a vendor fact — a blast radius cap, * so a typo (`ceiling: 100000`) cannot silently disarm the guard for a whole vendor. Every real * declaration is far under it. */ export declare const MAX_RATE_BUDGET_CEILING = 1000; /** * The sub-window every declaration's BURST is measured over, regardless of its own window length. * A rolling window bounds total spend but says nothing about how fast it may be spent: a one-hour * window with a 600-unit ceiling admits all 600 in a single millisecond, twenty times what the * austere fallback allows in a minute, and neither `MAX_RATE_BUDGET_CEILING` nor * `MAX_RATE_BUDGET_UNITS_PER_SECOND` (which evaluates to 0.167/s there) reaches it. So a declaration * whose window is longer than this MUST also declare `burstCeiling`, and the kernel refuses against * it independently. */ export declare const RATE_BUDGET_BURST_WINDOW_MS = 60000; /** * The most weighted units per SECOND any declaration may imply (`ceiling / (windowMs/1000)`). * The per-dimension caps above do not bound the RATE — `ceiling: 1000, windowMs: 1000` satisfies * both and still buys 1000 units a second, which is not a budget. This is the bound that makes the * "blast radius cap" claim true without depending on a declaration's window length. */ export declare const MAX_RATE_BUDGET_UNITS_PER_SECOND = 20; /** * The cheapest a single call may be priced. NOTHING IS FREE: a zero-weight call would let an * unbounded loop through, and the ledger's "entries can never outnumber the ceiling" invariant * (which bounds `load()`) depends on every entry costing at least one unit. */ export declare const MIN_RATE_BUDGET_WEIGHT = 1; /** * One pricing rule. `match` is a RegExp SOURCE string tested against the *call key* — whatever * string the pack's guarded client uses to name the call it is about to make (a REST path for an * HTTP pack, a dotted SDK method name for an SDK-shaped pack). First matching rule wins, so order * matters; a call matching nothing is priced at `defaultWeight`. * * `whenQueryPresent` / `whenQueryAbsent` let one path split by request shape (e.g. a cheap probe * distinguished from a full fetch only by a query parameter) without needing a vendor-specific * predicate FUNCTION in the declaration — declarations stay pure, inspectable data. */ export type RateBudgetWeightRule = { /** RegExp source, tested against the call key. */ match: string; /** Weighted cost when this rule matches. At least `MIN_RATE_BUDGET_WEIGHT`. */ weight: number; /** Only match when EVERY named query key is present. */ whenQueryPresent?: string[]; /** Only match when EVERY named query key is absent. */ whenQueryAbsent?: string[]; }; /** What a pack declares. Pure data — no vendor code in the kernel; the one function a declaration may hold is a served * bucket's computed weight, which its client budget never reads. */ export type RateBudgetDeclaration = { /** Rolling window, in ms. Spend older than this is pruned. */ windowMs: number; /** Weighted units allowed inside one window. */ ceiling: number; /** * Weighted units allowed inside any 60-SECOND sub-window, enforced independently of `ceiling`. * * REQUIRED when `windowMs` is longer than 60s, and refused as meaningless when it is not (a * window that is already a minute has its ceiling as its burst). This is what stops a long window * from buying an enormous instantaneous burst as a side effect of bounding a long-horizon limit — * the thing github and linear legitimately need, and the thing a careless declaration would get by * accident. Must be ≤ `ceiling`; like every other axis it may only ever be TIGHTENED. */ burstCeiling?: number; /** Cost of a call no rule prices. Never zero — an unknown endpoint must never be free. */ defaultWeight: number; /** * Seconds. A `Retry-After` above this is not something to sleep off — it means the credential is * in real trouble, so it FAILS LOUDLY rather than scheduling a long sleep. */ maxRetryAfterSeconds?: number; /** Ordered pricing rules; first match wins. */ rules?: RateBudgetWeightRule[]; /** * WHY these numbers — the vendor's documented (or observed) limits, and the reasoning that * turned them into this ceiling. Required: a budget nobody can explain is a budget nobody can * review, and the ceiling is the one number that can cost days if it is wrong. */ reason: string; /** The vendor's documented allowance, in calls a minute, and the page that documents it, which the pack cites on a * `// source:` line (checked like every other vendor fact): required of a budget that admits more than the fallback * (`twin-standard invariants`, its RATE row). */ allowance?: { perMinute: number; source: string; }; /** The limits as the vendor's own server keeps them: what its simulated twin enforces while a World's scenario switches * them on (`rate-limit`, architecture "Scenarios"; world-core scenario-consume.ts rateLimited), never this client's * ceiling. A request is counted in every bucket it belongs to and refused by the first one it would exhaust. */ buckets?: RateBucket[]; /** The refusal a bucket that declares none answers with. */ refused?: RateRefusal; }; /** What a bucket's key, its weight function and its templates read of one request: its operation id, its path * parameters, its query, headers and body as the vendor reads it, the credential it presents (a hash, never the * credential) and the account it is served in. */ export type RateBucketRequest = { operation: string; params: Record; query: URLSearchParams; headers: Headers; body: unknown; credential: string; account: string; }; /** One limit the vendor keeps: `limit` units a `per` window (`1s`, `1h`), counted per `key` in World time. */ export type RateBucket = { /** The bucket's name: `{bucket}` in a template, and what a scenario's `rate-limit` names to switch it on alone. */ name: string; /** The template a request's count is kept under: `{credential}`, `{account}`, `{operation}` and any path parameter * (`{credential}` alone is one count per credential; `{account}:{channel_id}` one per account and channel). A * request missing a parameter the key names is not counted in this bucket. */ key: string; limit: number; per: string; /** `fixed-window`: windows from the epoch, each starting at zero. `token-bucket`: `limit` tokens refilled evenly over * `per`, a request admitted while its weight in tokens is left. */ counting: 'fixed-window' | 'token-bucket'; /** The operations this bucket counts; absent, every operation. */ operations?: string[]; /** A request's weight, as the client budget's `weights` price a call: by operation id (an operation not listed weighs * 1), or computed from the request by the pack (a query's complexity, a format's quota units). Absent, every request * weighs 1. */ weights?: Record | ((request: RateBucketRequest) => number); /** The most requests of one key in flight at once; one more is refused by this bucket. */ concurrency?: number; /** `{global}` in a template: a limit across all of a credential's routes, as the vendor tells its clients. */ global?: boolean; /** The unit `{reset}` (the instant the bucket next admits, from the epoch) and `{resetAfter}` (the time until then) * are written in, rounded up: seconds, the default, or milliseconds. */ reset?: 'seconds' | 'ms'; /** This bucket's refusal; absent, the declaration's `refused`. */ refused?: RateRefusal; /** Headers on every answer to a request this bucket counted (the vendor's remaining-quota headers), templates over the * values, written only while a scenario switches the bucket on. */ headers?: Record; }; /** A bucket's refusal: the vendor's own status and error (its manifest's envelope, `message` a template over the values), * or `body`, the whole body as a template, and its headers. A template reads `{limit}`, `{remaining}`, `{used}`, * `{reset}`, `{resetAfter}`, `{bucket}` and `{global}`; a body value that is one placeholder alone keeps its type. */ export type RateRefusal = { error: ErrorSpec; body?: unknown; headers?: Record; }; /** The values a rate template is filled with. */ export type RateValues = { limit: number; remaining: number; used: number; reset: number; resetAfter: number; bucket: string; global: boolean; }; /** A rate template filled with `values`: a string's placeholders replaced, a string that is one placeholder alone given * the value itself, arrays and objects filled throughout. */ export declare function fillRateTemplate(template: unknown, values: RateValues): unknown; /** * A declaration bound to the vendor it governs, with every pattern already compiled. The `RegExp`s * are built ONCE here rather than per call: `priceCall` runs in front of every vendor request, and * recompiling a pattern per call is both wasted work and a needless amplifier for a pathological * pattern. (Declarations are repo source, not user input — this is a performance fix, not a * sanitizer.) */ export type RateBudgetPolicy = Required> & Pick & { vendor: string; rules: RateBudgetWeightRule[]; /** `compiled[i]` is `rules[i].match`, compiled. Same length, same order. */ compiled: RegExp[]; }; /** * The allowance a vendor gets when NOBODY declared one. * * 60 weighted units per 60s at a default weight of 2 — 30 calls a minute, one every two seconds. * That is comfortably above any human- or agent-driven explicit pull (a few dozen calls), and far * below the shape that causes lockouts (a loop emitting hundreds of calls a minute). It is * deliberately NOT generous: an undeclared vendor is one nobody has thought about, and the safe * assumption about an unexamined vendor is that its limits are tight. * * There is no opt-out. A pack that genuinely needs more says so, in its declaration, with a reason. * * ⚠️ HONESTLY: this is tighter than a real declaration in CALL COUNT, but it is NOT uniformly * tighter, because it prices every call the same. A vendor whose pack prices one endpoint high (a * render at 20, a recursive walk at 2) gets that endpoint priced at 2 here — cheaper, not dearer. * That is why `RateBudget` reads the policy LIVE rather than snapshotting it at construction, and * why a pack's binding (its `XBudget` subclass, whose module declares on import) is the only * construction path you should use. */ export declare const DEFAULT_RATE_BUDGET: RateBudgetDeclaration; /** * DECLARE a vendor's budget. Idempotent for an identical declaration; a REPEAT declaration that * would WIDEN the allowance (higher ceiling, shorter window, cheaper default, longer tolerated * back-off) is refused. Without that rule, "declare a bigger budget just before constructing the * client" would be the clean way around every guarantee below. */ export declare function declareRateBudget(vendor: string, decl: RateBudgetDeclaration): RateBudgetPolicy; /** The declared policy for a vendor, or the conservative fallback bound to that vendor. */ export declare function rateBudgetPolicy(vendor: string): RateBudgetPolicy; /** Has anyone declared a budget for this vendor? (`false` ⇒ it runs on `DEFAULT_RATE_BUDGET`.) */ export declare function hasRateBudgetDeclaration(vendor: string): boolean; /** Every declared policy, sorted by vendor (deterministic) — for operator/audit listings. */ export declare function listRateBudgets(): RateBudgetPolicy[]; /** * Price one call against a policy. Keyed off the request the client is ABOUT to make, so an * unclassified key still costs `defaultWeight` — an unknown endpoint must never be free. */ export declare function priceCall(policy: RateBudgetPolicy, key: string, query?: Record): number; /** Price one call for a vendor, using its declared policy (or the fallback). */ export declare function rateBudgetWeight(vendor: string, key: string, query?: Record): number; export type RateBudgetErrorKind = /** The rolling-window ceiling would be exceeded by this call. */ 'ceiling' /** A prior response told us to back off and the cooldown has not elapsed. */ | 'cooldown' /** The ledger could not be read/parsed — treated as a full window (see below). */ | 'ledger-unreadable' /** The ledger could not be persisted, so spend cannot be tracked. Refuse rather than fly blind. */ | 'ledger-unwritable' /** The injected clock is not a millisecond epoch — pruning would be nonsense, so refuse. */ | 'clock-invalid' /** The 60-second BURST bound would be exceeded, even though the long window has room. */ | 'burst' /** A `Retry-After` beyond the cap — fail loudly instead of sleeping it off. */ | 'retry-after-too-large'; /** * Thrown INSTEAD OF calling the vendor. Never swallowed, never converted to a retry: the caller is * meant to stop. Carries how long to wait so a caller can schedule rather than spin. */ export declare class RateBudgetError extends Error { readonly kind: RateBudgetErrorKind; /** The vendor whose budget refused — so a multi-vendor caller can tell which one stopped. */ readonly vendor: string; /** Milliseconds until the budget could plausibly admit this call again. */ readonly retryAfterMs: number; constructor(kind: RateBudgetErrorKind, vendor: string, message: string, retryAfterMs: number); } /** A charge already committed to the ledger by `checkBudget`, settled later by `recordCall`. */ export type RateBudgetReservation = { id: string; weight: number; at: number; }; export type RateBudgetSnapshot = { vendor: string; spend: number; /** Weighted spend in the last 60s — the quantity `burstCeiling` bounds. */ burstSpend: number; ceiling: number; burstCeiling: number; windowMs: number; cooldownUntil: number; entries: number; path: string; }; export type RateBudgetOptions = { /** The vendor whose allowance this is. Required — the ledger is keyed by it. */ vendor: string; /** Ledger file path. Injectable so tests never touch the real one. */ path?: string; /** * Scope the ledger to ONE project root instead of the home dir. Note that two roots sharing a * credential then get two allowances — prefer the token-keyed default unless you specifically * want per-world accounting. */ root?: string; /** The credential whose quota this is. Only its HASH is used, to name the default ledger file. */ token?: string; /** Injected clock (ms since epoch). Tests advance it by hand; production passes nothing. */ now?: () => number; /** Window in ms. Can only be made LONGER than the declared one (shorter would widen spend). */ windowMs?: number; /** Weighted ceiling. Can only be made LOWER than the declared one. */ ceiling?: number; /** Seconds; a `Retry-After` above this fails loudly. Can only be made SMALLER. */ maxRetryAfterSeconds?: number; }; /** * Where the ledger lives. Vendors rate-limit PER CREDENTIAL, so the default is keyed by VENDOR and * a hash of the token, and lives in the user's home directory — deliberately NOT under the project * state root, because a cwd-scoped ledger hands the same credential a fresh allowance in every * checkout, worktree and CI matrix leg. Pass `root` to opt into world-scoped accounting anyway. * Only the hash is ever written to disk; the token itself never is. * * Two vendors never collide (the vendor is a path segment) and two credentials for one vendor never * collide (the hash is the filename). */ export declare function rateBudgetPath(opts: { vendor: string; root?: string; token?: string; }): string; /** * The guard. One instance per ledger path; cheap to construct, so callers may build one per client. * All state lives in the FILE, never in the instance — that is what makes a second instance (or a * second process) see the first one's spend. There is no memoization anywhere, by design. */ /** * Refuse a "budget" whose GUARD HAS BEEN REPLACED, and hand back the same object when it is intact. * * Every pack's guarded factory takes an optional `budget` so several clients can share one ledger. * `instanceof` alone admits a subclass or proxy that replaces a guard with a no-op. * The check is on the METHODS as well as the prototype chain: the three functions a guarded factory * actually calls must be the very functions `RateBudget.prototype` defines. An own-property * override, a subclass override and a `get`-trapping proxy all fail that identity comparison. The * exact-prototype test additionally pins the vendor binding, so another vendor's budget subclass * cannot stand in for this one's. * * HONEST LIMIT, since the point of this function is not over-claiming: a determined caller can still * defeat it (a proxy that returns the real function to the probe and a no-op afterwards, a * `Object.defineProperty` on `RateBudget.prototype` itself, an injected clock, a ledger path in a * temp dir). Nothing reachable from inside this process can stop that, and the module header says so * up front. What this closes is the ACCIDENT and the one-liner — the shapes that actually happen. */ export declare function assertBudgetGuardIntact(budget: unknown, expected: new (...args: never[]) => T, where: string): T; export declare class RateBudget { readonly vendor: string; readonly path: string; private readonly clock; private readonly askedWindowMs; private readonly askedCeiling; private readonly askedMaxRetryAfterSeconds; constructor(opts: RateBudgetOptions); /** * The effective policy, read LIVE from the declaration registry on every use rather than captured * at construction. * * A budget built for a vendor whose declaration module has not been imported yet falls back to * `DEFAULT_RATE_BUDGET`. The fallback is NOT uniformly tighter than a pack's own numbers — its ceiling is lower, but it * prices every call at `defaultWeight`, which for a vendor with an expensive endpoint (a render, * a recursive walk) is far CHEAPER than the pack's declared weight for it. Capturing that * snapshot would freeze the wrong prices for the instance's whole life. Reading live means the * pack's real weights take effect the moment its declaration lands. * * A caller cannot hand in a policy object — it comes only from the registry, and the registry * refuses a widening re-declaration — so "construct a client around a huge made-up budget" is * still not a move. */ get policy(): RateBudgetPolicy; /** Window in ms. The caller may only LENGTHEN it; a shorter one would widen spend. */ get windowMs(): number; /** Weighted ceiling. The caller may only LOWER it. */ get ceiling(): number; /** * Weighted units allowed in any 60-SECOND sub-window, enforced independently of `ceiling`. For a * pack whose window already IS 60s this equals the ceiling and the second check is a no-op; for a * longer window it is the bound that stops the whole window being spent in an instant. Never * looser than `ceiling` (a lowered ceiling lowers it too). */ get burstCeiling(): number; /** Tolerated back-off, in seconds. The caller may only SHRINK it. */ get maxRetryAfterSeconds(): number; /** Price a call against THIS vendor's declared rules, as they stand right now. */ weightFor(key: string, query?: Record): number; /** * Read the clock and sanity-check it. Catches the ACCIDENT class that silently disables pruning: * a clock in seconds, a `performance.now()`-style monotonic clock, or NaN. Entry timestamps * written under one epoch prune instantly under another, which would void the whole budget * without anyone noticing. (A deliberate fast-forwarding clock is NOT stopped by this — nothing * can stop that while the seam exists; it is disclosed at the top instead of pretended away.) */ private now; private lockPath; /** The store the ledger persists through where there is no filesystem of this machine's to hold it: a hosted World's * (its SQL store, one instance serializing its requests). Null on the filesystem, where the ledger is the file below, * locked across processes as it always was. A hosted World's ledger is its own: two hosted Worlds sealed with one * credential each keep an allowance, where a machine's Worlds share one per credential. */ private store; /** Serialize ledger updates with the kernel's lock, retaining every live owner. */ private withLock; /** * Read the ledger. A MISSING file is the legitimate first-run case (no state ⇒ no spend). A file * that exists but cannot be read or parsed is the dangerous case, and it FAILS CLOSED: we cannot * know what was already spent, so the window is treated as fully consumed. A fresh ledger * carrying a one-window cooldown is written in its place, so the guard self-heals after the * window instead of needing a human to delete a file. */ private load; /** Replace a corrupt ledger with a valid one that is already in cooldown, and refuse this call. */ private quarantine; /** Atomic replace: write a temp file, then rename over the target. No partial ledger is visible. */ private save; private prune; private static spendOf; /** * THE GATE. Prunes the window, refuses if we are in cooldown or if `weight` would breach the * ceiling, and otherwise RESERVES the weight (committing it to the ledger) before returning. * When it throws, the caller MUST NOT call the vendor — that is the entire contract. */ checkBudget(weight: number): RateBudgetReservation; /** * Record the OUTCOME of a call. Settles the reservation `checkBudget` made (never charging * twice); when called without one — a direct caller, or a call made outside the guarded path — * it appends the charge itself, so spend is recorded either way. * * If the response carried `Retry-After`, a 429, or an `X-…-RateLimit-Remaining: 0` exhaustion * signal, a COOLDOWN is persisted: every later call then fails fast in `checkBudget` WITHOUT * touching the vendor. A `Retry-After` beyond the cap additionally throws — that is not something * to sleep off. */ recordCall(weight: number, headers?: Record, opts?: { status?: number; reservation?: RateBudgetReservation | null; }): void; /** Current weighted spend in the window. Reads the FILE, so it sees other processes' spend. */ spend(): number; /** Everything an operator (or a test) wants to see, in one read. */ snapshot(): RateBudgetSnapshot; } /** * A `*-ratelimit-reset` value → seconds to wait, or `null` when it cannot be trusted. * * Vendors disagree about the UNIT, and getting it wrong is not a rounding error — it is a multi-day * self-inflicted outage. Three shapes are seen in practice, distinguished by MAGNITUDE because none * of them is labelled: * • a small number → a delta, already in seconds (`x-ratelimit-reset: 45`) * • ~1e9-1e10 → an absolute epoch in SECONDS (GitHub) * • ~1e12-1e13 → an absolute epoch in MILLISECONDS (Linear documents exactly this) * * Reading a millisecond epoch as a second epoch yields a back-off of roughly fifty thousand YEARS, * which the cooldown cap then clamps to a week — so ONE exhausted response would lock the credential * out client-side for seven days and need a human to delete the ledger file. That is the module * inflicting the very outage it exists to prevent. * * Anything that still resolves to more than a day is treated as UNPARSEABLE rather than obeyed: * no real rate limit resets a day out, so such a value means the unit guess was wrong, and the * honest answer is `null` (the caller falls back to a one-window cooldown) rather than a number * nobody can justify. Non-finite and negative values are likewise `null`. */ export declare function resetToSeconds(reset: number, nowMs?: number): number | null;