Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/minimax/src/quota.ts

Raw
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { boundedBody, object } from "./api.ts";

export const QUOTA_URL = "https://www.minimax.io/v1/token_plan/remains";
const ACTIVITY_EVENT = "quota:provider-activity";

export interface QuotaLeft {
	fiveHourLeft?: number;
	weeklyLeft?: number;
	observedAt: number;
}

function left(value: unknown): number | undefined {
	return typeof value === "number" && Number.isFinite(value) && value >= 0
		? Math.round(value)
		: undefined;
}

/** Only the remaining percentages; counts are zero placeholders on current M Plan replies. */
export function parseQuota(data: unknown): QuotaLeft | undefined {
	const root = object(data);
	if (object(root["base_resp"])["status_code"] !== 0) return undefined;
	const pools = Array.isArray(root["model_remains"])
		? root["model_remains"].slice(0, 64).map(object)
		: [];
	const pool = pools.find((p) => p["model_name"] === "general") ?? pools[0];
	if (!pool) return undefined;
	const fiveHourLeft = left(pool["current_interval_remaining_percent"]);
	const weeklyLeft = left(pool["current_weekly_remaining_percent"]);
	if (fiveHourLeft === undefined && weeklyLeft === undefined) return undefined;
	return {
		...(fiveHourLeft === undefined ? {} : { fiveHourLeft }),
		...(weeklyLeft === undefined ? {} : { weeklyLeft }),
		observedAt: Date.now(),
	};
}

export function quotaLine(quota: unknown): string | undefined {
	const q = object(quota);
	const parts: string[] = [];
	if (typeof q["fiveHourLeft"] === "number")
		parts.push(`5h ${q["fiveHourLeft"]}%`);
	if (typeof q["weeklyLeft"] === "number") parts.push(`wk ${q["weeklyLeft"]}%`);
	return parts.length ? `M Plan left ${parts.join(" · ")}` : undefined;
}

/**
 * Best-effort, non-consuming read after a consuming operation succeeded.
 * Never throws; always announces activity so the quota extension can refresh.
 */
export async function observeQuota(
	pi: ExtensionAPI,
	key: string,
	signal?: AbortSignal,
	fetcher: typeof globalThis.fetch = globalThis.fetch,
): Promise<QuotaLeft | undefined> {
	try {
		const response = await fetcher(QUOTA_URL, {
			method: "GET",
			headers: {
				Authorization: `Bearer ${key}`,
				"Content-Type": "application/json",
			},
			redirect: "error",
			signal: AbortSignal.any([
				AbortSignal.timeout(5000),
				...(signal ? [signal] : []),
			]),
		});
		if (!response.ok) {
			await response.body?.cancel();
			return undefined;
		}
		return parseQuota(
			JSON.parse((await boundedBody(response, 256 * 1024)).toString("utf8")),
		);
	} catch {
		return undefined;
	} finally {
		try {
			pi.events.emit(ACTIVITY_EVENT, { provider: "minimax" });
		} catch {
			/* Optional integration; never fail the operation. */
		}
	}
}