Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix: address reset-aware routing review feedback
Jan Leon269186b9d196
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.tsindex 2205d2841c..4f17162dc5 100644--- a/open-sse/services/combo.ts+++ b/open-sse/services/combo.ts@@ -741,7 +741,8 @@ function resolveResetAwareConfig(config: Record<string, unknown> | null | undefiRESET_AWARE_DEFAULTS.weeklyWeight);const totalWeight = sessionWeight + weeklyWeight;- const normalizedSessionWeight = totalWeight > 0 ? sessionWeight / totalWeight : 0.35;+ const normalizedSessionWeight =+ totalWeight > 0 ? sessionWeight / totalWeight : RESET_AWARE_DEFAULTS.sessionWeight;return {sessionWeight: normalizedSessionWeight,@@ -776,7 +777,7 @@ function getQuotaWindow(function getResetUrgency(resetAt: string | null | undefined, windowMs: number): number {if (!resetAt) return 0.5;- const resetTime = new Date(resetAt).getTime();+ const resetTime = resetAt ? new Date(resetAt).getTime() : NaN;if (!Number.isFinite(resetTime)) return 0.5;const msUntilReset = resetTime - Date.now();if (msUntilReset <= 0) return 1;@@ -824,7 +825,9 @@ function scoreResetAwareQuota(quota: unknown, config: ReturnType<typeof resolveRasync function getQuotaAwareConnectionsForTarget(target: ResolvedComboTarget,- connectionCache: Map<string, Array<Record<string, unknown>>>+ connectionCache: Map<string, Array<Record<string, unknown>>>,+ comboName: string,+ log: { warn?: (...args: unknown[]) => void }) {const provider = getResetAwareProvider(target);if (!provider || !getQuotaFetcher(provider)) return [];@@ -835,34 +838,69 @@ async function getQuotaAwareConnectionsForTarget(provider,Array.isArray(connections) ? (connections as Array<Record<string, unknown>>) : []);- } catch {+ } catch (error) {+ log.warn?.("COMBO", "Reset-aware failed to load quota-aware connections.", {+ comboName,+ err: error,+ operation: "getProviderConnections",+ provider,+ });connectionCache.set(provider, []);}}return connectionCache.get(provider) || [];}+function normalizeConnectionIds(value: unknown): string[] | null {+ if (!Array.isArray(value)) return null;+ const ids = value.filter(+ (connectionId): connectionId is string =>+ typeof connectionId === "string" && connectionId.trim().length > 0+ );+ return ids.length > 0 ? ids : null;+}++function filterAllowedConnectionIds(+ connectionIds: string[],+ apiKeyAllowedConnectionIds: string[] | null | undefined+): string[] {+ const allowedIds = normalizeConnectionIds(apiKeyAllowedConnectionIds);+ if (!allowedIds) return connectionIds;+ const allowedSet = new Set(allowedIds);+ return connectionIds.filter((connectionId) => allowedSet.has(connectionId));+}+function getTargetConnectionIds(target: ResolvedComboTarget,- connections: Array<Record<string, unknown>>+ connections: Array<Record<string, unknown>>,+ apiKeyAllowedConnectionIds?: string[] | null): string[] {- if (target.connectionId) return [target.connectionId];+ let connectionIds: string[];+ if (target.connectionId) {+ connectionIds = [target.connectionId];+ return filterAllowedConnectionIds(connectionIds, apiKeyAllowedConnectionIds);+ }+if (Array.isArray(target.allowedConnectionIds) && target.allowedConnectionIds.length > 0) {- return target.allowedConnectionIds.filter(+ connectionIds = target.allowedConnectionIds.filter((connectionId): connectionId is string =>typeof connectionId === "string" && connectionId.trim().length > 0);+ return filterAllowedConnectionIds(connectionIds, apiKeyAllowedConnectionIds);}- return connections++ connectionIds = connections.map((connection) => (typeof connection.id === "string" ? connection.id : null)).filter((connectionId): connectionId is string => !!connectionId);+ return filterAllowedConnectionIds(connectionIds, apiKeyAllowedConnectionIds);}async function orderTargetsByResetAwareQuota(targets: ResolvedComboTarget[],comboName: string,configSource: Record<string, unknown> | null | undefined,- log: { warn?: (...args: unknown[]) => void }+ log: { warn?: (...args: unknown[]) => void },+ apiKeyAllowedConnectionIds?: string[] | null) {if (targets.length === 0) return targets;@@ -871,14 +909,30 @@ async function orderTargetsByResetAwareQuota(const connectionById = new Map<string, Record<string, unknown>>();const expandedTargets: ResolvedComboTarget[] = [];- for (const target of targets) {- const connections = await getQuotaAwareConnectionsForTarget(target, connectionCache);+ const targetsWithConnections = await Promise.all(+ targets.map(async (target) => ({+ connections: await getQuotaAwareConnectionsForTarget(target, connectionCache, comboName, log),+ target,+ }))+ );++ for (const { target, connections } of targetsWithConnections) {for (const connection of connections) {if (typeof connection.id === "string") connectionById.set(connection.id, connection);}- const connectionIds = getTargetConnectionIds(target, connections);+ const unrestrictedConnectionIds = getTargetConnectionIds(target, connections);+ const connectionIds = filterAllowedConnectionIds(+ unrestrictedConnectionIds,+ apiKeyAllowedConnectionIds+ );if (connectionIds.length === 0) {+ if (+ unrestrictedConnectionIds.length > 0 &&+ normalizeConnectionIds(apiKeyAllowedConnectionIds)+ ) {+ continue;+ }expandedTargets.push(target);continue;}@@ -904,10 +958,13 @@ async function orderTargetsByResetAwareQuota(try {quota = await fetcher(target.connectionId, connectionById.get(target.connectionId));} catch (error) {- log.warn?.(- "COMBO",- `Reset-aware quota fetch failed for provider=${provider} connection=${target.connectionId}: ${error instanceof Error ? error.message : String(error)}`- );+ log.warn?.("COMBO", "Reset-aware quota fetch failed.", {+ comboName,+ connectionId: target.connectionId,+ err: error,+ operation: "quotaFetch",+ provider,+ });}}const { score } = scoreResetAwareQuota(quota, config);@@ -1315,6 +1372,7 @@ export async function handleComboChat({allCombos,relayOptions,signal,+ apiKeyAllowedConnections = null,}) {const strategy = normalizeRoutingStrategy(combo.strategy || "priority");const relayConfig =@@ -1724,7 +1782,13 @@ export async function handleComboChat({orderedTargets = await sortTargetsByCost(orderedTargets);log.info("COMBO", `Cost-optimized ordering: cheapest first (${orderedTargets[0]?.modelStr})`);} else if (strategy === "reset-aware") {- orderedTargets = await orderTargetsByResetAwareQuota(orderedTargets, combo.name, config, log);+ orderedTargets = await orderTargetsByResetAwareQuota(+ orderedTargets,+ combo.name,+ config,+ log,+ apiKeyAllowedConnections+ );log.info("COMBO",`Reset-aware ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} first`diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.tsindex b8fcc35448..0d13eda7cb 100644--- a/src/sse/handlers/chat.ts+++ b/src/sse/handlers/chat.ts@@ -370,6 +370,7 @@ export async function handleChat(request: any, clientRawRequest: any = null) {log,settings,allCombos,+ apiKeyAllowedConnections: apiKeyInfo?.allowedConnections ?? null,relayOptions:combo.strategy === "context-relay"? {diff --git a/tests/unit/combo-strategies.test.ts b/tests/unit/combo-strategies.test.tsindex ded0f90763..6909faebff 100644--- a/tests/unit/combo-strategies.test.ts+++ b/tests/unit/combo-strategies.test.ts@@ -16,6 +16,7 @@ const { invalidateCodexQuotaCache, registerCodexConnection, registerCodexQuotaFeawait import("../../open-sse/services/codexQuotaFetcher.ts");const { registerQuotaFetcher } = await import("../../open-sse/services/quotaPreflight.ts");const combosDb = await import("../../src/lib/db/combos.ts");+const providersDb = await import("../../src/lib/db/providers.ts");const { recordComboRequest } = await import("../../open-sse/services/comboMetrics.ts");const { saveModelsDevCapabilities } = await import("../../src/lib/modelsDevSync.ts");@@ -125,6 +126,7 @@ function codexQuota({}function installCodexQuotaMock(quotasByToken: Record<string, unknown>) {+ const previousFetch = globalThis.fetch;globalThis.fetch = async (_input: RequestInfo | URL, init?: RequestInit) => {const headers = init?.headers as Record<string, string> | undefined;const authorization = headers?.Authorization || headers?.authorization || "";@@ -133,6 +135,9 @@ function installCodexQuotaMock(quotasByToken: Record<string, unknown>) {if (!quota) return Response.json({ error: "missing quota" }, { status: 404 });return Response.json(quota);};+ return () => {+ globalThis.fetch = previousFetch;+ };}function resetAwareCombo(@@ -162,7 +167,10 @@ function resetAwareCombo(};}-async function selectedConnectionFor(combo: Record<string, unknown>) {+async function selectedConnectionFor(+ combo: Record<string, unknown>,+ options: { apiKeyAllowedConnections?: string[] | null } = {}+) {const calls: Array<string | null> = [];const response = await handleComboChat({body: reqBodyTextArray,@@ -173,10 +181,11 @@ async function selectedConnectionFor(combo: Record<string, unknown>) {signal: undefined,settings: {},log: makeLog(),+ apiKeyAllowedConnections: options.apiKeyAllowedConnections,handleSingleModel: async (_body: unknown,modelStr: string,- target?: { connectionId?: string | null }+ target?: { connectionId?: string | null; allowedConnectionIds?: string[] | null }) => {calls.push(target?.connectionId ?? null);return okResponse(modelStr);@@ -242,30 +251,32 @@ test("auto strategy handles null and empty prompt edge cases without throwing",assert.equal(await selectedModelFor(combo, { model: combo.name, messages: [] }), "openai/gpt-4");});-test("reset-aware strategy prefers lower weekly remaining quota when reset is much sooner", async () => {+test("reset-aware strategy prefers lower weekly remaining quota when reset is much sooner", async (t) => {const soon = { id: `soon-${randomUUID()}`, token: `token-soon-${randomUUID()}` };const later = { id: `later-${randomUUID()}`, token: `token-later-${randomUUID()}` };- installCodexQuotaMock({- [soon.token]: codexQuota({- used5h: 10,- reset5hSeconds: 3600,- used7d: 40,- reset7dSeconds: 24 * 3600,- }),- [later.token]: codexQuota({- used5h: 10,- reset5hSeconds: 3600,- used7d: 20,- reset7dSeconds: 5 * 24 * 3600,- }),- });+ t.after(+ installCodexQuotaMock({+ [soon.token]: codexQuota({+ used5h: 10,+ reset5hSeconds: 3600,+ used7d: 40,+ reset7dSeconds: 24 * 3600,+ }),+ [later.token]: codexQuota({+ used5h: 10,+ reset5hSeconds: 3600,+ used7d: 20,+ reset7dSeconds: 5 * 24 * 3600,+ }),+ })+ );const combo = resetAwareCombo(`reset-aware-soon-${randomUUID()}`, [soon, later]);assert.equal(await selectedConnectionFor(combo), soon.id);});-test("reset-aware strategy avoids accounts near 5h exhaustion", async () => {+test("reset-aware strategy avoids accounts near 5h exhaustion", async (t) => {const exhausted5h = {id: `exhausted-${randomUUID()}`,token: `token-exhausted-${randomUUID()}`,@@ -274,27 +285,29 @@ test("reset-aware strategy avoids accounts near 5h exhaustion", async () => {id: `healthy-${randomUUID()}`,token: `token-healthy-${randomUUID()}`,};- installCodexQuotaMock({- [exhausted5h.token]: codexQuota({- used5h: 98,- reset5hSeconds: 20 * 60,- used7d: 5,- reset7dSeconds: 24 * 3600,- }),- [healthy5h.token]: codexQuota({- used5h: 20,- reset5hSeconds: 4 * 3600,- used7d: 50,- reset7dSeconds: 4 * 24 * 3600,- }),- });+ t.after(+ installCodexQuotaMock({+ [exhausted5h.token]: codexQuota({+ used5h: 98,+ reset5hSeconds: 20 * 60,+ used7d: 5,+ reset7dSeconds: 24 * 3600,+ }),+ [healthy5h.token]: codexQuota({+ used5h: 20,+ reset5hSeconds: 4 * 3600,+ used7d: 50,+ reset7dSeconds: 4 * 24 * 3600,+ }),+ })+ );const combo = resetAwareCombo(`reset-aware-guard-${randomUUID()}`, [exhausted5h, healthy5h]);assert.equal(await selectedConnectionFor(combo), healthy5h.id);});-test("reset-aware strategy rotates similar scores with round-robin tie breaking", async () => {+test("reset-aware strategy rotates similar scores with round-robin tie breaking", async (t) => {const first = { id: `first-${randomUUID()}`, token: `token-first-${randomUUID()}` };const second = {id: `second-${randomUUID()}`,@@ -308,10 +321,12 @@ test("reset-aware strategy rotates similar scores with round-robin tie breaking"secondary_window: { used_percent: 50, reset_at: reset7dAt },},};- installCodexQuotaMock({- [first.token]: quota,- [second.token]: quota,- });+ t.after(+ installCodexQuotaMock({+ [first.token]: quota,+ [second.token]: quota,+ })+ );const combo = resetAwareCombo(`reset-aware-rr-${randomUUID()}`, [first, second], {resetAwareTieBandPercent: 100,@@ -360,6 +375,57 @@ test("reset-aware strategy uses registered quota fetchers for non-Codex providerassert.equal(await selectedConnectionFor(combo), soon);});+test("reset-aware strategy respects API-key allowed connections during expansion", async () => {+ const provider = `limited-provider-${randomUUID()}`;+ const disallowed = await providersDb.createProviderConnection({+ provider,+ authType: "apikey",+ name: `disallowed-${randomUUID()}`,+ apiKey: "sk-disallowed",+ isActive: true,+ });+ const allowed = await providersDb.createProviderConnection({+ provider,+ authType: "apikey",+ name: `allowed-${randomUUID()}`,+ apiKey: "sk-allowed",+ isActive: true,+ });+ const allowedId = String(allowed.id);+ const disallowedId = String(disallowed.id);+ const fetchedConnectionIds: string[] = [];++ registerQuotaFetcher(provider, async (connectionId) => {+ fetchedConnectionIds.push(connectionId);+ return {+ used: connectionId === disallowedId ? 60 : 20,+ total: 100,+ percentUsed: connectionId === disallowedId ? 0.6 : 0.2,+ resetAt: new Date(Date.now() + 24 * 3600 * 1000).toISOString(),+ };+ });++ const combo = {+ name: `reset-aware-api-key-${randomUUID()}`,+ strategy: "reset-aware",+ models: [+ {+ kind: "model",+ provider,+ providerId: provider,+ model: "balanced-model",+ id: "limited-provider-step",+ },+ ],+ };++ assert.equal(+ await selectedConnectionFor(combo, { apiKeyAllowedConnections: [allowedId] }),+ allowedId+ );+ assert.deepEqual(fetchedConnectionIds, [allowedId]);+});+test("reset-aware strategy scores provider-specific weekly windows when available", async () => {const provider = `weekly-provider-${randomUUID()}`;const soon = `weekly-soon-${randomUUID()}`;