mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-18 07:58:27 +00:00
feat(identity): refresh pinned CLI versions from their release feeds (#15642)
Onda 2 (HouMinXi) validada num único board em `.claude/worktrees/batch-w2` sobre `origin/release/v3.8.52` (`e05f1bd78bac`), 26 PRs, superfícies protegidas 0. Evidência: `typecheck:core` limpo. changelog-integrity, complexity (2973/3218) e cognitive-complexity (1356/1437) dentro do baseline. Testes focados: 235 passaram. Os 5 vermelhos não são deste diff: o `.test.tsx` do cloudflared passa no Vitest (1/1); o intervalo do Codex usage passou 3/3 isolado (flake sob carga); o banner no-auth cai no mesmo `useContext` nulo de `tests/unit/request-log-detail-stream.test.ts`, que já existe no tip, por causa do React duplicado em `node_modules/node_modules` desta worktree. O file-size do board ainda vê o teto antigo de `gateways.ts` (já corrigido em #15679) e o crescimento próprio desta onda em RoutingTab, auth, responseSanitizer, search, proxyFetch e stream. Esse rebaseline entra no follow-up, fora do squash. ⚠️ base-red inherited: #15306 (timeouts de suíte no tip, não neste diff). Obrigado, @HouMinXi.
This commit is contained in:
@@ -12,9 +12,23 @@ const DEFAULT_CODEX_USER_AGENT_PLATFORM = "Windows 10.0.26200";
|
||||
const DEFAULT_CODEX_USER_AGENT_ARCH = "x64";
|
||||
const CODEX_VERSION_OVERRIDE_ENV = "CODEX_CLIENT_VERSION";
|
||||
const CODEX_USER_AGENT_OVERRIDE_ENV = "CODEX_USER_AGENT";
|
||||
const CODEX_RELEASE_URL = "https://api.github.com/repos/openai/codex/releases/latest";
|
||||
export const CODEX_VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
export const CODEX_VERSION_FETCH_TIMEOUT_MS = 20_000;
|
||||
const SAFE_HEADER_TOKEN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/;
|
||||
const SAFE_HEADER_VALUE_PATTERN = /^[\x20-\x7E]{1,200}$/;
|
||||
const SAFE_CODEX_SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;
|
||||
const CODEX_DOTTED_TRIPLE_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
|
||||
|
||||
type CodexVersionCache = {
|
||||
fetchedAt: number;
|
||||
version: string;
|
||||
};
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
let versionCache: CodexVersionCache | null = null;
|
||||
let versionInFlight: Promise<string> | null = null;
|
||||
|
||||
function getSafeEnvValue(name: string, pattern: RegExp): string | null {
|
||||
const raw = process.env[name];
|
||||
@@ -26,11 +40,97 @@ function getSafeEnvValue(name: string, pattern: RegExp): string | null {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function parseCodexReleaseTag(tagName: unknown): string | null {
|
||||
if (typeof tagName !== "string") return null;
|
||||
const stripped = tagName.trim().replace(/^rust-v/, "");
|
||||
const match = CODEX_DOTTED_TRIPLE_PATTERN.exec(stripped);
|
||||
return match ? match[0] : null;
|
||||
}
|
||||
|
||||
function compareDottedTriple(left: string, right: string): number {
|
||||
const leftParts = left.split(".").map((part) => Number.parseInt(part, 10));
|
||||
const rightParts = right.split(".").map((part) => Number.parseInt(part, 10));
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (leftParts[i] !== rightParts[i]) return leftParts[i] - rightParts[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function pickCodexVersionAtLeastPin(candidate: string | null): string {
|
||||
if (candidate && compareDottedTriple(candidate, DEFAULT_CODEX_CLIENT_VERSION) > 0) {
|
||||
return candidate;
|
||||
}
|
||||
return DEFAULT_CODEX_CLIENT_VERSION;
|
||||
}
|
||||
|
||||
async function fetchCodexReleaseTag(fetchImpl: FetchLike): Promise<string | null> {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), CODEX_VERSION_FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetchImpl(CODEX_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "OmniRoute-CodexVersion/1.0",
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const payload = (await response.json()) as { tag_name?: unknown };
|
||||
return parseCodexReleaseTag(payload?.tag_name);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the advertised Codex CLI version from the latest GitHub release.
|
||||
* A fetched dotted triple newer than the pin replaces it; any failure, a
|
||||
* malformed tag, or an older release keeps the pin. Cached for six hours.
|
||||
*/
|
||||
export function resolveCodexClientVersion(fetchImpl: FetchLike = fetch): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (versionCache && now - versionCache.fetchedAt < CODEX_VERSION_CACHE_TTL_MS) {
|
||||
return Promise.resolve(pickCodexVersionAtLeastPin(versionCache.version));
|
||||
}
|
||||
if (versionInFlight) return versionInFlight;
|
||||
|
||||
versionInFlight = (async () => {
|
||||
const fetched = await fetchCodexReleaseTag(fetchImpl);
|
||||
const version = pickCodexVersionAtLeastPin(fetched ?? versionCache?.version ?? null);
|
||||
if (fetched) {
|
||||
versionCache = { fetchedAt: Date.now(), version };
|
||||
}
|
||||
return version;
|
||||
})();
|
||||
|
||||
return versionInFlight.finally(() => {
|
||||
versionInFlight = null;
|
||||
});
|
||||
}
|
||||
|
||||
export function getCachedCodexClientVersion(): string {
|
||||
return pickCodexVersionAtLeastPin(versionCache?.version ?? null);
|
||||
}
|
||||
|
||||
export function seedCodexClientVersionCache(version: string, fetchedAt = Date.now()): void {
|
||||
if (!CODEX_DOTTED_TRIPLE_PATTERN.test(version)) {
|
||||
throw new TypeError(`Invalid Codex client version: ${version}`);
|
||||
}
|
||||
versionCache = { fetchedAt, version };
|
||||
}
|
||||
|
||||
export function clearCodexClientVersionCache(): void {
|
||||
versionCache = null;
|
||||
versionInFlight = null;
|
||||
}
|
||||
|
||||
export function getCodexClientVersion(): string {
|
||||
return (
|
||||
getSafeEnvValue(CODEX_VERSION_OVERRIDE_ENV, SAFE_HEADER_TOKEN_PATTERN) ||
|
||||
DEFAULT_CODEX_CLIENT_VERSION
|
||||
);
|
||||
const override = getSafeEnvValue(CODEX_VERSION_OVERRIDE_ENV, SAFE_HEADER_TOKEN_PATTERN);
|
||||
if (override) return override;
|
||||
if (!process.env.NODE_TEST_CONTEXT && !versionCache && !versionInFlight) void resolveCodexClientVersion();
|
||||
return getCachedCodexClientVersion();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,11 +6,22 @@ import type { AntigravityClientProfile } from "@/shared/constants/antigravityCli
|
||||
// VS Code Copilot Chat extension. The CLI's `copilot-developer-cli` integration
|
||||
// id is the catalog-unlock lever: it exposes the full entitled model set
|
||||
// (gemini-3.x, gpt-5.4-nano, the full opus reasoning range) where `vscode-chat`
|
||||
// returns a narrower list. Version strings track the live-captured CLI 1.0.88.
|
||||
// returns a narrower list. Version strings start at the live-captured CLI
|
||||
// 1.0.88 and follow a newer `@github/copilot` publish when the registry
|
||||
// answers. Copilot gates models on that version and 400s a pin that is behind.
|
||||
export const GITHUB_COPILOT_API_VERSION = "2026-08-01";
|
||||
export const GITHUB_COPILOT_CLI_VERSION = "1.0.88";
|
||||
const GITHUB_COPILOT_VERSION_OVERRIDE_ENV = "GITHUB_COPILOT_CLI_VERSION";
|
||||
const SAFE_COPILOT_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/;
|
||||
const COPILOT_DOTTED_TRIPLE_PATTERN = /^\d+\.\d+\.\d+$/;
|
||||
const NPM_GITHUB_COPILOT_LATEST_URL = "https://registry.npmjs.org/@github/copilot/latest";
|
||||
export const GITHUB_COPILOT_VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
export const GITHUB_COPILOT_VERSION_FETCH_TIMEOUT_MS = 20_000;
|
||||
|
||||
type CopilotFetchLike = typeof fetch;
|
||||
|
||||
let copilotVersionCache: { fetchedAt: number; version: string } | null = null;
|
||||
let copilotVersionInFlight: Promise<string> | null = null;
|
||||
|
||||
function getSafeCopilotEnvValue(name: string, pattern: RegExp): string | null {
|
||||
const raw = typeof process === "undefined" ? undefined : process.env?.[name];
|
||||
@@ -22,12 +33,96 @@ function getSafeCopilotEnvValue(name: string, pattern: RegExp): string | null {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function parseCopilotDottedTriple(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return COPILOT_DOTTED_TRIPLE_PATTERN.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function compareCopilotDottedTriple(left: string, right: string): number {
|
||||
const leftParts = left.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
const rightParts = right.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (leftParts[i] !== rightParts[i]) return leftParts[i] - rightParts[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** A fetched version replaces the pin only when it is strictly newer. */
|
||||
function pickCopilotVersionAtLeastPin(candidate: string | null): string {
|
||||
if (candidate && compareCopilotDottedTriple(candidate, GITHUB_COPILOT_CLI_VERSION) > 0) {
|
||||
return candidate;
|
||||
}
|
||||
return GITHUB_COPILOT_CLI_VERSION;
|
||||
}
|
||||
|
||||
function readFreshCopilotVersionCache(now = Date.now()): string | null {
|
||||
if (!copilotVersionCache) return null;
|
||||
if (now - copilotVersionCache.fetchedAt >= GITHUB_COPILOT_VERSION_CACHE_TTL_MS) return null;
|
||||
return copilotVersionCache.version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the advertised Copilot CLI version from `@github/copilot` on npm.
|
||||
* A dotted triple newer than 1.0.88 replaces it; any failure, a non-triple,
|
||||
* or an older publish keeps the pin. Cached for six hours. The fetch aborts
|
||||
* at 20s — registry responses from this host regularly exceed a few seconds.
|
||||
*/
|
||||
export function resolveGitHubCopilotCliVersion(
|
||||
fetchImpl: CopilotFetchLike = fetch
|
||||
): Promise<string> {
|
||||
const now = Date.now();
|
||||
const fresh = readFreshCopilotVersionCache(now);
|
||||
if (fresh) return Promise.resolve(pickCopilotVersionAtLeastPin(fresh));
|
||||
if (copilotVersionInFlight) return copilotVersionInFlight;
|
||||
|
||||
copilotVersionInFlight = (async () => {
|
||||
let resolved: string | null = null;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), GITHUB_COPILOT_VERSION_FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetchImpl(NPM_GITHUB_COPILOT_LATEST_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "OmniRoute-CopilotVersion/1.0",
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
const payload = (await response.json()) as { version?: unknown };
|
||||
resolved = parseCopilotDottedTriple(payload?.version);
|
||||
}
|
||||
} catch {
|
||||
resolved = null;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
if (resolved && compareCopilotDottedTriple(resolved, GITHUB_COPILOT_CLI_VERSION) > 0) {
|
||||
copilotVersionCache = { fetchedAt: Date.now(), version: resolved };
|
||||
}
|
||||
return pickCopilotVersionAtLeastPin(resolved ?? readFreshCopilotVersionCache());
|
||||
})();
|
||||
|
||||
const current = copilotVersionInFlight;
|
||||
void current.finally(() => {
|
||||
if (copilotVersionInFlight === current) copilotVersionInFlight = null;
|
||||
});
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Test seam: drop the registry cache so the next resolve hits the network. */
|
||||
export function resetGitHubCopilotCliVersionCache(): void {
|
||||
copilotVersionCache = null;
|
||||
copilotVersionInFlight = null;
|
||||
}
|
||||
|
||||
/** Captured pin, overridable via GITHUB_COPILOT_CLI_VERSION (#12417). */
|
||||
export function getGitHubCopilotCliVersion(): string {
|
||||
return (
|
||||
getSafeCopilotEnvValue(GITHUB_COPILOT_VERSION_OVERRIDE_ENV, SAFE_COPILOT_VERSION_PATTERN) ||
|
||||
GITHUB_COPILOT_CLI_VERSION
|
||||
);
|
||||
const override = getSafeCopilotEnvValue(GITHUB_COPILOT_VERSION_OVERRIDE_ENV, SAFE_COPILOT_VERSION_PATTERN);
|
||||
if (override) return override;
|
||||
if (!process.env.NODE_TEST_CONTEXT && !readFreshCopilotVersionCache() && !copilotVersionInFlight) void resolveGitHubCopilotCliVersion();
|
||||
return pickCopilotVersionAtLeastPin(readFreshCopilotVersionCache());
|
||||
}
|
||||
|
||||
export const GITHUB_COPILOT_EDITOR_VERSION = `copilot/${GITHUB_COPILOT_CLI_VERSION}`;
|
||||
@@ -82,14 +177,199 @@ export const QWEN_STAINLESS_LANG = "js";
|
||||
|
||||
export const QODER_DEFAULT_USER_AGENT = "Qoder-Cli";
|
||||
|
||||
// CODEBUDDY_CN_USER_AGENT is the single source of truth for the CLI/CodeBuddy version
|
||||
// CODEBUDDY_CN_USER_AGENT is the captured pin for the CLI/CodeBuddy version
|
||||
// string. It MUST stay identical across OAuth (src/lib/oauth/constants/oauth.ts), chat
|
||||
// completions (open-sse/config/providers/registry/codebuddy-cn/index.ts) and usage/quota
|
||||
// (open-sse/services/usage/codebuddy-cn.ts) — a mismatched version string across a
|
||||
// (open-sse/services/usage/codebuddy-cn.ts) - a mismatched version string across a
|
||||
// single account's auth vs. chat calls is exactly the kind of internally-inconsistent
|
||||
// client fingerprint Tencent's WAF flags as anomalous (#12702).
|
||||
// client fingerprint Tencent's WAF flags as anomalous (#12702). Request paths read
|
||||
// getCodeBuddyCnUserAgent(), which may replace both numbers with a newer npm publish.
|
||||
export const CODEBUDDY_CN_USER_AGENT = "CLI/2.108.1 CodeBuddy/2.108.1";
|
||||
|
||||
const QWEN_DOTTED_TRIPLE_PATTERN = /^\d+\.\d+\.\d+$/;
|
||||
const NPM_QWEN_CODE_LATEST_URL = "https://registry.npmjs.org/@qwen-code/qwen-code/latest";
|
||||
const NPM_CODEBUDDY_LATEST_URL = "https://registry.npmjs.org/@tencent-ai/codebuddy-code/latest";
|
||||
export const QWEN_CLI_VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
export const QWEN_CLI_VERSION_FETCH_TIMEOUT_MS = 20_000;
|
||||
export const CODEBUDDY_CN_VERSION_CACHE_TTL_MS = QWEN_CLI_VERSION_CACHE_TTL_MS;
|
||||
export const CODEBUDDY_CN_VERSION_FETCH_TIMEOUT_MS = QWEN_CLI_VERSION_FETCH_TIMEOUT_MS;
|
||||
|
||||
type NpmFetchLike = typeof fetch;
|
||||
|
||||
type VersionCache = { fetchedAt: number; version: string };
|
||||
|
||||
let qwenVersionCache: VersionCache | null = null;
|
||||
let qwenVersionInFlight: Promise<string> | null = null;
|
||||
let codeBuddyVersionCache: VersionCache | null = null;
|
||||
let codeBuddyVersionInFlight: Promise<string> | null = null;
|
||||
|
||||
function parseDottedTriple(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return QWEN_DOTTED_TRIPLE_PATTERN.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function compareDottedTriple(left: string, right: string): number {
|
||||
const leftParts = left.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
const rightParts = right.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (leftParts[i] !== rightParts[i]) return leftParts[i] - rightParts[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function readFreshVersionCache(
|
||||
cache: VersionCache | null,
|
||||
ttlMs: number,
|
||||
now = Date.now()
|
||||
): string | null {
|
||||
if (!cache) return null;
|
||||
if (now - cache.fetchedAt >= ttlMs) return null;
|
||||
return cache.version;
|
||||
}
|
||||
|
||||
function shouldAutoRefreshCliVersion(): boolean {
|
||||
if (typeof process === "undefined") return false;
|
||||
return !process.env.NODE_TEST_CONTEXT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Warm one npm `latest` document. A dotted triple newer than `pin` is cached
|
||||
* for six hours; a rejected fetch, a non-2xx, a non-triple, or an older
|
||||
* publish leaves the pin in place. The fetch aborts at 20s.
|
||||
*/
|
||||
function refreshNpmDottedTriple(options: {
|
||||
url: string;
|
||||
pin: string;
|
||||
userAgent: string;
|
||||
timeoutMs: number;
|
||||
ttlMs: number;
|
||||
readCache: () => VersionCache | null;
|
||||
setCache: (next: VersionCache) => void;
|
||||
readInFlight: () => Promise<string> | null;
|
||||
setInFlight: (next: Promise<string> | null) => void;
|
||||
fetchImpl: NpmFetchLike;
|
||||
}): Promise<string> {
|
||||
const fresh = readFreshVersionCache(options.readCache(), options.ttlMs);
|
||||
if (fresh && compareDottedTriple(fresh, options.pin) > 0) return Promise.resolve(fresh);
|
||||
const existing = options.readInFlight();
|
||||
if (existing) return existing;
|
||||
|
||||
const current = (async () => {
|
||||
let resolved: string | null = null;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), options.timeoutMs);
|
||||
try {
|
||||
const response = await options.fetchImpl(options.url, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": options.userAgent,
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
const payload = (await response.json()) as { version?: unknown };
|
||||
resolved = parseDottedTriple(payload?.version);
|
||||
}
|
||||
} catch {
|
||||
resolved = null;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
if (resolved && compareDottedTriple(resolved, options.pin) > 0) {
|
||||
options.setCache({ fetchedAt: Date.now(), version: resolved });
|
||||
return resolved;
|
||||
}
|
||||
const stillFresh = readFreshVersionCache(options.readCache(), options.ttlMs);
|
||||
if (stillFresh && compareDottedTriple(stillFresh, options.pin) > 0) return stillFresh;
|
||||
return options.pin;
|
||||
})();
|
||||
|
||||
options.setInFlight(current);
|
||||
void current.finally(() => {
|
||||
if (options.readInFlight() === current) options.setInFlight(null);
|
||||
});
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Sync hot path. Cache if newer than the pin, else the pin. Never waits. */
|
||||
export function getQwenCliVersion(): string {
|
||||
if (shouldAutoRefreshCliVersion() && !qwenVersionInFlight) {
|
||||
const fresh = readFreshVersionCache(qwenVersionCache, QWEN_CLI_VERSION_CACHE_TTL_MS);
|
||||
if (!fresh || compareDottedTriple(fresh, QWEN_CLI_VERSION) <= 0) {
|
||||
void refreshQwenCliVersion();
|
||||
}
|
||||
}
|
||||
const fresh = readFreshVersionCache(qwenVersionCache, QWEN_CLI_VERSION_CACHE_TTL_MS);
|
||||
if (fresh && compareDottedTriple(fresh, QWEN_CLI_VERSION) > 0) return fresh;
|
||||
return QWEN_CLI_VERSION;
|
||||
}
|
||||
|
||||
export function refreshQwenCliVersion(fetchImpl: NpmFetchLike = fetch): Promise<string> {
|
||||
return refreshNpmDottedTriple({
|
||||
url: NPM_QWEN_CODE_LATEST_URL,
|
||||
pin: QWEN_CLI_VERSION,
|
||||
userAgent: "OmniRoute-QwenCodeVersion/1.0",
|
||||
timeoutMs: QWEN_CLI_VERSION_FETCH_TIMEOUT_MS,
|
||||
ttlMs: QWEN_CLI_VERSION_CACHE_TTL_MS,
|
||||
readCache: () => qwenVersionCache,
|
||||
setCache: (next) => {
|
||||
qwenVersionCache = next;
|
||||
},
|
||||
readInFlight: () => qwenVersionInFlight,
|
||||
setInFlight: (next) => {
|
||||
qwenVersionInFlight = next;
|
||||
},
|
||||
fetchImpl,
|
||||
});
|
||||
}
|
||||
|
||||
export function resetQwenCliVersionCache(): void {
|
||||
qwenVersionCache = null;
|
||||
qwenVersionInFlight = null;
|
||||
}
|
||||
|
||||
function formatCodeBuddyCnUserAgent(version: string): string {
|
||||
return `CLI/${version} CodeBuddy/${version}`;
|
||||
}
|
||||
|
||||
/** Sync hot path. Both numbers move together, or the captured pin stays. */
|
||||
export function getCodeBuddyCnUserAgent(): string {
|
||||
if (shouldAutoRefreshCliVersion() && !codeBuddyVersionInFlight) {
|
||||
const fresh = readFreshVersionCache(codeBuddyVersionCache, CODEBUDDY_CN_VERSION_CACHE_TTL_MS);
|
||||
if (!fresh) void refreshCodeBuddyCnUserAgent();
|
||||
}
|
||||
const fresh = readFreshVersionCache(codeBuddyVersionCache, CODEBUDDY_CN_VERSION_CACHE_TTL_MS);
|
||||
if (fresh) return formatCodeBuddyCnUserAgent(fresh);
|
||||
return CODEBUDDY_CN_USER_AGENT;
|
||||
}
|
||||
|
||||
export function refreshCodeBuddyCnUserAgent(fetchImpl: NpmFetchLike = fetch): Promise<string> {
|
||||
const pinVersion = CODEBUDDY_CN_USER_AGENT.match(/(\d+\.\d+\.\d+)/)?.[1] ?? "0.0.0";
|
||||
return refreshNpmDottedTriple({
|
||||
url: NPM_CODEBUDDY_LATEST_URL,
|
||||
pin: pinVersion,
|
||||
userAgent: "OmniRoute-CodeBuddyVersion/1.0",
|
||||
timeoutMs: CODEBUDDY_CN_VERSION_FETCH_TIMEOUT_MS,
|
||||
ttlMs: CODEBUDDY_CN_VERSION_CACHE_TTL_MS,
|
||||
readCache: () => codeBuddyVersionCache,
|
||||
setCache: (next) => {
|
||||
codeBuddyVersionCache = next;
|
||||
},
|
||||
readInFlight: () => codeBuddyVersionInFlight,
|
||||
setInFlight: (next) => {
|
||||
codeBuddyVersionInFlight = next;
|
||||
},
|
||||
fetchImpl,
|
||||
}).then((version) => formatCodeBuddyCnUserAgent(version));
|
||||
}
|
||||
|
||||
export function resetCodeBuddyCnVersionCache(): void {
|
||||
codeBuddyVersionCache = null;
|
||||
codeBuddyVersionInFlight = null;
|
||||
}
|
||||
|
||||
export const KIRO_SDK_USER_AGENT = "AWS-SDK-JS/3.0.0 kiro-ide/1.0.0";
|
||||
export const KIRO_AMZ_USER_AGENT = "aws-sdk-js/3.0.0 kiro-ide/1.0.0";
|
||||
export const KIRO_STREAMING_TARGET =
|
||||
@@ -174,7 +454,7 @@ export function normalizeStainlessArch(arch: string = getRuntimeArch()): string
|
||||
return arch ? `other:${arch}` : "unknown";
|
||||
}
|
||||
|
||||
export function getQwenCliUserAgent(version = QWEN_CLI_VERSION): string {
|
||||
export function getQwenCliUserAgent(version = getQwenCliVersion()): string {
|
||||
// Qoder's DashScope-compatible backend expects Qwen Code's runtime-derived wire identity.
|
||||
// Keep it runtime-derived so packaged deployments use their own platform/architecture.
|
||||
return `QwenCode/${version} (${getRuntimePlatform()}; ${getRuntimeArch()})`;
|
||||
|
||||
@@ -57,8 +57,133 @@ export function normalizeKimiDeviceId(value: unknown): string {
|
||||
].join("-");
|
||||
}
|
||||
|
||||
const KIMI_VERSION_OVERRIDE_ENV = "KIMI_CLI_VERSION";
|
||||
const DOTTED_TRIPLE_PATTERN = /^\d+\.\d+\.\d+$/;
|
||||
const NPM_KIMI_CODE_LATEST_URL = "https://registry.npmjs.org/@moonshot-ai/kimi-code/latest";
|
||||
export const KIMI_CODE_VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
export const KIMI_CODE_VERSION_FETCH_TIMEOUT_MS = 20_000;
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
let cachedVersion: string | null = null;
|
||||
let cachedAt = 0;
|
||||
let inFlight: Promise<string> | null = null;
|
||||
let fetchImpl: FetchLike = fetch;
|
||||
|
||||
function parseDottedTriple(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return DOTTED_TRIPLE_PATTERN.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function compareDottedTriple(a: string, b: string): number {
|
||||
const aParts = a.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
const bParts = b.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (aParts[i] !== bParts[i]) return aParts[i] - bParts[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function pickAtLeastPin(version: string | null): string {
|
||||
if (!version || compareDottedTriple(version, KIMI_CODE_CLI_VERSION) <= 0) {
|
||||
return KIMI_CODE_CLI_VERSION;
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
function readEnvOverride(): string | null {
|
||||
const raw = typeof process === "undefined" ? undefined : process.env?.[KIMI_VERSION_OVERRIDE_ENV];
|
||||
const normalized = sanitizeKimiHeaderValue(raw, "");
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
function readFreshCache(): string | null {
|
||||
if (!cachedVersion) return null;
|
||||
if (Date.now() - cachedAt >= KIMI_CODE_VERSION_CACHE_TTL_MS) return null;
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync hot path. Env override wins. Otherwise a cached registry version newer
|
||||
* than the pin, else the pin. Outside tests, a stale cache starts one
|
||||
* background refresh; this call itself never waits on the network.
|
||||
*/
|
||||
export function getKimiCodeCliVersion(): string {
|
||||
return sanitizeKimiHeaderValue(process.env.KIMI_CLI_VERSION, KIMI_CODE_CLI_VERSION);
|
||||
const override = readEnvOverride();
|
||||
if (override) return override;
|
||||
if (typeof process !== "undefined" && !process.env.NODE_TEST_CONTEXT && !readFreshCache() && !inFlight) {
|
||||
void refreshKimiCodeCliVersion();
|
||||
}
|
||||
return pickAtLeastPin(readFreshCache());
|
||||
}
|
||||
|
||||
/**
|
||||
* Warm the npm cache (20s timeout, 6h TTL, coalesced, never rejects).
|
||||
* A failure, or a publish that is not newer than the pin, leaves the pin
|
||||
* (or the previous fresh cache) in place.
|
||||
*/
|
||||
export function refreshKimiCodeCliVersion(): Promise<string> {
|
||||
const override = readEnvOverride();
|
||||
if (override) return Promise.resolve(override);
|
||||
|
||||
const fresh = readFreshCache();
|
||||
if (fresh) return Promise.resolve(pickAtLeastPin(fresh));
|
||||
|
||||
if (inFlight) return inFlight;
|
||||
|
||||
inFlight = (async () => {
|
||||
let resolved: string | null = null;
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), KIMI_CODE_VERSION_FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetchImpl(NPM_KIMI_CODE_LATEST_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "OmniRoute-KimiCodeVersion/1.0",
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
const payload = (await response.json()) as { version?: unknown };
|
||||
resolved = parseDottedTriple(payload?.version);
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
} catch {
|
||||
resolved = null;
|
||||
}
|
||||
|
||||
if (resolved && compareDottedTriple(resolved, KIMI_CODE_CLI_VERSION) > 0) {
|
||||
cachedVersion = resolved;
|
||||
cachedAt = Date.now();
|
||||
}
|
||||
return pickAtLeastPin(resolved ?? readFreshCache());
|
||||
})();
|
||||
|
||||
const current = inFlight;
|
||||
void current.finally(() => {
|
||||
if (inFlight === current) inFlight = null;
|
||||
});
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Test seam: drop the registry cache so the next refresh hits the network. */
|
||||
export function resetKimiCodeCliVersionCache(): void {
|
||||
cachedVersion = null;
|
||||
cachedAt = 0;
|
||||
inFlight = null;
|
||||
}
|
||||
|
||||
/** Test seam: replace the registry fetch. Production leaves the global fetch. */
|
||||
export function setKimiCodeCliVersionFetch(next: FetchLike): void {
|
||||
fetchImpl = next;
|
||||
}
|
||||
|
||||
export function resetKimiCodeCliVersionFetch(): void {
|
||||
fetchImpl = fetch;
|
||||
}
|
||||
|
||||
export function getKimiCodeCliUserAgent(): string {
|
||||
|
||||
@@ -1022,11 +1022,12 @@ export class CursorExecutor extends BaseExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
buildHeaders(credentials) {
|
||||
async buildHeaders(credentials) {
|
||||
const ghostMode = credentials.providerSpecificData?.ghostMode !== false;
|
||||
const cleanToken = stripCursorOAuthTokenPrefix(credentials.accessToken ?? "");
|
||||
const requestId = crypto.randomUUID();
|
||||
const traceParent = `00-${crypto.randomBytes(16).toString("hex")}-${crypto.randomBytes(8).toString("hex")}-01`;
|
||||
const clientVersion = formatCursorAgentClientVersion(await getCursorAgentCliVersion());
|
||||
|
||||
// Mirrors cursor-agent's actual headers for agent.v1.AgentService/Run.
|
||||
// Notably: no x-cursor-checksum, no machineId, no x-amzn-trace-id.
|
||||
@@ -1041,7 +1042,7 @@ export class CursorExecutor extends BaseExecutor {
|
||||
traceparent: traceParent,
|
||||
"user-agent": "connect-es/1.6.1",
|
||||
"x-cursor-client-type": "cli",
|
||||
"x-cursor-client-version": formatCursorAgentClientVersion(getCursorAgentCliVersion()),
|
||||
"x-cursor-client-version": clientVersion,
|
||||
"x-ghost-mode": ghostMode ? "true" : "false",
|
||||
"x-original-request-id": requestId,
|
||||
"x-request-id": requestId,
|
||||
@@ -1253,7 +1254,7 @@ export class CursorExecutor extends BaseExecutor {
|
||||
url = await resolveCursorAgentUrl(executionCredentials, signal);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
const headers = this.buildHeaders(executionCredentials);
|
||||
const headers = await this.buildHeaders(executionCredentials);
|
||||
return {
|
||||
response: new Response(
|
||||
JSON.stringify({
|
||||
@@ -1273,7 +1274,7 @@ export class CursorExecutor extends BaseExecutor {
|
||||
transformedBody: body,
|
||||
};
|
||||
}
|
||||
const headers = this.buildHeaders(executionCredentials);
|
||||
const headers = await this.buildHeaders(executionCredentials);
|
||||
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
|
||||
|
||||
const messages: ChatMessage[] = body.messages || [];
|
||||
|
||||
@@ -78,7 +78,7 @@ async function fetchCursorAgentUrls(
|
||||
"content-type": "application/proto",
|
||||
"user-agent": "connect-es/1.6.1",
|
||||
"x-cursor-client-type": "cli",
|
||||
"x-cursor-client-version": formatCursorAgentClientVersion(getCursorAgentCliVersion()),
|
||||
"x-cursor-client-version": formatCursorAgentClientVersion(await getCursorAgentCliVersion()),
|
||||
},
|
||||
body: Buffer.alloc(0),
|
||||
signal: signal ? mergeAbortSignals(signal, timeoutSignal) : timeoutSignal,
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
import { buildErrorBody } from "../utils/error.ts";
|
||||
import { hasUsefulStreamContent } from "../utils/streamReadiness.ts";
|
||||
import { resolveSuppressThinkClose, THINKING_MARKER_HEADER } from "../utils/thinkCloseMarker.ts";
|
||||
import { getZedClientVersion } from "./zedClientVersion.ts";
|
||||
|
||||
// Wire values for the `provider` field of POST /completions. These are NOT
|
||||
// display names: cloud.zed.dev matches them exactly, and an unrecognized value
|
||||
@@ -528,7 +529,7 @@ export class ZedHostedExecutor extends BaseExecutor {
|
||||
Accept: "application/x-ndjson, text/event-stream, */*",
|
||||
"User-Agent": `OmniRoute/zed-hosted`,
|
||||
"x-zed-version":
|
||||
(this.config as Record<string, unknown>)?.appVersion?.toString() || "0.200.0",
|
||||
(this.config as Record<string, unknown>)?.appVersion?.toString() || getZedClientVersion(),
|
||||
[ZED_HEADERS.clientSupportsStatus]: "true",
|
||||
[ZED_HEADERS.clientSupportsStreamEnded]: "true",
|
||||
},
|
||||
|
||||
115
open-sse/executors/zedClientVersion.ts
Normal file
115
open-sse/executors/zedClientVersion.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Advertised Zed editor version for the x-zed-version header.
|
||||
*
|
||||
* The captured pin is the floor. A newer dotted triple from the latest
|
||||
* zed-industries/zed GitHub release replaces it for 6 hours. The lookup is
|
||||
* fire-and-forget; a cold or failed fetch stays on the pin. An explicit
|
||||
* executor config.appVersion still wins over both.
|
||||
*/
|
||||
|
||||
export const ZED_CLIENT_VERSION = "0.200.0";
|
||||
|
||||
const ZED_RELEASE_URL = "https://api.github.com/repos/zed-industries/zed/releases/latest";
|
||||
export const ZED_VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
export const ZED_VERSION_FETCH_TIMEOUT_MS = 20_000;
|
||||
const DOTTED_TRIPLE_PATTERN = /^\d+\.\d+\.\d+$/;
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
let cachedVersion: string | null = null;
|
||||
let cachedAt = 0;
|
||||
let inFlight: Promise<string> | null = null;
|
||||
|
||||
function parseReleaseTag(tagName: unknown): string | null {
|
||||
if (typeof tagName !== "string") return null;
|
||||
const stripped = tagName.trim().replace(/^v/, "");
|
||||
return DOTTED_TRIPLE_PATTERN.test(stripped) ? stripped : null;
|
||||
}
|
||||
|
||||
function compareDottedTriple(left: string, right: string): number {
|
||||
const leftParts = left.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
const rightParts = right.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (leftParts[i] !== rightParts[i]) return leftParts[i] - rightParts[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function pickAtLeastPin(version: string | null): string {
|
||||
if (!version || compareDottedTriple(version, ZED_CLIENT_VERSION) <= 0) {
|
||||
return ZED_CLIENT_VERSION;
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
function readFreshCache(): string | null {
|
||||
if (!cachedVersion) return null;
|
||||
if (Date.now() - cachedAt >= ZED_VERSION_CACHE_TTL_MS) return null;
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync hot path. A cached release newer than the pin, else the pin.
|
||||
* Outside tests, a stale cache starts one background refresh; this call
|
||||
* itself never waits on the network.
|
||||
*/
|
||||
export function getZedClientVersion(): string {
|
||||
if (typeof process !== "undefined" && !process.env.NODE_TEST_CONTEXT && !readFreshCache() && !inFlight) {
|
||||
void refreshZedClientVersion();
|
||||
}
|
||||
return pickAtLeastPin(readFreshCache());
|
||||
}
|
||||
|
||||
/**
|
||||
* Warm the GitHub cache (20s timeout, 6h TTL, coalesced, never rejects).
|
||||
* Any failure — network, non-2xx, or a tag that is not a dotted triple —
|
||||
* leaves the pin (or the previous fresh cache) in place. A fetched version
|
||||
* is stored only when it is newer than the pin.
|
||||
*/
|
||||
export function refreshZedClientVersion(fetchImpl: FetchLike = fetch): Promise<string> {
|
||||
const fresh = readFreshCache();
|
||||
if (fresh) return Promise.resolve(pickAtLeastPin(fresh));
|
||||
if (inFlight) return inFlight;
|
||||
|
||||
inFlight = (async () => {
|
||||
let resolved: string | null = null;
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), ZED_VERSION_FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetchImpl(ZED_RELEASE_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "OmniRoute-ZedVersion/1.0",
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
const payload = (await response.json()) as { tag_name?: unknown };
|
||||
resolved = parseReleaseTag(payload?.tag_name);
|
||||
}
|
||||
} catch {
|
||||
resolved = null;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
if (resolved && compareDottedTriple(resolved, ZED_CLIENT_VERSION) > 0) {
|
||||
cachedVersion = resolved;
|
||||
cachedAt = Date.now();
|
||||
}
|
||||
return pickAtLeastPin(resolved ?? readFreshCache());
|
||||
})();
|
||||
|
||||
const current = inFlight;
|
||||
void current.finally(() => {
|
||||
if (inFlight === current) inFlight = null;
|
||||
});
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Test seam: drop the release cache so the next refresh hits the network. */
|
||||
export function resetZedClientVersionCache(): void {
|
||||
cachedVersion = null;
|
||||
cachedAt = 0;
|
||||
inFlight = null;
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
* Wire header: `x-cursor-client-version: cli-${id}` where `id` is a dated
|
||||
* build like `2026.07.08-0c04a8a` (not the IDE `3.x` semver).
|
||||
*
|
||||
* Resolution: CURSOR_AGENT_CLI_VERSION env → local install detect →
|
||||
* disk-cached installer scrape (stale-while-revalidate) → pin.
|
||||
* Resolution: CURSOR_AGENT_CLI_VERSION env, then local install detect,
|
||||
* then a disk-cached installer scrape (stale-while-revalidate), then the pin.
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -24,15 +24,14 @@ import { CURSOR_AGENT_CLI_VERSION } from "./cursorAgentCliVersionPin.ts";
|
||||
export { CURSOR_AGENT_CLI_VERSION };
|
||||
|
||||
const VERSION_ID_RE = /^\d{4}\.\d{2}\.\d{2}-[0-9a-f]+$/;
|
||||
const CACHE_TTL_MS = 60 * 60 * 1000;
|
||||
const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
const INSTALL_URL = "https://cursor.com/install";
|
||||
const REMOTE_TIMEOUT_MS = 5_000;
|
||||
const REMOTE_TIMEOUT_MS = 20_000;
|
||||
const VERSION_CACHE_FILE = "cursor-agent-cli-version.json";
|
||||
|
||||
let cachedVersion: string | null = null;
|
||||
let cachedAt = 0;
|
||||
let remoteRefreshInFlight: Promise<void> | null = null;
|
||||
let remoteRefreshScheduled = false;
|
||||
let remoteRefreshInFlight: Promise<string | null> | null = null;
|
||||
|
||||
/** Test seam: override fetch for installer scrape. */
|
||||
let fetchImpl: typeof fetch = fetch;
|
||||
@@ -43,6 +42,24 @@ export function isCursorAgentCliVersionId(value: string): boolean {
|
||||
return VERSION_ID_RE.test(value);
|
||||
}
|
||||
|
||||
/** Calendar date embedded in a `YYYY.MM.DD-<hash>` build id, or null. */
|
||||
export function cursorAgentCliVersionDate(id: string): string | null {
|
||||
if (!isCursorAgentCliVersionId(id)) return null;
|
||||
return id.slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer `candidate` only when its date is strictly later than `floor`.
|
||||
* A missing, invalid, or older-or-equal candidate keeps the floor (the pin).
|
||||
*/
|
||||
export function preferNewerCursorAgentCliVersion(floor: string, candidate: string | null): string {
|
||||
if (!candidate || !isCursorAgentCliVersionId(candidate)) return floor;
|
||||
const floorDate = cursorAgentCliVersionDate(floor);
|
||||
const candidateDate = cursorAgentCliVersionDate(candidate);
|
||||
if (!floorDate || !candidateDate || candidateDate <= floorDate) return floor;
|
||||
return candidate;
|
||||
}
|
||||
|
||||
export function formatCursorAgentClientVersion(id: string): string {
|
||||
return `cli-${id}`;
|
||||
}
|
||||
@@ -160,89 +177,101 @@ function writeDiskVersionCache(cache: DiskVersionCache): void {
|
||||
}
|
||||
|
||||
async function fetchInstallerVersionId(): Promise<string | null> {
|
||||
const response = await fetchImpl(INSTALL_URL, {
|
||||
signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const text = await response.text();
|
||||
return extractVersionIdFromInstallerScript(text);
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), REMOTE_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetchImpl(INSTALL_URL, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const text = await response.text();
|
||||
return extractVersionIdFromInstallerScript(text);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRemoteVersionRefresh(): void {
|
||||
if (remoteRefreshInFlight || remoteRefreshScheduled) return;
|
||||
// Defer so sync header resolution never starts network in the same turn.
|
||||
remoteRefreshScheduled = true;
|
||||
setTimeout(() => {
|
||||
remoteRefreshScheduled = false;
|
||||
if (remoteRefreshInFlight) return;
|
||||
remoteRefreshInFlight = (async () => {
|
||||
try {
|
||||
const id = await fetchInstallerVersionId();
|
||||
if (id) writeDiskVersionCache({ version: id, fetchedAt: Date.now() });
|
||||
} catch {
|
||||
// Ignore — pin / stale cache remain valid.
|
||||
} finally {
|
||||
remoteRefreshInFlight = null;
|
||||
}
|
||||
})();
|
||||
}, 0);
|
||||
function ensureRemoteVersion(): Promise<string | null> {
|
||||
if (remoteRefreshInFlight) return remoteRefreshInFlight;
|
||||
remoteRefreshInFlight = (async () => {
|
||||
const id = await fetchInstallerVersionId();
|
||||
if (id) writeDiskVersionCache({ version: id, fetchedAt: Date.now() });
|
||||
return id;
|
||||
})().finally(() => {
|
||||
remoteRefreshInFlight = null;
|
||||
});
|
||||
return remoteRefreshInFlight;
|
||||
}
|
||||
|
||||
function resolveLocalCursorAgentCliVersion(now: number): string | null {
|
||||
const fromEnv = process.env.CURSOR_AGENT_CLI_VERSION?.trim();
|
||||
if (fromEnv && isCursorAgentCliVersionId(fromEnv)) return fromEnv;
|
||||
|
||||
const home = process.env.HOME || process.env.USERPROFILE || homedir();
|
||||
const fromFs = detectCursorAgentCliVersionFromFs(home);
|
||||
if (fromFs) return fromFs;
|
||||
|
||||
const disk = readDiskVersionCache();
|
||||
if (disk && now - disk.fetchedAt < CACHE_TTL_MS) {
|
||||
return preferNewerCursorAgentCliVersion(CURSOR_AGENT_CLI_VERSION, disk.version);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve CLI build id synchronously for request headers.
|
||||
* Env → local FS → disk cache (refresh in background if stale) → pin.
|
||||
* CLI build id for `x-cursor-client-version`.
|
||||
* Env and a local install win. Otherwise https://cursor.com/install is fetched
|
||||
* (20s timeout, cached 6h) and used only when its date is strictly later than
|
||||
* the pin. A rejected or unusable fetch keeps the pin.
|
||||
*/
|
||||
export function getCursorAgentCliVersion(): string {
|
||||
export async function getCursorAgentCliVersion(): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (cachedVersion && now - cachedAt < CACHE_TTL_MS) {
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
const fromEnv = process.env.CURSOR_AGENT_CLI_VERSION?.trim();
|
||||
if (fromEnv && isCursorAgentCliVersionId(fromEnv)) {
|
||||
cachedVersion = fromEnv;
|
||||
cachedAt = now;
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
const home = process.env.HOME || process.env.USERPROFILE || homedir();
|
||||
const fromFs = detectCursorAgentCliVersionFromFs(home);
|
||||
if (fromFs) {
|
||||
cachedVersion = fromFs;
|
||||
const local = resolveLocalCursorAgentCliVersion(now);
|
||||
if (local && local !== CURSOR_AGENT_CLI_VERSION) {
|
||||
cachedVersion = local;
|
||||
cachedAt = now;
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
const disk = readDiskVersionCache();
|
||||
if (disk) {
|
||||
cachedVersion = disk.version;
|
||||
cachedAt = now;
|
||||
// Stale-while-revalidate (oakimov): always serve disk cache; refresh in
|
||||
// background when fresh (keep warm) or stale.
|
||||
scheduleRemoteVersionRefresh();
|
||||
return cachedVersion;
|
||||
if (disk && now - disk.fetchedAt < CACHE_TTL_MS) {
|
||||
const cached = preferNewerCursorAgentCliVersion(CURSOR_AGENT_CLI_VERSION, disk.version);
|
||||
if (cached !== CURSOR_AGENT_CLI_VERSION) {
|
||||
cachedVersion = cached;
|
||||
cachedAt = now;
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
scheduleRemoteVersionRefresh();
|
||||
return CURSOR_AGENT_CLI_VERSION;
|
||||
// Do not block the request on the installer scrape. Use the disk cache or
|
||||
// the pin now, and let the fetch land for the next call.
|
||||
if (!process.env.NODE_TEST_CONTEXT) void ensureRemoteVersion().catch(() => null);
|
||||
const resolved = preferNewerCursorAgentCliVersion(
|
||||
CURSOR_AGENT_CLI_VERSION,
|
||||
disk?.version ?? null
|
||||
);
|
||||
cachedVersion = resolved;
|
||||
cachedAt = Date.now();
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Await a remote installer scrape (tests / warm-up). Writes disk cache on success.
|
||||
*/
|
||||
export async function refreshCursorAgentCliVersionFromInstaller(): Promise<string | null> {
|
||||
try {
|
||||
const id = await fetchInstallerVersionId();
|
||||
if (id) {
|
||||
writeDiskVersionCache({ version: id, fetchedAt: Date.now() });
|
||||
cachedVersion = id;
|
||||
cachedAt = Date.now();
|
||||
return id;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return null;
|
||||
const id = await fetchInstallerVersionId();
|
||||
if (!id) return null;
|
||||
const resolved = preferNewerCursorAgentCliVersion(CURSOR_AGENT_CLI_VERSION, id);
|
||||
writeDiskVersionCache({ version: resolved, fetchedAt: Date.now() });
|
||||
cachedVersion = resolved;
|
||||
cachedAt = Date.now();
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** Exposed for testing: reset the in-memory cache. */
|
||||
@@ -250,7 +279,6 @@ export function resetCursorAgentCliVersionCache(): void {
|
||||
cachedVersion = null;
|
||||
cachedAt = 0;
|
||||
remoteRefreshInFlight = null;
|
||||
remoteRefreshScheduled = false;
|
||||
}
|
||||
|
||||
/** Exposed for testing: inject fetch + cache dir. */
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
/**
|
||||
* Wire-version data captured from the signed Claude Code binary.
|
||||
*
|
||||
* Keep this leaf dependency-free so server executors, compatibility bridges,
|
||||
* and client-facing identity presets can share one source of truth.
|
||||
* Keep this leaf dependency-free (no project imports) so server executors,
|
||||
* compatibility bridges, and client-facing identity presets can share one
|
||||
* source of truth.
|
||||
*
|
||||
* `CLAUDE_CODE_CLIENT_VERSION` is the captured pin. Runtime callers that
|
||||
* advertise the version on the wire must go through getClaudeCodeClientVersion()
|
||||
* so operators can bump past Anthropic's model gate without a rebuild (#12417).
|
||||
* The getter also reads a 6h cache of `@anthropic-ai/claude-code` on npm and
|
||||
* uses that version when it is newer than the pin. The env override wins over
|
||||
* both. The lookup is fire-and-forget; a cold or failed fetch stays on the pin.
|
||||
*/
|
||||
export const CLAUDE_CODE_CLIENT_VERSION = "2.1.280";
|
||||
export const CLAUDE_CODE_CLIENT_BUILD_REVISION = "1e2";
|
||||
@@ -19,6 +23,17 @@ export type ClaudeCodeEntrypoint = "cli" | "sdk-cli";
|
||||
const CLAUDE_VERSION_OVERRIDE_ENV = "CLAUDE_CODE_CLIENT_VERSION";
|
||||
const CLAUDE_BUILD_REVISION_OVERRIDE_ENV = "CLAUDE_CODE_CLIENT_BUILD_REVISION";
|
||||
const SAFE_HEADER_TOKEN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/;
|
||||
const DOTTED_TRIPLE_PATTERN = /^\d+\.\d+\.\d+$/;
|
||||
|
||||
const NPM_CLAUDE_CODE_LATEST_URL = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
|
||||
export const CLAUDE_CODE_VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
export const CLAUDE_CODE_VERSION_FETCH_TIMEOUT_MS = 20_000;
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
let cachedVersion: string | null = null;
|
||||
let cachedAt = 0;
|
||||
let inFlight: Promise<string> | null = null;
|
||||
|
||||
function getSafeEnvValue(name: string, pattern: RegExp): string | null {
|
||||
const raw = typeof process === "undefined" ? undefined : process.env?.[name];
|
||||
@@ -30,8 +45,110 @@ function getSafeEnvValue(name: string, pattern: RegExp): string | null {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function parseDottedTriple(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return DOTTED_TRIPLE_PATTERN.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function compareDottedTriple(a: string, b: string): number {
|
||||
const aParts = a.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
const bParts = b.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (aParts[i] !== bParts[i]) return aParts[i] - bParts[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function pickAtLeastPin(version: string | null): string {
|
||||
if (!version || compareDottedTriple(version, CLAUDE_CODE_CLIENT_VERSION) <= 0) {
|
||||
return CLAUDE_CODE_CLIENT_VERSION;
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
function readFreshCache(): string | null {
|
||||
if (!cachedVersion) return null;
|
||||
if (Date.now() - cachedAt >= CLAUDE_CODE_VERSION_CACHE_TTL_MS) return null;
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
function shouldAutoRefreshClaudeCodeVersion(): boolean {
|
||||
if (typeof process === "undefined") return false;
|
||||
return !process.env.NODE_TEST_CONTEXT && !process.env.VITEST && process.env.NODE_ENV !== "test";
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync hot path. Env override wins. Otherwise a cached registry version newer
|
||||
* than the pin, else the pin. Outside tests, a stale cache starts one
|
||||
* background refresh; this call itself never waits on the network.
|
||||
*/
|
||||
export function getClaudeCodeClientVersion(): string {
|
||||
return getSafeEnvValue(CLAUDE_VERSION_OVERRIDE_ENV, SAFE_HEADER_TOKEN_PATTERN) || CLAUDE_CODE_CLIENT_VERSION;
|
||||
const override = getSafeEnvValue(CLAUDE_VERSION_OVERRIDE_ENV, SAFE_HEADER_TOKEN_PATTERN);
|
||||
if (override) return override;
|
||||
if (shouldAutoRefreshClaudeCodeVersion() && !readFreshCache() && !inFlight) {
|
||||
void refreshClaudeCodeClientVersion();
|
||||
}
|
||||
return pickAtLeastPin(readFreshCache());
|
||||
}
|
||||
|
||||
/**
|
||||
* Warm the npm cache (5s timeout, 6h TTL, coalesced, never rejects).
|
||||
* Any failure — network, non-2xx, or a payload that is not a dotted triple —
|
||||
* leaves the pin (or the previous fresh cache) in place.
|
||||
*/
|
||||
export function refreshClaudeCodeClientVersion(fetchImpl: FetchLike = fetch): Promise<string> {
|
||||
const override = getSafeEnvValue(CLAUDE_VERSION_OVERRIDE_ENV, SAFE_HEADER_TOKEN_PATTERN);
|
||||
if (override) return Promise.resolve(override);
|
||||
|
||||
const fresh = readFreshCache();
|
||||
if (fresh) return Promise.resolve(pickAtLeastPin(fresh));
|
||||
|
||||
if (inFlight) return inFlight;
|
||||
|
||||
inFlight = (async () => {
|
||||
let resolved: string | null = null;
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), CLAUDE_CODE_VERSION_FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetchImpl(NPM_CLAUDE_CODE_LATEST_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "OmniRoute-ClaudeCodeVersion/1.0",
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
const payload = (await response.json()) as { version?: unknown };
|
||||
resolved = parseDottedTriple(payload?.version);
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
} catch {
|
||||
resolved = null;
|
||||
}
|
||||
|
||||
if (resolved && compareDottedTriple(resolved, CLAUDE_CODE_CLIENT_VERSION) > 0) {
|
||||
cachedVersion = resolved;
|
||||
cachedAt = Date.now();
|
||||
}
|
||||
return pickAtLeastPin(resolved ?? readFreshCache());
|
||||
})();
|
||||
|
||||
const current = inFlight;
|
||||
void current.finally(() => {
|
||||
if (inFlight === current) inFlight = null;
|
||||
});
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Test seam: drop the registry cache so the next refresh hits the network. */
|
||||
export function resetClaudeCodeClientVersionCache(): void {
|
||||
cachedVersion = null;
|
||||
cachedAt = 0;
|
||||
inFlight = null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
import { getClaudeCodeUserAgent } from "./claudeCodeClient";
|
||||
import { getCodexCliRsHeaders } from "./codexClient";
|
||||
import { getGeminiCliUserAgent } from "./geminiCliClient";
|
||||
|
||||
export interface ClientIdentityProfile {
|
||||
readonly id: string;
|
||||
@@ -48,7 +49,7 @@ const GEMINI_CLI_PROFILE: ClientIdentityProfile = Object.freeze({
|
||||
id: "gemini-cli",
|
||||
label: "Gemini CLI",
|
||||
headers: Object.freeze({
|
||||
"User-Agent": "GeminiCLI/0.1.0 (linux; x64)",
|
||||
"User-Agent": getGeminiCliUserAgent(),
|
||||
}),
|
||||
});
|
||||
const MUSE_CLI_PROFILE: ClientIdentityProfile = Object.freeze({
|
||||
|
||||
130
src/shared/constants/geminiCliClient.ts
Normal file
130
src/shared/constants/geminiCliClient.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* Wire version advertised for the Gemini CLI identity preset.
|
||||
*
|
||||
* `GEMINI_CLI_CLIENT_VERSION` is the captured pin. Callers that put the
|
||||
* version on the wire must go through getGeminiCliClientVersion() so a
|
||||
* newer `@google/gemini-cli` publish is picked up without a rebuild. The
|
||||
* getter reads a 6h cache of the npm `latest` document and uses that
|
||||
* version when it is a dotted triple newer than the pin. The lookup is
|
||||
* fire-and-forget; a cold or failed fetch stays on the pin.
|
||||
*/
|
||||
export const GEMINI_CLI_CLIENT_VERSION = "0.1.0";
|
||||
export const GEMINI_CLI_USER_AGENT_SUFFIX = "(linux; x64)";
|
||||
|
||||
const NPM_GEMINI_CLI_LATEST_URL = "https://registry.npmjs.org/@google/gemini-cli/latest";
|
||||
export const GEMINI_CLI_VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
export const GEMINI_CLI_VERSION_FETCH_TIMEOUT_MS = 20_000;
|
||||
|
||||
const DOTTED_TRIPLE_PATTERN = /^\d+\.\d+\.\d+$/;
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
let cachedVersion: string | null = null;
|
||||
let cachedAt = 0;
|
||||
let inFlight: Promise<string> | null = null;
|
||||
|
||||
function parseDottedTriple(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return DOTTED_TRIPLE_PATTERN.test(trimmed) ? trimmed : null;
|
||||
}
|
||||
|
||||
function compareDottedTriple(a: string, b: string): number {
|
||||
const aParts = a.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
const bParts = b.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (aParts[i] !== bParts[i]) return aParts[i] - bParts[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function pickAtLeastPin(version: string | null): string {
|
||||
if (!version || compareDottedTriple(version, GEMINI_CLI_CLIENT_VERSION) <= 0) {
|
||||
return GEMINI_CLI_CLIENT_VERSION;
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
function readFreshCache(): string | null {
|
||||
if (!cachedVersion) return null;
|
||||
if (Date.now() - cachedAt >= GEMINI_CLI_VERSION_CACHE_TTL_MS) return null;
|
||||
return cachedVersion;
|
||||
}
|
||||
|
||||
function shouldAutoRefreshGeminiCliVersion(): boolean {
|
||||
if (typeof process === "undefined") return false;
|
||||
return !process.env.NODE_TEST_CONTEXT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync hot path. A cached registry version newer than the pin, else the pin.
|
||||
* Outside tests, a stale cache starts one background refresh; this call
|
||||
* itself never waits on the network.
|
||||
*/
|
||||
export function getGeminiCliClientVersion(): string {
|
||||
if (shouldAutoRefreshGeminiCliVersion() && !readFreshCache() && !inFlight) {
|
||||
void refreshGeminiCliClientVersion();
|
||||
}
|
||||
return pickAtLeastPin(readFreshCache());
|
||||
}
|
||||
|
||||
export function getGeminiCliUserAgent(): string {
|
||||
return `GeminiCLI/${getGeminiCliClientVersion()} ${GEMINI_CLI_USER_AGENT_SUFFIX}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Warm the npm cache (20s timeout, 6h TTL, coalesced, never rejects).
|
||||
* Any failure -- network, non-2xx, or a payload that is not a dotted triple --
|
||||
* leaves the pin (or the previous fresh cache) in place. A fetched triple
|
||||
* older than or equal to the pin is discarded.
|
||||
*/
|
||||
export function refreshGeminiCliClientVersion(fetchImpl: FetchLike = fetch): Promise<string> {
|
||||
const fresh = readFreshCache();
|
||||
if (fresh) return Promise.resolve(pickAtLeastPin(fresh));
|
||||
|
||||
if (inFlight) return inFlight;
|
||||
|
||||
inFlight = (async () => {
|
||||
let resolved: string | null = null;
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), GEMINI_CLI_VERSION_FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetchImpl(NPM_GEMINI_CLI_LATEST_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "OmniRoute-GeminiCliVersion/1.0",
|
||||
},
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.ok) {
|
||||
const payload = (await response.json()) as { version?: unknown };
|
||||
resolved = parseDottedTriple(payload?.version);
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
} catch {
|
||||
resolved = null;
|
||||
}
|
||||
|
||||
if (resolved && compareDottedTriple(resolved, GEMINI_CLI_CLIENT_VERSION) > 0) {
|
||||
cachedVersion = resolved;
|
||||
cachedAt = Date.now();
|
||||
}
|
||||
return pickAtLeastPin(resolved ?? readFreshCache());
|
||||
})();
|
||||
|
||||
const current = inFlight;
|
||||
void current.finally(() => {
|
||||
if (inFlight === current) inFlight = null;
|
||||
});
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Test seam: drop the registry cache so the next refresh hits the network. */
|
||||
export function resetGeminiCliClientVersionCache(): void {
|
||||
cachedVersion = null;
|
||||
cachedAt = 0;
|
||||
inFlight = null;
|
||||
}
|
||||
100
tests/unit/claude-code-client-version-fetch.test.ts
Normal file
100
tests/unit/claude-code-client-version-fetch.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Registry lookup for the advertised Claude Code client version.
|
||||
*
|
||||
* Anthropic gates models on the version OmniRoute sends. The captured pin is
|
||||
* the floor; a newer dotted triple from the npm `latest` document replaces it
|
||||
* for 6 hours. A rejected fetch, a non-triple, or an older publish stays on
|
||||
* the pin. CLAUDE_CODE_CLIENT_VERSION in the environment beats both.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const canonical = await import("../../src/shared/constants/claudeCodeClient.ts");
|
||||
|
||||
const NPM_LATEST = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
async function withEnv<T>(
|
||||
entries: Record<string, string | undefined>,
|
||||
fn: () => T | Promise<T>
|
||||
): Promise<T> {
|
||||
const previous = new Map<string, string | undefined>();
|
||||
for (const [key, value] of Object.entries(entries)) {
|
||||
previous.set(key, process.env[key]);
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
for (const [key, value] of previous.entries()) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
canonical.resetClaudeCodeClientVersionCache();
|
||||
});
|
||||
|
||||
test("a fetched version newer than the pin is returned", async () => {
|
||||
const urls: string[] = [];
|
||||
const fetchMock = async (url: string | URL | Request) => {
|
||||
urls.push(String(url));
|
||||
return jsonResponse({ version: "2.1.291" });
|
||||
};
|
||||
|
||||
await withEnv({ CLAUDE_CODE_CLIENT_VERSION: undefined }, async () => {
|
||||
assert.equal(
|
||||
await canonical.refreshClaudeCodeClientVersion(fetchMock as typeof fetch),
|
||||
"2.1.291"
|
||||
);
|
||||
assert.equal(canonical.getClaudeCodeClientVersion(), "2.1.291");
|
||||
});
|
||||
assert.equal(urls.length, 1);
|
||||
assert.equal(urls[0], NPM_LATEST);
|
||||
});
|
||||
|
||||
test("a fetch that rejects falls back to the pin", async () => {
|
||||
const fetchMock = async () => {
|
||||
throw new Error("registry unreachable");
|
||||
};
|
||||
|
||||
await withEnv({ CLAUDE_CODE_CLIENT_VERSION: undefined }, async () => {
|
||||
assert.equal(
|
||||
await canonical.refreshClaudeCodeClientVersion(fetchMock as typeof fetch),
|
||||
canonical.CLAUDE_CODE_CLIENT_VERSION
|
||||
);
|
||||
assert.equal(canonical.getClaudeCodeClientVersion(), canonical.CLAUDE_CODE_CLIENT_VERSION);
|
||||
});
|
||||
});
|
||||
|
||||
test("the env override beats the fetched value", async () => {
|
||||
let calls = 0;
|
||||
const fetchMock = async () => {
|
||||
calls += 1;
|
||||
return jsonResponse({ version: "9.9.9" });
|
||||
};
|
||||
|
||||
await withEnv({ CLAUDE_CODE_CLIENT_VERSION: "2.1.259" }, async () => {
|
||||
assert.equal(
|
||||
await canonical.refreshClaudeCodeClientVersion(fetchMock as typeof fetch),
|
||||
"2.1.259"
|
||||
);
|
||||
assert.equal(canonical.getClaudeCodeClientVersion(), "2.1.259");
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
81
tests/unit/codex-client-version-fetch.test.ts
Normal file
81
tests/unit/codex-client-version-fetch.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { DEFAULT_CODEX_CLIENT_VERSION } from "../../src/shared/constants/codexClient.ts";
|
||||
import {
|
||||
clearCodexClientVersionCache,
|
||||
getCodexClientVersion,
|
||||
resolveCodexClientVersion,
|
||||
} from "../../open-sse/config/codexClient.ts";
|
||||
|
||||
const CODEX_RELEASE_URL = "https://api.github.com/repos/openai/codex/releases/latest";
|
||||
|
||||
function releaseFetch(tagName: string): typeof fetch {
|
||||
return (async (url: string | URL | Request) => {
|
||||
assert.equal(String(url), CODEX_RELEASE_URL);
|
||||
return new Response(JSON.stringify({ tag_name: tagName }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
async function withEnv<T>(
|
||||
entries: Record<string, string | undefined>,
|
||||
fn: () => T | Promise<T>
|
||||
): Promise<T> {
|
||||
const previous = new Map<string, string | undefined>();
|
||||
for (const [key, value] of Object.entries(entries)) {
|
||||
previous.set(key, process.env[key]);
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
for (const [key, value] of previous.entries()) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
clearCodexClientVersionCache();
|
||||
delete process.env.CODEX_CLIENT_VERSION;
|
||||
});
|
||||
|
||||
test("a fetched Codex release newer than the pin is returned", async () => {
|
||||
await withEnv({ CODEX_CLIENT_VERSION: undefined }, async () => {
|
||||
const version = await resolveCodexClientVersion(releaseFetch("rust-v0.160.1"));
|
||||
assert.equal(version, "0.160.1");
|
||||
assert.equal(getCodexClientVersion(), "0.160.1");
|
||||
assert.notEqual(version, DEFAULT_CODEX_CLIENT_VERSION);
|
||||
});
|
||||
});
|
||||
|
||||
test("a rejected fetch falls back to the pinned Codex version", async () => {
|
||||
await withEnv({ CODEX_CLIENT_VERSION: undefined }, async () => {
|
||||
const failingFetch = (async () => {
|
||||
throw new Error("network down");
|
||||
}) as typeof fetch;
|
||||
|
||||
const version = await resolveCodexClientVersion(failingFetch);
|
||||
assert.equal(version, DEFAULT_CODEX_CLIENT_VERSION);
|
||||
assert.equal(getCodexClientVersion(), DEFAULT_CODEX_CLIENT_VERSION);
|
||||
});
|
||||
});
|
||||
|
||||
test("CODEX_CLIENT_VERSION beats a newer fetched release", async () => {
|
||||
await withEnv({ CODEX_CLIENT_VERSION: "0.99.0" }, async () => {
|
||||
const version = await resolveCodexClientVersion(releaseFetch("rust-v0.160.1"));
|
||||
assert.equal(version, "0.160.1");
|
||||
assert.equal(getCodexClientVersion(), "0.99.0");
|
||||
});
|
||||
});
|
||||
99
tests/unit/copilot-cli-version-fetch.test.ts
Normal file
99
tests/unit/copilot-cli-version-fetch.test.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Registry lookup for the advertised GitHub Copilot CLI version.
|
||||
*
|
||||
* Copilot gates models on the version OmniRoute sends and 400s a pin that is
|
||||
* behind. The captured 1.0.88 pin is the floor; a newer dotted triple from
|
||||
* `@github/copilot` on npm replaces it for 6 hours, in both `copilot/<ver>`
|
||||
* and `GitHubCopilotChat/<ver>`. A rejected fetch, a non-triple, or an older
|
||||
* publish stays on the pin. GITHUB_COPILOT_CLI_VERSION in the environment
|
||||
* beats both.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const copilot = await import("../../open-sse/config/providerHeaderProfiles.ts");
|
||||
|
||||
const NPM_LATEST = "https://registry.npmjs.org/@github/copilot/latest";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
async function withEnv<T>(
|
||||
entries: Record<string, string | undefined>,
|
||||
fn: () => T | Promise<T>
|
||||
): Promise<T> {
|
||||
const previous = new Map<string, string | undefined>();
|
||||
for (const [key, value] of Object.entries(entries)) {
|
||||
previous.set(key, process.env[key]);
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
for (const [key, value] of previous.entries()) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
copilot.resetGitHubCopilotCliVersionCache();
|
||||
});
|
||||
|
||||
test("a fetched version newer than the pin appears in both Copilot header strings", async () => {
|
||||
const urls: string[] = [];
|
||||
const fetchMock = async (url: string | URL | Request) => {
|
||||
urls.push(String(url));
|
||||
return jsonResponse({ version: "1.0.92" });
|
||||
};
|
||||
|
||||
await withEnv({ GITHUB_COPILOT_CLI_VERSION: undefined }, async () => {
|
||||
assert.equal(
|
||||
await copilot.resolveGitHubCopilotCliVersion(fetchMock as typeof fetch),
|
||||
"1.0.92"
|
||||
);
|
||||
assert.equal(copilot.getGitHubCopilotCliVersion(), "1.0.92");
|
||||
const headers = copilot.getGitHubCopilotChatHeaders();
|
||||
assert.equal(headers["editor-version"], "copilot/1.0.92");
|
||||
assert.equal(
|
||||
headers["user-agent"],
|
||||
`copilot/1.0.92 (${process.platform}) term/unknown`
|
||||
);
|
||||
assert.equal(copilot.getGitHubCopilotChatUserAgent(), "GitHubCopilotChat/1.0.92");
|
||||
const internal = copilot.getGitHubCopilotInternalUserHeaders("token gh");
|
||||
assert.equal(internal["User-Agent"], "GitHubCopilotChat/1.0.92");
|
||||
assert.equal(internal["Editor-Version"], "copilot/1.0.92");
|
||||
});
|
||||
assert.equal(urls.length, 1);
|
||||
assert.equal(urls[0], NPM_LATEST);
|
||||
assert.equal(copilot.GITHUB_COPILOT_CLI_VERSION, "1.0.88");
|
||||
});
|
||||
|
||||
test("a fetch that rejects keeps the pinned 1.0.88", async () => {
|
||||
const fetchMock = async () => {
|
||||
throw new Error("registry unreachable");
|
||||
};
|
||||
|
||||
await withEnv({ GITHUB_COPILOT_CLI_VERSION: undefined }, async () => {
|
||||
assert.equal(
|
||||
await copilot.resolveGitHubCopilotCliVersion(fetchMock as typeof fetch),
|
||||
"1.0.88"
|
||||
);
|
||||
assert.equal(copilot.getGitHubCopilotCliVersion(), copilot.GITHUB_COPILOT_CLI_VERSION);
|
||||
const headers = copilot.getGitHubCopilotChatHeaders();
|
||||
assert.equal(headers["editor-version"], "copilot/1.0.88");
|
||||
assert.equal(copilot.getGitHubCopilotChatUserAgent(), "GitHubCopilotChat/1.0.88");
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,7 @@ const {
|
||||
resetCursorAgentCliVersionTestHooks,
|
||||
} = await import("../../open-sse/utils/cursorAgentCliVersion.ts");
|
||||
|
||||
function withEnv(vars: Record<string, string | undefined>, fn: () => void) {
|
||||
function withEnv(vars: Record<string, string | undefined>, fn: () => void | Promise<void>) {
|
||||
const saved: Record<string, string | undefined> = {};
|
||||
for (const key of Object.keys(vars)) {
|
||||
saved[key] = process.env[key];
|
||||
@@ -26,13 +26,22 @@ function withEnv(vars: Record<string, string | undefined>, fn: () => void) {
|
||||
if (next === undefined) delete process.env[key];
|
||||
else process.env[key] = next;
|
||||
}
|
||||
try {
|
||||
fn();
|
||||
} finally {
|
||||
const restore = () => {
|
||||
for (const key of Object.keys(saved)) {
|
||||
if (saved[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = saved[key];
|
||||
}
|
||||
};
|
||||
try {
|
||||
const result = fn();
|
||||
if (result && typeof (result as Promise<void>).then === "function") {
|
||||
return (result as Promise<void>).finally(restore);
|
||||
}
|
||||
restore();
|
||||
return result;
|
||||
} catch (err) {
|
||||
restore();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,64 +107,75 @@ test("detectCursorAgentCliVersionFromFs uses CURSOR_DATA_DIR versions when no sh
|
||||
}
|
||||
});
|
||||
|
||||
test("getCursorAgentCliVersion env override wins", () => {
|
||||
withEnv({ CURSOR_AGENT_CLI_VERSION: "2026.01.02-abc1234" }, () => {
|
||||
test("getCursorAgentCliVersion env override wins", async () => {
|
||||
await withEnv({ CURSOR_AGENT_CLI_VERSION: "2026.01.02-abc1234" }, async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(getCursorAgentCliVersion(), "2026.01.02-abc1234");
|
||||
assert.equal(await getCursorAgentCliVersion(), "2026.01.02-abc1234");
|
||||
});
|
||||
resetCursorAgentCliVersionCache();
|
||||
});
|
||||
|
||||
test("getCursorAgentCliVersion ignores invalid env and uses pin when FS empty", () => {
|
||||
test("getCursorAgentCliVersion ignores invalid env and uses pin when FS empty", async () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-home-pin-"));
|
||||
const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-cache-pin-"));
|
||||
try {
|
||||
withEnv(
|
||||
configureCursorAgentCliVersionForTests({
|
||||
cacheDir,
|
||||
fetchImpl: (async () => {
|
||||
throw new Error("offline");
|
||||
}) as typeof fetch,
|
||||
});
|
||||
await withEnv(
|
||||
{
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CURSOR_AGENT_CLI_VERSION: "3.9",
|
||||
CURSOR_DATA_DIR: undefined,
|
||||
},
|
||||
() => {
|
||||
async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(getCursorAgentCliVersion(), CURSOR_AGENT_CLI_VERSION);
|
||||
assert.equal(await getCursorAgentCliVersion(), CURSOR_AGENT_CLI_VERSION);
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
resetCursorAgentCliVersionCache();
|
||||
resetCursorAgentCliVersionTestHooks();
|
||||
fs.rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
fs.rmSync(cacheDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
test("getCursorAgentCliVersion caches until reset", () => {
|
||||
withEnv({ CURSOR_AGENT_CLI_VERSION: "2026.02.03-111aaaa" }, () => {
|
||||
test("getCursorAgentCliVersion caches until reset", async () => {
|
||||
await withEnv({ CURSOR_AGENT_CLI_VERSION: "2026.02.03-111aaaa" }, async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(getCursorAgentCliVersion(), "2026.02.03-111aaaa");
|
||||
assert.equal(await getCursorAgentCliVersion(), "2026.02.03-111aaaa");
|
||||
process.env.CURSOR_AGENT_CLI_VERSION = "2026.02.03-222bbbb";
|
||||
assert.equal(getCursorAgentCliVersion(), "2026.02.03-111aaaa", "cached");
|
||||
assert.equal(await getCursorAgentCliVersion(), "2026.02.03-111aaaa", "cached");
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(getCursorAgentCliVersion(), "2026.02.03-222bbbb");
|
||||
assert.equal(await getCursorAgentCliVersion(), "2026.02.03-222bbbb");
|
||||
});
|
||||
resetCursorAgentCliVersionCache();
|
||||
});
|
||||
|
||||
test("getCursorAgentCliVersion reads CURSOR_DATA_DIR via isolated HOME", () => {
|
||||
test("getCursorAgentCliVersion reads CURSOR_DATA_DIR via isolated HOME", async () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-home-get-"));
|
||||
const data = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-data-get-"));
|
||||
try {
|
||||
const id = "2026.03.15-cafebabe";
|
||||
fs.mkdirSync(path.join(data, "versions", id), { recursive: true });
|
||||
withEnv(
|
||||
await withEnv(
|
||||
{
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CURSOR_DATA_DIR: data,
|
||||
CURSOR_AGENT_CLI_VERSION: undefined,
|
||||
},
|
||||
() => {
|
||||
async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(getCursorAgentCliVersion(), id);
|
||||
assert.equal(formatCursorAgentClientVersion(getCursorAgentCliVersion()), `cli-${id}`);
|
||||
assert.equal(await getCursorAgentCliVersion(), id);
|
||||
assert.equal(
|
||||
formatCursorAgentClientVersion(await getCursorAgentCliVersion()),
|
||||
`cli-${id}`
|
||||
);
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
@@ -193,17 +213,16 @@ test("disk cache hit serves immediately without blocking on network", async () =
|
||||
path.join(cacheDir, "cursor-agent-cli-version.json"),
|
||||
JSON.stringify({ version: cachedId, fetchedAt: Date.now() })
|
||||
);
|
||||
withEnv(
|
||||
await withEnv(
|
||||
{
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CURSOR_AGENT_CLI_VERSION: undefined,
|
||||
CURSOR_DATA_DIR: undefined,
|
||||
},
|
||||
() => {
|
||||
async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
// Sync path returns disk cache immediately (oakimov SWR may refresh in background).
|
||||
assert.equal(getCursorAgentCliVersion(), cachedId);
|
||||
assert.equal(await getCursorAgentCliVersion(), cachedId);
|
||||
assert.equal(fetchCalls, 0, "must not block on network");
|
||||
}
|
||||
);
|
||||
@@ -245,19 +264,18 @@ test("invalid installer HTML falls through to pin", async () => {
|
||||
try {
|
||||
configureCursorAgentCliVersionForTests({
|
||||
cacheDir,
|
||||
fetchImpl: (async () =>
|
||||
new Response("<html>no lab url</html>", { status: 200 })) as typeof fetch,
|
||||
fetchImpl: (async () => new Response("<html>no lab url</html>", { status: 200 })) as typeof fetch,
|
||||
});
|
||||
withEnv(
|
||||
await withEnv(
|
||||
{
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CURSOR_AGENT_CLI_VERSION: undefined,
|
||||
CURSOR_DATA_DIR: undefined,
|
||||
},
|
||||
() => {
|
||||
async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(getCursorAgentCliVersion(), CURSOR_AGENT_CLI_VERSION);
|
||||
assert.equal(await getCursorAgentCliVersion(), CURSOR_AGENT_CLI_VERSION);
|
||||
}
|
||||
);
|
||||
const id = await refreshCursorAgentCliVersionFromInstaller();
|
||||
@@ -268,3 +286,66 @@ test("invalid installer HTML falls through to pin", async () => {
|
||||
fs.rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
function installerHtml(id: string): string {
|
||||
return `DOWNLOAD_URL="https://downloads.cursor.com/lab/${id}/\${OS}/\${ARCH}/agent-cli-package.tar.gz"`;
|
||||
}
|
||||
|
||||
test("fetched install version newer than the pin is returned", async () => {
|
||||
const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-cache-newer-"));
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-home-newer-"));
|
||||
const fetchedId = "2026.10.01-e373342";
|
||||
try {
|
||||
configureCursorAgentCliVersionForTests({
|
||||
cacheDir,
|
||||
fetchImpl: (async () => new Response(installerHtml(fetchedId), { status: 200 })) as typeof fetch,
|
||||
});
|
||||
await withEnv(
|
||||
{
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CURSOR_AGENT_CLI_VERSION: undefined,
|
||||
CURSOR_DATA_DIR: undefined,
|
||||
},
|
||||
async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(await getCursorAgentCliVersion(), "2026.07.08-0c04a8a");
|
||||
assert.equal(await refreshCursorAgentCliVersionFromInstaller(), fetchedId);
|
||||
assert.equal(await getCursorAgentCliVersion(), fetchedId);
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
resetCursorAgentCliVersionTestHooks();
|
||||
fs.rmSync(cacheDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
fs.rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
test("rejected install fetch keeps the pin", async () => {
|
||||
const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-cache-reject-"));
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-cli-home-reject-"));
|
||||
try {
|
||||
configureCursorAgentCliVersionForTests({
|
||||
cacheDir,
|
||||
fetchImpl: (async () => {
|
||||
throw new Error("network down");
|
||||
}) as typeof fetch,
|
||||
});
|
||||
await withEnv(
|
||||
{
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
CURSOR_AGENT_CLI_VERSION: undefined,
|
||||
CURSOR_DATA_DIR: undefined,
|
||||
},
|
||||
async () => {
|
||||
resetCursorAgentCliVersionCache();
|
||||
assert.equal(await getCursorAgentCliVersion(), CURSOR_AGENT_CLI_VERSION);
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
resetCursorAgentCliVersionTestHooks();
|
||||
fs.rmSync(cacheDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
fs.rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -74,9 +74,9 @@ describe("CursorExecutor credential resolution", () => {
|
||||
__resetCursorApiKeyAuthForTest();
|
||||
});
|
||||
|
||||
it("sends the stripped IDE session token for OAuth connections", () => {
|
||||
it("sends the stripped IDE session token for OAuth connections", async () => {
|
||||
const executor = new CursorExecutor();
|
||||
const headers = executor.buildHeaders({
|
||||
const headers = await executor.buildHeaders({
|
||||
accessToken: "user_01::ide.session.jwt",
|
||||
providerSpecificData: {},
|
||||
});
|
||||
@@ -101,7 +101,7 @@ describe("CursorExecutor credential resolution", () => {
|
||||
providerSpecificData: {},
|
||||
});
|
||||
assert.ok(!(resolved instanceof Response));
|
||||
const headers = executor.buildHeaders(resolved);
|
||||
const headers = await executor.buildHeaders(resolved);
|
||||
assert.equal(headers.authorization, `Bearer ${jwt(exp)}`);
|
||||
assert.ok(!headers.authorization.includes(API_KEY));
|
||||
assert.equal(calls.length, 1);
|
||||
|
||||
54
tests/unit/gemini-cli-client-version-fetch.test.ts
Normal file
54
tests/unit/gemini-cli-client-version-fetch.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Registry lookup for the advertised Gemini CLI client version.
|
||||
*
|
||||
* The captured pin is the floor; a newer dotted triple from the npm
|
||||
* `@google/gemini-cli` `latest` document replaces it for 6 hours. A rejected
|
||||
* fetch, a non-triple, or an older publish stays on the pin.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const canonical = await import("../../src/shared/constants/geminiCliClient.ts");
|
||||
|
||||
const NPM_LATEST = "https://registry.npmjs.org/@google/gemini-cli/latest";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
canonical.resetGeminiCliClientVersionCache();
|
||||
});
|
||||
|
||||
test("a fetched version newer than the pin is returned", async () => {
|
||||
const urls: string[] = [];
|
||||
const fetchMock = async (url: string | URL | Request) => {
|
||||
urls.push(String(url));
|
||||
return jsonResponse({ version: "0.62.0" });
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
await canonical.refreshGeminiCliClientVersion(fetchMock as typeof fetch),
|
||||
"0.62.0"
|
||||
);
|
||||
assert.equal(canonical.getGeminiCliClientVersion(), "0.62.0");
|
||||
assert.equal(canonical.getGeminiCliUserAgent(), "GeminiCLI/0.62.0 (linux; x64)");
|
||||
assert.equal(urls.length, 1);
|
||||
assert.equal(urls[0], NPM_LATEST);
|
||||
});
|
||||
|
||||
test("a fetch that rejects falls back to the pin", async () => {
|
||||
const fetchMock = async () => {
|
||||
throw new Error("registry unreachable");
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
await canonical.refreshGeminiCliClientVersion(fetchMock as typeof fetch),
|
||||
"0.1.0"
|
||||
);
|
||||
assert.equal(canonical.getGeminiCliClientVersion(), canonical.GEMINI_CLI_CLIENT_VERSION);
|
||||
assert.equal(canonical.getGeminiCliUserAgent(), "GeminiCLI/0.1.0 (linux; x64)");
|
||||
});
|
||||
92
tests/unit/kimi-code-cli-version-fetch.test.ts
Normal file
92
tests/unit/kimi-code-cli-version-fetch.test.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Registry lookup for the advertised Kimi Code CLI version.
|
||||
*
|
||||
* The captured pin is the floor. A newer dotted triple from the npm `latest`
|
||||
* document of `@moonshot-ai/kimi-code` replaces it for 6 hours. A rejected
|
||||
* fetch, a non-triple, or an older publish stays on the pin. KIMI_CLI_VERSION
|
||||
* in the environment beats both and must not start a fetch.
|
||||
*
|
||||
* The getter is the only production path: it stays sync and fires the lookup
|
||||
* in the background. These tests stub fetch, then read the getter after the
|
||||
* microtask that started the fetch has run.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const canonical = await import("../../open-sse/config/providers/registry/kimi/coding/runtime.ts");
|
||||
|
||||
const NPM_LATEST = "https://registry.npmjs.org/@moonshot-ai/kimi-code/latest";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
async function withEnv<T>(
|
||||
entries: Record<string, string | undefined>,
|
||||
fn: () => T | Promise<T>
|
||||
): Promise<T> {
|
||||
const previous = new Map<string, string | undefined>();
|
||||
for (const [key, value] of Object.entries(entries)) {
|
||||
previous.set(key, process.env[key]);
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
for (const [key, value] of previous.entries()) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Let the sync getter's `void` fetch reach the stub and settle. */
|
||||
async function flushBackgroundFetch(): Promise<void> {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
canonical.resetKimiCodeCliVersionCache();
|
||||
canonical.resetKimiCodeCliVersionFetch();
|
||||
});
|
||||
|
||||
test("a fetched version newer than the pin is kept by the getter", async () => {
|
||||
const urls: string[] = [];
|
||||
canonical.setKimiCodeCliVersionFetch(async (url: string | URL | Request) => {
|
||||
urls.push(String(url));
|
||||
return jsonResponse({ version: "2.1.2" });
|
||||
});
|
||||
|
||||
await withEnv({ KIMI_CLI_VERSION: undefined, NODE_TEST_CONTEXT: undefined }, async () => {
|
||||
assert.equal(canonical.getKimiCodeCliVersion(), canonical.KIMI_CODE_CLI_VERSION);
|
||||
await flushBackgroundFetch();
|
||||
assert.equal(canonical.getKimiCodeCliVersion(), "2.1.2");
|
||||
assert.equal(canonical.getKimiCodeCliUserAgent(), "kimi-code-cli/2.1.2");
|
||||
});
|
||||
assert.equal(urls.length, 1);
|
||||
assert.equal(urls[0], NPM_LATEST);
|
||||
});
|
||||
|
||||
test("a fetch that rejects stays on the pin", async () => {
|
||||
canonical.setKimiCodeCliVersionFetch(async () => {
|
||||
throw new Error("registry unreachable");
|
||||
});
|
||||
|
||||
await withEnv({ KIMI_CLI_VERSION: undefined, NODE_TEST_CONTEXT: undefined }, async () => {
|
||||
assert.equal(canonical.getKimiCodeCliVersion(), canonical.KIMI_CODE_CLI_VERSION);
|
||||
await flushBackgroundFetch();
|
||||
assert.equal(canonical.getKimiCodeCliVersion(), canonical.KIMI_CODE_CLI_VERSION);
|
||||
assert.equal(canonical.getKimiCodeCliUserAgent(), `kimi-code-cli/${canonical.KIMI_CODE_CLI_VERSION}`);
|
||||
});
|
||||
});
|
||||
94
tests/unit/qwen-codebuddy-version-fetch.test.ts
Normal file
94
tests/unit/qwen-codebuddy-version-fetch.test.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Registry lookups for the advertised Qwen Code and CodeBuddy CN identities.
|
||||
*
|
||||
* Both gates reject a pin that is behind the published CLI. The captured pin
|
||||
* is the floor; a newer dotted triple from npm replaces it for 6 hours. A
|
||||
* rejected fetch, a non-triple, or an older publish stays on the pin. The
|
||||
* sync getters return the cache or the pin immediately and never wait on
|
||||
* the network.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const profiles = await import("../../open-sse/config/providerHeaderProfiles.ts");
|
||||
|
||||
const QWEN_NPM_LATEST = "https://registry.npmjs.org/@qwen-code/qwen-code/latest";
|
||||
const CODEBUDDY_NPM_LATEST = "https://registry.npmjs.org/@tencent-ai/codebuddy-code/latest";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
profiles.resetQwenCliVersionCache();
|
||||
profiles.resetCodeBuddyCnVersionCache();
|
||||
});
|
||||
|
||||
test("a fetched Qwen version newer than the pin is returned", async () => {
|
||||
const urls: string[] = [];
|
||||
const fetchMock = async (url: string | URL | Request) => {
|
||||
urls.push(String(url));
|
||||
return jsonResponse({ version: "0.25.0" });
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
await profiles.refreshQwenCliVersion(fetchMock as typeof fetch),
|
||||
"0.25.0"
|
||||
);
|
||||
assert.equal(profiles.getQwenCliVersion(), "0.25.0");
|
||||
assert.equal(
|
||||
profiles.getQwenCliUserAgent(),
|
||||
`QwenCode/0.25.0 (${process.platform}; ${process.arch})`
|
||||
);
|
||||
assert.equal(urls.length, 1);
|
||||
assert.equal(urls[0], QWEN_NPM_LATEST);
|
||||
assert.equal(profiles.QWEN_CLI_VERSION, "0.19.3");
|
||||
});
|
||||
|
||||
test("a Qwen fetch that rejects stays on the pin", async () => {
|
||||
const fetchMock = async () => {
|
||||
throw new Error("registry unreachable");
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
await profiles.refreshQwenCliVersion(fetchMock as typeof fetch),
|
||||
profiles.QWEN_CLI_VERSION
|
||||
);
|
||||
assert.equal(profiles.getQwenCliVersion(), profiles.QWEN_CLI_VERSION);
|
||||
assert.equal(
|
||||
profiles.getQwenCliUserAgent(),
|
||||
`QwenCode/${profiles.QWEN_CLI_VERSION} (${process.platform}; ${process.arch})`
|
||||
);
|
||||
});
|
||||
|
||||
test("a fetched CodeBuddy version newer than the pin moves both numbers together", async () => {
|
||||
const urls: string[] = [];
|
||||
const fetchMock = async (url: string | URL | Request) => {
|
||||
urls.push(String(url));
|
||||
return jsonResponse({ version: "2.161.4" });
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
await profiles.refreshCodeBuddyCnUserAgent(fetchMock as typeof fetch),
|
||||
"CLI/2.161.4 CodeBuddy/2.161.4"
|
||||
);
|
||||
assert.equal(profiles.getCodeBuddyCnUserAgent(), "CLI/2.161.4 CodeBuddy/2.161.4");
|
||||
assert.equal(urls.length, 1);
|
||||
assert.equal(urls[0], CODEBUDDY_NPM_LATEST);
|
||||
assert.equal(profiles.CODEBUDDY_CN_USER_AGENT, "CLI/2.108.1 CodeBuddy/2.108.1");
|
||||
});
|
||||
|
||||
test("a CodeBuddy fetch that rejects stays on the pin", async () => {
|
||||
const fetchMock = async () => {
|
||||
throw new Error("registry unreachable");
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
await profiles.refreshCodeBuddyCnUserAgent(fetchMock as typeof fetch),
|
||||
profiles.CODEBUDDY_CN_USER_AGENT
|
||||
);
|
||||
assert.equal(profiles.getCodeBuddyCnUserAgent(), profiles.CODEBUDDY_CN_USER_AGENT);
|
||||
});
|
||||
49
tests/unit/zed-client-version-fetch.test.ts
Normal file
49
tests/unit/zed-client-version-fetch.test.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* GitHub lookup for the advertised Zed editor version.
|
||||
*
|
||||
* Zed gates hosted completions on x-zed-version. The captured 0.200.0 pin is
|
||||
* the floor; a newer dotted triple from zed-industries/zed replaces it for
|
||||
* 6 hours. A rejected fetch, a non-triple, or an older tag stays on the pin.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const zed = await import("../../open-sse/executors/zedClientVersion.ts");
|
||||
|
||||
const ZED_RELEASE_URL = "https://api.github.com/repos/zed-industries/zed/releases/latest";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
zed.resetZedClientVersionCache();
|
||||
});
|
||||
|
||||
test("a fetched version newer than the pin is returned", async () => {
|
||||
const urls: string[] = [];
|
||||
const fetchMock = async (url: string | URL | Request) => {
|
||||
urls.push(String(url));
|
||||
return jsonResponse({ tag_name: "v1.22.0" });
|
||||
};
|
||||
|
||||
assert.equal(await zed.refreshZedClientVersion(fetchMock as typeof fetch), "1.22.0");
|
||||
assert.equal(zed.getZedClientVersion(), "1.22.0");
|
||||
assert.equal(urls.length, 1);
|
||||
assert.equal(urls[0], ZED_RELEASE_URL);
|
||||
});
|
||||
|
||||
test("a fetch that rejects falls back to the pin", async () => {
|
||||
const fetchMock = async () => {
|
||||
throw new Error("github unreachable");
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
await zed.refreshZedClientVersion(fetchMock as typeof fetch),
|
||||
zed.ZED_CLIENT_VERSION
|
||||
);
|
||||
assert.equal(zed.getZedClientVersion(), "0.200.0");
|
||||
});
|
||||
Reference in New Issue
Block a user