b100325fe0
Build Electron Desktop App / Validate version (push) Failing after 29s
Build Electron Desktop App / Build Electron (macos-arm64) (push) Has been skipped
Build Electron Desktop App / Build Electron (linux) (push) Has been skipped
Build Electron Desktop App / Build Electron (macos-intel) (push) Has been skipped
Build Electron Desktop App / Build Electron (windows) (push) Has been skipped
Build Electron Desktop App / Create Release (push) Has been skipped
Build Electron Desktop App / Publish to npm (push) Has been skipped
* feat(qoder): native cosy integration * feat(qoder): implement native COSY encryption algorithm and remove CLI child instances, plus workflow bumps * feat(resilience): context overflow fallback, OAuth token detection, empty content guard & context-optimized combo strategy - Add isContextOverflowError + isContextOverflow detectors (400 + token-limit signals) - Auto-fallback to next family model on context overflow in chatCore - Add isEmptyContentResponse to catch fake-success empty responses, trigger fallback + recursive retry - Add OAUTH_INVALID_TOKEN error type (T11) with isOAuthInvalidToken signal matching; warn instead of deactivating node - Add getModelContextLimit helper in modelsDevSync (reads limit_context from synced capabilities) - Upgrade getTokenLimit in contextManager to check models.dev DB before registry (fixes gemini-2.5-pro: 1000000→1048576) - Add findLargerContextModel in modelFamilyFallback for context-aware model selection - Add sortModelsByContextSize + context-optimized combo strategy in combo.ts - Update context-manager unit test for corrected gemini-2.5-pro limit Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(review): address Gemini code review — tool_calls path, infinite recursion, dedup signals, findLargerContextModel - Fix isEmptyContentResponse: check message.tool_calls/delta.tool_calls instead of firstChoice.tool_calls (wrong OpenAI API path, caused tool-call responses to be falsely flagged as empty) - Fix empty content fallback: replace recursive handleChatCore call (infinite recursion risk + wrong model due to original body.model) with non-recursive pattern — call executeProviderRequest, parse fallback response body, reassign responseBody and fall through to existing processing - Fix context overflow: use findLargerContextModel over family candidates first, fall back to getNextFamilyFallback — ensures we pick a model with actually larger context window on overflow - Fix signal dedup: export CONTEXT_OVERFLOW_SIGNALS + CONTEXT_OVERFLOW_REGEX from errorClassifier.ts; import shared regex in modelFamilyFallback.ts, removing duplicate signal list and per-call RegExp construction Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(UI): add context-optimized strategy to frontend schema and options * fix(sse): preserve Responses API events in stream translation When translating Claude-format responses (e.g. GLM) to Responses API format for Codex CLI, the sanitizer stripped {event, data} structured items to {"object":"chat.completion.chunk"}, losing all content and the critical response.completed event. Only run sanitizeStreamingChunk on OpenAI Chat Completions chunks, skipping items that have the Responses API {event, data} structure. * test(sse): add regression test for Claude→Responses stream sanitization Verifies that {event,data} structured items from the Responses API translator bypass sanitizeStreamingChunk when translating Claude-format providers (e.g. GLM) to Responses API format for Codex CLI. * fix(sse): strengthen Responses API event detection with response. prefix check Use explicit `response.` prefix check instead of generic `event && data` presence check, as recommended in PR review. * fix: pin Next.js to 16.0.10 to prevent Turbopack hashed module bug Remove ^ prefix from next and eslint-config-next to prevent automatic upgrades to 16.1.x+ which introduced content-based hashing for external module references in Turbopack. Also remove duplicate Material Symbols @import from globals.css (font already loaded via <link> in layout.tsx). Fixes #509 * align cc-compatible cache handling with client passthrough * chore: integrate resilience and turbopack fixes (PRs #992, #990, #987) * chore(release): bump to v3.5.2 — changelog, docs, version sync * docs(i18n): sync documentation updates to 33 languages * fix(qoder): replace any with unknown to comply with strict any-budget --------- Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com> Co-authored-by: oyi77 <oyi77@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Chris Staley <christopher-s@users.noreply.github.com> Co-authored-by: Ivan <shanin-i2011@yandex.ru> Co-authored-by: R.D. <rogerproself@gmail.com>
312 lines
8.2 KiB
TypeScript
312 lines
8.2 KiB
TypeScript
/**
|
|
* Cache Control Policy
|
|
*
|
|
* Determines when to preserve client-side prompt caching headers (cache_control)
|
|
* vs. applying OmniRoute's own caching strategy.
|
|
*
|
|
* Client-side caching (e.g., Claude Code) should be preserved when:
|
|
* 1. Client is Claude Code or similar caching-aware client
|
|
* 2. Request will hit a deterministic target (single model or deterministic combo strategy)
|
|
* 3. Provider supports prompt caching (Anthropic, Alibaba Qwen, etc.)
|
|
*/
|
|
|
|
import type { RoutingStrategyValue } from "../../src/shared/constants/routingStrategies";
|
|
|
|
/**
|
|
* Cache control preservation modes
|
|
*/
|
|
export type CacheControlMode = "auto" | "always" | "never";
|
|
|
|
/**
|
|
* Cache control settings from the database
|
|
*/
|
|
export interface CacheControlSettings {
|
|
alwaysPreserveClientCache?: CacheControlMode;
|
|
}
|
|
|
|
/**
|
|
* Cache metrics for tracking effectiveness
|
|
*/
|
|
export interface CacheControlMetrics {
|
|
// Totals
|
|
totalRequests: number;
|
|
requestsWithCacheControl: number;
|
|
|
|
// Token counts
|
|
totalInputTokens: number;
|
|
totalCachedTokens: number;
|
|
totalCacheCreationTokens: number;
|
|
|
|
// Savings
|
|
tokensSaved: number;
|
|
estimatedCostSaved: number;
|
|
|
|
// Breakdowns
|
|
byProvider: Record<
|
|
string,
|
|
{
|
|
requests: number;
|
|
inputTokens: number;
|
|
cachedTokens: number;
|
|
cacheCreationTokens: number;
|
|
}
|
|
>;
|
|
byStrategy: Record<
|
|
string,
|
|
{
|
|
requests: number;
|
|
inputTokens: number;
|
|
cachedTokens: number;
|
|
cacheCreationTokens: number;
|
|
}
|
|
>;
|
|
|
|
lastUpdated: string;
|
|
}
|
|
|
|
/**
|
|
* Routing strategies that are deterministic (same request → same provider)
|
|
*/
|
|
const DETERMINISTIC_STRATEGIES: Set<RoutingStrategyValue> = new Set(["priority", "cost-optimized"]);
|
|
|
|
/**
|
|
* Providers that support prompt caching
|
|
*/
|
|
const CACHING_PROVIDERS = new Set(["claude", "anthropic", "zai", "qwen", "deepseek"]);
|
|
|
|
/**
|
|
* Detect if the client is Claude Code or another caching-aware client
|
|
*/
|
|
export function isClaudeCodeClient(userAgent: string | null | undefined): boolean {
|
|
if (!userAgent) return false;
|
|
const ua = userAgent.toLowerCase();
|
|
|
|
// Claude Code user agents
|
|
if (ua.includes("claude-code") || ua.includes("claude_code")) return true;
|
|
if (ua.includes("anthropic") && ua.includes("cli")) return true;
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Check if a provider supports prompt caching
|
|
* Supports caching if:
|
|
* 1. Provider is in the known caching providers list, OR
|
|
* 2. Provider uses Claude protocol (detected via targetFormat)
|
|
*/
|
|
export function providerSupportsCaching(
|
|
provider: string | null | undefined,
|
|
targetFormat?: string | null
|
|
): boolean {
|
|
if (!provider) return false;
|
|
if (CACHING_PROVIDERS.has(provider.toLowerCase())) return true;
|
|
// All Claude-protocol providers support prompt caching
|
|
if (targetFormat === "claude") return true;
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Check if a routing strategy is deterministic
|
|
*/
|
|
export function isDeterministicStrategy(
|
|
strategy: RoutingStrategyValue | null | undefined
|
|
): boolean {
|
|
if (!strategy) return false;
|
|
return DETERMINISTIC_STRATEGIES.has(strategy);
|
|
}
|
|
|
|
/**
|
|
* Determine if client-side cache_control headers should be preserved
|
|
*
|
|
* @param userAgent - User-Agent header from the request
|
|
* @param isCombo - Whether this is a combo model
|
|
* @param comboStrategy - The combo's routing strategy (if applicable)
|
|
* @param targetProvider - The target provider for the request
|
|
* @param settings - Cache control settings from database (optional)
|
|
* @returns true if cache_control should be preserved, false if OmniRoute should manage it
|
|
*/
|
|
export function shouldPreserveCacheControl({
|
|
userAgent,
|
|
isCombo,
|
|
comboStrategy,
|
|
targetProvider,
|
|
targetFormat,
|
|
settings,
|
|
}: {
|
|
userAgent: string | null | undefined;
|
|
isCombo: boolean;
|
|
comboStrategy?: RoutingStrategyValue | null;
|
|
targetProvider: string | null | undefined;
|
|
targetFormat?: string | null;
|
|
settings?: CacheControlSettings;
|
|
}): boolean {
|
|
// User override takes precedence
|
|
if (settings?.alwaysPreserveClientCache === "always") {
|
|
return true;
|
|
}
|
|
if (settings?.alwaysPreserveClientCache === "never") {
|
|
return false;
|
|
}
|
|
|
|
// Auto mode: use automatic detection (existing logic)
|
|
// Must be a caching-aware client
|
|
if (!isClaudeCodeClient(userAgent)) {
|
|
return false;
|
|
}
|
|
|
|
// Target provider must support caching
|
|
if (!providerSupportsCaching(targetProvider, targetFormat)) {
|
|
return false;
|
|
}
|
|
|
|
// Single model: always preserve (deterministic)
|
|
if (!isCombo) {
|
|
return true;
|
|
}
|
|
|
|
// Combo: only preserve if strategy is deterministic
|
|
return isDeterministicStrategy(comboStrategy);
|
|
}
|
|
|
|
/**
|
|
* Track cache control metrics for a request
|
|
*/
|
|
export function trackCacheMetrics({
|
|
preserved,
|
|
provider,
|
|
strategy,
|
|
metrics,
|
|
inputTokens,
|
|
cachedTokens,
|
|
cacheCreationTokens,
|
|
}: {
|
|
preserved: boolean;
|
|
provider: string;
|
|
strategy: string | null | undefined;
|
|
metrics: CacheControlMetrics;
|
|
inputTokens?: number;
|
|
cachedTokens?: number;
|
|
cacheCreationTokens?: number;
|
|
}): CacheControlMetrics {
|
|
const now = new Date().toISOString();
|
|
|
|
// Initialize metrics if empty
|
|
if (!metrics) {
|
|
metrics = {
|
|
totalRequests: 0,
|
|
requestsWithCacheControl: 0,
|
|
totalInputTokens: 0,
|
|
totalCachedTokens: 0,
|
|
totalCacheCreationTokens: 0,
|
|
tokensSaved: 0,
|
|
estimatedCostSaved: 0,
|
|
byProvider: {},
|
|
byStrategy: {},
|
|
lastUpdated: now,
|
|
};
|
|
}
|
|
|
|
// Increment total requests
|
|
metrics.totalRequests++;
|
|
|
|
// Track token counts
|
|
const input = inputTokens || 0;
|
|
const cached = cachedTokens || 0;
|
|
const creation = cacheCreationTokens || 0;
|
|
|
|
metrics.totalInputTokens += input;
|
|
metrics.totalCachedTokens += cached;
|
|
metrics.totalCacheCreationTokens += creation;
|
|
|
|
// Calculate tokens saved (cached tokens are reused, not charged)
|
|
if (cached > 0) {
|
|
metrics.tokensSaved += cached;
|
|
}
|
|
|
|
// Only track requests where cache_control was preserved
|
|
if (preserved) {
|
|
metrics.requestsWithCacheControl++;
|
|
|
|
// Initialize provider tracking
|
|
if (!metrics.byProvider[provider]) {
|
|
metrics.byProvider[provider] = {
|
|
requests: 0,
|
|
inputTokens: 0,
|
|
cachedTokens: 0,
|
|
cacheCreationTokens: 0,
|
|
};
|
|
}
|
|
metrics.byProvider[provider].requests++;
|
|
metrics.byProvider[provider].inputTokens += input;
|
|
metrics.byProvider[provider].cachedTokens += cached;
|
|
metrics.byProvider[provider].cacheCreationTokens += creation;
|
|
|
|
// Initialize strategy tracking
|
|
if (strategy && !metrics.byStrategy[strategy]) {
|
|
metrics.byStrategy[strategy] = {
|
|
requests: 0,
|
|
inputTokens: 0,
|
|
cachedTokens: 0,
|
|
cacheCreationTokens: 0,
|
|
};
|
|
}
|
|
if (strategy) {
|
|
metrics.byStrategy[strategy].requests++;
|
|
metrics.byStrategy[strategy].inputTokens += input;
|
|
metrics.byStrategy[strategy].cachedTokens += cached;
|
|
metrics.byStrategy[strategy].cacheCreationTokens += creation;
|
|
}
|
|
}
|
|
|
|
metrics.lastUpdated = now;
|
|
return metrics;
|
|
}
|
|
|
|
/**
|
|
* Record cache token usage and update metrics
|
|
*/
|
|
export function updateCacheTokenMetrics({
|
|
metrics,
|
|
provider,
|
|
strategy,
|
|
inputTokens,
|
|
cachedTokens,
|
|
cacheCreationTokens,
|
|
costSaved,
|
|
}: {
|
|
metrics: CacheControlMetrics;
|
|
provider: string;
|
|
strategy: string | null | undefined;
|
|
inputTokens: number;
|
|
cachedTokens: number;
|
|
cacheCreationTokens: number;
|
|
costSaved?: number;
|
|
}): CacheControlMetrics {
|
|
metrics.totalCachedTokens += cachedTokens;
|
|
metrics.totalCacheCreationTokens += cacheCreationTokens;
|
|
metrics.totalInputTokens += inputTokens;
|
|
|
|
// Cached tokens are reused (saved), creation tokens are new cache writes
|
|
metrics.tokensSaved += cachedTokens;
|
|
if (costSaved !== undefined) {
|
|
metrics.estimatedCostSaved += costSaved;
|
|
}
|
|
|
|
// Update provider tracking
|
|
if (metrics.byProvider[provider]) {
|
|
metrics.byProvider[provider].cachedTokens += cachedTokens;
|
|
metrics.byProvider[provider].cacheCreationTokens += cacheCreationTokens;
|
|
metrics.byProvider[provider].inputTokens += inputTokens;
|
|
}
|
|
|
|
// Update strategy tracking
|
|
if (strategy && metrics.byStrategy[strategy]) {
|
|
metrics.byStrategy[strategy].cachedTokens += cachedTokens;
|
|
metrics.byStrategy[strategy].cacheCreationTokens += cacheCreationTokens;
|
|
metrics.byStrategy[strategy].inputTokens += inputTokens;
|
|
}
|
|
|
|
metrics.lastUpdated = new Date().toISOString();
|
|
return metrics;
|
|
}
|