This commit is contained in:
2026-07-06 00:01:34 +07:00
parent 2729408ef3
commit e7470e955e
108 changed files with 4131 additions and 529 deletions

View File

@@ -0,0 +1,63 @@
import { buildClineHeaders } from "../shared/clineAuth.js";
const CLINEPASS_MODELS_ENDPOINT = "https://api.cline.bot/api/v1/models";
const FETCH_TIMEOUT_MS = 5000;
/**
* Build request headers for the ClinePass /models endpoint (Cline's upstream API).
* - API keys are sent as plain Bearer tokens.
* - OAuth access tokens must carry the WorkOS `workos:` prefix (handled by buildClineHeaders).
*/
function buildModelListHeaders(token, isApiKey) {
if (isApiKey) {
return {
Accept: "application/json",
Authorization: `Bearer ${token}`,
};
}
return buildClineHeaders(token, { Accept: "application/json" });
}
/**
* Fetch ClinePass live model catalog from Cline's /models endpoint.
*
* @param {object} credentials - Connection credentials ({ accessToken, apiKey })
* @returns {Promise<{ models: { id: string, name: string }[] } | null>}
*/
export async function resolveClinepassModels(credentials) {
const isApiKey = Boolean(credentials?.apiKey);
const token = isApiKey ? credentials.apiKey : credentials?.accessToken;
if (!token) return null;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const headers = buildModelListHeaders(token, isApiKey);
const response = await fetch(CLINEPASS_MODELS_ENDPOINT, {
method: "GET",
headers,
signal: controller.signal,
});
if (!response.ok) return null;
const json = await response.json();
const rawList = Array.isArray(json) ? json : json?.data;
if (!Array.isArray(rawList)) return null;
const models = rawList
.filter((m) => typeof m?.id === "string" && m.id.startsWith("cline-pass/"))
.map((m) => ({
id: m.id,
name: m.name || m.id,
}));
return models.length ? { models } : null;
} catch {
return null;
} finally {
clearTimeout(timer);
}
}

View File

@@ -0,0 +1,176 @@
import { createHash } from "crypto";
import { proxyAwareFetch } from "../utils/proxyFetch.js";
export const KIMCHI_API = "https://llm.kimchi.dev";
export const KIMCHI_USER_AGENT = "kimchi/0.1.40";
const FETCH_TIMEOUT_MS = 20_000;
const CACHE_TTL_MS = 5 * 60 * 1000;
const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);
/** @type {Map<string, { expiresAt: number, models: object[], rawModels: object[] }>} */
const catalogCache = new Map();
/** @type {Map<string, object>} */
const metadataByModelId = new Map();
function normalizeKimchiEndpoint(endpoint) {
const raw = typeof endpoint === "string" ? endpoint.trim() : "";
return (raw || KIMCHI_API).replace(/\/+$/, "");
}
export function buildKimchiModelsUrl(endpoint) {
return `${normalizeKimchiEndpoint(endpoint)}/v1/models/metadata?include_in_cli=true`;
}
function readToken(credentials) {
return (
credentials?.accessToken
|| credentials?.apiKey
|| credentials?.providerSpecificData?.apiKey
|| null
);
}
function cacheKey(credentials, endpoint) {
const psd = credentials?.providerSpecificData || {};
const seed = psd.userId || psd.username || credentials?.refreshToken || readToken(credentials) || "anonymous";
return createHash("sha256")
.update(`kimchi:${normalizeKimchiEndpoint(endpoint)}:${seed}`)
.digest("hex");
}
function toModelKind(inputModalities) {
return Array.isArray(inputModalities) && inputModalities.includes("image")
? "imageToText"
: "llm";
}
export function normalizeKimchiModel(item) {
if (!item || typeof item !== "object") return null;
const id = item.slug || item.id || item.model || item.name;
if (typeof id !== "string" || id.trim() === "") return null;
const inputModalities = Array.isArray(item.input_modalities)
? item.input_modalities.filter((value) => value === "text" || value === "image")
: [];
const limits = item.limits && typeof item.limits === "object" ? item.limits : {};
const contextLength = Number(limits.context_window || item.contextLength || item.context_length) || undefined;
const maxOutputTokens = Number(limits.max_output_tokens || item.maxOutputTokens || item.max_output_tokens) || undefined;
const upstreamProvider = typeof item.provider === "string" ? item.provider : "";
const reasoning = item.reasoning === true;
const kind = toModelKind(inputModalities);
const model = {
...item,
id: id.trim(),
name: String(item.display_name || item.displayName || item.name || id).trim(),
provider: upstreamProvider,
upstreamProvider,
reasoning,
inputModalities,
kind,
type: kind,
capabilities: {
vision: inputModalities.includes("image"),
reasoning,
...(contextLength ? { contextWindow: contextLength } : {}),
...(maxOutputTokens ? { maxOutput: maxOutputTokens } : {}),
...(upstreamProvider ? { upstreamProvider } : {}),
},
...(contextLength ? { contextLength } : {}),
...(maxOutputTokens ? { maxOutputTokens } : {}),
};
if (upstreamProvider === "anthropic") {
model.compat = { supportsReasoningEffort: false, cacheControlFormat: "anthropic" };
}
return model;
}
function rememberModels(models) {
for (const model of models || []) {
if (!model?.id) continue;
metadataByModelId.set(model.id, model);
metadataByModelId.set(model.id.toLowerCase(), model);
}
}
export function getCachedKimchiModelMetadata(modelId) {
if (typeof modelId !== "string" || modelId.trim() === "") return null;
const raw = modelId.includes("/") ? modelId.split("/").pop() : modelId;
return metadataByModelId.get(raw) || metadataByModelId.get(raw.toLowerCase()) || null;
}
async function fetchKimchiCatalogRaw(token, endpoint, options = {}) {
const url = buildKimchiModelsUrl(endpoint);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(new Error("Kimchi models fetch timeout")), FETCH_TIMEOUT_MS);
const signal = options.signal
? AbortSignal.any([options.signal, controller.signal])
: controller.signal;
try {
const response = await proxyAwareFetch(url, {
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": `Bearer ${token}`,
"User-Agent": KIMCHI_USER_AGENT,
},
cache: "no-store",
signal,
}, options.proxyOptions || null);
if (!response.ok) {
const error = new Error(`Kimchi models ${response.status}: ${response.statusText}`);
error.status = response.status;
error.retryable = RETRYABLE_STATUSES.has(response.status);
throw error;
}
const data = await response.json();
return Array.isArray(data?.models) ? data.models : [];
} finally {
clearTimeout(timeout);
}
}
export async function resolveKimchiModels(credentials, options = {}) {
const token = readToken(credentials);
if (!token) return null;
const endpoint = credentials?.providerSpecificData?.kimchiEndpoint || options.endpoint || KIMCHI_API;
const key = cacheKey(credentials, endpoint);
const now = Date.now();
if (!options.forceRefresh) {
const cached = catalogCache.get(key);
if (cached && cached.expiresAt > now) return cached;
}
let rawModels;
try {
rawModels = await fetchKimchiCatalogRaw(token, endpoint, options);
} catch (error) {
options.log?.warn?.("KIMCHI_MODELS", error.message);
return null;
}
const models = rawModels.map(normalizeKimchiModel).filter(Boolean);
if (models.length === 0) return null;
rememberModels(models);
const entry = {
expiresAt: Date.now() + CACHE_TTL_MS,
models,
rawModels,
};
catalogCache.set(key, entry);
return entry;
}
export function clearKimchiCatalog() {
catalogCache.clear();
metadataByModelId.clear();
}

View File

@@ -5,9 +5,9 @@
import { getGitHubUsage } from "./usage/github.js";
import { getGeminiUsage, getAntigravityUsage } from "./usage/google.js";
import { getClaudeUsage } from "./usage/claude.js";
import { getCodexUsage, consumeCodexRateLimitResetCredit } from "./usage/codex.js";
import { getCodexUsage, consumeCodexRateLimitResetCredit, getCodexRateLimitResetCredits } from "./usage/codex.js";
export { consumeCodexRateLimitResetCredit };
export { consumeCodexRateLimitResetCredit, getCodexRateLimitResetCredits };
import { getKiroUsage } from "./usage/kiro.js";
import { getMiniMaxUsage } from "./usage/minimax.js";
import { getCodeBuddyCnUsage } from "./usage/codebuddy-cn.js";

View File

@@ -109,15 +109,22 @@ export async function getCodeBuddyCnUsage(accessToken, apiKey, providerSpecificD
total: num(acc.CycleCapacitySizePrecise, acc.CycleCapacitySize),
resetAt: parseResetTime(acc.CycleEndTime),
unlimited: false,
// Recurring allowance: the CycleEndTime is the next refresh, not the
// final expiry. The UI must show "Resets in", not "Expires in".
recurring: true,
};
});
// Bonus packs: use the lifetime Capacity balance; resetAt is the expiry.
// These are one-shot credits (CycleEndTime == DeductionEndTime), so they
// never replenish — mark recurring:false so the UI shows "Expires in"
// instead of implying a monthly refill.
bonuses.forEach((acc, i) => {
quotas[`Bonus Pack ${i + 1}`] = {
used: num(acc.CapacityUsedPrecise, acc.CapacityUsed),
total: num(acc.CapacitySizePrecise, acc.CapacitySize),
resetAt: parseResetTime(acc.CycleEndTime),
unlimited: false,
recurring: false,
};
});

View File

@@ -8,9 +8,23 @@ import { U, parseResetTime, toFiniteNumber } from "./shared.js";
// Codex (OpenAI) API config
const CODEX_CONFIG = {
usageUrl: U("codex").url,
resetCreditsUrl: U("codex").resetCreditsUrl,
resetCreditsConsumeUrl: U("codex").resetCreditsConsumeUrl,
};
function toIsoDate(value) {
if (!value) return null;
const date = value instanceof Date
? value
: new Date(typeof value === "number" && value < 1e12 ? value * 1000 : value);
const time = date.getTime();
return Number.isFinite(time) ? date.toISOString() : null;
}
function getCodexAccountId(providerSpecificData) {
return providerSpecificData?.workspaceId || providerSpecificData?.accountId || providerSpecificData?.chatgptAccountId || null;
}
function getCodexRateLimitBody(snapshot) {
if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) return null;
return snapshot.rate_limit && typeof snapshot.rate_limit === "object"
@@ -101,6 +115,48 @@ export async function getCodexUsage(accessToken, proxyOptions = null) {
}
}
export async function getCodexRateLimitResetCredits(accessToken, proxyOptions = null, providerSpecificData = null) {
if (!accessToken) {
throw new Error("No Codex access token available. Please re-authorize the connection.");
}
const accountId = getCodexAccountId(providerSpecificData);
const headers = {
"Authorization": `Bearer ${accessToken}`,
"Accept": "application/json",
"OpenAI-Beta": "codex-1",
"originator": "codex_cli_rs",
};
if (accountId) headers["ChatGPT-Account-ID"] = accountId;
const response = await proxyAwareFetch(CODEX_CONFIG.resetCreditsUrl, {
method: "GET",
headers,
}, proxyOptions);
let data = null;
try {
data = await response.json();
} catch {
data = null;
}
if (!response.ok) {
const message = data?.message || data?.error || data?.detail || `Codex reset credits API unavailable (${response.status}).`;
throw new Error(message);
}
const credits = Array.isArray(data?.credits) ? data.credits : [];
return {
availableCount: Math.max(0, toFiniteNumber(data?.available_count ?? data?.availableCount, 0)),
credits: credits.map((credit) => ({
status: String(credit?.status || "unknown"),
grantedAt: toIsoDate(credit?.granted_at ?? credit?.grantedAt),
expiresAt: toIsoDate(credit?.expires_at ?? credit?.expiresAt),
})),
};
}
// Consume one Codex rate-limit reset credit (irreversible, spends 1 credit)
export async function consumeCodexRateLimitResetCredit(accessToken, redeemRequestId, proxyOptions = null) {
if (!accessToken) {