Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
/**
* moonshotQuotaFetcher.ts — Moonshot Open Platform balance quota fetcher
*
* GET {origin}/v1/users/me/balance
* { code: 0, data: { available_balance, voucher_balance, cash_balance } }
*
* Origin comes from the connection baseUrl (api.moonshot.cn or api.moonshot.ai).
* Do not hardcode .ai as a fallback for .cn keys.
*
* Cache: 60s in-memory. Registration: registerMoonshotQuotaFetcher() at startup.
*/
import { toNumber } from "@/shared/utils/numeric";
import {
registerQuotaCacheInvalidator,
registerQuotaFetcher,
type QuotaInfo,
} from "./quotaPreflight.ts";
import { registerMonitorFetcher } from "./quotaMonitor.ts";
import { throttleQuotaFetch } from "./quotaFetchThrottle.ts";
import { fetchWithConnectionProxy } from "./connectionProxyFetch.ts";
import { isUrlHostOrSubdomain } from "../utils/urlHost.ts";
import {
isKimiCodingBaseUrl,
isKimiCodingConnection,
isMoonshotOpenPlatformConnection,
moonshotBalanceUrl,
resolveMoonshotOrigin,
} from "./usage/moonshotOpenPlatform.ts";
import { getKimiUsage } from "./usage/kimi.ts";
import type { UsageQuota } from "./usage/quota.ts";
const CACHE_TTL_MS = 60_000;
export interface MoonshotQuota extends QuotaInfo {
availableBalance: number;
voucherBalance: number;
cashBalance: number;
origin: string;
limitReached: boolean;
}
interface CacheEntry {
quota: QuotaInfo | null;
fetchedAt: number;
}
const quotaCache = new Map<string, CacheEntry>();
const _cacheCleanup = setInterval(() => {
const now = Date.now();
for (const [key, entry] of quotaCache) {
if (now - entry.fetchedAt > CACHE_TTL_MS * 5) {
quotaCache.delete(key);
}
}
}, 5 * 60_000);
if (typeof _cacheCleanup === "object" && "unref" in _cacheCleanup) {
(_cacheCleanup as { unref?: () => void }).unref?.();
}
function toRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function parseMoonshotQuotaResponse(data: unknown, origin: string): MoonshotQuota | null {
const obj = toRecord(data);
const code = obj.code;
if (code !== 0 && code !== undefined) return null;
const payload = toRecord(obj.data);
if (!("available_balance" in payload) && !("availableBalance" in payload)) return null;
const availableBalance = toNumber(payload.available_balance ?? payload.availableBalance, 0);
const voucherBalance = toNumber(payload.voucher_balance ?? payload.voucherBalance, 0);
const cashBalance = toNumber(payload.cash_balance ?? payload.cashBalance, 0);
const limitReached = availableBalance <= 0;
const percentUsed = limitReached ? 1 : 0;
return {
used: percentUsed * 100,
total: 100,
percentUsed,
resetAt: null,
availableBalance,
voucherBalance,
cashBalance,
origin,
limitReached,
windows: { balance: { percentUsed, resetAt: null } },
};
}
function connectionApiKey(connection?: Record<string, unknown>): string | null {
const value = connection?.apiKey;
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function percentUsedFromRemaining(remainingPercentage: unknown): number | null {
if (typeof remainingPercentage !== "number" || !Number.isFinite(remainingPercentage)) return null;
return (100 - Math.max(0, Math.min(100, remainingPercentage))) / 100;
}
async function fetchKimiCodingQuotaAsPreflight(
connection?: Record<string, unknown>
): Promise<QuotaInfo | null> {
const usage = (await getKimiUsage(
typeof connection?.accessToken === "string" ? connection.accessToken : undefined,
typeof connection?.apiKey === "string" ? connection.apiKey : undefined,
toRecord(connection?.providerSpecificData)
)) as { quotas?: Record<string, UsageQuota> };
const quotas = usage?.quotas;
if (!quotas) return null;
const windows: NonNullable<QuotaInfo["windows"]> = {};
for (const [name, quota] of Object.entries(quotas)) {
const percentUsed = percentUsedFromRemaining(quota.remainingPercentage);
if (percentUsed === null) continue;
windows[name] = { percentUsed, resetAt: quota.resetAt ?? null };
}
const ranked = Object.values(windows);
const first = ranked[0];
if (!first) return null;
const worst = ranked.reduce((a, b) => (a.percentUsed > b.percentUsed ? a : b), first);
const window5h = windows.code_5h;
const window7d = windows.code_7d;
return {
used: 0,
total: 0,
percentUsed: worst.percentUsed,
resetAt: worst.resetAt,
windows,
window5h,
window7d,
limitReached: worst.percentUsed >= 1 - 1e-9,
};
}
export async function fetchMoonshotQuota(
connectionId: string,
connection?: Record<string, unknown>
): Promise<QuotaInfo | null> {
const cached = quotaCache.get(connectionId);
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
return cached.quota;
}
const codingConn = {
provider: typeof connection?.provider === "string" ? connection.provider : undefined,
providerSpecificData: connection?.providerSpecificData,
};
if (isKimiCodingConnection(codingConn)) {
try {
await throttleQuotaFetch();
const codingQuota = await fetchKimiCodingQuotaAsPreflight(connection);
quotaCache.set(connectionId, { quota: codingQuota, fetchedAt: Date.now() });
return codingQuota;
} catch {
quotaCache.set(connectionId, { quota: null, fetchedAt: Date.now() });
return null;
}
}
const apiKey = connectionApiKey(connection);
if (!apiKey) return null;
const origin = resolveMoonshotOrigin({
provider: typeof connection?.provider === "string" ? connection.provider : undefined,
providerSpecificData: connection?.providerSpecificData,
});
if (!origin) return null;
const url = moonshotBalanceUrl(origin);
const authHeader = ["Bearer", apiKey].join(" ");
try {
await throttleQuotaFetch();
const response = await fetchWithConnectionProxy(connectionId, url, {
method: "GET",
headers: {
Authorization: authHeader,
"Content-Type": "application/json",
Accept: "application/json",
},
signal: AbortSignal.timeout(8_000),
});
if (!response) return null;
if (response.status === 401 || response.status === 403) {
quotaCache.delete(connectionId);
return null;
}
if (!response.ok) return null;
const data = await response.json();
const quota = parseMoonshotQuotaResponse(data, origin);
if (!quota) return null;
quotaCache.set(connectionId, { quota, fetchedAt: Date.now() });
return quota;
} catch {
return null;
}
}
export function invalidateMoonshotQuotaCache(connectionId: string): void {
quotaCache.delete(connectionId);
}
export type MoonshotUsageConnection = {
id?: string;
provider?: string;
apiKey?: string;
providerSpecificData?: unknown;
};
export async function getMoonshotOpenPlatformUsage(connection: MoonshotUsageConnection): Promise<{
plan?: string;
quotas?: Record<string, UsageQuota>;
message?: string;
limitReached?: boolean;
}> {
const origin = resolveMoonshotOrigin(connection);
if (!origin) {
return { message: "Not a Moonshot Open Platform connection." };
}
const quota = (await fetchMoonshotQuota(connection.id || "moonshot", {
apiKey: connection.apiKey,
provider: connection.provider,
providerSpecificData: connection.providerSpecificData,
})) as MoonshotQuota | null;
if (!quota) {
return { message: "Moonshot API key not available. Add a key to view usage." };
}
const domestic = isUrlHostOrSubdomain(origin, "moonshot.cn");
return {
plan: domestic ? "Kimi 开放平台(国内)" : "Kimi Open Platform",
quotas: buildMoonshotBalanceQuotas(quota, domestic ? "CNY" : "USD"),
limitReached: quota.limitReached,
};
}
function balanceQuota(remaining: number, currency: string): UsageQuota {
const leftover = remaining > 0 ? 100 : 0;
return {
used: 0,
total: 0,
remaining,
remainingPercentage: leftover,
resetAt: null,
unlimited: false,
currency,
};
}
function buildMoonshotBalanceQuotas(
quota: MoonshotQuota,
currency: string
): Record<string, UsageQuota> {
return {
available: balanceQuota(quota.availableBalance, currency),
voucher: balanceQuota(quota.voucherBalance, currency),
cash: balanceQuota(quota.cashBalance, currency),
};
}
export function registerMoonshotQuotaFetcher(): void {
registerQuotaFetcher("moonshot", fetchMoonshotQuota);
registerQuotaFetcher("kimi", fetchMoonshotQuota);
registerQuotaCacheInvalidator("moonshot", invalidateMoonshotQuotaCache);
registerQuotaCacheInvalidator("kimi", invalidateMoonshotQuotaCache);
registerMonitorFetcher("moonshot", fetchMoonshotQuota);
registerMonitorFetcher("kimi", fetchMoonshotQuota);
}
export function registerMoonshotFetchersForNodes(
nodes: Array<{ id?: string | null; prefix?: string | null; baseUrl?: string | null }>
): void {
for (const node of nodes) {
const origin = resolveMoonshotOrigin({}, node.baseUrl);
if (!origin && !isKimiCodingBaseUrl(node.baseUrl)) continue;
if (typeof node.id === "string" && node.id) {
registerQuotaFetcher(node.id, fetchMoonshotQuota);
registerQuotaCacheInvalidator(node.id, invalidateMoonshotQuotaCache);
registerMonitorFetcher(node.id, fetchMoonshotQuota);
}
if (typeof node.prefix === "string" && node.prefix) {
registerQuotaFetcher(node.prefix, fetchMoonshotQuota);
registerQuotaCacheInvalidator(node.prefix, invalidateMoonshotQuotaCache);
registerMonitorFetcher(node.prefix, fetchMoonshotQuota);
}
}
}
export { isMoonshotOpenPlatformConnection };