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: preserve key_value settings across DB recreation (#1333)
Paijo4eedf4d1cd80
diff --git a/open-sse/services/accountFallback.ts b/open-sse/services/accountFallback.tsindex cfd621dcaa..95bdf510df 100644--- a/open-sse/services/accountFallback.ts+++ b/open-sse/services/accountFallback.ts@@ -61,6 +61,31 @@ export const OAUTH_INVALID_TOKEN_SIGNALS = ["invalid credentials",];+// Context overflow patterns — the prompt exceeds the model's maximum context length.+// Different providers phrase this differently. Used to decide whether a 400 error+// should trigger combo fallback (a different model may have a larger context window).+const CONTEXT_OVERFLOW_PATTERNS = [+ /\binput is too long\b/i,+ /\binput too long\b/i,+ /\bcontext.*(too long|exceeded|overflow|limit)/i,+ /\btoo many tokens\b/i,+ /\bprompt is too long\b/i,+ /\bcontext window/i,+ /\bmaximum context/i,+ /\bmax.*token/i,+ /\btoken limit/i,+ /\brequest too large\b/i,+];++// Malformed request patterns — the model rejected the message format but a different+// provider/model in the combo may accept it.+const MALFORMED_REQUEST_PATTERNS = [+ /\bimproperly formed request\b/i,+ /\binvalid.*message.*format/i,+ /\bmessages must alternate/i,+ /\bempty (message|content)/i,+];+/*** T06: Returns true if response body indicates the account is permanently deactivated.*/@@ -860,8 +885,20 @@ export function checkFallbackError(};}- // 400 Bad Request - don't fallback (same request will fail on all accounts)+ // 400 — context overflow / malformed request may succeed on another model in the comboif (status === HTTP_STATUS.BAD_REQUEST) {+ const isOverflow = CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(errorStr));+ const isMalformed = MALFORMED_REQUEST_PATTERNS.some((p) => p.test(errorStr));++ if (isOverflow || isMalformed) {+ return {+ shouldFallback: true,+ cooldownMs: 0,+ reason: RateLimitReason.MODEL_CAPACITY,+ };+ }++ // Generic 400 — same request will likely fail on all accounts; don't fallback.return { shouldFallback: false, cooldownMs: 0, reason: RateLimitReason.UNKNOWN };}diff --git a/src/lib/db/core.ts b/src/lib/db/core.tsindex 3e07a1619d..00d9c6c1d1 100644--- a/src/lib/db/core.ts+++ b/src/lib/db/core.ts@@ -771,6 +771,54 @@ export function getDbInstance(): SqliteDatabase {}const jsonDbFile = JSON_DB_FILE;+ // ── key_value Preservation Guard (#1332) ──+ // Before any potential DB file rename/recreation, read all key_value data+ // so it can be restored if the DB is recreated from scratch (e.g., schema+ // mismatch, probe failure, or npm update wiping the file).+ const SKIP_PRESERVE_NAMESPACES = new Set([+ "syncedAvailableModels",+ "providerLimitsCache",+ "lkgp",+ ]);+ const KEY_VALUE_PRESERVE_LIMIT = 10_000;+ let preservedKeyValue: Array<{ namespace: string; key: string; value: string }> = [];++ if (!isCloud && SQLITE_FILE && fs.existsSync(sqliteFile)) {+ try {+ const kvProbe = new Database(sqliteFile, { readonly: true });+ try {+ const hasKv = kvProbe+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='key_value'")+ .get();+ if (hasKv) {+ const rowCount = (kvProbe.prepare("SELECT COUNT(*) AS c FROM key_value").get() as { c: number }).c;+ if (rowCount > KEY_VALUE_PRESERVE_LIMIT) {+ console.warn(+ `[DB] key_value has ${rowCount} rows (limit ${KEY_VALUE_PRESERVE_LIMIT}), skipping preservation`+ );+ } else {+ preservedKeyValue = kvProbe+ .prepare("SELECT namespace, key, value FROM key_value")+ .all() as Array<{ namespace: string; key: string; value: string }>;+ preservedKeyValue = preservedKeyValue.filter(+ (row) => !SKIP_PRESERVE_NAMESPACES.has(row.namespace)+ );+ if (preservedKeyValue.length > 0) {+ console.log(+ `[DB] Preserved ${preservedKeyValue.length} key_value entries before potential recreation`+ );+ }+ }+ }+ } finally {+ kvProbe.close();+ }+ } catch (e: unknown) {+ const message = e instanceof Error ? e.message : String(e);+ console.warn(`[DB] Could not preserve key_value: ${message}`);+ }+ }+// Detect and handle old schema format — preserve data when possible (#146)// Uses a single probe connection that becomes the real connection when possible.if (fs.existsSync(sqliteFile)) {@@ -943,6 +991,23 @@ export function getDbInstance(): SqliteDatabase {migrateFromJson(db, jsonDbFile);}+ // ── key_value Restoration (#1332) ──+ // Restore preserved key_value data that was read before potential DB recreation.+ // Uses INSERT OR IGNORE so fresh defaults seeded by migrations are not overwritten.+ if (preservedKeyValue.length > 0) {+ const insertKv = db.prepare(+ "INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES (?, ?, ?)"+ );+ const restoreKv = db.transaction(() => {+ for (const row of preservedKeyValue) {+ insertKv.run(row.namespace, row.key, row.value);+ }+ });+ restoreKv();+ console.log(`[DB] Restored ${preservedKeyValue.length} preserved key_value entries`);+ preservedKeyValue = [];+ }+// Store schema versionconst versionStmt = db.prepare("INSERT OR REPLACE INTO db_meta (key, value) VALUES ('schema_version', '1')"