Merge origin/master (v0.5.91) into gitea/new_feature

Resolve conflicts:
- streamingHandler.js: adopt upstreamResponseHeaders while keeping 0-token detail row avoidance
- capabilities.js: preserve user-asserted caps and globalThis slots without local caching of catalogSource
- AddCustomModelModal.js & providers/[id]/page.js: wire STT transport marker with custom model edits/assertions
- models/custom/route.js & aliasRepo.js: persist custom model transport and invalidate user caps
- usageRepo.js: key byApiKey live stats by full API key and keep tail in maskApiKey
- UsageStats.js: lazy load charts dynamically
This commit is contained in:
2026-09-28 21:17:33 +07:00
123 changed files with 5882 additions and 411 deletions

View File

@@ -1,6 +1,12 @@
import { buildClineHeaders } from "../shared/clineAuth.js";
const CLINEPASS_MODELS_ENDPOINT = "https://api.cline.bot/api/v1/models";
// Cline's free tier is published here, not in /api/v1/models: the catalog
// endpoint carries no `cline-free/*` ids at all. Cline's own SDK calls this
// feed unauthenticated (sdk/packages/core/src/services/llms/cline-recommended-models.ts),
// so no Authorization header is sent — adding one would only make the request
// fail on a header the endpoint ignores.
const CLINE_RECOMMENDED_MODELS_ENDPOINT = "https://api.cline.bot/api/v1/ai/cline/recommended-models";
const FETCH_TIMEOUT_MS = 5000;
/**
@@ -72,6 +78,40 @@ export async function resolveClinepassModels(credentials) {
return models.length ? { models } : null;
}
/**
* Fetch Cline's recommended-models feed and return only its `free[]` tier.
* Returns null on any failure — the free tier is additive, so a dead feed must
* never take the /api/v1/models catalog down with it.
* @param {{accessToken?: string, apiKey?: string}} credentials
* @returns {Promise<{id: string, name: string}[] | null>}
*/
async function fetchClineFreeTierModels() {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const response = await fetch(CLINE_RECOMMENDED_MODELS_ENDPOINT, {
method: "GET",
headers: { Accept: "application/json" },
signal: controller.signal,
});
if (!response.ok) return null;
const json = await response.json();
const free = Array.isArray(json?.free) ? json.free : [];
if (!free.length) return null;
return free
.filter((m) => typeof m?.id === "string" && m.id.trim() !== "")
.map((m) => ({ id: m.id, name: m.name || m.id }));
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
/**
* Fetch Cline live model catalog from Cline's /models endpoint.
* Unlike resolveClinepassModels, this returns ALL models (including
@@ -91,5 +131,15 @@ export async function resolveClineModels(credentials) {
name: m.name || m.id,
}));
return models.length ? { models } : null;
// Free tier: /api/v1/models lists no `cline-free/*` ids, so merge the feed's
// free[] in. First writer wins on a shared id, keeping the catalog's entry
// for anything the two sources agree on.
const freeTier = await fetchClineFreeTierModels();
const byId = new Map(models.map((m) => [m.id, m]));
for (const m of freeTier || []) {
if (!byId.has(m.id)) byId.set(m.id, m);
}
const merged = Array.from(byId.values());
return merged.length ? { models: merged } : null;
}

View File

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

View File

@@ -3,7 +3,7 @@
*/
import { proxyAwareFetch } from "../../utils/proxyFetch.js";
import { ANTHROPIC_API_VERSION } from "../../providers/shared.js";
import { ANTHROPIC_API_VERSION, CLAUDE_CLI_VERSION } from "../../providers/shared.js";
import { U, parseResetTime } from "./shared.js";
// Claude API config (urls from registry, apiVersion is header logic kept here)
@@ -11,7 +11,11 @@ const CLAUDE_CONFIG = {
oauthUsageUrl: U("claude").oauthUrl,
usageUrl: U("claude").orgUrl,
settingsUrl: U("claude").settingsUrl,
profileUrl: U("claude").profileUrl,
resetUrl: U("claude").resetUrl,
apiVersion: ANTHROPIC_API_VERSION,
// Reset grants are gated by surface: only "(external, cli)" UA is eligible
userAgent: `claude-cli/${CLAUDE_CLI_VERSION} (external, cli)`,
};
// OAuth usage endpoint rate-limits (429); cool down per-token to stop hammering it.
@@ -64,12 +68,14 @@ async function fetchClaudeUsageRaw(accessToken, proxyOptions = null) {
}
// Primary: OAuth usage endpoint (Claude Code consumer OAuth tokens)
const oauthResponse = await proxyAwareFetch(CLAUDE_CONFIG.oauthUsageUrl, {
// cedar_ember=1 adds the "limit reset" grant block (same flag Claude Code sends)
const oauthResponse = await proxyAwareFetch(`${CLAUDE_CONFIG.oauthUsageUrl}?cedar_ember=1`, {
method: "GET",
headers: {
"Authorization": `Bearer ${accessToken}`,
"anthropic-beta": "oauth-2025-04-20",
"anthropic-version": CLAUDE_CONFIG.apiVersion,
"User-Agent": CLAUDE_CONFIG.userAgent,
},
}, proxyOptions);
@@ -129,6 +135,7 @@ async function fetchClaudeUsageRaw(accessToken, proxyOptions = null) {
return {
plan: "Claude Code",
extraUsage: data.extra_usage ?? null,
resetCredits: parseClaudeResetGrants(data.cedar_ember),
quotas,
};
}
@@ -146,6 +153,70 @@ async function fetchClaudeUsageRaw(accessToken, proxyOptions = null) {
}
}
// Free "limit reset" grants (Anthropic program id "cedar_ember").
// Shape: { eligible, next_grant_id, grants: [{ id, resets_left, ends_at, paused, clears }] }
export function parseClaudeResetGrants(block) {
if (!block?.eligible || !Array.isArray(block.grants)) return null;
const grants = block.grants.filter((g) => g?.id && !g.paused && Number(g.resets_left) > 0);
const next = grants.find((g) => g.id === block.next_grant_id) || grants[0] || null;
return {
availableCount: grants.reduce((sum, g) => sum + Number(g.resets_left), 0),
nextGrantId: next?.id || null,
expiresAt: next?.ends_at || null,
clears: next?.clears || [],
cooldownUntil: block.cooldown_until || null,
weeklyResetsAt: block.weekly_resets_at || null,
grants: block.grants.filter((g) => g?.id).map((g) => ({
id: g.id,
label: g.label || "",
resetsLeft: Number(g.resets_left) || 0,
resetsTotal: Number(g.resets_total) || 0,
startsAt: g.starts_at || null,
endsAt: g.ends_at || null,
clears: Array.isArray(g.clears) ? g.clears : [],
paused: g.paused === true,
usableNow: g.usable_now === true,
useRequiresLimit: g.use_requires_limit !== false,
})),
};
}
// Spend one reset grant: refills the limits listed in grant.clears. Irreversible.
export async function consumeClaudeResetGrant(accessToken, grantId, proxyOptions = null) {
if (!accessToken) throw new Error("No Claude access token available. Please re-authorize the connection.");
if (!/^[a-z0-9_-]{1,40}$/.test(grantId || "")) throw new Error("Invalid reset grant id.");
const headers = {
"Authorization": `Bearer ${accessToken}`,
"anthropic-beta": "oauth-2025-04-20",
"anthropic-version": CLAUDE_CONFIG.apiVersion,
"User-Agent": CLAUDE_CONFIG.userAgent,
"Content-Type": "application/json",
};
const profileRes = await proxyAwareFetch(CLAUDE_CONFIG.profileUrl, { method: "GET", headers }, proxyOptions);
const profile = await profileRes.json().catch(() => null);
const orgId = profile?.organization?.uuid;
if (!profileRes.ok || !orgId) throw new Error(`Cannot resolve Claude organization (${profileRes.status}).`);
const res = await proxyAwareFetch(CLAUDE_CONFIG.resetUrl.replace("{org_id}", orgId), {
method: "POST",
headers,
body: JSON.stringify({ program: "cedar_ember", grant_id: grantId, request_id: crypto.randomUUID() }),
}, proxyOptions);
const data = await res.json().catch(() => null);
usageCache.delete(accessToken); // next read must show refilled limits
return {
ok: res.ok && data?.result === "reset",
status: res.status,
result: data?.result || null,
reason: data?.reason || null,
resetsLeft: data?.resets_left ?? null,
message: data?.error?.message || null,
};
}
/**
* Legacy Claude usage for API key / org admin users
*/