Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/quota/src/providers/anthropic.ts

Raw
import { fetchJson } from "../http.ts";
import {
	amount,
	epoch,
	finite,
	headerNumber,
	isoTime,
	label,
	list,
	object,
	percent,
	windowBucket,
} from "../parse.ts";
import type { ProviderQuota, QuotaBucket, QuotaProvider } from "../types.ts";

export function parseAnthropic(data: unknown): ProviderQuota {
	const d = object(data);
	const buckets = new Map<string, QuotaBucket>();
	for (const [key, raw] of Object.entries(d).slice(0, 256)) {
		if (raw == null || !/^(five_hour|seven_day(?:_[a-z0-9_]+)?)$/.test(key))
			continue;
		const w = object(raw);
		const scope = key.startsWith("seven_day_")
			? key.slice(10).replaceAll("_", " ")
			: undefined;
		const id =
			key === "five_hour"
				? "session"
				: scope
					? `weekly:${scope.toLowerCase()}`
					: "weekly";
		buckets.set(
			id,
			windowBucket(
				id,
				key === "five_hour" ? "5h" : "Weekly",
				percent(w["utilization"]),
				key === "five_hour" ? 18000000 : 604800000,
				isoTime(w["resets_at"]),
				scope,
			),
		);
	}
	for (const raw of list(d["limits"])) {
		const w = object(raw);
		const kind = label(w["kind"]);
		if (!kind) continue;
		const model = object(object(w["scope"])["model"]);
		const scope =
			[label(model["display_name"]), label(object(w["scope"])["surface"])]
				.filter(Boolean)
				.join(" / ") || undefined;
		const id =
			kind === "session" && !scope
				? "session"
				: kind === "weekly_all" && !scope
					? "weekly"
					: kind === "weekly_scoped" && scope
						? `weekly:${scope.toLowerCase()}`
						: `${kind}:${scope ?? "all"}`;
		const previous = buckets.get(id);
		if (previous && previous.value.state !== "unknown") continue;
		const weekly = kind.startsWith("weekly");
		// is_active has no established visibility/applicability semantics.
		buckets.set(
			id,
			windowBucket(
				id,
				kind === "session"
					? "5h"
					: weekly
						? "Weekly"
						: kind.replaceAll("_", " "),
				percent(w["percent"]),
				kind === "session" ? 18000000 : weekly ? 604800000 : undefined,
				isoTime(w["resets_at"]),
				scope,
			),
		);
	}
	const extra = object(d["extra_usage"]);
	if (extra["is_enabled"] === true) {
		const currency = label(extra["currency"]);
		const places = finite(extra["decimal_places"]);
		const monetary =
			currency !== undefined &&
			places !== undefined &&
			Number.isInteger(places) &&
			places >= 0 &&
			places <= 6;
		const divisor = monetary ? 10 ** places : 1;
		const used = finite(extra["used_credits"]);
		const total = finite(extra["monthly_limit"]);
		const value = amount(
			monetary ? "currency" : "unknown",
			used === undefined ? undefined : used / divisor,
			total === undefined ? undefined : total / divisor,
			undefined,
			monetary ? currency : undefined,
		);
		buckets.set("extra-usage", {
			id: "extra-usage",
			label: "Extra usage",
			kind: "spend-cap",
			observedAt: Date.now(),
			period: { label: "Monthly" },
			value,
		});
	}
	return {
		provider: "anthropic",
		name: "Anthropic",
		buckets: [...buckets.values()],
		observedAt: Date.now(),
	};
}

export function parseAnthropicHeaders(
	headers: Record<string, string>,
): ProviderQuota | undefined {
	const buckets: QuotaBucket[] = [];
	for (const [window, id, title, duration, scope] of [
		["5h", "session", "5h", 18000000, undefined],
		["7d", "weekly", "Weekly", 604800000, undefined],
		["7d_oi", "weekly:fable", "Weekly", 604800000, "Fable"],
	] as const) {
		const base = `anthropic-ratelimit-unified-${window}`;
		const used = headerNumber(headers, `${base}-utilization`);
		if (used === undefined) continue;
		buckets.push(
			windowBucket(
				id,
				title,
				percent(used * 100),
				duration,
				epoch(headerNumber(headers, `${base}-reset`), 1000),
				scope,
			),
		);
	}
	return buckets.length
		? {
				provider: "anthropic",
				name: "Anthropic",
				buckets,
				observedAt: Date.now(),
			}
		: undefined;
}

export const anthropic: QuotaProvider = {
	name: "Anthropic",
	headers: parseAnthropicHeaders,
	async fetch(key) {
		return parseAnthropic(
			await fetchJson("https://api.anthropic.com/api/oauth/usage", {
				headers: {
					Authorization: `Bearer ${key}`,
					"anthropic-beta": "oauth-2025-04-20",
					Accept: "application/json",
				},
			}),
		);
	},
};