Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageLimits.ts

48 lines1.9 KB

1/**
2 * Muse Code's subscription usage limits. Meta reports the account's windows
3 * with every model response, and Muse forwards them as `usage/changed`. When a
4 * window runs out, Meta refuses the next request and Muse fails the turn.
5 */
6import * as DateTime from "effect/DateTime";
7​
8import { LATEST_DATE_MS, type MuseSubscriptionUsage } from "./protocol.ts";
9​
10/**
11 * Muse surfaces Meta's quota refusal as `API error 429: Subscription quota
12 * exhausted. Your usage window resets at 2026-10-13T10:45:52Z.`, at times
13 * wrapped by a credential proxy. Muse can also type the stop as `error.quota`,
14 * but a relayed refusal arrives untyped, so the text still counts.
15 */
16export function isMuseUsageLimitFailure(message: string | undefined): boolean {
17 return message !== undefined && /\b429\b/.test(message) && /quota|usage limit/i.test(message);
19​
20const NAMED_RESET =
21 /\bresets at (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}))/i;
22​
23/**
24 * When a stopped turn can run again: every exhausted window must reset first.
25 * The resets come from the typed quota, the time the refusal names, and the
26 * used-up windows of the last report before it; the latest one still ahead wins.
27 */
28export function museUsageLimitResetAt(
29 usage: MuseSubscriptionUsage | undefined,
30 nowMs: number,
31 refusal?: {
32 readonly quota?: { readonly resetsAtMs: number } | undefined;
33 readonly message?: string | undefined;
34 },
35): string | null {
36 const named = refusal?.message?.match(NAMED_RESET)?.[1];
37 const resets = [
38 ...[usage?.window, usage?.weekly].map((window) =>
39 window && window.usedPercent >= 100 ? window.resetsAtMs : undefined,
40 ),
41 refusal?.quota?.resetsAtMs,
42 named === undefined ? undefined : Date.parse(named),
43 ].filter(
44 (ms): ms is number =>
45 ms !== undefined && Number.isFinite(ms) && ms > nowMs && ms <= LATEST_DATE_MS,
46 );
47 return resets.length > 0 ? DateTime.formatIso(DateTime.makeUnsafe(Math.max(...resets))) : null;