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
feat: add real Gemini CLI quota tracking via retrieveUserQuota API
Chris Staley35e2892b982b
diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.tsindex 7be61c8f6c..0228412b9f 100644--- a/open-sse/config/providerRegistry.ts+++ b/open-sse/config/providerRegistry.ts@@ -226,23 +226,18 @@ export const REGISTRY: Record<string, RegistryEntry> = {oauth: {clientIdEnv: "GEMINI_CLI_OAUTH_CLIENT_ID",clientIdDefault: "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",- clientSecretEnv: "GEMINI_CLI_OAUTH_CLIENT_SECRET",+ clientSecretEnv: "GEMINI_OAUTH_CLIENT_SECRET",clientSecretDefault: "",},models: [- { id: "gemini-3.1-pro-high", name: "Gemini 3.1 Pro High" },- { id: "gemini-3.1-pro-low", name: "Gemini 3.1 Pro Low" },- { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },- { id: "gemini-3-1-pro", name: "Gemini 3.1 Pro (Alt ID)" },+ { id: "gemini-3-pro-preview", name: "Gemini 3 Pro Preview" },{ id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro Preview" },- { id: "gemini-3.1-flash-lite-preview", name: "Gemini 3.1 Flash Lite Preview" },+ { id: "gemini-3.1-pro-preview-customtools", name: "Gemini 3.1 Pro Preview Custom Tools" },{ id: "gemini-3-flash-preview", name: "Gemini 3 Flash Preview" },+ { id: "gemini-3.1-flash-lite-preview", name: "Gemini 3.1 Flash Lite Preview" },{ id: "gemini-2.5-pro", name: "Gemini 2.5 Pro" },{ id: "gemini-2.5-flash", name: "Gemini 2.5 Flash" },{ id: "gemini-2.5-flash-lite", name: "Gemini 2.5 Flash Lite" },- { id: "gemini-2.0-flash", name: "Gemini 2.0 Flash" },- { id: "gemini-1.5-pro", name: "Gemini 1.5 Pro" },- { id: "gemini-1.5-flash", name: "Gemini 1.5 Flash" },],},diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.tsindex c1f1114a2e..fcd547e47b 100644--- a/open-sse/services/usage.ts+++ b/open-sse/services/usage.ts@@ -159,13 +159,13 @@ async function getGlmUsage(apiKey: string, providerSpecificData?: Record<string,* @returns {Promise<unknown>} Usage data with quotas*/export async function getUsageForProvider(connection) {- const { provider, accessToken, apiKey, providerSpecificData } = connection;+ const { provider, accessToken, apiKey, providerSpecificData, projectId } = connection;switch (provider) {case "github":return await getGitHubUsage(accessToken, providerSpecificData);case "gemini-cli":- return await getGeminiUsage(accessToken);+ return await getGeminiUsage(accessToken, providerSpecificData, projectId);case "antigravity":return await getAntigravityUsage(accessToken, undefined);case "claude":@@ -195,24 +195,22 @@ function parseResetTime(resetValue) {if (!resetValue) return null;try {- // If it's already a Date object+ let date;if (resetValue instanceof Date) {- return resetValue.toISOString();- }-- // If it's a number (Unix timestamp in milliseconds)- if (typeof resetValue === "number") {- return new Date(resetValue).toISOString();+ date = resetValue;+ } else if (typeof resetValue === "number") {+ date = new Date(resetValue);+ } else if (typeof resetValue === "string") {+ date = new Date(resetValue);+ } else {+ return null;}- // If it's a string (ISO date or parseable date string)- if (typeof resetValue === "string") {- return new Date(resetValue).toISOString();- }+ // Epoch-zero (1970-01-01) means no scheduled reset — treat as null+ if (date.getTime() <= 0) return null;- return null;+ return date.toISOString();} catch (error) {- console.warn(`Failed to parse reset time: ${resetValue}`, error);return null;}}@@ -417,34 +415,176 @@ function inferGitHubPlanName(data: JsonRecord, premiumQuota: UsageQuota | null):return "GitHub Copilot";}+// ── Gemini CLI subscription info cache ──────────────────────────────────────+// Prevents duplicate loadCodeAssist calls within the same quota cycle.+// Key: truncated accessToken → { data, fetchedAt }+const _geminiCliSubCache = new Map();+const GEMINI_CLI_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes+/**- * Gemini CLI Usage (Google Cloud)+ * Gemini CLI Usage — fetch per-model quota from Cloud Code Assist API.+ * Gemini CLI and Antigravity share the same upstream (cloudcode-pa.googleapis.com),+ * so this follows the same pattern as getAntigravityUsage().*/-async function getGeminiUsage(accessToken) {+async function getGeminiUsage(accessToken, providerSpecificData?, connectionProjectId?) {try {- // Gemini CLI uses Google Cloud quotas- // Try to get quota info from Cloud Resource Manager+ const subscriptionInfo = await getGeminiCliSubscriptionInfoCached(accessToken);+ const projectId =+ connectionProjectId ||+ providerSpecificData?.projectId ||+ subscriptionInfo?.cloudaicompanionProject ||+ null;++ const plan = getGeminiCliPlanLabel(subscriptionInfo);++ if (!projectId) {+ return { plan, message: "Gemini CLI project ID not available." };+ }++ // Use retrieveUserQuota (same endpoint as Gemini CLI /stats command).+ // Returns per-model buckets with remainingFraction and resetTime.const response = await fetch(- "https://cloudresourcemanager.googleapis.com/v1/projects?filter=lifecycleState:ACTIVE",+ "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota",{+ method: "POST",headers: {Authorization: `Bearer ${accessToken}`,- Accept: "application/json",+ "Content-Type": "application/json",},+ body: JSON.stringify({ project: projectId }),});if (!response.ok) {- // Quota API may not be accessible, return generic message- return {- message: "Gemini CLI uses Google Cloud quotas. Check Google Cloud Console for details.",- };+ return { plan, message: `Gemini CLI quota error (${response.status}).` };+ }++ const data = await response.json();+ const quotas: Record<string, UsageQuota> = {};++ if (Array.isArray(data.buckets)) {+ for (const bucket of data.buckets) {+ if (!bucket.modelId || bucket.remainingFraction == null) continue;++ const remainingFraction = toNumber(bucket.remainingFraction, 0);+ const remainingPercentage = remainingFraction * 100;+ const QUOTA_NORMALIZED_BASE = 1000;+ const total = QUOTA_NORMALIZED_BASE;+ const remaining = Math.round(total * remainingFraction);+ const used = total - remaining;++ quotas[bucket.modelId] = {+ used,+ total,+ resetAt: parseResetTime(bucket.resetTime),+ remainingPercentage,+ unlimited: false,+ };+ }}- return { message: "Gemini CLI connected. Usage tracked via Google Cloud Console." };+ return { plan, quotas };} catch (error) {- return { message: "Unable to fetch Gemini usage. Check Google Cloud Console." };+ return { message: `Gemini CLI error: ${(error as Error).message}` };+ }+}++/**+ * Get Gemini CLI subscription info (cached, 5 min TTL)+ */+async function getGeminiCliSubscriptionInfoCached(accessToken) {+ const cacheKey = accessToken.substring(0, 16);+ const cached = _geminiCliSubCache.get(cacheKey);++ if (cached && Date.now() - cached.fetchedAt < GEMINI_CLI_CACHE_TTL_MS) {+ return cached.data;}++ const data = await getGeminiCliSubscriptionInfo(accessToken);+ _geminiCliSubCache.set(cacheKey, { data, fetchedAt: Date.now() });+ return data;+}++/**+ * Get Gemini CLI subscription info using correct headers.+ */+async function getGeminiCliSubscriptionInfo(accessToken) {+ try {+ const response = await fetch(+ "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist",+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ metadata: {+ ideType: "IDE_UNSPECIFIED",+ platform: "PLATFORM_UNSPECIFIED",+ pluginType: "GEMINI",+ },+ }),+ }+ );++ if (!response.ok) return null;++ return await response.json();+ } catch {+ return null;+ }+}++/**+ * Map Gemini CLI subscription tier to display label (same tiers as Antigravity).+ */+function getGeminiCliPlanLabel(subscriptionInfo) {+ if (!subscriptionInfo || Object.keys(subscriptionInfo).length === 0) return "Free";++ let tierId = "";+ if (Array.isArray(subscriptionInfo.allowedTiers)) {+ for (const tier of subscriptionInfo.allowedTiers) {+ if (tier.isDefault && tier.id) {+ tierId = tier.id.trim().toUpperCase();+ break;+ }+ }+ }++ if (!tierId) {+ tierId = (subscriptionInfo.currentTier?.id || "").toUpperCase();+ }++ if (tierId) {+ if (tierId.includes("ULTRA")) return "Ultra";+ if (tierId.includes("PRO")) return "Pro";+ if (tierId.includes("ENTERPRISE")) return "Enterprise";+ if (tierId.includes("BUSINESS") || tierId.includes("STANDARD")) return "Business";+ if (tierId.includes("FREE") || tierId.includes("INDIVIDUAL") || tierId.includes("LEGACY"))+ return "Free";+ }++ const tierName =+ subscriptionInfo.currentTier?.name ||+ subscriptionInfo.currentTier?.displayName ||+ subscriptionInfo.subscriptionType ||+ subscriptionInfo.tier ||+ "";+ const upper = tierName.toUpperCase();++ if (upper.includes("ULTRA")) return "Ultra";+ if (upper.includes("PRO")) return "Pro";+ if (upper.includes("ENTERPRISE")) return "Enterprise";+ if (upper.includes("STANDARD") || upper.includes("BUSINESS")) return "Business";+ if (upper.includes("INDIVIDUAL") || upper.includes("FREE")) return "Free";++ if (subscriptionInfo.currentTier?.upgradeSubscriptionType) return "Free";+ if (tierName) {+ return tierName.charAt(0).toUpperCase() + tierName.slice(1).toLowerCase();+ }++ return "Free";}// ── Antigravity subscription info cache ──────────────────────────────────────diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsxindex 4075c078e9..a0a450c127 100644--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx@@ -28,6 +28,7 @@ const QUOTA_BAR_YELLOW_THRESHOLD = 20;// Provider display configconst PROVIDER_CONFIG = {antigravity: { label: "Antigravity", color: "#F59E0B" },+ "gemini-cli": { label: "Gemini CLI", color: "#4285F4" },github: { label: "GitHub Copilot", color: "#333" },kiro: { label: "Kiro AI", color: "#FF6B35" },codex: { label: "OpenAI Codex", color: "#10A37F" },@@ -279,12 +280,13 @@ export default function ProviderLimits() {const sortedConnections = useMemo(() => {const priority = {antigravity: 1,- github: 2,- codex: 3,- claude: 4,- kiro: 5,- glm: 6,- "kimi-coding": 7,+ "gemini-cli": 2,+ github: 3,+ codex: 4,+ claude: 5,+ kiro: 6,+ glm: 7,+ "kimi-coding": 8,};return [...filteredConnections].sort((a, b) => (priority[a.provider] || 9) - (priority[b.provider] || 9)@@ -624,6 +626,7 @@ export default function ProviderLimits() {>{/* Model label */}<span+ title={q.modelKey || q.name}className="text-[11px] font-semibold py-0.5 px-2 rounded whitespace-nowrap min-w-[60px] text-center"style={{ background: colors.bg, color: colors.text }}>diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsxindex a14643b785..b01a36514b 100644--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsx+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsx@@ -11,15 +11,6 @@ const PROVIDER_PLAN_FALLBACKS = new Set([]);const QUOTA_LABEL_MAP: Record<string, string> = {- "gemini-3-pro-high": "G3 Pro",- "gemini-3-pro-low": "G3 Pro Low",- "gemini-3-flash": "G3 Flash",- "gemini-2.5-flash": "G2.5 Flash",- "claude-opus-4-6-thinking": "Opus 4.6 Tk",- "claude-opus-4-5-thinking": "Opus 4.5 Tk",- "claude-opus-4-5": "Opus 4.5",- "claude-sonnet-4-5-thinking": "Sonnet 4.5 Tk",- "claude-sonnet-4-5": "Sonnet 4.5",chat: "Chat",completions: "Completions",premium_interactions: "Premium",@@ -254,6 +245,14 @@ export function parseQuotaData(provider, data) {}break;+ case "gemini-cli":+ if (data.quotas) {+ Object.entries(data.quotas).forEach(([modelKey, quota]: [string, any]) => {+ normalizedQuotas.push(normalizeQuotaEntry(modelKey, quota, { modelKey }));+ });+ }+ break;+default:// Generic fallback for unknown providersif (data.quotas) {diff --git a/src/app/api/providers/[id]/models/route.ts b/src/app/api/providers/[id]/models/route.tsindex ef8a8d1a36..4a9f95a1e9 100644--- a/src/app/api/providers/[id]/models/route.ts+++ b/src/app/api/providers/[id]/models/route.ts@@ -139,19 +139,7 @@ const PROVIDER_MODELS_CONFIG: Record<string, ProviderModelsConfigEntry> = {name: m.displayName || (m.name || "").replace(/^models\//, ""),})),},- "gemini-cli": {- url: "https://generativelanguage.googleapis.com/v1beta/models",- method: "GET",- headers: { "Content-Type": "application/json" },- authHeader: "Authorization",- authPrefix: "Bearer ",- parseResponse: (data) =>- (data.models || []).map((m) => ({- ...m,- id: (m.name || m.id || "").replace(/^models\//, ""),- name: m.displayName || (m.name || "").replace(/^models\//, ""),- })),- },+ // gemini-cli handled via retrieveUserQuota (see GET handler)qwen: {url: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/models",method: "GET",@@ -505,6 +493,71 @@ export async function GET(return buildResponse({ provider, connectionId, models });}+ if (provider === "gemini-cli") {+ // Gemini CLI doesn't have a /models endpoint. Instead, query the quota+ // endpoint to discover available models from the quota buckets.+ if (!accessToken) {+ return NextResponse.json(+ { error: "No access token for Gemini CLI. Please reconnect OAuth." },+ { status: 400 }+ );+ }++ const psd = asRecord(connection.providerSpecificData);+ const projectId =+ connection.projectId || psd.projectId || null;++ if (!projectId) {+ return NextResponse.json(+ { error: "Gemini CLI project ID not available. Please reconnect OAuth." },+ { status: 400 }+ );+ }++ try {+ const quotaRes = await fetch(+ "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota",+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ project: projectId }),+ }+ );++ if (!quotaRes.ok) {+ const errText = await quotaRes.text();+ console.log(`[models] Gemini CLI quota fetch failed (${quotaRes.status}):`, errText);+ return NextResponse.json(+ { error: `Failed to fetch Gemini CLI models: ${quotaRes.status}` },+ { status: quotaRes.status }+ );+ }++ const quotaData = await quotaRes.json();+ const buckets: Array<{ modelId?: string; tokenType?: string }> =+ quotaData.buckets || [];++ const models = buckets+ .filter((b) => b.modelId)+ .map((b) => ({+ id: b.modelId,+ name: b.modelId,+ owned_by: "google",+ }));++ return buildResponse({ provider, connectionId, models });+ } catch (err: any) {+ console.log("[models] Gemini CLI model fetch error:", err.message);+ return NextResponse.json(+ { error: "Failed to fetch Gemini CLI models" },+ { status: 500 }+ );+ }+ }+if (isAnthropicCompatibleProvider(provider)) {let baseUrl = getProviderBaseUrl(connection.providerSpecificData);if (!baseUrl) {diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.tsindex 85ea9128dc..266dc08234 100644--- a/src/shared/constants/providers.ts+++ b/src/shared/constants/providers.ts@@ -656,6 +656,7 @@ export const ID_TO_ALIAS = Object.values(AI_PROVIDERS).reduce((acc, p) => {// Providers that support usage/quota APIexport const USAGE_SUPPORTED_PROVIDERS = ["antigravity",+ "gemini-cli","kiro","github","codex",