Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/quota/src/providers/kimi.ts

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

function duration(window: Record<string, unknown>): number | undefined {
	const factor = (
		{
			TIME_UNIT_SECOND: 1000,
			TIME_UNIT_MINUTE: 60000,
			TIME_UNIT_HOUR: 3600000,
			TIME_UNIT_DAY: 86400000,
		} as Record<string, number>
	)[String(window["timeUnit"])];
	const n = finite(window["duration"]);
	return factor !== undefined && n !== undefined && n > 0
		? finite(n * factor)
		: undefined;
}

/** Best effort: retain monthly, scoped and rate windows without guessing legacy totals are weekly. */
export function parseKimi(data: unknown): ProviderQuota {
	const d = object(data);
	const buckets = new Map<string, QuotaBucket>();
	const occurrences = new Map<string, number>();
	for (const raw of list(d["limits"])) {
		const limit = object(raw);
		const detail = object(limit["detail"]);
		const ms = duration(object(limit["window"]));
		const scope = label(limit["scope"]);
		const base = `limits:${ms ?? "unknown"}:${scope ?? "all"}`;
		const occurrence = occurrences.get(base) ?? 0;
		occurrences.set(base, occurrence + 1);
		const id = `${base}:${occurrence}`;
		buckets.set(
			id,
			windowBucket(
				id,
				durationLabel(ms, "Rate limit"),
				amount(
					"unknown",
					numeric(detail["used"]),
					numeric(detail["limit"]),
					numeric(detail["remaining"]),
				),
				ms,
				isoTime(detail["resetTime"]),
				scope,
			),
		);
	}
	for (const [key, raw] of Object.entries(object(d["usages"])).slice(0, 256)) {
		if (raw == null) continue;
		const entry = object(raw);
		const ratio = numeric(entry["used_ratio"]);
		const names: Record<string, string> = {
			limit_5h: "5h",
			limit_month_total: "Monthly total",
			limit_month_code: "Monthly code",
		};
		// The API can report a conflicting ratio beside a rate measurement.
		// Preserve both sources until equivalence/precedence is established.
		buckets.set(
			`usages:${key}`,
			windowBucket(
				`usages:${key}`,
				names[key] ?? label(key.replaceAll("_", " ")) ?? "Usage",
				percent(ratio === undefined ? undefined : ratio * 100),
				key === "limit_5h" ? 18000000 : undefined,
				isoTime(entry["reset_time"]),
				"Plan",
			),
		);
	}
	if (d["usage"] != null) {
		const usage = object(d["usage"]);
		buckets.set(
			"membership",
			windowBucket(
				"membership",
				"Membership",
				amount(
					"unknown",
					numeric(usage["used"]),
					numeric(usage["limit"]),
					numeric(usage["remaining"]),
				),
				undefined,
				isoTime(usage["resetTime"]),
			),
		);
	}
	return {
		provider: "kimi-coding",
		name: "Kimi",
		buckets: [...buckets.values()],
		observedAt: Date.now(),
	};
}

export const kimi: QuotaProvider = {
	name: "Kimi",
	async fetch(key) {
		return parseKimi(
			await fetchJson("https://api.kimi.com/coding/v1/usages", {
				headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
			}),
		);
	},
};