Merge origin/master (v0.5.69) into gitea/new_feature
This commit is contained in:
@@ -203,7 +203,8 @@ async function onboardUser(accessToken, tierID, externalSignal, endpoints, provi
|
||||
|
||||
const reqBody = { tierId: tierID, metadata: LOAD_CODE_ASSIST_METADATA };
|
||||
const headers = provider === "antigravity" ? ANTIGRAVITY_LOAD_CODE_ASSIST_HEADERS : LOAD_CODE_ASSIST_HEADERS;
|
||||
const MAX_ATTEMPTS = 5;
|
||||
const MAX_ATTEMPTS = Number(process.env.ONBOARD_MAX_ATTEMPTS) || 2;
|
||||
const BASE_RETRY_DELAY_MS = Number(process.env.ONBOARD_RETRY_DELAY_MS) || 12_000;
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||
// Bail out immediately if the connection was removed
|
||||
@@ -241,9 +242,10 @@ async function onboardUser(accessToken, tierID, externalSignal, endpoints, provi
|
||||
throw new Error("onboardUser done but no project_id in response");
|
||||
}
|
||||
|
||||
// Server not done yet – wait and retry
|
||||
// Server not done yet – wait and retry with jitter
|
||||
const jitter = Math.floor(Math.random() * 5000);
|
||||
console.log(`[ProjectId] Onboard attempt ${attempt}/${MAX_ATTEMPTS}: not done yet, waiting...`);
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
await new Promise(resolve => setTimeout(resolve, BASE_RETRY_DELAY_MS + jitter));
|
||||
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
@@ -256,9 +258,10 @@ async function onboardUser(accessToken, tierID, externalSignal, endpoints, provi
|
||||
console.warn(`[ProjectId] onboardUser failed after ${MAX_ATTEMPTS} attempts: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
// Continue to next attempt instead of throwing (which would skip remaining retries)
|
||||
// Wait with jitter before retrying
|
||||
const jitter = Math.floor(Math.random() * 5000);
|
||||
console.warn(`[ProjectId] onboardUser attempt ${attempt} failed: ${error.message}, retrying...`);
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
await new Promise(resolve => setTimeout(resolve, BASE_RETRY_DELAY_MS + jitter));
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
externalSignal?.removeEventListener("abort", forwardAbort);
|
||||
|
||||
170
open-sse/services/thoughtSignatureStore.js
Normal file
170
open-sse/services/thoughtSignatureStore.js
Normal file
@@ -0,0 +1,170 @@
|
||||
import { makeKv } from "../../src/lib/db/helpers/kvStore.js";
|
||||
|
||||
const MAX_SIGNATURES = 2000;
|
||||
const MAX_PERSISTED_SIGNATURES = 10_000;
|
||||
const MEMORY_TTL_MS = 1000 * 60 * 60; // 1 hour
|
||||
const PERSISTED_TTL_MS = 1000 * 60 * 60 * 24 * 7; // 7 days
|
||||
const SCOPE = "gemini_thought_signatures";
|
||||
|
||||
const signatureKv = makeKv(SCOPE);
|
||||
const memorySignatures = new Map();
|
||||
let pruneCounter = 0;
|
||||
|
||||
function pruneMemoryExpired() {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of memorySignatures.entries()) {
|
||||
if (value.expiresAt <= now) {
|
||||
memorySignatures.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
while (memorySignatures.size > MAX_SIGNATURES) {
|
||||
const oldestKey = memorySignatures.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
memorySignatures.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
async function maybePrunePersisted() {
|
||||
pruneCounter++;
|
||||
if (pruneCounter % 100 !== 0) return;
|
||||
|
||||
try {
|
||||
const all = await signatureKv.getAll();
|
||||
const keys = Object.keys(all);
|
||||
const now = Date.now();
|
||||
const expiredKeys = [];
|
||||
const valid = [];
|
||||
|
||||
for (const k of keys) {
|
||||
const entry = all[k];
|
||||
if (!entry || typeof entry.signature !== "string" || (entry.expiresAt && entry.expiresAt <= now)) {
|
||||
expiredKeys.push(k);
|
||||
} else {
|
||||
valid.push({ key: k, createdAt: entry.createdAt || 0 });
|
||||
}
|
||||
}
|
||||
|
||||
for (const k of expiredKeys) {
|
||||
await signatureKv.remove(k).catch(() => {});
|
||||
}
|
||||
|
||||
if (valid.length > MAX_PERSISTED_SIGNATURES) {
|
||||
valid.sort((a, b) => b.createdAt - a.createdAt);
|
||||
const toRemove = valid.slice(MAX_PERSISTED_SIGNATURES);
|
||||
for (const item of toRemove) {
|
||||
await signatureKv.remove(item.key).catch(() => {});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Fail-open
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a thought signature for a tool_call_id with optional sessionId namespace (RAM + SQLite async)
|
||||
*/
|
||||
export function storeGeminiThoughtSignature(toolCallId, signature, sessionId = null) {
|
||||
if (typeof toolCallId !== "string" || !toolCallId) return;
|
||||
if (typeof signature !== "string" || !signature) return;
|
||||
|
||||
const now = Date.now();
|
||||
pruneMemoryExpired();
|
||||
|
||||
const keys = [];
|
||||
if (sessionId && typeof sessionId === "string") {
|
||||
keys.push(`${sessionId}:${toolCallId}`);
|
||||
}
|
||||
keys.push(toolCallId);
|
||||
|
||||
for (const k of keys) {
|
||||
memorySignatures.set(k, {
|
||||
signature,
|
||||
expiresAt: now + MEMORY_TTL_MS,
|
||||
});
|
||||
|
||||
// Async persist to SQLite kv table without blocking
|
||||
signatureKv.set(k, {
|
||||
signature,
|
||||
createdAt: now,
|
||||
expiresAt: now + PERSISTED_TTL_MS,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
maybePrunePersisted().catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a thought signature by tool_call_id (RAM first, then SQLite fallback)
|
||||
*/
|
||||
export async function getGeminiThoughtSignature(toolCallId, sessionId = null) {
|
||||
if (typeof toolCallId !== "string" || !toolCallId) return null;
|
||||
|
||||
pruneMemoryExpired();
|
||||
|
||||
if (sessionId && typeof sessionId === "string") {
|
||||
const sessionKey = `${sessionId}:${toolCallId}`;
|
||||
const sessionEntry = memorySignatures.get(sessionKey);
|
||||
if (sessionEntry && sessionEntry.expiresAt > Date.now()) {
|
||||
return sessionEntry.signature;
|
||||
}
|
||||
}
|
||||
|
||||
const entry = memorySignatures.get(toolCallId);
|
||||
if (entry && entry.expiresAt > Date.now()) {
|
||||
return entry.signature;
|
||||
}
|
||||
|
||||
try {
|
||||
if (sessionId && typeof sessionId === "string") {
|
||||
const sessionKey = `${sessionId}:${toolCallId}`;
|
||||
const sessionRow = await signatureKv.get(sessionKey);
|
||||
if (sessionRow && typeof sessionRow.signature === "string" && (!sessionRow.expiresAt || sessionRow.expiresAt > Date.now())) {
|
||||
memorySignatures.set(sessionKey, {
|
||||
signature: sessionRow.signature,
|
||||
expiresAt: Date.now() + MEMORY_TTL_MS,
|
||||
});
|
||||
return sessionRow.signature;
|
||||
}
|
||||
}
|
||||
|
||||
const row = await signatureKv.get(toolCallId);
|
||||
if (row && typeof row.signature === "string") {
|
||||
if (row.expiresAt && row.expiresAt <= Date.now()) {
|
||||
signatureKv.remove(toolCallId).catch(() => {});
|
||||
return null;
|
||||
}
|
||||
memorySignatures.set(toolCallId, {
|
||||
signature: row.signature,
|
||||
expiresAt: Date.now() + MEMORY_TTL_MS,
|
||||
});
|
||||
return row.signature;
|
||||
}
|
||||
} catch {
|
||||
// Fail-open
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous get from RAM cache only (for sync translators)
|
||||
*/
|
||||
export function getGeminiThoughtSignatureSync(toolCallId, sessionId = null) {
|
||||
if (typeof toolCallId !== "string" || !toolCallId) return null;
|
||||
pruneMemoryExpired();
|
||||
|
||||
if (sessionId && typeof sessionId === "string") {
|
||||
const sessionKey = `${sessionId}:${toolCallId}`;
|
||||
const sessionEntry = memorySignatures.get(sessionKey);
|
||||
if (sessionEntry && sessionEntry.expiresAt > Date.now()) {
|
||||
return sessionEntry.signature;
|
||||
}
|
||||
}
|
||||
|
||||
const entry = memorySignatures.get(toolCallId);
|
||||
if (entry && entry.expiresAt > Date.now()) {
|
||||
return entry.signature;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
refreshXaiToken,
|
||||
refreshAccessToken,
|
||||
refreshKimiToken,
|
||||
refreshClineToken,
|
||||
refreshClaudeOAuthToken,
|
||||
refreshGoogleToken,
|
||||
refreshCodexToken,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
export {
|
||||
refreshAccessToken,
|
||||
refreshKimiToken,
|
||||
refreshClineToken,
|
||||
refreshClaudeOAuthToken,
|
||||
refreshGoogleToken,
|
||||
refreshCodexToken,
|
||||
@@ -145,6 +147,7 @@ const REFRESH_HANDLERS = {
|
||||
"codebuddy-cn": (c, log) => refreshCodebuddyToken(c.refreshToken, log),
|
||||
"codebuddy-intl": (c, log) => refreshCodebuddyIntlToken(c.refreshToken, log),
|
||||
trae: (c, log) => refreshTraeToken(c.refreshToken, c, log),
|
||||
cline: (c, log) => refreshClineToken(c.refreshToken, log),
|
||||
zed: () => refreshZedToken(),
|
||||
windsurf: (c, log) => refreshWindsurfToken(c, log),
|
||||
// Kimi Code OAuth (merged into id `kimi`); legacy id still routes here
|
||||
|
||||
@@ -147,6 +147,53 @@ export async function refreshKimiToken(refreshToken, credentials, log) {
|
||||
return refreshAccessToken("kimi", refreshToken, credentials, log);
|
||||
}
|
||||
|
||||
export async function refreshClineToken(refreshToken, log) {
|
||||
if (!refreshToken) return null;
|
||||
|
||||
return dedupRefresh("cline", refreshToken, async () => {
|
||||
try {
|
||||
const response = await fetch(PROVIDERS.cline?.refreshUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
refreshToken,
|
||||
grantType: "refresh_token",
|
||||
clientType: "extension",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
log?.error?.("TOKEN_REFRESH", "Failed to refresh Cline token", {
|
||||
status: response.status,
|
||||
error: errorText,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const body = await response.json();
|
||||
const tokens = body?.data || body;
|
||||
if (!tokens?.accessToken) return null;
|
||||
|
||||
const expiresIn = tokens.expiresAt
|
||||
? Math.max(1, Math.floor((new Date(tokens.expiresAt).getTime() - Date.now()) / 1000))
|
||||
: (tokens.expiresIn || tokens.expires_in || 3600);
|
||||
|
||||
return {
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken || refreshToken,
|
||||
expiresIn,
|
||||
};
|
||||
} catch (error) {
|
||||
log?.error?.("TOKEN_REFRESH", `Error refreshing Cline token: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}, log);
|
||||
}
|
||||
|
||||
// Claude OAuth: JSON body, client_id only. Delegate to refreshAccessToken("claude", ...).
|
||||
export async function refreshClaudeOAuthToken(refreshToken, log) {
|
||||
return refreshAccessToken("claude", refreshToken, {}, log);
|
||||
|
||||
@@ -15,12 +15,14 @@ import { getXaiUsage } from "./usage/xai.js";
|
||||
import { getGrokCliUsage } from "./usage/grok-cli.js";
|
||||
import { getKimiUsage } from "./usage/kimi.js";
|
||||
import { getDeepseekUsage } from "./usage/deepseek.js";
|
||||
import { getCommandCodeUsage } from "./usage/commandcode.js";
|
||||
import { getOpenCodeGoUsage } from "./usage/opencode-go.js";
|
||||
import { getGroqUsage } from "./usage/groq.js";
|
||||
import { getZedUsage } from "./usage/zed.js";
|
||||
import { resolveQoderCredentials } from "./qoderModels.js";
|
||||
import { getGlmUsage } from "./usage/glm.js";
|
||||
import {
|
||||
getIflowUsage,
|
||||
getOllamaUsage,
|
||||
getGlmUsage,
|
||||
getVercelAiGatewayUsage,
|
||||
getQoderUsage,
|
||||
} from "./usage/misc.js";
|
||||
@@ -56,8 +58,10 @@ const USAGE_HANDLERS = {
|
||||
"codebuddy-intl": (c) => getCodeBuddyIntlUsage(c.accessToken, c.apiKey, c.providerSpecificData, c.proxyOptions),
|
||||
"grok-cli": (c) => getGrokCliUsage(c.accessToken, c.providerSpecificData, c.proxyOptions),
|
||||
kimi: (c) => getKimiUsage(c.accessToken, c.apiKey, c.proxyOptions, c.providerSpecificData),
|
||||
"opencode-go": (c) => getOpenCodeGoUsage(c.apiKey, c.proxyOptions),
|
||||
deepseek: (c) => getDeepseekUsage(c.apiKey, c.proxyOptions),
|
||||
commandcode: (c) => getCommandCodeUsage(c.apiKey, c.proxyOptions),
|
||||
groq: (c) => getGroqUsage(c.apiKey, c.proxyOptions),
|
||||
zed: (c) => getZedUsage(c.accessToken, c.providerSpecificData, c.proxyOptions),
|
||||
};
|
||||
|
||||
export async function getUsageForProvider(connection, proxyOptions = null, options = {}) {
|
||||
|
||||
@@ -102,14 +102,34 @@ async function fetchClaudeUsageRaw(accessToken, proxyOptions = null) {
|
||||
quotas["weekly (7d)"] = createQuotaObject(data.seven_day);
|
||||
}
|
||||
|
||||
// Parse model-specific weekly windows (e.g. seven_day_sonnet, seven_day_opus)
|
||||
// Parse model-specific weekly windows (e.g. seven_day_sonnet, seven_day_opus, seven_day_fable)
|
||||
const MODEL_DISPLAY_NAMES = {
|
||||
fable_5_1: "fable",
|
||||
fable_5: "fable",
|
||||
};
|
||||
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
if (key.startsWith("seven_day_") && key !== "seven_day" && hasUtilization(value)) {
|
||||
const modelName = key.replace("seven_day_", "");
|
||||
const rawName = key.replace("seven_day_", "");
|
||||
const modelName = MODEL_DISPLAY_NAMES[rawName] || rawName;
|
||||
quotas[`weekly ${modelName} (7d)`] = createQuotaObject(value);
|
||||
} else if ((key === "fable" || key === "fable_5" || key === "fable_5_1") && hasUtilization(value)) {
|
||||
quotas["weekly fable (7d)"] = createQuotaObject(value);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: surface Fable quota row if weekly window exists but Fable was not returned yet
|
||||
if (!quotas["weekly fable (7d)"] && hasUtilization(data.seven_day)) {
|
||||
quotas["weekly fable (7d)"] = {
|
||||
used: 0,
|
||||
total: 100,
|
||||
remaining: 100,
|
||||
remainingPercentage: 100,
|
||||
resetAt: parseResetTime(data.seven_day.resets_at),
|
||||
unlimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
plan: "Claude Code",
|
||||
extraUsage: data.extra_usage ?? null,
|
||||
|
||||
@@ -21,6 +21,13 @@ function toIsoDate(value) {
|
||||
return Number.isFinite(time) ? date.toISOString() : null;
|
||||
}
|
||||
|
||||
function errorMessage(value, fallback) {
|
||||
if (!value) return fallback;
|
||||
if (typeof value === "string") return value;
|
||||
if (typeof value.message === "string") return value.message;
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function getCodexAccountId(providerSpecificData) {
|
||||
return providerSpecificData?.workspaceId || providerSpecificData?.accountId || providerSpecificData?.chatgptAccountId || null;
|
||||
}
|
||||
@@ -80,6 +87,23 @@ function getCodexReviewRateLimit(data) {
|
||||
}) || null;
|
||||
}
|
||||
|
||||
function getCodexSparkRateLimit(data) {
|
||||
if (data.spark_rate_limit || data.gpt_5_3_codex_spark_rate_limit) {
|
||||
return data.spark_rate_limit || data.gpt_5_3_codex_spark_rate_limit;
|
||||
}
|
||||
|
||||
const byLimitId = data.rate_limits_by_limit_id;
|
||||
if (byLimitId && typeof byLimitId === "object" && !Array.isArray(byLimitId)) {
|
||||
return byLimitId["gpt-5.3-codex-spark"] || byLimitId.gpt_5_3_codex_spark || byLimitId.spark || null;
|
||||
}
|
||||
|
||||
const additional = Array.isArray(data.additional_rate_limits) ? data.additional_rate_limits : [];
|
||||
return additional.find((entry) => {
|
||||
const id = String(entry?.limit_name || entry?.metered_feature || entry?.id || "").toLowerCase();
|
||||
return id.includes("spark") || id.includes("5.3-codex-spark");
|
||||
}) || null;
|
||||
}
|
||||
|
||||
export async function getCodexUsage(accessToken, proxyOptions = null) {
|
||||
try {
|
||||
const response = await proxyAwareFetch(CODEX_CONFIG.usageUrl, {
|
||||
@@ -97,16 +121,19 @@ export async function getCodexUsage(accessToken, proxyOptions = null) {
|
||||
const data = await response.json();
|
||||
const normalRateLimit = data.rate_limit || data.rate_limits || data.rate_limits_by_limit_id?.codex || {};
|
||||
const reviewRateLimit = getCodexReviewRateLimit(data);
|
||||
const sparkRateLimit = getCodexSparkRateLimit(data);
|
||||
const availableResetCredits = Math.max(0, toFiniteNumber(data.rate_limit_reset_credits?.available_count, 0));
|
||||
const quotas = {};
|
||||
|
||||
appendCodexQuotaWindows(quotas, "", normalRateLimit);
|
||||
appendCodexQuotaWindows(quotas, "review", reviewRateLimit);
|
||||
appendCodexQuotaWindows(quotas, "spark", sparkRateLimit);
|
||||
|
||||
return {
|
||||
plan: data.plan_type || data.summary?.plan || "unknown",
|
||||
limitReached: getCodexRateLimitBody(normalRateLimit)?.limit_reached || false,
|
||||
reviewLimitReached: getCodexRateLimitBody(reviewRateLimit)?.limit_reached || false,
|
||||
sparkLimitReached: getCodexRateLimitBody(sparkRateLimit)?.limit_reached || false,
|
||||
resetCredits: { availableCount: availableResetCredits },
|
||||
quotas,
|
||||
};
|
||||
@@ -142,7 +169,7 @@ export async function getCodexRateLimitResetCredits(accessToken, proxyOptions =
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const message = data?.message || data?.error || data?.detail || `Codex reset credits API unavailable (${response.status}).`;
|
||||
const message = errorMessage(data?.message || data?.error || data?.detail, `Codex reset credits API unavailable (${response.status}).`);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
|
||||
88
open-sse/services/usage/glm.js
Normal file
88
open-sse/services/usage/glm.js
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* GLM Coding Plan usage (international + China regions)
|
||||
*/
|
||||
|
||||
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
|
||||
import { U } from "./shared.js";
|
||||
|
||||
// GLM quota endpoints (region-aware) — url from registry transport.usage
|
||||
const GLM_QUOTA_URLS = {
|
||||
international: U("glm").url,
|
||||
china: U("glm-cn").url,
|
||||
};
|
||||
|
||||
/**
|
||||
* GLM Coding Plan usage (international + China regions)
|
||||
* Supports both TOKENS_LIMIT and CREDIT_LIMIT and dynamic intervals (e.g. session 5h, weekly 7d).
|
||||
*/
|
||||
export async function getGlmUsage(apiKey, provider, proxyOptions = null) {
|
||||
if (!apiKey) {
|
||||
return { message: "GLM API key not available." };
|
||||
}
|
||||
|
||||
const region = provider === "glm-cn" ? "china" : "international";
|
||||
const quotaUrl = GLM_QUOTA_URLS[region];
|
||||
|
||||
try {
|
||||
const response = await proxyAwareFetch(
|
||||
quotaUrl,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
proxyOptions,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
return { message: "GLM API key invalid or expired." };
|
||||
}
|
||||
return { message: `GLM quota API error (${response.status}).` };
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
const data = json?.data && typeof json.data === "object" ? json.data : {};
|
||||
const limits = Array.isArray(data.limits) ? data.limits : [];
|
||||
const quotas = {};
|
||||
|
||||
for (const limit of limits) {
|
||||
// 1. Accept both TOKENS_LIMIT and CREDIT_LIMIT from GLM API
|
||||
if (!limit || (limit.type !== "TOKENS_LIMIT" && limit.type !== "CREDIT_LIMIT")) continue;
|
||||
const usedPercent = Number(limit.percentage) || 0;
|
||||
const resetMs = Number(limit.nextResetTime) || 0;
|
||||
const remaining = Math.max(0, 100 - usedPercent);
|
||||
|
||||
// 2. Map key dynamically based on type and period (unit) to avoid overwriting
|
||||
let key = "session";
|
||||
if (limit.unit === 3) {
|
||||
key = `Session (${limit.number}h)`;
|
||||
} else if (limit.unit === 6) {
|
||||
key = "Weekly (7d)";
|
||||
} else if (limit.type === "TOKENS_LIMIT") {
|
||||
key = "Tokens";
|
||||
} else {
|
||||
key = `Limit (${limit.number})`;
|
||||
}
|
||||
|
||||
quotas[key] = {
|
||||
used: usedPercent,
|
||||
total: 100,
|
||||
remaining,
|
||||
remainingPercentage: remaining,
|
||||
resetAt: resetMs > 0 ? new Date(resetMs).toISOString() : null,
|
||||
unlimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
const levelRaw = typeof data.level === "string" ? data.level : "";
|
||||
const plan = levelRaw
|
||||
? levelRaw.charAt(0).toUpperCase() + levelRaw.slice(1).toLowerCase()
|
||||
: "Unknown";
|
||||
|
||||
return { plan, quotas };
|
||||
} catch (error) {
|
||||
return { message: `GLM error: ${error.message}` };
|
||||
}
|
||||
}
|
||||
@@ -161,6 +161,9 @@ export async function getAntigravityUsage(accessToken, providerSpecificData, pro
|
||||
if (data.models) {
|
||||
// Filter only recommended/important models (must match PROVIDER_MODELS ag ids)
|
||||
const importantModels = [
|
||||
'gemini-3.8-flash-high',
|
||||
'gemini-3.8-flash-medium',
|
||||
'gemini-3.8-flash-low',
|
||||
'gemini-3.7-flash-high',
|
||||
'gemini-3.7-flash-medium',
|
||||
'gemini-3.7-flash-low',
|
||||
|
||||
133
open-sse/services/usage/groq.js
Normal file
133
open-sse/services/usage/groq.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Groq usage — no dedicated quota endpoint. Rate-limit info instead rides on
|
||||
* every API response as x-ratelimit-* headers (requests + tokens, always
|
||||
* included). We piggyback on the models list (already used as
|
||||
* transport.validateUrl) so reading usage never costs tokens.
|
||||
*
|
||||
* Headers:
|
||||
* x-ratelimit-limit-requests / x-ratelimit-remaining-requests
|
||||
* x-ratelimit-limit-tokens / x-ratelimit-remaining-tokens
|
||||
* x-ratelimit-reset-requests / x-ratelimit-reset-tokens (duration strings, e.g. "2m59.56s")
|
||||
*
|
||||
* Docs: https://console.groq.com/docs/rate-limits
|
||||
*/
|
||||
|
||||
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
|
||||
import { U } from "./shared.js";
|
||||
|
||||
const MODELS_URL = U("groq").url;
|
||||
|
||||
// Groq reset headers are Go-style duration strings ("2m59.56s", "7.66s"), not
|
||||
// timestamps — parse the h/m/s/ms components and add them to now().
|
||||
function parseGroqDurationMs(value) {
|
||||
if (typeof value !== "string" || !value.trim()) return null;
|
||||
|
||||
const re = /(\d+(?:\.\d+)?)(ms|s|m|h)/g;
|
||||
let match;
|
||||
let totalMs = 0;
|
||||
let matched = false;
|
||||
while ((match = re.exec(value))) {
|
||||
matched = true;
|
||||
const amount = Number(match[1]);
|
||||
const unit = match[2];
|
||||
const unitMs = unit === "h" ? 3600000 : unit === "m" ? 60000 : unit === "ms" ? 1 : 1000;
|
||||
totalMs += amount * unitMs;
|
||||
}
|
||||
return matched ? totalMs : null;
|
||||
}
|
||||
|
||||
function resetAtFromDuration(value) {
|
||||
const ms = parseGroqDurationMs(value);
|
||||
return ms === null ? null : new Date(Date.now() + ms).toISOString();
|
||||
}
|
||||
|
||||
function buildRateLimitQuota(headers, limitKey, remainingKey, resetKey) {
|
||||
// headers.get() returns null when absent, and Number(null) is 0 (a finite
|
||||
// number) — check presence explicitly so a missing header can't masquerade
|
||||
// as a real "0 remaining" quota.
|
||||
const limitRaw = headers.get(limitKey);
|
||||
const remainingRaw = headers.get(remainingKey);
|
||||
if (limitRaw === null || remainingRaw === null) return null;
|
||||
|
||||
const limit = Number(limitRaw);
|
||||
const remaining = Number(remainingRaw);
|
||||
if (!Number.isFinite(limit) || !Number.isFinite(remaining)) return null;
|
||||
|
||||
return {
|
||||
used: Math.max(0, limit - remaining),
|
||||
total: limit,
|
||||
resetAt: resetAtFromDuration(headers.get(resetKey)),
|
||||
unlimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|null|undefined} apiKey
|
||||
* @param {object|null} proxyOptions
|
||||
*/
|
||||
export async function getGroqUsage(apiKey, proxyOptions = null) {
|
||||
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
|
||||
return { message: "Groq API key not available. Add a key to view usage." };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await proxyAwareFetch(
|
||||
MODELS_URL,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey.trim()}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
proxyOptions,
|
||||
);
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
return { plan: "Groq", message: "Groq authentication failed. Check the API key." };
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text().catch(() => "");
|
||||
return {
|
||||
plan: "Groq",
|
||||
message: `Groq usage API error (${response.status})${errText ? `: ${errText.slice(0, 120)}` : ""}`,
|
||||
};
|
||||
}
|
||||
|
||||
// The quota data lives in headers, not the body — drain it so the
|
||||
// connection can be released without needing the payload.
|
||||
await response.text().catch(() => {});
|
||||
|
||||
const requests = buildRateLimitQuota(
|
||||
response.headers,
|
||||
"x-ratelimit-limit-requests",
|
||||
"x-ratelimit-remaining-requests",
|
||||
"x-ratelimit-reset-requests",
|
||||
);
|
||||
const tokens = buildRateLimitQuota(
|
||||
response.headers,
|
||||
"x-ratelimit-limit-tokens",
|
||||
"x-ratelimit-remaining-tokens",
|
||||
"x-ratelimit-reset-tokens",
|
||||
);
|
||||
|
||||
if (!requests && !tokens) {
|
||||
// Key is valid (request succeeded) but no rate-limit bucket reported —
|
||||
// distinguish "not tracked yet" from an auth/error state.
|
||||
return {
|
||||
plan: "Groq",
|
||||
message: "Groq connected. No rate-limit data reported for this key yet.",
|
||||
quotas: {},
|
||||
};
|
||||
}
|
||||
|
||||
const quotas = {};
|
||||
if (requests) quotas["Requests"] = requests;
|
||||
if (tokens) quotas["Tokens"] = tokens;
|
||||
|
||||
return { plan: "Groq", quotas };
|
||||
} catch (error) {
|
||||
return { message: `Groq error: ${error.message}` };
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,8 @@
|
||||
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
|
||||
import { U } from "./shared.js";
|
||||
|
||||
// GLM quota endpoints (region-aware) — url from registry transport.usage
|
||||
const GLM_QUOTA_URLS = {
|
||||
international: U("glm").url,
|
||||
china: U("glm-cn").url,
|
||||
};
|
||||
export { getGlmUsage } from "./glm.js";
|
||||
|
||||
|
||||
// Vercel AI Gateway credits endpoint
|
||||
// Returns { balance: "95.50", total_used: "4.50" } (USD as decimal strings).
|
||||
@@ -112,63 +109,7 @@ export async function getOllamaUsage(apiKey, providerSpecificData, proxyOptions
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GLM Coding Plan usage (international + China regions)
|
||||
*/
|
||||
export async function getGlmUsage(apiKey, provider, proxyOptions = null) {
|
||||
if (!apiKey) {
|
||||
return { message: "GLM API key not available." };
|
||||
}
|
||||
|
||||
const region = provider === "glm-cn" ? "china" : "international";
|
||||
const quotaUrl = GLM_QUOTA_URLS[region];
|
||||
|
||||
try {
|
||||
const response = await proxyAwareFetch(quotaUrl, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
}, proxyOptions);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
return { message: "GLM API key invalid or expired." };
|
||||
}
|
||||
return { message: `GLM quota API error (${response.status}).` };
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
const data = json?.data && typeof json.data === "object" ? json.data : {};
|
||||
const limits = Array.isArray(data.limits) ? data.limits : [];
|
||||
const quotas = {};
|
||||
|
||||
for (const limit of limits) {
|
||||
if (!limit || limit.type !== "TOKENS_LIMIT") continue;
|
||||
const usedPercent = Number(limit.percentage) || 0;
|
||||
const resetMs = Number(limit.nextResetTime) || 0;
|
||||
const remaining = Math.max(0, 100 - usedPercent);
|
||||
|
||||
quotas["session"] = {
|
||||
used: usedPercent,
|
||||
total: 100,
|
||||
remaining,
|
||||
remainingPercentage: remaining,
|
||||
resetAt: resetMs > 0 ? new Date(resetMs).toISOString() : null,
|
||||
unlimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
const levelRaw = typeof data.level === "string" ? data.level : "";
|
||||
const plan = levelRaw
|
||||
? levelRaw.charAt(0).toUpperCase() + levelRaw.slice(1).toLowerCase()
|
||||
: "Unknown";
|
||||
|
||||
return { plan, quotas };
|
||||
} catch (error) {
|
||||
return { message: `GLM error: ${error.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vercel AI Gateway usage — credit balance for the API key
|
||||
|
||||
107
open-sse/services/usage/opencode-go.js
Normal file
107
open-sse/services/usage/opencode-go.js
Normal file
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* OpenCode Go usage — GET https://opencode.ai/zen/go/v1/usage
|
||||
* Auth: Bearer <apiKey>
|
||||
*/
|
||||
|
||||
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
|
||||
import { parseResetTime, toFiniteNumber, U } from "./shared.js";
|
||||
|
||||
const USAGE_URL = U("opencode-go").url;
|
||||
const QUOTA_NAMES = {
|
||||
rolling: "Rolling",
|
||||
weekly: "Weekly",
|
||||
monthly: "Monthly",
|
||||
};
|
||||
|
||||
function parsePercent(value) {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function getOpenCodeGoUsage(apiKey = null, proxyOptions = null) {
|
||||
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
|
||||
return {
|
||||
message: "OpenCode Go API key not available. Add a key to view usage.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await proxyAwareFetch(
|
||||
USAGE_URL,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey.trim()}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
proxyOptions,
|
||||
);
|
||||
|
||||
if (response.status === 401) {
|
||||
return {
|
||||
plan: "OpenCode Go",
|
||||
message: "OpenCode Go authentication failed. Check the API key.",
|
||||
};
|
||||
}
|
||||
|
||||
if (response.status === 403) {
|
||||
const error = await response.json().catch(() => null);
|
||||
const subscriptionRequired = error?.error?.type === "EntitlementError";
|
||||
return {
|
||||
plan: "OpenCode Go",
|
||||
message: subscriptionRequired
|
||||
? "OpenCode Go subscription required for this API key."
|
||||
: "OpenCode Go access forbidden for this API key.",
|
||||
};
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
plan: "OpenCode Go",
|
||||
message: `OpenCode Go usage API error (${response.status}).`,
|
||||
};
|
||||
}
|
||||
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!data?.usage || typeof data.usage !== "object") {
|
||||
return {
|
||||
plan: "OpenCode Go",
|
||||
message: "OpenCode Go usage response did not contain quota data.",
|
||||
};
|
||||
}
|
||||
|
||||
const quotas = {};
|
||||
for (const [period, name] of Object.entries(QUOTA_NAMES)) {
|
||||
const quota = data.usage[period];
|
||||
if (!quota || typeof quota !== "object") continue;
|
||||
const percent = parsePercent(quota.percent);
|
||||
if (percent === null) continue;
|
||||
const used = Math.max(0, Math.min(100, toFiniteNumber(percent, 0)));
|
||||
quotas[name] = {
|
||||
used,
|
||||
total: 100,
|
||||
remaining: 100 - used,
|
||||
remainingPercentage: 100 - used,
|
||||
resetAt: parseResetTime(quota.resetsAt),
|
||||
unlimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
if (Object.keys(quotas).length === 0) {
|
||||
return {
|
||||
plan: "OpenCode Go",
|
||||
message: "OpenCode Go usage response did not contain valid quota data.",
|
||||
};
|
||||
}
|
||||
|
||||
return { plan: "OpenCode Go", quotas };
|
||||
} catch (error) {
|
||||
return { message: `OpenCode Go error: ${error.message}` };
|
||||
}
|
||||
}
|
||||
222
open-sse/services/usage/zed.js
Normal file
222
open-sse/services/usage/zed.js
Normal file
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* Zed usage — GET https://cloud.zed.dev/client/users/me
|
||||
* Auth: Authorization: {user_id} {access_token}
|
||||
*
|
||||
* Quota rows are derived from plan.usage (edit_predictions, optional model_requests)
|
||||
* and subscription_period.ended_at for billing-cycle reset.
|
||||
*/
|
||||
|
||||
import { fetchZedAuthenticatedUser } from "../../shared/zedAuth.js";
|
||||
import { parseResetTime, toFiniteNumber } from "./shared.js";
|
||||
|
||||
/** Map plan_v3 ids to dashboard labels (CodexBar-compatible). */
|
||||
export function formatZedPlanLabel(rawPlan) {
|
||||
const raw = String(rawPlan || "").trim();
|
||||
if (!raw) return "Zed";
|
||||
switch (raw.toLowerCase()) {
|
||||
case "zed_free":
|
||||
return "Zed Free";
|
||||
case "zed_pro":
|
||||
return "Zed Pro";
|
||||
case "zed_pro_trial":
|
||||
return "Zed Pro Trial";
|
||||
case "zed_student":
|
||||
return "Zed Student";
|
||||
case "zed_business":
|
||||
return "Zed Business";
|
||||
default:
|
||||
return raw
|
||||
.replace(/_/g, " ")
|
||||
.split(/\s+/)
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Zed UsageLimit JSON: "unlimited", a number, or { limited: N }.
|
||||
*/
|
||||
export function parseZedUsageLimit(limit) {
|
||||
if (limit == null) return { unlimited: false, total: 0 };
|
||||
|
||||
if (limit === "unlimited" || limit?.unlimited === true) {
|
||||
return { unlimited: true, total: 0 };
|
||||
}
|
||||
|
||||
if (typeof limit === "number" && Number.isFinite(limit)) {
|
||||
return { unlimited: false, total: Math.max(0, limit) };
|
||||
}
|
||||
|
||||
if (typeof limit === "string") {
|
||||
const trimmed = limit.trim();
|
||||
if (trimmed === "unlimited") return { unlimited: true, total: 0 };
|
||||
const parsed = Number(trimmed);
|
||||
if (Number.isFinite(parsed)) return { unlimited: false, total: Math.max(0, parsed) };
|
||||
}
|
||||
|
||||
const limited = limit.limited ?? limit.Limited;
|
||||
if (typeof limited === "number" && Number.isFinite(limited)) {
|
||||
return { unlimited: false, total: Math.max(0, limited) };
|
||||
}
|
||||
|
||||
return { unlimited: false, total: 0 };
|
||||
}
|
||||
|
||||
/** limit `{ limited: 0 }` on Pro/Student means token billing, not a 0-cap request quota. */
|
||||
export function isZedTokenBillingModelRequestsLimit(limitRaw) {
|
||||
const info = parseZedUsageLimit(limitRaw);
|
||||
return !info.unlimited && info.total === 0;
|
||||
}
|
||||
|
||||
function makeZedQuotaRow(name, usedRaw, limitRaw, resetAt = null) {
|
||||
const used = Math.max(0, toFiniteNumber(usedRaw, 0));
|
||||
const limitInfo = parseZedUsageLimit(limitRaw);
|
||||
|
||||
if (limitInfo.unlimited) {
|
||||
return {
|
||||
used,
|
||||
total: 0,
|
||||
remainingPercentage: 100,
|
||||
resetAt: resetAt || null,
|
||||
unlimited: true,
|
||||
};
|
||||
}
|
||||
|
||||
const total = limitInfo.total;
|
||||
if (total <= 0) {
|
||||
return {
|
||||
used,
|
||||
total: 0,
|
||||
remainingPercentage: 0,
|
||||
resetAt: resetAt || null,
|
||||
unlimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
const clampedUsed = Math.min(used, total);
|
||||
const remaining = Math.max(0, total - clampedUsed);
|
||||
return {
|
||||
used: clampedUsed,
|
||||
total,
|
||||
remainingPercentage: (remaining / total) * 100,
|
||||
resetAt: resetAt || null,
|
||||
unlimited: false,
|
||||
};
|
||||
}
|
||||
|
||||
function usageBucketLimit(bucket) {
|
||||
if (!bucket || typeof bucket !== "object") return null;
|
||||
if (bucket.limit != null) return bucket.limit;
|
||||
return bucket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map /client/users/me JSON → { plan, quotas, message } for the dashboard.
|
||||
*/
|
||||
export function parseZedAuthenticatedUserUsage(userInfo) {
|
||||
const plan = userInfo?.plan || {};
|
||||
const planId =
|
||||
plan.plan_v3 || plan.plan_v2 || plan.plan || userInfo?.plan_v3 || null;
|
||||
const resetAt =
|
||||
parseResetTime(plan.subscription_period?.ended_at) ||
|
||||
parseResetTime(plan.subscriptionPeriod?.endedAt) ||
|
||||
null;
|
||||
|
||||
const quotas = {};
|
||||
const usage = plan.usage || {};
|
||||
|
||||
const editPredictions = usage.edit_predictions || usage.editPredictions;
|
||||
if (editPredictions) {
|
||||
quotas["Edit Predictions"] = makeZedQuotaRow(
|
||||
"Edit Predictions",
|
||||
editPredictions.used,
|
||||
editPredictions.limit,
|
||||
resetAt,
|
||||
);
|
||||
}
|
||||
|
||||
const modelRequests = usage.model_requests || usage.modelRequests;
|
||||
if (modelRequests) {
|
||||
const limitRaw =
|
||||
modelRequests.limit != null
|
||||
? modelRequests.limit
|
||||
: usageBucketLimit(modelRequests)?.limit;
|
||||
const limitInfo = parseZedUsageLimit(limitRaw);
|
||||
// Token-billed plans report model_requests.limit=0 — not a request quota.
|
||||
if (limitInfo.unlimited || limitInfo.total > 0) {
|
||||
quotas["Hosted Model Requests"] = makeZedQuotaRow(
|
||||
"Hosted Model Requests",
|
||||
modelRequests.used,
|
||||
limitRaw,
|
||||
resetAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const tokenBillingNote =
|
||||
modelRequests &&
|
||||
isZedTokenBillingModelRequestsLimit(
|
||||
modelRequests.limit ?? usageBucketLimit(modelRequests)?.limit,
|
||||
)
|
||||
? "Hosted AI models are billed per token (not request count). Edit Predictions are tracked below. Token spend is on dashboard.zed.dev."
|
||||
: null;
|
||||
|
||||
let planLabel = formatZedPlanLabel(planId);
|
||||
if (plan.trial_started_at || plan.trialStartedAt) {
|
||||
if (!/trial/i.test(planLabel)) planLabel = `${planLabel} (Trial active)`;
|
||||
}
|
||||
|
||||
let message = tokenBillingNote;
|
||||
if (plan.has_overdue_invoices || plan.hasOverdueInvoices) {
|
||||
message = "This Zed account has overdue invoices. Usage may be blocked until billing is resolved.";
|
||||
}
|
||||
|
||||
return {
|
||||
plan: planLabel,
|
||||
quotas,
|
||||
message,
|
||||
hasOverdueInvoices: !!(plan.has_overdue_invoices || plan.hasOverdueInvoices),
|
||||
trialStarted: !!(plan.trial_started_at || plan.trialStartedAt),
|
||||
planId: planId || null,
|
||||
resetAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|null|undefined} accessToken
|
||||
* @param {object|null|undefined} providerSpecificData
|
||||
* @param {object|null|undefined} proxyOptions
|
||||
*/
|
||||
export async function getZedUsage(
|
||||
accessToken = null,
|
||||
providerSpecificData = {},
|
||||
proxyOptions = null,
|
||||
) {
|
||||
const psd = providerSpecificData || {};
|
||||
const userId = psd.userId;
|
||||
|
||||
if (!accessToken || typeof accessToken !== "string" || !accessToken.trim()) {
|
||||
return { message: "Zed access token not available. Re-connect Zed to view quota." };
|
||||
}
|
||||
if (!userId) {
|
||||
return { message: "Zed credential is missing user id. Re-connect Zed to view quota." };
|
||||
}
|
||||
|
||||
const credentials = {
|
||||
accessToken: accessToken.trim(),
|
||||
providerSpecificData: psd,
|
||||
};
|
||||
|
||||
try {
|
||||
const userInfo = await fetchZedAuthenticatedUser(credentials, { proxyOptions });
|
||||
return parseZedAuthenticatedUserUsage(userInfo);
|
||||
} catch (error) {
|
||||
const status = error?.status;
|
||||
if (status === 401 || status === 403) {
|
||||
return {
|
||||
message: "Zed authentication failed. Sign in again from the dashboard or Zed editor.",
|
||||
};
|
||||
}
|
||||
return { message: `Zed error: ${error.message || "Failed to fetch quota"}` };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user