Просмотр исходного кода

feat: add codex priority billing source setting (#960)

* feat: add codex priority billing source setting

* fix: address codex priority billing review comments
Ding 3 недель назад
Родитель
Сommit
040b9d030d
30 измененных файлов с 5022 добавлено и 163 удалено
  1. 1 0
      drizzle/0085_busy_ken_ellis.sql
  2. 4009 0
      drizzle/meta/0085_snapshot.json
  3. 7 0
      drizzle/meta/_journal.json
  4. 7 0
      messages/en/settings/config.json
  5. 7 0
      messages/ja/settings/config.json
  6. 7 0
      messages/ru/settings/config.json
  7. 7 0
      messages/zh-CN/settings/config.json
  8. 7 0
      messages/zh-TW/settings/config.json
  9. 7 1
      src/actions/system-config.ts
  10. 37 1
      src/app/[locale]/settings/config/_components/system-settings-form.tsx
  11. 1 0
      src/app/[locale]/settings/config/page.tsx
  12. 4 0
      src/app/api/admin/system-config/route.ts
  13. 88 65
      src/app/v1/_lib/proxy/response-handler.ts
  14. 103 26
      src/app/v1/_lib/proxy/session.ts
  15. 5 0
      src/drizzle/schema.ts
  16. 1 0
      src/lib/config/index.ts
  17. 11 0
      src/lib/config/system-settings-cache.ts
  18. 7 1
      src/lib/utils/special-settings.ts
  19. 3 0
      src/lib/validation/schemas.ts
  20. 3 0
      src/repository/_shared/transformers.test.ts
  21. 5 0
      src/repository/_shared/transformers.ts
  22. 130 58
      src/repository/system-config.ts
  23. 2 0
      src/types/special-settings.ts
  24. 7 0
      src/types/system-config.ts
  25. 272 5
      tests/integration/billing-model-source.test.ts
  26. 16 0
      tests/unit/actions/system-config-save.test.ts
  27. 2 0
      tests/unit/lib/config/system-settings-cache.test.ts
  28. 22 1
      tests/unit/lib/utils/special-settings.test.ts
  29. 16 5
      tests/unit/proxy/session.test.ts
  30. 228 0
      tests/unit/repository/system-config-update-missing-columns.test.ts

+ 1 - 0
drizzle/0085_busy_ken_ellis.sql

@@ -0,0 +1 @@
+ALTER TABLE "system_settings" ADD COLUMN "codex_priority_billing_source" varchar(20) DEFAULT 'requested' NOT NULL;

+ 4009 - 0
drizzle/meta/0085_snapshot.json

@@ -0,0 +1,4009 @@
+{
+  "id": "70edcf0a-ce4e-4951-9ebf-d92e95632f7c",
+  "prevId": "1d1ba01c-7adc-467e-bc9c-90abab9e5b92",
+  "version": "7",
+  "dialect": "postgresql",
+  "tables": {
+    "public.error_rules": {
+      "name": "error_rules",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "pattern": {
+          "name": "pattern",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "match_type": {
+          "name": "match_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'regex'"
+        },
+        "category": {
+          "name": "category",
+          "type": "varchar(50)",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "description": {
+          "name": "description",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "override_response": {
+          "name": "override_response",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "override_status_code": {
+          "name": "override_status_code",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "is_default": {
+          "name": "is_default",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "priority": {
+          "name": "priority",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 0
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {
+        "idx_error_rules_enabled": {
+          "name": "idx_error_rules_enabled",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "priority",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "unique_pattern": {
+          "name": "unique_pattern",
+          "columns": [
+            {
+              "expression": "pattern",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": true,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_category": {
+          "name": "idx_category",
+          "columns": [
+            {
+              "expression": "category",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_match_type": {
+          "name": "idx_match_type",
+          "columns": [
+            {
+              "expression": "match_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.keys": {
+      "name": "keys",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "user_id": {
+          "name": "user_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "key": {
+          "name": "key",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "name": {
+          "name": "name",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": true
+        },
+        "expires_at": {
+          "name": "expires_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "can_login_web_ui": {
+          "name": "can_login_web_ui",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "limit_5h_usd": {
+          "name": "limit_5h_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_daily_usd": {
+          "name": "limit_daily_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "daily_reset_mode": {
+          "name": "daily_reset_mode",
+          "type": "daily_reset_mode",
+          "typeSchema": "public",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'fixed'"
+        },
+        "daily_reset_time": {
+          "name": "daily_reset_time",
+          "type": "varchar(5)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'00:00'"
+        },
+        "limit_weekly_usd": {
+          "name": "limit_weekly_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_monthly_usd": {
+          "name": "limit_monthly_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_total_usd": {
+          "name": "limit_total_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cost_reset_at": {
+          "name": "cost_reset_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_concurrent_sessions": {
+          "name": "limit_concurrent_sessions",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 0
+        },
+        "provider_group": {
+          "name": "provider_group",
+          "type": "varchar(200)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'default'"
+        },
+        "cache_ttl_preference": {
+          "name": "cache_ttl_preference",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "deleted_at": {
+          "name": "deleted_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        }
+      },
+      "indexes": {
+        "idx_keys_user_id": {
+          "name": "idx_keys_user_id",
+          "columns": [
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_keys_key": {
+          "name": "idx_keys_key",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_keys_created_at": {
+          "name": "idx_keys_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_keys_deleted_at": {
+          "name": "idx_keys_deleted_at",
+          "columns": [
+            {
+              "expression": "deleted_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.message_request": {
+      "name": "message_request",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "provider_id": {
+          "name": "provider_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "user_id": {
+          "name": "user_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "key": {
+          "name": "key",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "model": {
+          "name": "model",
+          "type": "varchar(128)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "duration_ms": {
+          "name": "duration_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cost_usd": {
+          "name": "cost_usd",
+          "type": "numeric(21, 15)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0'"
+        },
+        "cost_multiplier": {
+          "name": "cost_multiplier",
+          "type": "numeric(10, 4)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "session_id": {
+          "name": "session_id",
+          "type": "varchar(64)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "request_sequence": {
+          "name": "request_sequence",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 1
+        },
+        "provider_chain": {
+          "name": "provider_chain",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "status_code": {
+          "name": "status_code",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "api_type": {
+          "name": "api_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "endpoint": {
+          "name": "endpoint",
+          "type": "varchar(256)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "original_model": {
+          "name": "original_model",
+          "type": "varchar(128)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "input_tokens": {
+          "name": "input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "output_tokens": {
+          "name": "output_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "ttfb_ms": {
+          "name": "ttfb_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_creation_input_tokens": {
+          "name": "cache_creation_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_read_input_tokens": {
+          "name": "cache_read_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_creation_5m_input_tokens": {
+          "name": "cache_creation_5m_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_creation_1h_input_tokens": {
+          "name": "cache_creation_1h_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_ttl_applied": {
+          "name": "cache_ttl_applied",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "context_1m_applied": {
+          "name": "context_1m_applied",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "swap_cache_ttl_applied": {
+          "name": "swap_cache_ttl_applied",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "special_settings": {
+          "name": "special_settings",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "error_message": {
+          "name": "error_message",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "error_stack": {
+          "name": "error_stack",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "error_cause": {
+          "name": "error_cause",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "blocked_by": {
+          "name": "blocked_by",
+          "type": "varchar(50)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "blocked_reason": {
+          "name": "blocked_reason",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "user_agent": {
+          "name": "user_agent",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "messages_count": {
+          "name": "messages_count",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "deleted_at": {
+          "name": "deleted_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        }
+      },
+      "indexes": {
+        "idx_message_request_user_date_cost": {
+          "name": "idx_message_request_user_date_cost",
+          "columns": [
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "cost_usd",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_user_created_at_cost_stats": {
+          "name": "idx_message_request_user_created_at_cost_stats",
+          "columns": [
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "cost_usd",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND (\"message_request\".\"blocked_by\" IS NULL OR \"message_request\".\"blocked_by\" <> 'warmup')",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_user_query": {
+          "name": "idx_message_request_user_query",
+          "columns": [
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_provider_created_at_active": {
+          "name": "idx_message_request_provider_created_at_active",
+          "columns": [
+            {
+              "expression": "provider_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND (\"message_request\".\"blocked_by\" IS NULL OR \"message_request\".\"blocked_by\" <> 'warmup')",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_session_id": {
+          "name": "idx_message_request_session_id",
+          "columns": [
+            {
+              "expression": "session_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_session_id_prefix": {
+          "name": "idx_message_request_session_id_prefix",
+          "columns": [
+            {
+              "expression": "\"session_id\" varchar_pattern_ops",
+              "asc": true,
+              "isExpression": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND (\"message_request\".\"blocked_by\" IS NULL OR \"message_request\".\"blocked_by\" <> 'warmup')",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_session_seq": {
+          "name": "idx_message_request_session_seq",
+          "columns": [
+            {
+              "expression": "session_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "request_sequence",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_endpoint": {
+          "name": "idx_message_request_endpoint",
+          "columns": [
+            {
+              "expression": "endpoint",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_blocked_by": {
+          "name": "idx_message_request_blocked_by",
+          "columns": [
+            {
+              "expression": "blocked_by",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_provider_id": {
+          "name": "idx_message_request_provider_id",
+          "columns": [
+            {
+              "expression": "provider_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_user_id": {
+          "name": "idx_message_request_user_id",
+          "columns": [
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_key": {
+          "name": "idx_message_request_key",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_key_created_at_id": {
+          "name": "idx_message_request_key_created_at_id",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            },
+            {
+              "expression": "id",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_key_model_active": {
+          "name": "idx_message_request_key_model_active",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "model",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND \"message_request\".\"model\" IS NOT NULL AND (\"message_request\".\"blocked_by\" IS NULL OR \"message_request\".\"blocked_by\" <> 'warmup')",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_key_endpoint_active": {
+          "name": "idx_message_request_key_endpoint_active",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "endpoint",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND \"message_request\".\"endpoint\" IS NOT NULL AND (\"message_request\".\"blocked_by\" IS NULL OR \"message_request\".\"blocked_by\" <> 'warmup')",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_created_at_id_active": {
+          "name": "idx_message_request_created_at_id_active",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            },
+            {
+              "expression": "id",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_model_active": {
+          "name": "idx_message_request_model_active",
+          "columns": [
+            {
+              "expression": "model",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND \"message_request\".\"model\" IS NOT NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_status_code_active": {
+          "name": "idx_message_request_status_code_active",
+          "columns": [
+            {
+              "expression": "status_code",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND \"message_request\".\"status_code\" IS NOT NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_created_at": {
+          "name": "idx_message_request_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_deleted_at": {
+          "name": "idx_message_request_deleted_at",
+          "columns": [
+            {
+              "expression": "deleted_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_key_last_active": {
+          "name": "idx_message_request_key_last_active",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND (\"message_request\".\"blocked_by\" IS NULL OR \"message_request\".\"blocked_by\" <> 'warmup')",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_key_cost_active": {
+          "name": "idx_message_request_key_cost_active",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "cost_usd",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL AND (\"message_request\".\"blocked_by\" IS NULL OR \"message_request\".\"blocked_by\" <> 'warmup')",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_message_request_session_user_info": {
+          "name": "idx_message_request_session_user_info",
+          "columns": [
+            {
+              "expression": "session_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"message_request\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.model_prices": {
+      "name": "model_prices",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "model_name": {
+          "name": "model_name",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "price_data": {
+          "name": "price_data",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "source": {
+          "name": "source",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'litellm'"
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {
+        "idx_model_prices_latest": {
+          "name": "idx_model_prices_latest",
+          "columns": [
+            {
+              "expression": "model_name",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_model_prices_model_name": {
+          "name": "idx_model_prices_model_name",
+          "columns": [
+            {
+              "expression": "model_name",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_model_prices_created_at": {
+          "name": "idx_model_prices_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_model_prices_source": {
+          "name": "idx_model_prices_source",
+          "columns": [
+            {
+              "expression": "source",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.notification_settings": {
+      "name": "notification_settings",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "enabled": {
+          "name": "enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "use_legacy_mode": {
+          "name": "use_legacy_mode",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "circuit_breaker_enabled": {
+          "name": "circuit_breaker_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "circuit_breaker_webhook": {
+          "name": "circuit_breaker_webhook",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "daily_leaderboard_enabled": {
+          "name": "daily_leaderboard_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "daily_leaderboard_webhook": {
+          "name": "daily_leaderboard_webhook",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "daily_leaderboard_time": {
+          "name": "daily_leaderboard_time",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'09:00'"
+        },
+        "daily_leaderboard_top_n": {
+          "name": "daily_leaderboard_top_n",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 5
+        },
+        "cost_alert_enabled": {
+          "name": "cost_alert_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "cost_alert_webhook": {
+          "name": "cost_alert_webhook",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cost_alert_threshold": {
+          "name": "cost_alert_threshold",
+          "type": "numeric(5, 2)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.80'"
+        },
+        "cost_alert_check_interval": {
+          "name": "cost_alert_check_interval",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 60
+        },
+        "cache_hit_rate_alert_enabled": {
+          "name": "cache_hit_rate_alert_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "cache_hit_rate_alert_webhook": {
+          "name": "cache_hit_rate_alert_webhook",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_hit_rate_alert_window_mode": {
+          "name": "cache_hit_rate_alert_window_mode",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'auto'"
+        },
+        "cache_hit_rate_alert_check_interval": {
+          "name": "cache_hit_rate_alert_check_interval",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 5
+        },
+        "cache_hit_rate_alert_historical_lookback_days": {
+          "name": "cache_hit_rate_alert_historical_lookback_days",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 7
+        },
+        "cache_hit_rate_alert_min_eligible_requests": {
+          "name": "cache_hit_rate_alert_min_eligible_requests",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 20
+        },
+        "cache_hit_rate_alert_min_eligible_tokens": {
+          "name": "cache_hit_rate_alert_min_eligible_tokens",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 0
+        },
+        "cache_hit_rate_alert_abs_min": {
+          "name": "cache_hit_rate_alert_abs_min",
+          "type": "numeric(5, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.05'"
+        },
+        "cache_hit_rate_alert_drop_rel": {
+          "name": "cache_hit_rate_alert_drop_rel",
+          "type": "numeric(5, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.3'"
+        },
+        "cache_hit_rate_alert_drop_abs": {
+          "name": "cache_hit_rate_alert_drop_abs",
+          "type": "numeric(5, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.1'"
+        },
+        "cache_hit_rate_alert_cooldown_minutes": {
+          "name": "cache_hit_rate_alert_cooldown_minutes",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 30
+        },
+        "cache_hit_rate_alert_top_n": {
+          "name": "cache_hit_rate_alert_top_n",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 10
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {},
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.notification_target_bindings": {
+      "name": "notification_target_bindings",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "notification_type": {
+          "name": "notification_type",
+          "type": "notification_type",
+          "typeSchema": "public",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "target_id": {
+          "name": "target_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "schedule_cron": {
+          "name": "schedule_cron",
+          "type": "varchar(100)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "schedule_timezone": {
+          "name": "schedule_timezone",
+          "type": "varchar(50)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "template_override": {
+          "name": "template_override",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {
+        "unique_notification_target_binding": {
+          "name": "unique_notification_target_binding",
+          "columns": [
+            {
+              "expression": "notification_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "target_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": true,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_notification_bindings_type": {
+          "name": "idx_notification_bindings_type",
+          "columns": [
+            {
+              "expression": "notification_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_notification_bindings_target": {
+          "name": "idx_notification_bindings_target",
+          "columns": [
+            {
+              "expression": "target_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {
+        "notification_target_bindings_target_id_webhook_targets_id_fk": {
+          "name": "notification_target_bindings_target_id_webhook_targets_id_fk",
+          "tableFrom": "notification_target_bindings",
+          "tableTo": "webhook_targets",
+          "columnsFrom": [
+            "target_id"
+          ],
+          "columnsTo": [
+            "id"
+          ],
+          "onDelete": "cascade",
+          "onUpdate": "no action"
+        }
+      },
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.provider_endpoint_probe_logs": {
+      "name": "provider_endpoint_probe_logs",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "endpoint_id": {
+          "name": "endpoint_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "source": {
+          "name": "source",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'scheduled'"
+        },
+        "ok": {
+          "name": "ok",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "status_code": {
+          "name": "status_code",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "latency_ms": {
+          "name": "latency_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "error_type": {
+          "name": "error_type",
+          "type": "varchar(64)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "error_message": {
+          "name": "error_message",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {
+        "idx_provider_endpoint_probe_logs_endpoint_created_at": {
+          "name": "idx_provider_endpoint_probe_logs_endpoint_created_at",
+          "columns": [
+            {
+              "expression": "endpoint_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_provider_endpoint_probe_logs_created_at": {
+          "name": "idx_provider_endpoint_probe_logs_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {
+        "provider_endpoint_probe_logs_endpoint_id_provider_endpoints_id_fk": {
+          "name": "provider_endpoint_probe_logs_endpoint_id_provider_endpoints_id_fk",
+          "tableFrom": "provider_endpoint_probe_logs",
+          "tableTo": "provider_endpoints",
+          "columnsFrom": [
+            "endpoint_id"
+          ],
+          "columnsTo": [
+            "id"
+          ],
+          "onDelete": "cascade",
+          "onUpdate": "no action"
+        }
+      },
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.provider_endpoints": {
+      "name": "provider_endpoints",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "vendor_id": {
+          "name": "vendor_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "provider_type": {
+          "name": "provider_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'claude'"
+        },
+        "url": {
+          "name": "url",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "label": {
+          "name": "label",
+          "type": "varchar(200)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "sort_order": {
+          "name": "sort_order",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 0
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "last_probed_at": {
+          "name": "last_probed_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "last_probe_ok": {
+          "name": "last_probe_ok",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "last_probe_status_code": {
+          "name": "last_probe_status_code",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "last_probe_latency_ms": {
+          "name": "last_probe_latency_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "last_probe_error_type": {
+          "name": "last_probe_error_type",
+          "type": "varchar(64)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "last_probe_error_message": {
+          "name": "last_probe_error_message",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "deleted_at": {
+          "name": "deleted_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        }
+      },
+      "indexes": {
+        "uniq_provider_endpoints_vendor_type_url": {
+          "name": "uniq_provider_endpoints_vendor_type_url",
+          "columns": [
+            {
+              "expression": "vendor_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "provider_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "url",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": true,
+          "where": "\"provider_endpoints\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_provider_endpoints_vendor_type": {
+          "name": "idx_provider_endpoints_vendor_type",
+          "columns": [
+            {
+              "expression": "vendor_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "provider_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"provider_endpoints\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_provider_endpoints_enabled": {
+          "name": "idx_provider_endpoints_enabled",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "vendor_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "provider_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"provider_endpoints\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_provider_endpoints_pick_enabled": {
+          "name": "idx_provider_endpoints_pick_enabled",
+          "columns": [
+            {
+              "expression": "vendor_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "provider_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "sort_order",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"provider_endpoints\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_provider_endpoints_created_at": {
+          "name": "idx_provider_endpoints_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_provider_endpoints_deleted_at": {
+          "name": "idx_provider_endpoints_deleted_at",
+          "columns": [
+            {
+              "expression": "deleted_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {
+        "provider_endpoints_vendor_id_provider_vendors_id_fk": {
+          "name": "provider_endpoints_vendor_id_provider_vendors_id_fk",
+          "tableFrom": "provider_endpoints",
+          "tableTo": "provider_vendors",
+          "columnsFrom": [
+            "vendor_id"
+          ],
+          "columnsTo": [
+            "id"
+          ],
+          "onDelete": "cascade",
+          "onUpdate": "no action"
+        }
+      },
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.provider_vendors": {
+      "name": "provider_vendors",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "website_domain": {
+          "name": "website_domain",
+          "type": "varchar(255)",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "display_name": {
+          "name": "display_name",
+          "type": "varchar(200)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "website_url": {
+          "name": "website_url",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "favicon_url": {
+          "name": "favicon_url",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {
+        "uniq_provider_vendors_website_domain": {
+          "name": "uniq_provider_vendors_website_domain",
+          "columns": [
+            {
+              "expression": "website_domain",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": true,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_provider_vendors_created_at": {
+          "name": "idx_provider_vendors_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.providers": {
+      "name": "providers",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "name": {
+          "name": "name",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "description": {
+          "name": "description",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "url": {
+          "name": "url",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "key": {
+          "name": "key",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "provider_vendor_id": {
+          "name": "provider_vendor_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "weight": {
+          "name": "weight",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 1
+        },
+        "priority": {
+          "name": "priority",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 0
+        },
+        "group_priorities": {
+          "name": "group_priorities",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'null'::jsonb"
+        },
+        "cost_multiplier": {
+          "name": "cost_multiplier",
+          "type": "numeric(10, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'1.0'"
+        },
+        "group_tag": {
+          "name": "group_tag",
+          "type": "varchar(255)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "provider_type": {
+          "name": "provider_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'claude'"
+        },
+        "preserve_client_ip": {
+          "name": "preserve_client_ip",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "model_redirects": {
+          "name": "model_redirects",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "allowed_models": {
+          "name": "allowed_models",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'null'::jsonb"
+        },
+        "allowed_clients": {
+          "name": "allowed_clients",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'[]'::jsonb"
+        },
+        "blocked_clients": {
+          "name": "blocked_clients",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'[]'::jsonb"
+        },
+        "active_time_start": {
+          "name": "active_time_start",
+          "type": "varchar(5)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "active_time_end": {
+          "name": "active_time_end",
+          "type": "varchar(5)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "codex_instructions_strategy": {
+          "name": "codex_instructions_strategy",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'auto'"
+        },
+        "mcp_passthrough_type": {
+          "name": "mcp_passthrough_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'none'"
+        },
+        "mcp_passthrough_url": {
+          "name": "mcp_passthrough_url",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_5h_usd": {
+          "name": "limit_5h_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_daily_usd": {
+          "name": "limit_daily_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "daily_reset_mode": {
+          "name": "daily_reset_mode",
+          "type": "daily_reset_mode",
+          "typeSchema": "public",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'fixed'"
+        },
+        "daily_reset_time": {
+          "name": "daily_reset_time",
+          "type": "varchar(5)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'00:00'"
+        },
+        "limit_weekly_usd": {
+          "name": "limit_weekly_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_monthly_usd": {
+          "name": "limit_monthly_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_total_usd": {
+          "name": "limit_total_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "total_cost_reset_at": {
+          "name": "total_cost_reset_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_concurrent_sessions": {
+          "name": "limit_concurrent_sessions",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 0
+        },
+        "max_retry_attempts": {
+          "name": "max_retry_attempts",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "circuit_breaker_failure_threshold": {
+          "name": "circuit_breaker_failure_threshold",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 5
+        },
+        "circuit_breaker_open_duration": {
+          "name": "circuit_breaker_open_duration",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 1800000
+        },
+        "circuit_breaker_half_open_success_threshold": {
+          "name": "circuit_breaker_half_open_success_threshold",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 2
+        },
+        "proxy_url": {
+          "name": "proxy_url",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "proxy_fallback_to_direct": {
+          "name": "proxy_fallback_to_direct",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "first_byte_timeout_streaming_ms": {
+          "name": "first_byte_timeout_streaming_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 0
+        },
+        "streaming_idle_timeout_ms": {
+          "name": "streaming_idle_timeout_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 0
+        },
+        "request_timeout_non_streaming_ms": {
+          "name": "request_timeout_non_streaming_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 0
+        },
+        "website_url": {
+          "name": "website_url",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "favicon_url": {
+          "name": "favicon_url",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_ttl_preference": {
+          "name": "cache_ttl_preference",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "swap_cache_ttl_billing": {
+          "name": "swap_cache_ttl_billing",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "context_1m_preference": {
+          "name": "context_1m_preference",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "codex_reasoning_effort_preference": {
+          "name": "codex_reasoning_effort_preference",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "codex_reasoning_summary_preference": {
+          "name": "codex_reasoning_summary_preference",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "codex_text_verbosity_preference": {
+          "name": "codex_text_verbosity_preference",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "codex_parallel_tool_calls_preference": {
+          "name": "codex_parallel_tool_calls_preference",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "codex_service_tier_preference": {
+          "name": "codex_service_tier_preference",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "anthropic_max_tokens_preference": {
+          "name": "anthropic_max_tokens_preference",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "anthropic_thinking_budget_preference": {
+          "name": "anthropic_thinking_budget_preference",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "anthropic_adaptive_thinking": {
+          "name": "anthropic_adaptive_thinking",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'null'::jsonb"
+        },
+        "gemini_google_search_preference": {
+          "name": "gemini_google_search_preference",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "tpm": {
+          "name": "tpm",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 0
+        },
+        "rpm": {
+          "name": "rpm",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 0
+        },
+        "rpd": {
+          "name": "rpd",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 0
+        },
+        "cc": {
+          "name": "cc",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 0
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "deleted_at": {
+          "name": "deleted_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        }
+      },
+      "indexes": {
+        "idx_providers_enabled_priority": {
+          "name": "idx_providers_enabled_priority",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "priority",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "weight",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"providers\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_providers_group": {
+          "name": "idx_providers_group",
+          "columns": [
+            {
+              "expression": "group_tag",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"providers\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_providers_vendor_type_url_active": {
+          "name": "idx_providers_vendor_type_url_active",
+          "columns": [
+            {
+              "expression": "provider_vendor_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "provider_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "url",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"providers\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_providers_created_at": {
+          "name": "idx_providers_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_providers_deleted_at": {
+          "name": "idx_providers_deleted_at",
+          "columns": [
+            {
+              "expression": "deleted_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_providers_vendor_type": {
+          "name": "idx_providers_vendor_type",
+          "columns": [
+            {
+              "expression": "provider_vendor_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "provider_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"providers\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_providers_enabled_vendor_type": {
+          "name": "idx_providers_enabled_vendor_type",
+          "columns": [
+            {
+              "expression": "provider_vendor_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "provider_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"providers\".\"deleted_at\" IS NULL AND \"providers\".\"is_enabled\" = true AND \"providers\".\"provider_vendor_id\" IS NOT NULL AND \"providers\".\"provider_vendor_id\" > 0",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {
+        "providers_provider_vendor_id_provider_vendors_id_fk": {
+          "name": "providers_provider_vendor_id_provider_vendors_id_fk",
+          "tableFrom": "providers",
+          "tableTo": "provider_vendors",
+          "columnsFrom": [
+            "provider_vendor_id"
+          ],
+          "columnsTo": [
+            "id"
+          ],
+          "onDelete": "restrict",
+          "onUpdate": "no action"
+        }
+      },
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.request_filters": {
+      "name": "request_filters",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "name": {
+          "name": "name",
+          "type": "varchar(100)",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "description": {
+          "name": "description",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "scope": {
+          "name": "scope",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "action": {
+          "name": "action",
+          "type": "varchar(30)",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "match_type": {
+          "name": "match_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "target": {
+          "name": "target",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "replacement": {
+          "name": "replacement",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "priority": {
+          "name": "priority",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true,
+          "default": 0
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "binding_type": {
+          "name": "binding_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'global'"
+        },
+        "provider_ids": {
+          "name": "provider_ids",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "group_tags": {
+          "name": "group_tags",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "rule_mode": {
+          "name": "rule_mode",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'simple'"
+        },
+        "execution_phase": {
+          "name": "execution_phase",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'guard'"
+        },
+        "operations": {
+          "name": "operations",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {
+        "idx_request_filters_enabled": {
+          "name": "idx_request_filters_enabled",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "priority",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_request_filters_scope": {
+          "name": "idx_request_filters_scope",
+          "columns": [
+            {
+              "expression": "scope",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_request_filters_action": {
+          "name": "idx_request_filters_action",
+          "columns": [
+            {
+              "expression": "action",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_request_filters_binding": {
+          "name": "idx_request_filters_binding",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "binding_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_request_filters_phase": {
+          "name": "idx_request_filters_phase",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "execution_phase",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.sensitive_words": {
+      "name": "sensitive_words",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "word": {
+          "name": "word",
+          "type": "varchar(255)",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "match_type": {
+          "name": "match_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'contains'"
+        },
+        "description": {
+          "name": "description",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {
+        "idx_sensitive_words_enabled": {
+          "name": "idx_sensitive_words_enabled",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "match_type",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_sensitive_words_created_at": {
+          "name": "idx_sensitive_words_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.system_settings": {
+      "name": "system_settings",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "site_title": {
+          "name": "site_title",
+          "type": "varchar(128)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'Claude Code Hub'"
+        },
+        "allow_global_usage_view": {
+          "name": "allow_global_usage_view",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "currency_display": {
+          "name": "currency_display",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'USD'"
+        },
+        "billing_model_source": {
+          "name": "billing_model_source",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'original'"
+        },
+        "codex_priority_billing_source": {
+          "name": "codex_priority_billing_source",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'requested'"
+        },
+        "timezone": {
+          "name": "timezone",
+          "type": "varchar(64)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "enable_auto_cleanup": {
+          "name": "enable_auto_cleanup",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "cleanup_retention_days": {
+          "name": "cleanup_retention_days",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 30
+        },
+        "cleanup_schedule": {
+          "name": "cleanup_schedule",
+          "type": "varchar(50)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0 2 * * *'"
+        },
+        "cleanup_batch_size": {
+          "name": "cleanup_batch_size",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 10000
+        },
+        "enable_client_version_check": {
+          "name": "enable_client_version_check",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "verbose_provider_error": {
+          "name": "verbose_provider_error",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "enable_http2": {
+          "name": "enable_http2",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "intercept_anthropic_warmup_requests": {
+          "name": "intercept_anthropic_warmup_requests",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "enable_thinking_signature_rectifier": {
+          "name": "enable_thinking_signature_rectifier",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "enable_thinking_budget_rectifier": {
+          "name": "enable_thinking_budget_rectifier",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "enable_billing_header_rectifier": {
+          "name": "enable_billing_header_rectifier",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "enable_response_input_rectifier": {
+          "name": "enable_response_input_rectifier",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "enable_codex_session_id_completion": {
+          "name": "enable_codex_session_id_completion",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "enable_claude_metadata_user_id_injection": {
+          "name": "enable_claude_metadata_user_id_injection",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "enable_response_fixer": {
+          "name": "enable_response_fixer",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "response_fixer_config": {
+          "name": "response_fixer_config",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'{\"fixTruncatedJson\":true,\"fixSseFormat\":true,\"fixEncoding\":true,\"maxJsonDepth\":200,\"maxFixSize\":1048576}'::jsonb"
+        },
+        "quota_db_refresh_interval_seconds": {
+          "name": "quota_db_refresh_interval_seconds",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false,
+          "default": 10
+        },
+        "quota_lease_percent_5h": {
+          "name": "quota_lease_percent_5h",
+          "type": "numeric(5, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.05'"
+        },
+        "quota_lease_percent_daily": {
+          "name": "quota_lease_percent_daily",
+          "type": "numeric(5, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.05'"
+        },
+        "quota_lease_percent_weekly": {
+          "name": "quota_lease_percent_weekly",
+          "type": "numeric(5, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.05'"
+        },
+        "quota_lease_percent_monthly": {
+          "name": "quota_lease_percent_monthly",
+          "type": "numeric(5, 4)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0.05'"
+        },
+        "quota_lease_cap_usd": {
+          "name": "quota_lease_cap_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {},
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.usage_ledger": {
+      "name": "usage_ledger",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "request_id": {
+          "name": "request_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "user_id": {
+          "name": "user_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "key": {
+          "name": "key",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "provider_id": {
+          "name": "provider_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "final_provider_id": {
+          "name": "final_provider_id",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "model": {
+          "name": "model",
+          "type": "varchar(128)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "original_model": {
+          "name": "original_model",
+          "type": "varchar(128)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "endpoint": {
+          "name": "endpoint",
+          "type": "varchar(256)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "api_type": {
+          "name": "api_type",
+          "type": "varchar(20)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "session_id": {
+          "name": "session_id",
+          "type": "varchar(64)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "status_code": {
+          "name": "status_code",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "is_success": {
+          "name": "is_success",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": false
+        },
+        "blocked_by": {
+          "name": "blocked_by",
+          "type": "varchar(50)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cost_usd": {
+          "name": "cost_usd",
+          "type": "numeric(21, 15)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'0'"
+        },
+        "cost_multiplier": {
+          "name": "cost_multiplier",
+          "type": "numeric(10, 4)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "input_tokens": {
+          "name": "input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "output_tokens": {
+          "name": "output_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_creation_input_tokens": {
+          "name": "cache_creation_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_read_input_tokens": {
+          "name": "cache_read_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_creation_5m_input_tokens": {
+          "name": "cache_creation_5m_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_creation_1h_input_tokens": {
+          "name": "cache_creation_1h_input_tokens",
+          "type": "bigint",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cache_ttl_applied": {
+          "name": "cache_ttl_applied",
+          "type": "varchar(10)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "context_1m_applied": {
+          "name": "context_1m_applied",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "swap_cache_ttl_applied": {
+          "name": "swap_cache_ttl_applied",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "duration_ms": {
+          "name": "duration_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "ttfb_ms": {
+          "name": "ttfb_ms",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": true
+        }
+      },
+      "indexes": {
+        "idx_usage_ledger_request_id": {
+          "name": "idx_usage_ledger_request_id",
+          "columns": [
+            {
+              "expression": "request_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": true,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_user_created_at": {
+          "name": "idx_usage_ledger_user_created_at",
+          "columns": [
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"blocked_by\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_key_created_at": {
+          "name": "idx_usage_ledger_key_created_at",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"blocked_by\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_provider_created_at": {
+          "name": "idx_usage_ledger_provider_created_at",
+          "columns": [
+            {
+              "expression": "final_provider_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"blocked_by\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_created_at_minute": {
+          "name": "idx_usage_ledger_created_at_minute",
+          "columns": [
+            {
+              "expression": "date_trunc('minute', \"created_at\" AT TIME ZONE 'UTC')",
+              "asc": true,
+              "isExpression": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_created_at_desc_id": {
+          "name": "idx_usage_ledger_created_at_desc_id",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            },
+            {
+              "expression": "id",
+              "isExpression": false,
+              "asc": false,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_session_id": {
+          "name": "idx_usage_ledger_session_id",
+          "columns": [
+            {
+              "expression": "session_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"session_id\" IS NOT NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_model": {
+          "name": "idx_usage_ledger_model",
+          "columns": [
+            {
+              "expression": "model",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"model\" IS NOT NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_key_cost": {
+          "name": "idx_usage_ledger_key_cost",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "cost_usd",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"blocked_by\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_user_cost_cover": {
+          "name": "idx_usage_ledger_user_cost_cover",
+          "columns": [
+            {
+              "expression": "user_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "cost_usd",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"blocked_by\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_provider_cost_cover": {
+          "name": "idx_usage_ledger_provider_cost_cover",
+          "columns": [
+            {
+              "expression": "final_provider_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "cost_usd",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"blocked_by\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_usage_ledger_key_created_at_desc_cover": {
+          "name": "idx_usage_ledger_key_created_at_desc_cover",
+          "columns": [
+            {
+              "expression": "key",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "\"created_at\" DESC NULLS LAST",
+              "asc": true,
+              "isExpression": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "final_provider_id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"usage_ledger\".\"blocked_by\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.users": {
+      "name": "users",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "name": {
+          "name": "name",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "description": {
+          "name": "description",
+          "type": "text",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "role": {
+          "name": "role",
+          "type": "varchar",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'user'"
+        },
+        "rpm_limit": {
+          "name": "rpm_limit",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "daily_limit_usd": {
+          "name": "daily_limit_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "provider_group": {
+          "name": "provider_group",
+          "type": "varchar(200)",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'default'"
+        },
+        "tags": {
+          "name": "tags",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'[]'::jsonb"
+        },
+        "limit_5h_usd": {
+          "name": "limit_5h_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_weekly_usd": {
+          "name": "limit_weekly_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_monthly_usd": {
+          "name": "limit_monthly_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_total_usd": {
+          "name": "limit_total_usd",
+          "type": "numeric(10, 2)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "cost_reset_at": {
+          "name": "cost_reset_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "limit_concurrent_sessions": {
+          "name": "limit_concurrent_sessions",
+          "type": "integer",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "daily_reset_mode": {
+          "name": "daily_reset_mode",
+          "type": "daily_reset_mode",
+          "typeSchema": "public",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'fixed'"
+        },
+        "daily_reset_time": {
+          "name": "daily_reset_time",
+          "type": "varchar(5)",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'00:00'"
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "expires_at": {
+          "name": "expires_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "allowed_clients": {
+          "name": "allowed_clients",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'[]'::jsonb"
+        },
+        "allowed_models": {
+          "name": "allowed_models",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "'[]'::jsonb"
+        },
+        "blocked_clients": {
+          "name": "blocked_clients",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": true,
+          "default": "'[]'::jsonb"
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "deleted_at": {
+          "name": "deleted_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        }
+      },
+      "indexes": {
+        "idx_users_active_role_sort": {
+          "name": "idx_users_active_role_sort",
+          "columns": [
+            {
+              "expression": "deleted_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "role",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "id",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"users\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_users_enabled_expires_at": {
+          "name": "idx_users_enabled_expires_at",
+          "columns": [
+            {
+              "expression": "is_enabled",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            },
+            {
+              "expression": "expires_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"users\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_users_tags_gin": {
+          "name": "idx_users_tags_gin",
+          "columns": [
+            {
+              "expression": "tags",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "where": "\"users\".\"deleted_at\" IS NULL",
+          "concurrently": false,
+          "method": "gin",
+          "with": {}
+        },
+        "idx_users_created_at": {
+          "name": "idx_users_created_at",
+          "columns": [
+            {
+              "expression": "created_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        },
+        "idx_users_deleted_at": {
+          "name": "idx_users_deleted_at",
+          "columns": [
+            {
+              "expression": "deleted_at",
+              "isExpression": false,
+              "asc": true,
+              "nulls": "last"
+            }
+          ],
+          "isUnique": false,
+          "concurrently": false,
+          "method": "btree",
+          "with": {}
+        }
+      },
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    },
+    "public.webhook_targets": {
+      "name": "webhook_targets",
+      "schema": "",
+      "columns": {
+        "id": {
+          "name": "id",
+          "type": "serial",
+          "primaryKey": true,
+          "notNull": true
+        },
+        "name": {
+          "name": "name",
+          "type": "varchar(100)",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "provider_type": {
+          "name": "provider_type",
+          "type": "webhook_provider_type",
+          "typeSchema": "public",
+          "primaryKey": false,
+          "notNull": true
+        },
+        "webhook_url": {
+          "name": "webhook_url",
+          "type": "varchar(1024)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "telegram_bot_token": {
+          "name": "telegram_bot_token",
+          "type": "varchar(256)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "telegram_chat_id": {
+          "name": "telegram_chat_id",
+          "type": "varchar(64)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "dingtalk_secret": {
+          "name": "dingtalk_secret",
+          "type": "varchar(256)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "custom_template": {
+          "name": "custom_template",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "custom_headers": {
+          "name": "custom_headers",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "proxy_url": {
+          "name": "proxy_url",
+          "type": "varchar(512)",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "proxy_fallback_to_direct": {
+          "name": "proxy_fallback_to_direct",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": false,
+          "default": false
+        },
+        "is_enabled": {
+          "name": "is_enabled",
+          "type": "boolean",
+          "primaryKey": false,
+          "notNull": true,
+          "default": true
+        },
+        "last_test_at": {
+          "name": "last_test_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "last_test_result": {
+          "name": "last_test_result",
+          "type": "jsonb",
+          "primaryKey": false,
+          "notNull": false
+        },
+        "created_at": {
+          "name": "created_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        },
+        "updated_at": {
+          "name": "updated_at",
+          "type": "timestamp with time zone",
+          "primaryKey": false,
+          "notNull": false,
+          "default": "now()"
+        }
+      },
+      "indexes": {},
+      "foreignKeys": {},
+      "compositePrimaryKeys": {},
+      "uniqueConstraints": {},
+      "policies": {},
+      "checkConstraints": {},
+      "isRLSEnabled": false
+    }
+  },
+  "enums": {
+    "public.daily_reset_mode": {
+      "name": "daily_reset_mode",
+      "schema": "public",
+      "values": [
+        "fixed",
+        "rolling"
+      ]
+    },
+    "public.notification_type": {
+      "name": "notification_type",
+      "schema": "public",
+      "values": [
+        "circuit_breaker",
+        "daily_leaderboard",
+        "cost_alert",
+        "cache_hit_rate_alert"
+      ]
+    },
+    "public.webhook_provider_type": {
+      "name": "webhook_provider_type",
+      "schema": "public",
+      "values": [
+        "wechat",
+        "feishu",
+        "dingtalk",
+        "telegram",
+        "custom"
+      ]
+    }
+  },
+  "schemas": {},
+  "sequences": {},
+  "roles": {},
+  "policies": {},
+  "views": {},
+  "_meta": {
+    "columns": {},
+    "schemas": {},
+    "tables": {}
+  }
+}

+ 7 - 0
drizzle/meta/_journal.json

@@ -596,6 +596,13 @@
       "when": 1773809022650,
       "tag": "0084_needy_jackpot",
       "breakpoints": true
+    },
+    {
+      "idx": 85,
+      "version": "7",
+      "when": 1774098220127,
+      "tag": "0085_busy_ken_ellis",
+      "breakpoints": true
     }
   ]
 }

+ 7 - 0
messages/en/settings/config.json

@@ -13,6 +13,13 @@
       "redirected": "After Redirection (Actual Model)"
     },
     "billingModelSourcePlaceholder": "Select billing model source",
+    "codexPriorityBillingSource": "Codex Priority Billing Source",
+    "codexPriorityBillingSourceDesc": "Controls which service_tier is used for Codex Priority (Fast Mode) surcharge billing. The default is Requested Service Tier; if Actual Service Tier is selected, the response value is used first and falls back to the request value when the response omits it.",
+    "codexPriorityBillingSourceOptions": {
+      "requested": "Requested Service Tier (Default)",
+      "actual": "Actual Service Tier (Fallback to Requested)"
+    },
+    "codexPriorityBillingSourcePlaceholder": "Select Codex Priority billing source",
     "cleanupBatchSize": "Batch Size",
     "cleanupBatchSizeDesc": "Number of records to delete per batch (range: 1000-100000, recommended 10000)",
     "cleanupBatchSizePlaceholder": "10000",

+ 7 - 0
messages/ja/settings/config.json

@@ -13,6 +13,13 @@
       "redirected": "リダイレクト後(実際のモデル)"
     },
     "billingModelSourcePlaceholder": "課金モデルソースを選択",
+    "codexPriorityBillingSource": "Codex Priority 課金参照元",
+    "codexPriorityBillingSourceDesc": "Codex Priority(Fast Mode)の追加課金に使う service_tier を制御します。デフォルトは Requested Service Tier です。Actual Service Tier を選ぶとレスポンス値を優先し、レスポンスに無い場合はリクエスト値へフォールバックします。",
+    "codexPriorityBillingSourceOptions": {
+      "requested": "Requested Service Tier(デフォルト)",
+      "actual": "Actual Service Tier(無い場合は Requested へフォールバック)"
+    },
+    "codexPriorityBillingSourcePlaceholder": "Codex Priority の課金参照元を選択",
     "cleanupBatchSize": "バッチサイズ",
     "cleanupBatchSizeDesc": "バッチごとに削除するレコード数(範囲:1000-100000、推奨10000)",
     "cleanupBatchSizePlaceholder": "10000",

+ 7 - 0
messages/ru/settings/config.json

@@ -13,6 +13,13 @@
       "redirected": "После перенаправления (фактическая модель)"
     },
     "billingModelSourcePlaceholder": "Выберите источник модели для тарификации",
+    "codexPriorityBillingSource": "Источник тарификации Codex Priority",
+    "codexPriorityBillingSourceDesc": "Определяет, какой service_tier использовать для отдельной тарификации Codex Priority (Fast Mode). По умолчанию используется Requested Service Tier; если выбран Actual Service Tier, сначала берется значение из ответа, а при его отсутствии используется значение из запроса.",
+    "codexPriorityBillingSourceOptions": {
+      "requested": "Requested Service Tier (по умолчанию)",
+      "actual": "Actual Service Tier (с откатом к Requested)"
+    },
+    "codexPriorityBillingSourcePlaceholder": "Выберите источник тарификации Codex Priority",
     "cleanupBatchSize": "Размер пакета",
     "cleanupBatchSizeDesc": "Количество записей для удаления за раз (диапазон: 1000-100000, рекомендуется 10000)",
     "cleanupBatchSizePlaceholder": "10000",

+ 7 - 0
messages/zh-CN/settings/config.json

@@ -30,6 +30,13 @@
       "original": "重定向前(原始模型)",
       "redirected": "重定向后(实际模型)"
     },
+    "codexPriorityBillingSource": "Codex Priority 计费来源",
+    "codexPriorityBillingSourcePlaceholder": "选择 Codex Priority 计费来源",
+    "codexPriorityBillingSourceDesc": "控制 Codex Priority(Fast Mode)单独计费使用哪个 service_tier。默认按 Requested Service Tier 计费;若选择 Actual Service Tier,则优先使用响应返回值,响应未返回时回退到请求值。",
+    "codexPriorityBillingSourceOptions": {
+      "requested": "Requested Service Tier(默认)",
+      "actual": "Actual Service Tier(缺失时回退 Requested)"
+    },
     "allowGlobalView": "允许查看全站使用量",
     "allowGlobalViewDesc": "关闭后,普通用户在仪表盘仅能查看自己密钥的使用统计。",
     "verboseProviderError": "详细供应商错误信息",

+ 7 - 0
messages/zh-TW/settings/config.json

@@ -13,6 +13,13 @@
       "redirected": "重新導向後(實際模型)"
     },
     "billingModelSourcePlaceholder": "選擇計費模型來源",
+    "codexPriorityBillingSource": "Codex Priority 計費來源",
+    "codexPriorityBillingSourceDesc": "控制 Codex Priority(Fast Mode)單獨計費使用哪個 service_tier。預設按 Requested Service Tier 計費;若選擇 Actual Service Tier,則優先使用回應返回值,回應未返回時回退到請求值。",
+    "codexPriorityBillingSourceOptions": {
+      "requested": "Requested Service Tier(預設)",
+      "actual": "Actual Service Tier(缺失時回退 Requested)"
+    },
+    "codexPriorityBillingSourcePlaceholder": "選擇 Codex Priority 計費來源",
     "cleanupBatchSize": "批次大小",
     "cleanupBatchSizeDesc": "每批刪除的記錄數(範圍:1000-100000,建議 10000)",
     "cleanupBatchSizePlaceholder": "10000",

+ 7 - 1
src/actions/system-config.ts

@@ -8,7 +8,11 @@ import { logger } from "@/lib/logger";
 import { resolveSystemTimezone } from "@/lib/utils/timezone";
 import { UpdateSystemSettingsSchema } from "@/lib/validation/schemas";
 import { getSystemSettings, updateSystemSettings } from "@/repository/system-config";
-import type { ResponseFixerConfig, SystemSettings } from "@/types/system-config";
+import type {
+  CodexPriorityBillingSource,
+  ResponseFixerConfig,
+  SystemSettings,
+} from "@/types/system-config";
 import type { ActionResult } from "./types";
 
 export async function fetchSystemSettings(): Promise<ActionResult<SystemSettings>> {
@@ -47,6 +51,7 @@ export async function saveSystemSettings(formData: {
   allowGlobalUsageView?: boolean;
   currencyDisplay?: string;
   billingModelSource?: string;
+  codexPriorityBillingSource?: CodexPriorityBillingSource;
   timezone?: string | null;
   enableAutoCleanup?: boolean;
   cleanupRetentionDays?: number;
@@ -84,6 +89,7 @@ export async function saveSystemSettings(formData: {
       allowGlobalUsageView: validated.allowGlobalUsageView,
       currencyDisplay: validated.currencyDisplay,
       billingModelSource: validated.billingModelSource,
+      codexPriorityBillingSource: validated.codexPriorityBillingSource,
       timezone: validated.timezone,
       enableAutoCleanup: validated.enableAutoCleanup,
       cleanupRetentionDays: validated.cleanupRetentionDays,

+ 37 - 1
src/app/[locale]/settings/config/_components/system-settings-form.tsx

@@ -41,7 +41,11 @@ import {
   shouldWarnQuotaLeaseCapZero,
   shouldWarnQuotaLeasePercentZero,
 } from "@/lib/utils/validation/quota-lease-warnings";
-import type { BillingModelSource, SystemSettings } from "@/types/system-config";
+import type {
+  BillingModelSource,
+  CodexPriorityBillingSource,
+  SystemSettings,
+} from "@/types/system-config";
 
 interface SystemSettingsFormProps {
   initialSettings: Pick<
@@ -50,6 +54,7 @@ interface SystemSettingsFormProps {
     | "allowGlobalUsageView"
     | "currencyDisplay"
     | "billingModelSource"
+    | "codexPriorityBillingSource"
     | "timezone"
     | "verboseProviderError"
     | "enableHttp2"
@@ -92,6 +97,8 @@ export function SystemSettingsForm({ initialSettings }: SystemSettingsFormProps)
   const [billingModelSource, setBillingModelSource] = useState<BillingModelSource>(
     initialSettings.billingModelSource
   );
+  const [codexPriorityBillingSource, setCodexPriorityBillingSource] =
+    useState<CodexPriorityBillingSource>(initialSettings.codexPriorityBillingSource);
   const [timezone, setTimezone] = useState<string | null>(initialSettings.timezone);
   const [verboseProviderError, setVerboseProviderError] = useState(
     initialSettings.verboseProviderError
@@ -170,6 +177,7 @@ export function SystemSettingsForm({ initialSettings }: SystemSettingsFormProps)
         allowGlobalUsageView,
         currencyDisplay,
         billingModelSource,
+        codexPriorityBillingSource,
         timezone,
         verboseProviderError,
         enableHttp2,
@@ -200,6 +208,7 @@ export function SystemSettingsForm({ initialSettings }: SystemSettingsFormProps)
         setAllowGlobalUsageView(result.data.allowGlobalUsageView);
         setCurrencyDisplay(result.data.currencyDisplay);
         setBillingModelSource(result.data.billingModelSource);
+        setCodexPriorityBillingSource(result.data.codexPriorityBillingSource);
         setTimezone(result.data.timezone);
         setVerboseProviderError(result.data.verboseProviderError);
         setEnableHttp2(result.data.enableHttp2);
@@ -301,6 +310,33 @@ export function SystemSettingsForm({ initialSettings }: SystemSettingsFormProps)
         <p className="text-xs text-muted-foreground">{t("billingModelSourceDesc")}</p>
       </div>
 
+      <div className="space-y-2">
+        <Label
+          htmlFor="codex-priority-billing-source"
+          className="text-sm font-medium text-foreground"
+        >
+          {t("codexPriorityBillingSource")}
+        </Label>
+        <Select
+          value={codexPriorityBillingSource}
+          onValueChange={(value) =>
+            setCodexPriorityBillingSource(value as CodexPriorityBillingSource)
+          }
+          disabled={isPending}
+        >
+          <SelectTrigger id="codex-priority-billing-source" className={selectTriggerClassName}>
+            <SelectValue placeholder={t("codexPriorityBillingSourcePlaceholder")} />
+          </SelectTrigger>
+          <SelectContent>
+            <SelectItem value="requested">
+              {t("codexPriorityBillingSourceOptions.requested")}
+            </SelectItem>
+            <SelectItem value="actual">{t("codexPriorityBillingSourceOptions.actual")}</SelectItem>
+          </SelectContent>
+        </Select>
+        <p className="text-xs text-muted-foreground">{t("codexPriorityBillingSourceDesc")}</p>
+      </div>
+
       {/* Timezone Select */}
       <div className="space-y-2">
         <Label htmlFor="timezone" className="text-sm font-medium text-foreground">

+ 1 - 0
src/app/[locale]/settings/config/page.tsx

@@ -44,6 +44,7 @@ async function SettingsConfigContent() {
             allowGlobalUsageView: settings.allowGlobalUsageView,
             currencyDisplay: settings.currencyDisplay,
             billingModelSource: settings.billingModelSource,
+            codexPriorityBillingSource: settings.codexPriorityBillingSource,
             timezone: settings.timezone,
             verboseProviderError: settings.verboseProviderError,
             enableHttp2: settings.enableHttp2,

+ 4 - 0
src/app/api/admin/system-config/route.ts

@@ -1,5 +1,6 @@
 import { z } from "zod";
 import { getSession } from "@/lib/auth";
+import { invalidateSystemSettingsCache } from "@/lib/config";
 import { logger } from "@/lib/logger";
 import { UpdateSystemSettingsSchema } from "@/lib/validation/schemas";
 import { getSystemSettings, updateSystemSettings } from "@/repository/system-config";
@@ -59,6 +60,8 @@ export async function POST(req: Request) {
       siteTitle: validated.siteTitle?.trim(),
       allowGlobalUsageView: validated.allowGlobalUsageView,
       currencyDisplay: validated.currencyDisplay,
+      billingModelSource: validated.billingModelSource,
+      codexPriorityBillingSource: validated.codexPriorityBillingSource,
       enableAutoCleanup: validated.enableAutoCleanup,
       cleanupRetentionDays: validated.cleanupRetentionDays,
       cleanupSchedule: validated.cleanupSchedule,
@@ -69,6 +72,7 @@ export async function POST(req: Request) {
       userId: session.user.id,
       changes: validated,
     });
+    invalidateSystemSettingsCache();
 
     return Response.json(updated);
   } catch (error) {

+ 88 - 65
src/app/v1/_lib/proxy/response-handler.ts

@@ -21,7 +21,6 @@ import {
   matchLongContextPricing,
 } from "@/lib/utils/cost-calculation";
 import { hasValidPriceData } from "@/lib/utils/price-data";
-import { resolvePricingForModelRecords } from "@/lib/utils/pricing-resolution";
 import { isSSEText, parseSSEData } from "@/lib/utils/sse";
 import {
   detectUpstreamErrorFromSseOrJsonText,
@@ -32,8 +31,6 @@ import {
   updateMessageRequestDetails,
   updateMessageRequestDuration,
 } from "@/repository/message";
-import { findLatestPriceByModel } from "@/repository/model-price";
-import { getSystemSettings } from "@/repository/system-config";
 import type { Provider } from "@/types/provider";
 import type { SessionUsageUpdate } from "@/types/session";
 import type { LongContextPricingSpecialSetting } from "@/types/special-settings";
@@ -214,26 +211,70 @@ export function parseServiceTierFromResponseText(responseText: string): string |
   return lastSeenServiceTier;
 }
 
-function isPriorityServiceTierApplied(
+type CodexPriorityBillingDecision = {
+  requestedServiceTier: string | null;
+  actualServiceTier: string | null;
+  billingSourcePreference: Awaited<ReturnType<ProxySession["getCodexPriorityBillingSource"]>>;
+  resolvedFrom: "requested" | "actual" | null;
+  effectivePriority: boolean;
+};
+
+async function resolveCodexPriorityBillingDecision(
   session: ProxySession,
   actualServiceTier: string | null
-): boolean {
-  if (actualServiceTier != null) {
-    return actualServiceTier === "priority";
+): Promise<CodexPriorityBillingDecision | null> {
+  if (session.provider?.providerType !== "codex") {
+    return null;
+  }
+
+  const requestedServiceTier = getRequestedCodexServiceTier(session);
+  let billingSourcePreference: Awaited<ReturnType<ProxySession["getCodexPriorityBillingSource"]>> =
+    "requested";
+
+  try {
+    billingSourcePreference = await session.getCodexPriorityBillingSource();
+  } catch (error) {
+    logger.warn(
+      "[ResponseHandler] Failed to load codex priority billing source, fallback to requested",
+      {
+        error: error instanceof Error ? error.message : String(error),
+      }
+    );
+  }
+
+  let resolvedFrom: "requested" | "actual" | null = null;
+  let effectiveTier: string | null = null;
+
+  if (billingSourcePreference === "actual") {
+    if (actualServiceTier != null) {
+      resolvedFrom = "actual";
+      effectiveTier = actualServiceTier;
+    } else if (requestedServiceTier != null) {
+      resolvedFrom = "requested";
+      effectiveTier = requestedServiceTier;
+    }
+  } else if (requestedServiceTier != null) {
+    resolvedFrom = "requested";
+    effectiveTier = requestedServiceTier;
   }
-  return getRequestedCodexServiceTier(session) === "priority";
+
+  return {
+    requestedServiceTier,
+    actualServiceTier,
+    billingSourcePreference,
+    resolvedFrom,
+    effectivePriority: effectiveTier === "priority",
+  };
 }
 
 function ensureCodexServiceTierResultSpecialSetting(
   session: ProxySession,
-  actualServiceTier: string | null
+  decision: CodexPriorityBillingDecision | null
 ): void {
-  if (session.provider?.providerType !== "codex") {
+  if (!decision) {
     return;
   }
 
-  const requestedServiceTier = getRequestedCodexServiceTier(session);
-  const effectivePriority = isPriorityServiceTierApplied(session, actualServiceTier);
   const existing = session
     .getSpecialSettings()
     ?.find((setting) => setting.type === "codex_service_tier_result");
@@ -245,10 +286,15 @@ function ensureCodexServiceTierResultSpecialSetting(
   session.addSpecialSetting({
     type: "codex_service_tier_result",
     scope: "response",
-    hit: effectivePriority || requestedServiceTier != null || actualServiceTier != null,
-    requestedServiceTier,
-    actualServiceTier,
-    effectivePriority,
+    hit:
+      decision.effectivePriority ||
+      decision.requestedServiceTier != null ||
+      decision.actualServiceTier != null,
+    requestedServiceTier: decision.requestedServiceTier,
+    actualServiceTier: decision.actualServiceTier,
+    billingSourcePreference: decision.billingSourcePreference,
+    resolvedFrom: decision.resolvedFrom,
+    effectivePriority: decision.effectivePriority,
   });
 }
 
@@ -952,8 +998,12 @@ export class ProxyResponseHandler {
         usageRecord = usageResult.usageRecord;
         usageMetrics = usageResult.usageMetrics;
         const actualServiceTier = parseServiceTierFromResponseText(responseText);
-        ensureCodexServiceTierResultSpecialSetting(session, actualServiceTier);
-        const priorityServiceTierApplied = isPriorityServiceTierApplied(session, actualServiceTier);
+        const codexPriorityBillingDecision = await resolveCodexPriorityBillingDecision(
+          session,
+          actualServiceTier
+        );
+        ensureCodexServiceTierResultSpecialSetting(session, codexPriorityBillingDecision);
+        const priorityServiceTierApplied = codexPriorityBillingDecision?.effectivePriority ?? false;
 
         if (usageMetrics) {
           usageMetrics = normalizeUsageWithSwap(
@@ -998,8 +1048,7 @@ export class ProxyResponseHandler {
         if (usageRecord && usageMetrics && messageContext) {
           const costUpdateResult = await updateRequestCostFromUsage(
             messageContext.id,
-            session.getOriginalModel(),
-            session.getCurrentModel(),
+            session,
             usageMetrics,
             provider,
             provider.costMultiplier,
@@ -1965,8 +2014,12 @@ export class ProxyResponseHandler {
         usageForCost = usageResult.usageMetrics;
 
         const actualServiceTier = parseServiceTierFromResponseText(allContent);
-        ensureCodexServiceTierResultSpecialSetting(session, actualServiceTier);
-        const priorityServiceTierApplied = isPriorityServiceTierApplied(session, actualServiceTier);
+        const codexPriorityBillingDecision = await resolveCodexPriorityBillingDecision(
+          session,
+          actualServiceTier
+        );
+        ensureCodexServiceTierResultSpecialSetting(session, codexPriorityBillingDecision);
+        const priorityServiceTierApplied = codexPriorityBillingDecision?.effectivePriority ?? false;
 
         if (usageForCost) {
           usageForCost = normalizeUsageWithSwap(
@@ -2006,8 +2059,7 @@ export class ProxyResponseHandler {
 
         const costUpdateResult = await updateRequestCostFromUsage(
           messageContext.id,
-          session.getOriginalModel(),
-          session.getCurrentModel(),
+          session,
           usageForCost,
           provider,
           provider.costMultiplier,
@@ -3062,8 +3114,7 @@ function normalizeUsageWithSwap(
 
 async function updateRequestCostFromUsage(
   messageId: number,
-  originalModel: string | null,
-  redirectedModel: string | null,
+  session: ProxySession,
   usage: UsageMetrics | null,
   provider: Provider | null,
   costMultiplier: number = 1.0,
@@ -3087,6 +3138,9 @@ async function updateRequestCostFromUsage(
     };
   }
 
+  const originalModel = session.getOriginalModel();
+  const redirectedModel = session.getCurrentModel();
+
   if (!originalModel && !redirectedModel) {
     logger.warn("[CostCalculation] No model name available", { messageId });
     return {
@@ -3098,47 +3152,13 @@ async function updateRequestCostFromUsage(
   }
 
   try {
-    const systemSettings = await getSystemSettings();
-    const billingModelSource = systemSettings.billingModelSource;
-
-    let primaryModel: string | null;
-    let fallbackModel: string | null;
-
-    if (billingModelSource === "original") {
-      primaryModel = originalModel;
-      fallbackModel = redirectedModel;
-    } else {
-      primaryModel = redirectedModel;
-      fallbackModel = originalModel;
-    }
-
-    logger.debug("[CostCalculation] Billing model source config", {
-      messageId,
-      billingModelSource,
-      primaryModel,
-      fallbackModel,
-    });
-
-    const primaryRecord = primaryModel ? await findLatestPriceByModel(primaryModel) : null;
-    const fallbackRecord =
-      fallbackModel && fallbackModel !== primaryModel
-        ? await findLatestPriceByModel(fallbackModel)
-        : null;
-
-    const resolvedPricing = resolvePricingForModelRecords({
-      provider,
-      primaryModelName: primaryModel,
-      fallbackModelName: fallbackModel,
-      primaryRecord,
-      fallbackRecord,
-    });
+    const resolvedPricing = await session.getResolvedPricingByBillingSource(provider);
 
     if (!resolvedPricing?.priceData || !hasValidPriceData(resolvedPricing.priceData)) {
       logger.warn("[CostCalculation] No price data found, skipping billing", {
         messageId,
         originalModel,
         redirectedModel,
-        billingModelSource,
       });
 
       requestCloudPriceTableSync({ reason: "missing-model" });
@@ -3237,8 +3257,12 @@ export async function finalizeRequestStats(
   const providerIdForPersistence = providerIdOverride ?? session.provider?.id;
   const { usageMetrics } = parseUsageFromResponseText(responseText, provider.providerType);
   const actualServiceTier = parseServiceTierFromResponseText(responseText);
-  ensureCodexServiceTierResultSpecialSetting(session, actualServiceTier);
-  const priorityServiceTierApplied = isPriorityServiceTierApplied(session, actualServiceTier);
+  const codexPriorityBillingDecision = await resolveCodexPriorityBillingDecision(
+    session,
+    actualServiceTier
+  );
+  ensureCodexServiceTierResultSpecialSetting(session, codexPriorityBillingDecision);
+  const priorityServiceTierApplied = codexPriorityBillingDecision?.effectivePriority ?? false;
   if (!usageMetrics) {
     await updateMessageRequestDetails(messageContext.id, {
       statusCode: statusCode,
@@ -3267,8 +3291,7 @@ export async function finalizeRequestStats(
 
   const costUpdateResult = await updateRequestCostFromUsage(
     messageContext.id,
-    session.getOriginalModel(),
-    session.getCurrentModel(),
+    session,
     normalizedUsage,
     provider,
     provider.costMultiplier,

+ 103 - 26
src/app/v1/_lib/proxy/session.ts

@@ -14,6 +14,7 @@ import type { ProviderChainItem } from "@/types/message";
 import type { ModelPriceData } from "@/types/model-price";
 import type { Provider, ProviderType } from "@/types/provider";
 import type { SpecialSetting } from "@/types/special-settings";
+import type { BillingModelSource, CodexPriorityBillingSource } from "@/types/system-config";
 import type { User } from "@/types/user";
 import { isCountTokensEndpointPath } from "./endpoint-paths";
 import { type EndpointPolicy, resolveEndpointPolicy } from "./endpoint-policy";
@@ -116,13 +117,21 @@ export class ProxySession {
   private cachedPriceData?: ModelPriceData | null;
 
   // Cached billing model source config (per-request)
-  private cachedBillingModelSource?: "original" | "redirected";
+  private cachedBillingModelSource?: BillingModelSource;
+
+  // Cached Codex Priority 计费来源(per-request)
+  private cachedCodexPriorityBillingSource?: CodexPriorityBillingSource;
 
   /**
-   * Promise cache for billingModelSource load (concurrency safe).
-   * Ensures system settings are loaded at most once per request/session.
+   * Promise cache for billing-related system settings load (concurrency safe).
+   * Ensures the relevant system settings are loaded at most once per request/session.
    */
-  private billingModelSourcePromise?: Promise<"original" | "redirected">;
+  private billingSettingsPromise?: Promise<{
+    billingModelSource: BillingModelSource;
+    codexPriorityBillingSource: CodexPriorityBillingSource;
+    source: "live" | "cache" | "default";
+  }>;
+  private billingSettingsSource?: "live" | "cache" | "default";
 
   // Resolved pricing cache (per request/provider combination)
   private resolvedPricingCache = new Map<string, ResolvedPricing | null>();
@@ -730,29 +739,12 @@ export class ProxySession {
     }
 
     if (this.cachedBillingModelSource === undefined) {
-      if (!this.billingModelSourcePromise) {
-        this.billingModelSourcePromise = (async () => {
-          try {
-            const { getSystemSettings } = await import("@/repository/system-config");
-            const systemSettings = await getSystemSettings();
-            const source = systemSettings.billingModelSource;
-
-            if (source !== "original" && source !== "redirected") {
-              logger.warn(
-                `[ProxySession] Invalid billingModelSource: ${String(source)}, fallback to "redirected"`
-              );
-              return "redirected";
-            }
-
-            return source;
-          } catch (error) {
-            logger.error("[ProxySession] Failed to load billing model source", { error });
-            return "redirected";
-          }
-        })();
-      }
+      await this.loadBillingSettings();
+    }
 
-      this.cachedBillingModelSource = await this.billingModelSourcePromise;
+    if (!this.hasUsableBillingSettings()) {
+      logger.warn("[ProxySession] Billing settings unavailable, skip pricing resolution");
+      return null;
     }
 
     const providerIdentity = provider ?? this.provider;
@@ -814,6 +806,91 @@ export class ProxySession {
     const resolved = await this.getResolvedPricingByBillingSource(provider);
     return resolved?.priceData ?? null;
   }
+
+  async getCodexPriorityBillingSource(): Promise<CodexPriorityBillingSource> {
+    if (this.cachedCodexPriorityBillingSource === undefined) {
+      await this.loadBillingSettings();
+    }
+
+    return this.cachedCodexPriorityBillingSource ?? "requested";
+  }
+
+  private async loadBillingSettings(): Promise<void> {
+    if (!this.billingSettingsPromise) {
+      this.billingSettingsPromise = (async () => {
+        try {
+          const { getSystemSettings } = await import("@/repository/system-config");
+          const systemSettings = await getSystemSettings();
+
+          const billingModelSource =
+            systemSettings.billingModelSource === "original" ||
+            systemSettings.billingModelSource === "redirected"
+              ? systemSettings.billingModelSource
+              : "redirected";
+          const codexPriorityBillingSource =
+            systemSettings.codexPriorityBillingSource === "actual" ||
+            systemSettings.codexPriorityBillingSource === "requested"
+              ? systemSettings.codexPriorityBillingSource
+              : "requested";
+
+          if (billingModelSource !== systemSettings.billingModelSource) {
+            logger.warn(
+              `[ProxySession] Invalid billingModelSource: ${String(systemSettings.billingModelSource)}, fallback to "redirected"`
+            );
+          }
+          if (codexPriorityBillingSource !== systemSettings.codexPriorityBillingSource) {
+            logger.warn(
+              `[ProxySession] Invalid codexPriorityBillingSource: ${String(systemSettings.codexPriorityBillingSource)}, fallback to "requested"`
+            );
+          }
+
+          return {
+            billingModelSource,
+            codexPriorityBillingSource,
+            source: "live" as const,
+          };
+        } catch (error) {
+          logger.warn(
+            "[ProxySession] Failed to load billing settings directly, trying cached fallback",
+            {
+              error,
+            }
+          );
+
+          const { getCachedSystemSettingsOnlyCache } = await import("@/lib/config");
+          const cachedSettings = getCachedSystemSettingsOnlyCache();
+          const hasPersistedCachedSettings = cachedSettings != null && cachedSettings.id !== 0;
+          if (hasPersistedCachedSettings && cachedSettings) {
+            return {
+              billingModelSource:
+                cachedSettings.billingModelSource === "original" ? "original" : "redirected",
+              codexPriorityBillingSource:
+                cachedSettings.codexPriorityBillingSource === "actual" ? "actual" : "requested",
+              source: "cache" as const,
+            };
+          }
+
+          logger.error("[ProxySession] Billing settings unavailable after direct read failure", {
+            error,
+          });
+          return {
+            billingModelSource: "redirected" as BillingModelSource,
+            codexPriorityBillingSource: "requested" as CodexPriorityBillingSource,
+            source: "default" as const,
+          };
+        }
+      })();
+    }
+
+    const settings = await this.billingSettingsPromise;
+    this.cachedBillingModelSource = settings.billingModelSource;
+    this.cachedCodexPriorityBillingSource = settings.codexPriorityBillingSource;
+    this.billingSettingsSource = settings.source;
+  }
+
+  private hasUsableBillingSettings(): boolean {
+    return this.billingSettingsSource !== "default";
+  }
 }
 
 function formatHeadersForLog(headers: Headers): string {

+ 5 - 0
src/drizzle/schema.ts

@@ -678,6 +678,11 @@ export const systemSettings = pgTable('system_settings', {
   // 计费模型来源配置: 'original' (重定向前) | 'redirected' (重定向后)
   billingModelSource: varchar('billing_model_source', { length: 20 }).notNull().default('original'),
 
+  // Codex Priority 单独计费来源配置: 'requested' (请求值) | 'actual' (响应值)
+  codexPriorityBillingSource: varchar('codex_priority_billing_source', { length: 20 })
+    .notNull()
+    .default('requested'),
+
   // 系统时区配置 (IANA timezone identifier)
   // 用于统一后端时间边界计算和前端日期/时间显示
   // null 表示使用环境变量 TZ 或默认 UTC

+ 1 - 0
src/lib/config/index.ts

@@ -6,6 +6,7 @@ export { config } from "./config";
 export { type EnvConfig, getEnvConfig, isDevelopment } from "./env.schema";
 export {
   getCachedSystemSettings,
+  getCachedSystemSettingsOnlyCache,
   invalidateSystemSettingsCache,
   isHttp2Enabled,
 } from "./system-settings-cache";

+ 11 - 0
src/lib/config/system-settings-cache.ts

@@ -23,11 +23,20 @@ const CACHE_TTL_MS = 60 * 1000;
 let cachedSettings: SystemSettings | null = null;
 let cachedAt: number = 0;
 
+/**
+ * Read the current in-memory settings cache only.
+ * Never triggers a DB refresh.
+ */
+export function getCachedSystemSettingsOnlyCache(): SystemSettings | null {
+  return cachedSettings;
+}
+
 /** Default settings used when cache fetch fails */
 const DEFAULT_SETTINGS: Pick<
   SystemSettings,
   | "enableHttp2"
   | "interceptAnthropicWarmupRequests"
+  | "codexPriorityBillingSource"
   | "enableThinkingSignatureRectifier"
   | "enableThinkingBudgetRectifier"
   | "enableBillingHeaderRectifier"
@@ -39,6 +48,7 @@ const DEFAULT_SETTINGS: Pick<
 > = {
   enableHttp2: false,
   interceptAnthropicWarmupRequests: false,
+  codexPriorityBillingSource: "requested",
   enableThinkingSignatureRectifier: true,
   enableThinkingBudgetRectifier: true,
   enableBillingHeaderRectifier: true,
@@ -104,6 +114,7 @@ export async function getCachedSystemSettings(): Promise<SystemSettings> {
       allowGlobalUsageView: false,
       currencyDisplay: "USD",
       billingModelSource: "original",
+      codexPriorityBillingSource: DEFAULT_SETTINGS.codexPriorityBillingSource,
       timezone: null,
       verboseProviderError: false,
       enableAutoCleanup: false,

+ 7 - 1
src/lib/utils/special-settings.ts

@@ -131,6 +131,8 @@ function buildSettingKey(setting: SpecialSetting): string {
         setting.hit,
         setting.requestedServiceTier,
         setting.actualServiceTier,
+        setting.billingSourcePreference ?? null,
+        setting.resolvedFrom ?? null,
         setting.effectivePriority,
       ]);
     case "response_input_rectifier":
@@ -207,7 +209,11 @@ export function hasPriorityServiceTierSpecialSetting(
       setting.type === "codex_service_tier_result"
   );
   if (codexServiceTierResult) {
-    if (codexServiceTierResult.actualServiceTier != null) {
+    if (
+      codexServiceTierResult.billingSourcePreference == null &&
+      codexServiceTierResult.resolvedFrom == null &&
+      codexServiceTierResult.actualServiceTier != null
+    ) {
       return codexServiceTierResult.actualServiceTier === "priority";
     }
     return codexServiceTierResult.effectivePriority;

+ 3 - 0
src/lib/validation/schemas.ts

@@ -904,6 +904,9 @@ export const UpdateSystemSettingsSchema = z.object({
   billingModelSource: z
     .enum(["original", "redirected"], { message: "不支持的计费模型来源" })
     .optional(),
+  codexPriorityBillingSource: z
+    .enum(["requested", "actual"], { message: "不支持的 Codex Priority 计费来源" })
+    .optional(),
   // 系统时区配置(可选)
   // 必须是有效的 IANA 时区标识符(如 "Asia/Shanghai", "America/New_York")
   timezone: z

+ 3 - 0
src/repository/_shared/transformers.test.ts

@@ -277,6 +277,7 @@ describe("src/repository/_shared/transformers.ts", () => {
       expect(result.allowGlobalUsageView).toBe(true);
       expect(result.currencyDisplay).toBe("USD");
       expect(result.billingModelSource).toBe("original");
+      expect(result.codexPriorityBillingSource).toBe("requested");
       expect(result.timezone).toBeNull();
       expect(result.enableAutoCleanup).toBe(false);
       expect(result.cleanupRetentionDays).toBe(30);
@@ -293,10 +294,12 @@ describe("src/repository/_shared/transformers.ts", () => {
     it("应映射 interceptAnthropicWarmupRequests 字段", () => {
       const result = toSystemSettings({
         id: 1,
+        codexPriorityBillingSource: "actual",
         interceptAnthropicWarmupRequests: true,
       });
 
       expect(result.id).toBe(1);
+      expect(result.codexPriorityBillingSource).toBe("actual");
       expect(result.interceptAnthropicWarmupRequests).toBe(true);
     });
   });

+ 5 - 0
src/repository/_shared/transformers.ts

@@ -197,6 +197,11 @@ export function toSystemSettings(dbSettings: any): SystemSettings {
     allowGlobalUsageView: dbSettings?.allowGlobalUsageView ?? true,
     currencyDisplay: dbSettings?.currencyDisplay ?? "USD",
     billingModelSource: dbSettings?.billingModelSource ?? "original",
+    codexPriorityBillingSource:
+      dbSettings?.codexPriorityBillingSource === "requested" ||
+      dbSettings?.codexPriorityBillingSource === "actual"
+        ? dbSettings.codexPriorityBillingSource
+        : "requested",
     timezone: dbSettings?.timezone ?? null,
     enableAutoCleanup: dbSettings?.enableAutoCleanup ?? false,
     cleanupRetentionDays: dbSettings?.cleanupRetentionDays ?? 30,

+ 130 - 58
src/repository/system-config.ts

@@ -140,6 +140,7 @@ function createFallbackSettings(): SystemSettings {
     allowGlobalUsageView: false,
     currencyDisplay: "USD",
     billingModelSource: "original",
+    codexPriorityBillingSource: "requested",
     timezone: null,
     enableAutoCleanup: false,
     cleanupRetentionDays: 30,
@@ -179,7 +180,7 @@ function createFallbackSettings(): SystemSettings {
  */
 export async function getSystemSettings(): Promise<SystemSettings> {
   async function selectSettingsRow() {
-    const fullSelection = {
+    const selectionWithoutCodexPriorityBillingSource = {
       id: systemSettings.id,
       siteTitle: systemSettings.siteTitle,
       allowGlobalUsageView: systemSettings.allowGlobalUsageView,
@@ -211,6 +212,10 @@ export async function getSystemSettings(): Promise<SystemSettings> {
       createdAt: systemSettings.createdAt,
       updatedAt: systemSettings.updatedAt,
     };
+    const fullSelection = {
+      ...selectionWithoutCodexPriorityBillingSource,
+      codexPriorityBillingSource: systemSettings.codexPriorityBillingSource,
+    };
 
     try {
       const [row] = await db.select(fullSelection).from(systemSettings).limit(1);
@@ -222,18 +227,35 @@ export async function getSystemSettings(): Promise<SystemSettings> {
           error,
         });
 
-        const minimalSelection = {
-          id: systemSettings.id,
-          siteTitle: systemSettings.siteTitle,
-          allowGlobalUsageView: systemSettings.allowGlobalUsageView,
-          currencyDisplay: systemSettings.currencyDisplay,
-          billingModelSource: systemSettings.billingModelSource,
-          createdAt: systemSettings.createdAt,
-          updatedAt: systemSettings.updatedAt,
-        };
-
-        const [row] = await db.select(minimalSelection).from(systemSettings).limit(1);
-        return row ?? null;
+        try {
+          const [row] = await db
+            .select(selectionWithoutCodexPriorityBillingSource)
+            .from(systemSettings)
+            .limit(1);
+          return row ?? null;
+        } catch (fallbackError) {
+          if (!isUndefinedColumnError(fallbackError)) {
+            throw fallbackError;
+          }
+
+          logger.warn("system_settings 表存在多个缺失列,继续使用最小字段集读取。", {
+            error: fallbackError,
+          });
+
+          // 第三层 / 最终回退:仅查询最小核心字段,剩余字段交给 toSystemSettings 补默认值。
+          const minimalSelection = {
+            id: systemSettings.id,
+            siteTitle: systemSettings.siteTitle,
+            allowGlobalUsageView: systemSettings.allowGlobalUsageView,
+            currencyDisplay: systemSettings.currencyDisplay,
+            billingModelSource: systemSettings.billingModelSource,
+            createdAt: systemSettings.createdAt,
+            updatedAt: systemSettings.updatedAt,
+          };
+
+          const [row] = await db.select(minimalSelection).from(systemSettings).limit(1);
+          return row ?? null;
+        }
       }
 
       throw error;
@@ -247,15 +269,36 @@ export async function getSystemSettings(): Promise<SystemSettings> {
       return toSystemSettings(settings);
     }
 
-    await db
-      .insert(systemSettings)
-      .values({
-        siteTitle: DEFAULT_SITE_TITLE,
-        allowGlobalUsageView: false,
-        currencyDisplay: "USD",
-        billingModelSource: "original",
-      })
-      .onConflictDoNothing();
+    try {
+      await db
+        .insert(systemSettings)
+        .values({
+          siteTitle: DEFAULT_SITE_TITLE,
+          allowGlobalUsageView: false,
+          currencyDisplay: "USD",
+          billingModelSource: "original",
+          codexPriorityBillingSource: "requested",
+        })
+        .onConflictDoNothing();
+    } catch (error) {
+      if (!isUndefinedColumnError(error)) {
+        throw error;
+      }
+
+      logger.warn("system_settings 表列缺失,使用降级字段集初始化默认记录。", {
+        error,
+      });
+
+      await db
+        .insert(systemSettings)
+        .values({
+          siteTitle: DEFAULT_SITE_TITLE,
+          allowGlobalUsageView: false,
+          currencyDisplay: "USD",
+          billingModelSource: "original",
+        })
+        .onConflictDoNothing();
+    }
 
     const fallback = await selectSettingsRow();
     if (!fallback) {
@@ -278,9 +321,46 @@ export async function getSystemSettings(): Promise<SystemSettings> {
 export async function updateSystemSettings(
   payload: UpdateSystemSettingsInput
 ): Promise<SystemSettings> {
-  const current = await getSystemSettings();
+  const returningWithoutCodexPriorityBillingSource = {
+    id: systemSettings.id,
+    siteTitle: systemSettings.siteTitle,
+    allowGlobalUsageView: systemSettings.allowGlobalUsageView,
+    currencyDisplay: systemSettings.currencyDisplay,
+    billingModelSource: systemSettings.billingModelSource,
+    timezone: systemSettings.timezone,
+    enableAutoCleanup: systemSettings.enableAutoCleanup,
+    cleanupRetentionDays: systemSettings.cleanupRetentionDays,
+    cleanupSchedule: systemSettings.cleanupSchedule,
+    cleanupBatchSize: systemSettings.cleanupBatchSize,
+    enableClientVersionCheck: systemSettings.enableClientVersionCheck,
+    verboseProviderError: systemSettings.verboseProviderError,
+    enableHttp2: systemSettings.enableHttp2,
+    interceptAnthropicWarmupRequests: systemSettings.interceptAnthropicWarmupRequests,
+    enableThinkingSignatureRectifier: systemSettings.enableThinkingSignatureRectifier,
+    enableThinkingBudgetRectifier: systemSettings.enableThinkingBudgetRectifier,
+    enableBillingHeaderRectifier: systemSettings.enableBillingHeaderRectifier,
+    enableResponseInputRectifier: systemSettings.enableResponseInputRectifier,
+    enableCodexSessionIdCompletion: systemSettings.enableCodexSessionIdCompletion,
+    enableClaudeMetadataUserIdInjection: systemSettings.enableClaudeMetadataUserIdInjection,
+    enableResponseFixer: systemSettings.enableResponseFixer,
+    responseFixerConfig: systemSettings.responseFixerConfig,
+    quotaDbRefreshIntervalSeconds: systemSettings.quotaDbRefreshIntervalSeconds,
+    quotaLeasePercent5h: systemSettings.quotaLeasePercent5h,
+    quotaLeasePercentDaily: systemSettings.quotaLeasePercentDaily,
+    quotaLeasePercentWeekly: systemSettings.quotaLeasePercentWeekly,
+    quotaLeasePercentMonthly: systemSettings.quotaLeasePercentMonthly,
+    quotaLeaseCapUsd: systemSettings.quotaLeaseCapUsd,
+    createdAt: systemSettings.createdAt,
+    updatedAt: systemSettings.updatedAt,
+  };
+  const fullReturning = {
+    ...returningWithoutCodexPriorityBillingSource,
+    codexPriorityBillingSource: systemSettings.codexPriorityBillingSource,
+  };
 
   try {
+    const current = await getSystemSettings();
+
     // 构建更新对象,只更新提供的字段(非 undefined)
     const updates: Partial<typeof systemSettings.$inferInsert> = {
       updatedAt: new Date(),
@@ -303,6 +383,9 @@ export async function updateSystemSettings(
     if (payload.billingModelSource !== undefined) {
       updates.billingModelSource = payload.billingModelSource;
     }
+    if (payload.codexPriorityBillingSource !== undefined) {
+      updates.codexPriorityBillingSource = payload.codexPriorityBillingSource;
+    }
 
     // 系统时区配置字段(如果提供)
     if (payload.timezone !== undefined) {
@@ -406,43 +489,32 @@ export async function updateSystemSettings(
         payload.quotaLeaseCapUsd === null ? null : String(payload.quotaLeaseCapUsd);
     }
 
-    const [updated] = await db
-      .update(systemSettings)
-      .set(updates)
-      .where(eq(systemSettings.id, current.id))
-      .returning({
-        id: systemSettings.id,
-        siteTitle: systemSettings.siteTitle,
-        allowGlobalUsageView: systemSettings.allowGlobalUsageView,
-        currencyDisplay: systemSettings.currencyDisplay,
-        billingModelSource: systemSettings.billingModelSource,
-        timezone: systemSettings.timezone,
-        enableAutoCleanup: systemSettings.enableAutoCleanup,
-        cleanupRetentionDays: systemSettings.cleanupRetentionDays,
-        cleanupSchedule: systemSettings.cleanupSchedule,
-        cleanupBatchSize: systemSettings.cleanupBatchSize,
-        enableClientVersionCheck: systemSettings.enableClientVersionCheck,
-        verboseProviderError: systemSettings.verboseProviderError,
-        enableHttp2: systemSettings.enableHttp2,
-        interceptAnthropicWarmupRequests: systemSettings.interceptAnthropicWarmupRequests,
-        enableThinkingSignatureRectifier: systemSettings.enableThinkingSignatureRectifier,
-        enableThinkingBudgetRectifier: systemSettings.enableThinkingBudgetRectifier,
-        enableBillingHeaderRectifier: systemSettings.enableBillingHeaderRectifier,
-        enableResponseInputRectifier: systemSettings.enableResponseInputRectifier,
-        enableCodexSessionIdCompletion: systemSettings.enableCodexSessionIdCompletion,
-        enableClaudeMetadataUserIdInjection: systemSettings.enableClaudeMetadataUserIdInjection,
-        enableResponseFixer: systemSettings.enableResponseFixer,
-        responseFixerConfig: systemSettings.responseFixerConfig,
-        quotaDbRefreshIntervalSeconds: systemSettings.quotaDbRefreshIntervalSeconds,
-        quotaLeasePercent5h: systemSettings.quotaLeasePercent5h,
-        quotaLeasePercentDaily: systemSettings.quotaLeasePercentDaily,
-        quotaLeasePercentWeekly: systemSettings.quotaLeasePercentWeekly,
-        quotaLeasePercentMonthly: systemSettings.quotaLeasePercentMonthly,
-        quotaLeaseCapUsd: systemSettings.quotaLeaseCapUsd,
-        createdAt: systemSettings.createdAt,
-        updatedAt: systemSettings.updatedAt,
+    let updated;
+    try {
+      [updated] = await db
+        .update(systemSettings)
+        .set(updates)
+        .where(eq(systemSettings.id, current.id))
+        .returning(fullReturning);
+    } catch (error) {
+      if (!isUndefinedColumnError(error)) {
+        throw error;
+      }
+
+      logger.warn("system_settings 表列缺失,使用降级字段集更新系统设置。", {
+        error,
       });
 
+      const downgradedUpdates = { ...updates };
+      delete downgradedUpdates.codexPriorityBillingSource;
+
+      [updated] = await db
+        .update(systemSettings)
+        .set(downgradedUpdates)
+        .where(eq(systemSettings.id, current.id))
+        .returning(returningWithoutCodexPriorityBillingSource);
+    }
+
     if (!updated) {
       throw new Error("更新系统设置失败");
     }

+ 2 - 0
src/types/special-settings.ts

@@ -252,6 +252,8 @@ export type CodexServiceTierResultSpecialSetting = {
   hit: boolean;
   requestedServiceTier: string | null;
   actualServiceTier: string | null;
+  billingSourcePreference?: "requested" | "actual" | null;
+  resolvedFrom?: "requested" | "actual" | null;
   effectivePriority: boolean;
 };
 

+ 7 - 0
src/types/system-config.ts

@@ -2,6 +2,7 @@ import type { CurrencyCode } from "@/lib/utils";
 
 // 计费模型来源: 'original' (重定向前) | 'redirected' (重定向后)
 export type BillingModelSource = "original" | "redirected";
+export type CodexPriorityBillingSource = "requested" | "actual";
 
 export interface ResponseFixerConfig {
   fixTruncatedJson: boolean;
@@ -22,6 +23,9 @@ export interface SystemSettings {
   // 计费模型来源配置
   billingModelSource: BillingModelSource;
 
+  // Codex Priority 单独计费口径
+  codexPriorityBillingSource: CodexPriorityBillingSource;
+
   // 系统时区配置 (IANA timezone identifier)
   // 用于统一后端时间边界计算和前端日期/时间显示
   // null 表示使用环境变量 TZ 或默认 UTC
@@ -98,6 +102,9 @@ export interface UpdateSystemSettingsInput {
   // 计费模型来源配置(可选)
   billingModelSource?: BillingModelSource;
 
+  // Codex Priority 单独计费口径(可选)
+  codexPriorityBillingSource?: CodexPriorityBillingSource;
+
   // 系统时区配置(可选)
   timezone?: string | null;
 

+ 272 - 5
tests/integration/billing-model-source.test.ts

@@ -78,6 +78,7 @@ vi.mock("@/lib/proxy-status-tracker", () => ({
 
 import { ProxyResponseHandler } from "@/app/v1/_lib/proxy/response-handler";
 import { ProxySession } from "@/app/v1/_lib/proxy/session";
+import { getCachedSystemSettings, invalidateSystemSettingsCache } from "@/lib/config";
 import { SessionManager } from "@/lib/session-manager";
 import { RateLimitService } from "@/lib/rate-limit";
 import { SessionTracker } from "@/lib/session-tracker";
@@ -91,10 +92,12 @@ import { getSystemSettings } from "@/repository/system-config";
 
 beforeEach(() => {
   cloudPriceSyncRequests.splice(0, cloudPriceSyncRequests.length);
+  invalidateSystemSettingsCache();
 });
 
 function makeSystemSettings(
-  billingModelSource: SystemSettings["billingModelSource"]
+  billingModelSource: SystemSettings["billingModelSource"],
+  codexPriorityBillingSource: SystemSettings["codexPriorityBillingSource"] = "requested"
 ): SystemSettings {
   const now = new Date();
   return {
@@ -103,6 +106,7 @@ function makeSystemSettings(
     allowGlobalUsageView: false,
     currencyDisplay: "USD",
     billingModelSource,
+    codexPriorityBillingSource,
     timezone: null,
     enableAutoCleanup: false,
     cleanupRetentionDays: 30,
@@ -112,6 +116,12 @@ function makeSystemSettings(
     verboseProviderError: false,
     enableHttp2: false,
     interceptAnthropicWarmupRequests: false,
+    enableThinkingSignatureRectifier: true,
+    enableThinkingBudgetRectifier: true,
+    enableBillingHeaderRectifier: true,
+    enableResponseInputRectifier: true,
+    enableCodexSessionIdCompletion: true,
+    enableClaudeMetadataUserIdInjection: true,
     enableResponseFixer: true,
     responseFixerConfig: {
       fixTruncatedJson: true,
@@ -260,6 +270,16 @@ async function drainAsyncTasks(): Promise<void> {
   await Promise.all(tasks);
 }
 
+function captureRateLimitCosts(): number[] {
+  const rateLimitCosts: number[] = [];
+  vi.mocked(RateLimitService.trackCost).mockImplementation(
+    async (_keyId: number, _providerId: number, _sessionId: string, costUsd: number) => {
+      rateLimitCosts.push(costUsd);
+    }
+  );
+  return rateLimitCosts;
+}
+
 async function runScenario({
   billingModelSource,
   isStream,
@@ -267,6 +287,8 @@ async function runScenario({
   billingModelSource: SystemSettings["billingModelSource"];
   isStream: boolean;
 }): Promise<{ dbCostUsd: string; sessionCostUsd: string; rateLimitCost: number }> {
+  invalidateSystemSettingsCache();
+
   const usage = { input_tokens: 2, output_tokens: 3 };
   const originalModel = "original-model";
   const redirectedModel = "redirected-model";
@@ -411,6 +433,7 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
         dbCosts.push(String(costUsd));
       }
     );
+    const rateLimitCosts = captureRateLimitCosts();
 
     const sessionCosts: string[] = [];
     vi.mocked(SessionManager.updateSessionUsage).mockImplementation(
@@ -441,7 +464,7 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
     expect(sessionCosts[0]).toBe("50");
   });
 
-  it("codex fast: uses priority pricing when response reports service_tier=priority", async () => {
+  it("codex fast: requested mode ignores actual priority when request tier is default", async () => {
     vi.mocked(getSystemSettings).mockResolvedValue(makeSystemSettings("redirected"));
     vi.mocked(updateMessageRequestDetails).mockResolvedValue(undefined);
     vi.mocked(updateMessageRequestDuration).mockResolvedValue(undefined);
@@ -474,6 +497,7 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
         dbCosts.push(String(costUsd));
       }
     );
+    const rateLimitCosts = captureRateLimitCosts();
 
     const sessionCosts: string[] = [];
     vi.mocked(SessionManager.updateSessionUsage).mockImplementation(
@@ -504,8 +528,9 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
     await ProxyResponseHandler.dispatch(session, response);
     await drainAsyncTasks();
 
-    expect(dbCosts[0]).toBe("64");
-    expect(sessionCosts[0]).toBe("64");
+    expect(dbCosts[0]).toBe("32");
+    expect(sessionCosts[0]).toBe("32");
+    expect(rateLimitCosts[0]).toBe(32);
   });
 
   it("codex fast: falls back to requested priority pricing when response omits service_tier", async () => {
@@ -541,6 +566,7 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
         dbCosts.push(String(costUsd));
       }
     );
+    const rateLimitCosts = captureRateLimitCosts();
 
     const session = createSession({
       originalModel: "gpt-5.4",
@@ -560,6 +586,7 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
     await drainAsyncTasks();
 
     expect(dbCosts[0]).toBe("64");
+    expect(rateLimitCosts[0]).toBe(64);
   });
 
   it("codex fast: uses long-context priority pricing when request is priority and response omits service_tier", async () => {
@@ -599,6 +626,7 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
         dbCosts.push(String(costUsd));
       }
     );
+    const rateLimitCosts = captureRateLimitCosts();
 
     const sessionCosts: string[] = [];
     vi.mocked(SessionManager.updateSessionUsage).mockImplementation(
@@ -628,9 +656,10 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
 
     expect(dbCosts[0]).toBe("1904147");
     expect(sessionCosts[0]).toBe("1904147");
+    expect(rateLimitCosts[0]).toBe(1904147);
   });
 
-  it("codex fast: does not use priority pricing when response explicitly reports non-priority tier", async () => {
+  it("codex fast: requested mode keeps priority pricing even when actual tier is downgraded", async () => {
     vi.mocked(getSystemSettings).mockResolvedValue(makeSystemSettings("redirected"));
     vi.mocked(updateMessageRequestDetails).mockResolvedValue(undefined);
     vi.mocked(updateMessageRequestDuration).mockResolvedValue(undefined);
@@ -663,6 +692,7 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
         dbCosts.push(String(costUsd));
       }
     );
+    const rateLimitCosts = captureRateLimitCosts();
 
     const session = createSession({
       originalModel: "gpt-5.4",
@@ -684,7 +714,244 @@ describe("Billing model source - Redis session cost vs DB cost", () => {
     await ProxyResponseHandler.dispatch(session, response);
     await drainAsyncTasks();
 
+    expect(dbCosts[0]).toBe("64");
+    expect(rateLimitCosts[0]).toBe(64);
+  });
+
+  it("codex fast: actual mode uses priority pricing when response reports service_tier=priority", async () => {
+    vi.mocked(getSystemSettings).mockResolvedValue(makeSystemSettings("redirected", "actual"));
+    vi.mocked(updateMessageRequestDetails).mockResolvedValue(undefined);
+    vi.mocked(updateMessageRequestDuration).mockResolvedValue(undefined);
+    vi.mocked(SessionManager.storeSessionResponse).mockResolvedValue(undefined);
+    vi.mocked(RateLimitService.trackUserDailyCost).mockResolvedValue(undefined);
+    vi.mocked(SessionTracker.refreshSession).mockResolvedValue(undefined);
+
+    vi.mocked(findLatestPriceByModel).mockImplementation(async (modelName: string) => {
+      if (modelName === "gpt-5.4") {
+        return makePriceRecord(modelName, {
+          mode: "responses",
+          model_family: "gpt",
+          litellm_provider: "chatgpt",
+          pricing: {
+            openai: {
+              input_cost_per_token: 1,
+              output_cost_per_token: 10,
+              input_cost_per_token_priority: 2,
+              output_cost_per_token_priority: 20,
+            },
+          },
+        });
+      }
+      return null;
+    });
+
+    const dbCosts: string[] = [];
+    vi.mocked(updateMessageRequestCost).mockImplementation(
+      async (_id: number, costUsd: unknown) => {
+        dbCosts.push(String(costUsd));
+      }
+    );
+    const rateLimitCosts = captureRateLimitCosts();
+
+    const session = createSession({
+      originalModel: "gpt-5.4",
+      redirectedModel: "gpt-5.4",
+      sessionId: "sess-gpt54-priority-actual-mode-upgrade",
+      messageId: 3204,
+      providerOverrides: {
+        name: "ChatGPT",
+        url: "https://chatgpt.com/backend-api/codex",
+        providerType: "codex",
+      },
+      requestMessage: { service_tier: "default" },
+    });
+
+    const response = createNonStreamResponse(
+      { input_tokens: 2, output_tokens: 3 },
+      { service_tier: "priority" }
+    );
+    await ProxyResponseHandler.dispatch(session, response);
+    await drainAsyncTasks();
+
+    expect(dbCosts[0]).toBe("64");
+    expect(rateLimitCosts[0]).toBe(64);
+  });
+
+  it("codex fast: actual mode does not use priority pricing when response explicitly reports non-priority tier", async () => {
+    vi.mocked(getSystemSettings).mockResolvedValue(makeSystemSettings("redirected", "actual"));
+    vi.mocked(updateMessageRequestDetails).mockResolvedValue(undefined);
+    vi.mocked(updateMessageRequestDuration).mockResolvedValue(undefined);
+    vi.mocked(SessionManager.storeSessionResponse).mockResolvedValue(undefined);
+    vi.mocked(RateLimitService.trackUserDailyCost).mockResolvedValue(undefined);
+    vi.mocked(SessionTracker.refreshSession).mockResolvedValue(undefined);
+
+    vi.mocked(findLatestPriceByModel).mockImplementation(async (modelName: string) => {
+      if (modelName === "gpt-5.4") {
+        return makePriceRecord(modelName, {
+          mode: "responses",
+          model_family: "gpt",
+          litellm_provider: "chatgpt",
+          pricing: {
+            openai: {
+              input_cost_per_token: 1,
+              output_cost_per_token: 10,
+              input_cost_per_token_priority: 2,
+              output_cost_per_token_priority: 20,
+            },
+          },
+        });
+      }
+      return null;
+    });
+
+    const dbCosts: string[] = [];
+    vi.mocked(updateMessageRequestCost).mockImplementation(
+      async (_id: number, costUsd: unknown) => {
+        dbCosts.push(String(costUsd));
+      }
+    );
+    const rateLimitCosts = captureRateLimitCosts();
+
+    const session = createSession({
+      originalModel: "gpt-5.4",
+      redirectedModel: "gpt-5.4",
+      sessionId: "sess-gpt54-priority-actual-mode-downgrade",
+      messageId: 3205,
+      providerOverrides: {
+        name: "ChatGPT",
+        url: "https://chatgpt.com/backend-api/codex",
+        providerType: "codex",
+      },
+      requestMessage: { service_tier: "priority" },
+    });
+
+    const response = createNonStreamResponse(
+      { input_tokens: 2, output_tokens: 3 },
+      { service_tier: "default" }
+    );
+    await ProxyResponseHandler.dispatch(session, response);
+    await drainAsyncTasks();
+
+    expect(dbCosts[0]).toBe("32");
+    expect(rateLimitCosts[0]).toBe(32);
+  });
+
+  it("codex fast: actual mode falls back to requested priority pricing when response omits service_tier", async () => {
+    vi.mocked(getSystemSettings).mockResolvedValue(makeSystemSettings("redirected", "actual"));
+    vi.mocked(updateMessageRequestDetails).mockResolvedValue(undefined);
+    vi.mocked(updateMessageRequestDuration).mockResolvedValue(undefined);
+    vi.mocked(SessionManager.storeSessionResponse).mockResolvedValue(undefined);
+    vi.mocked(RateLimitService.trackUserDailyCost).mockResolvedValue(undefined);
+    vi.mocked(SessionTracker.refreshSession).mockResolvedValue(undefined);
+
+    vi.mocked(findLatestPriceByModel).mockImplementation(async (modelName: string) => {
+      if (modelName === "gpt-5.4") {
+        return makePriceRecord(modelName, {
+          mode: "responses",
+          model_family: "gpt",
+          litellm_provider: "chatgpt",
+          pricing: {
+            openai: {
+              input_cost_per_token: 1,
+              output_cost_per_token: 10,
+              input_cost_per_token_priority: 2,
+              output_cost_per_token_priority: 20,
+            },
+          },
+        });
+      }
+      return null;
+    });
+
+    const dbCosts: string[] = [];
+    vi.mocked(updateMessageRequestCost).mockImplementation(
+      async (_id: number, costUsd: unknown) => {
+        dbCosts.push(String(costUsd));
+      }
+    );
+    const rateLimitCosts = captureRateLimitCosts();
+
+    const session = createSession({
+      originalModel: "gpt-5.4",
+      redirectedModel: "gpt-5.4",
+      sessionId: "sess-gpt54-priority-actual-mode-fallback",
+      messageId: 3206,
+      providerOverrides: {
+        name: "ChatGPT",
+        url: "https://chatgpt.com/backend-api/codex",
+        providerType: "codex",
+      },
+      requestMessage: { service_tier: "priority" },
+    });
+
+    const response = createNonStreamResponse({ input_tokens: 2, output_tokens: 3 });
+    await ProxyResponseHandler.dispatch(session, response);
+    await drainAsyncTasks();
+
+    expect(dbCosts[0]).toBe("64");
+    expect(rateLimitCosts[0]).toBe(64);
+  });
+
+  it("codex fast: actual mode reuses cached system setting when direct settings read fails", async () => {
+    vi.mocked(getSystemSettings).mockResolvedValueOnce(makeSystemSettings("redirected", "actual"));
+    await getCachedSystemSettings();
+
+    vi.mocked(getSystemSettings).mockRejectedValueOnce(new Error("db down"));
+    vi.mocked(updateMessageRequestDetails).mockResolvedValue(undefined);
+    vi.mocked(updateMessageRequestDuration).mockResolvedValue(undefined);
+    vi.mocked(SessionManager.storeSessionResponse).mockResolvedValue(undefined);
+    vi.mocked(RateLimitService.trackUserDailyCost).mockResolvedValue(undefined);
+    vi.mocked(SessionTracker.refreshSession).mockResolvedValue(undefined);
+
+    vi.mocked(findLatestPriceByModel).mockImplementation(async (modelName: string) => {
+      if (modelName === "gpt-5.4") {
+        return makePriceRecord(modelName, {
+          mode: "responses",
+          model_family: "gpt",
+          litellm_provider: "chatgpt",
+          pricing: {
+            openai: {
+              input_cost_per_token: 1,
+              output_cost_per_token: 10,
+              input_cost_per_token_priority: 2,
+              output_cost_per_token_priority: 20,
+            },
+          },
+        });
+      }
+      return null;
+    });
+
+    const dbCosts: string[] = [];
+    vi.mocked(updateMessageRequestCost).mockImplementation(
+      async (_id: number, costUsd: unknown) => {
+        dbCosts.push(String(costUsd));
+      }
+    );
+    const rateLimitCosts = captureRateLimitCosts();
+
+    const session = createSession({
+      originalModel: "gpt-5.4",
+      redirectedModel: "gpt-5.4",
+      sessionId: "sess-gpt54-priority-actual-mode-cached-settings",
+      messageId: 3207,
+      providerOverrides: {
+        name: "ChatGPT",
+        url: "https://chatgpt.com/backend-api/codex",
+        providerType: "codex",
+      },
+      requestMessage: { service_tier: "priority" },
+    });
+
+    const response = createNonStreamResponse(
+      { input_tokens: 2, output_tokens: 3 },
+      { service_tier: "default" }
+    );
+    await ProxyResponseHandler.dispatch(session, response);
+    await drainAsyncTasks();
+
     expect(dbCosts[0]).toBe("32");
+    expect(rateLimitCosts[0]).toBe(32);
   });
 });
 

+ 16 - 0
tests/unit/actions/system-config-save.test.ts

@@ -55,6 +55,7 @@ describe("saveSystemSettings", () => {
       allowGlobalUsageView: false,
       currencyDisplay: "CNY",
       billingModelSource: "original",
+      codexPriorityBillingSource: "requested",
       timezone: null,
       enableAutoCleanup: false,
       cleanupRetentionDays: 30,
@@ -179,6 +180,7 @@ describe("saveSystemSettings", () => {
       allowGlobalUsageView: true,
       currencyDisplay: "USD",
       billingModelSource: "original",
+      codexPriorityBillingSource: "actual",
       timezone: "America/New_York",
       enableAutoCleanup: false,
       cleanupRetentionDays: 30,
@@ -217,6 +219,7 @@ describe("saveSystemSettings", () => {
       siteTitle: "Updated Title",
       allowGlobalUsageView: true,
       currencyDisplay: "USD",
+      codexPriorityBillingSource: "actual",
       timezone: "America/New_York",
       verboseProviderError: true,
       enableHttp2: true,
@@ -234,4 +237,17 @@ describe("saveSystemSettings", () => {
     expect(result.ok).toBe(false);
     expect(result.error).toContain("Database error");
   });
+
+  it("should pass codexPriorityBillingSource through validation and save", async () => {
+    const result = await saveSystemSettings({
+      codexPriorityBillingSource: "actual",
+    });
+
+    expect(result.ok).toBe(true);
+    expect(updateSystemSettingsMock).toHaveBeenCalledWith(
+      expect.objectContaining({
+        codexPriorityBillingSource: "actual",
+      })
+    );
+  });
 });

+ 2 - 0
tests/unit/lib/config/system-settings-cache.test.ts

@@ -30,6 +30,7 @@ function createSettings(overrides: Partial<SystemSettings> = {}): SystemSettings
     allowGlobalUsageView: false,
     currencyDisplay: "USD",
     billingModelSource: "original",
+    codexPriorityBillingSource: "requested",
     timezone: null,
     enableAutoCleanup: false,
     cleanupRetentionDays: 30,
@@ -145,6 +146,7 @@ describe("SystemSettingsCache", () => {
         siteTitle: "Claude Code Hub",
         enableHttp2: false,
         interceptAnthropicWarmupRequests: false,
+        codexPriorityBillingSource: "requested",
       })
     );
     expect(loggerWarnMock).toHaveBeenCalledTimes(1);

+ 22 - 1
tests/unit/lib/utils/special-settings.test.ts

@@ -173,13 +173,15 @@ describe("hasPriorityServiceTierSpecialSetting", () => {
           hit: true,
           requestedServiceTier: "default",
           actualServiceTier: "priority",
+          billingSourcePreference: "actual",
+          resolvedFrom: "actual",
           effectivePriority: true,
         },
       ])
     ).toBe(true);
   });
 
-  test("returns false when codex actual service tier is non-priority even if request was priority", () => {
+  test("returns true when billing follows requested priority even if actual tier is downgraded", () => {
     expect(
       hasPriorityServiceTierSpecialSetting([
         {
@@ -198,6 +200,25 @@ describe("hasPriorityServiceTierSpecialSetting", () => {
           hit: true,
           requestedServiceTier: "priority",
           actualServiceTier: "default",
+          billingSourcePreference: "requested",
+          resolvedFrom: "requested",
+          effectivePriority: true,
+        },
+      ])
+    ).toBe(true);
+  });
+
+  test("returns false when billing follows actual non-priority tier", () => {
+    expect(
+      hasPriorityServiceTierSpecialSetting([
+        {
+          type: "codex_service_tier_result",
+          scope: "response",
+          hit: true,
+          requestedServiceTier: "priority",
+          actualServiceTier: "default",
+          billingSourcePreference: "actual",
+          resolvedFrom: "actual",
           effectivePriority: false,
         },
       ])

+ 16 - 5
tests/unit/proxy/session.test.ts

@@ -1,6 +1,7 @@
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
 import { isRawPassthroughEndpointPolicy } from "@/app/v1/_lib/proxy/endpoint-policy";
 import { V1_ENDPOINT_PATHS } from "@/app/v1/_lib/proxy/endpoint-paths";
+import { invalidateSystemSettingsCache } from "@/lib/config";
 import type { ModelPrice, ModelPriceData } from "@/types/model-price";
 import type { SystemSettings } from "@/types/system-config";
 import type { Provider } from "@/types/provider";
@@ -27,6 +28,7 @@ function makeSystemSettings(
     allowGlobalUsageView: false,
     currencyDisplay: "USD",
     billingModelSource,
+    codexPriorityBillingSource: "requested",
     timezone: null,
     enableAutoCleanup: false,
     cleanupRetentionDays: 30,
@@ -36,6 +38,12 @@ function makeSystemSettings(
     verboseProviderError: false,
     enableHttp2: false,
     interceptAnthropicWarmupRequests: false,
+    enableThinkingSignatureRectifier: true,
+    enableThinkingBudgetRectifier: true,
+    enableBillingHeaderRectifier: true,
+    enableResponseInputRectifier: true,
+    enableCodexSessionIdCompletion: true,
+    enableClaudeMetadataUserIdInjection: true,
     enableResponseFixer: true,
     responseFixerConfig: {
       fixTruncatedJson: true,
@@ -49,6 +57,10 @@ function makeSystemSettings(
   };
 }
 
+beforeEach(() => {
+  invalidateSystemSettingsCache();
+});
+
 function makePriceRecord(modelName: string, priceData: ModelPriceData): ModelPrice {
   return {
     id: 1,
@@ -255,7 +267,7 @@ describe("ProxySession.getCachedPriceDataByBillingSource", () => {
     expect(findLatestPriceByModel).toHaveBeenNthCalledWith(2, "redirected-model");
   });
 
-  it("应在 getSystemSettings 失败时回退到 redirected", async () => {
+  it("应在 getSystemSettings 失败且无缓存时跳过价格解析", async () => {
     const redirectedPriceData: ModelPriceData = {
       input_cost_per_token: 3,
       output_cost_per_token: 4,
@@ -272,10 +284,9 @@ describe("ProxySession.getCachedPriceDataByBillingSource", () => {
     });
 
     const result = await session.getCachedPriceDataByBillingSource();
-    expect(result).toEqual(redirectedPriceData);
+    expect(result).toBeNull();
     expect(getSystemSettings).toHaveBeenCalledTimes(1);
-    expect(findLatestPriceByModel).toHaveBeenCalledTimes(1);
-    expect(findLatestPriceByModel).toHaveBeenCalledWith("redirected-model");
+    expect(findLatestPriceByModel).not.toHaveBeenCalled();
 
     const internal = session as unknown as { cachedBillingModelSource?: unknown };
     expect(internal.cachedBillingModelSource).toBe("redirected");

+ 228 - 0
tests/unit/repository/system-config-update-missing-columns.test.ts

@@ -16,6 +16,22 @@ function createThenableQuery<T>(result: T) {
   return query;
 }
 
+function createRejectedThenableQuery(error: unknown) {
+  const query: any = {};
+
+  query.from = vi.fn(() => query);
+  query.limit = vi.fn(() => Promise.reject(error));
+
+  query.set = vi.fn(() => query);
+  query.where = vi.fn(() => query);
+  query.returning = vi.fn(() => Promise.reject(error));
+
+  query.values = vi.fn(() => query);
+  query.onConflictDoNothing = vi.fn(() => Promise.reject(error));
+
+  return query;
+}
+
 describe("SystemSettings:数据库缺列时的保存兜底", () => {
   test("updateSystemSettings 遇到 42703(列缺失)应返回可行动的错误信息", async () => {
     vi.resetModules();
@@ -112,4 +128,216 @@ describe("SystemSettings:数据库缺列时的保存兜底", () => {
 
     vi.useRealTimers();
   });
+
+  test("getSystemSettings 在仅缺 codex_priority_billing_source 列时应保留已有设置", async () => {
+    vi.resetModules();
+
+    const now = new Date("2026-01-04T00:00:00.000Z");
+    vi.useFakeTimers();
+    vi.setSystemTime(now);
+
+    const selectMock = vi
+      .fn()
+      .mockReturnValueOnce(createRejectedThenableQuery({ code: "42703" }))
+      .mockReturnValueOnce(
+        createThenableQuery([
+          {
+            id: 1,
+            siteTitle: "Claude Code Hub",
+            allowGlobalUsageView: false,
+            currencyDisplay: "USD",
+            billingModelSource: "original",
+            timezone: "Asia/Shanghai",
+            enableAutoCleanup: true,
+            cleanupRetentionDays: 90,
+            cleanupSchedule: "0 3 * * *",
+            cleanupBatchSize: 5000,
+            enableClientVersionCheck: true,
+            verboseProviderError: true,
+            enableHttp2: true,
+            interceptAnthropicWarmupRequests: true,
+            enableThinkingSignatureRectifier: false,
+            enableThinkingBudgetRectifier: false,
+            enableBillingHeaderRectifier: false,
+            enableResponseInputRectifier: false,
+            enableCodexSessionIdCompletion: false,
+            enableClaudeMetadataUserIdInjection: false,
+            enableResponseFixer: false,
+            responseFixerConfig: {
+              fixTruncatedJson: false,
+              fixSseFormat: false,
+              fixEncoding: false,
+              maxJsonDepth: 50,
+              maxFixSize: 2048,
+            },
+            quotaDbRefreshIntervalSeconds: 30,
+            quotaLeasePercent5h: "0.10",
+            quotaLeasePercentDaily: "0.11",
+            quotaLeasePercentWeekly: "0.12",
+            quotaLeasePercentMonthly: "0.13",
+            quotaLeaseCapUsd: "1.50",
+            createdAt: now,
+            updatedAt: now,
+          },
+        ])
+      );
+
+    vi.doMock("@/drizzle/db", () => ({
+      db: {
+        select: selectMock,
+        update: vi.fn(() => createThenableQuery([])),
+        insert: vi.fn(() => createThenableQuery([])),
+        execute: vi.fn(async () => ({ count: 0 })),
+      },
+    }));
+
+    const { getSystemSettings } = await import("@/repository/system-config");
+
+    const result = await getSystemSettings();
+
+    expect(result.codexPriorityBillingSource).toBe("requested");
+    expect(result.enableHttp2).toBe(true);
+    expect(result.interceptAnthropicWarmupRequests).toBe(true);
+    expect(result.verboseProviderError).toBe(true);
+    expect(result.quotaLeasePercentDaily).toBe(0.11);
+
+    vi.useRealTimers();
+  });
+
+  test("getSystemSettings 在缺少新列且无记录时应使用降级插入初始化", async () => {
+    vi.resetModules();
+
+    const now = new Date("2026-01-04T00:00:00.000Z");
+    vi.useFakeTimers();
+    vi.setSystemTime(now);
+
+    const selectMock = vi
+      .fn()
+      .mockReturnValueOnce(createRejectedThenableQuery({ code: "42703" }))
+      .mockReturnValueOnce(createThenableQuery([]))
+      .mockReturnValueOnce(createRejectedThenableQuery({ code: "42703" }))
+      .mockReturnValueOnce(
+        createThenableQuery([
+          {
+            id: 1,
+            siteTitle: "Claude Code Hub",
+            allowGlobalUsageView: false,
+            currencyDisplay: "USD",
+            billingModelSource: "original",
+            createdAt: now,
+            updatedAt: now,
+          },
+        ])
+      );
+
+    const rejectedInsertQuery = createThenableQuery([] as unknown[]);
+    rejectedInsertQuery.onConflictDoNothing = vi.fn(() => Promise.reject({ code: "42703" }));
+
+    const insertMock = vi
+      .fn()
+      .mockReturnValueOnce(rejectedInsertQuery)
+      .mockReturnValueOnce(createThenableQuery([]));
+
+    vi.doMock("@/drizzle/db", () => ({
+      db: {
+        select: selectMock,
+        update: vi.fn(() => createThenableQuery([])),
+        insert: insertMock,
+        execute: vi.fn(async () => ({ count: 0 })),
+      },
+    }));
+
+    const { getSystemSettings } = await import("@/repository/system-config");
+
+    const result = await getSystemSettings();
+
+    expect(result.siteTitle).toBe("Claude Code Hub");
+    expect(result.codexPriorityBillingSource).toBe("requested");
+    expect(insertMock).toHaveBeenCalledTimes(2);
+
+    vi.useRealTimers();
+  });
+
+  test("updateSystemSettings 在仅缺新列时应降级保存其他字段", async () => {
+    vi.resetModules();
+
+    const now = new Date("2026-01-04T00:00:00.000Z");
+    vi.useFakeTimers();
+    vi.setSystemTime(now);
+
+    const selectMock = vi
+      .fn()
+      .mockReturnValueOnce(createRejectedThenableQuery({ code: "42703" }))
+      .mockReturnValueOnce(
+        createThenableQuery([
+          {
+            id: 1,
+            siteTitle: "Claude Code Hub",
+            allowGlobalUsageView: false,
+            currencyDisplay: "USD",
+            billingModelSource: "original",
+            enableAutoCleanup: false,
+            cleanupRetentionDays: 30,
+            cleanupSchedule: "0 2 * * *",
+            cleanupBatchSize: 10000,
+            enableClientVersionCheck: false,
+            verboseProviderError: false,
+            enableHttp2: false,
+            interceptAnthropicWarmupRequests: false,
+            createdAt: now,
+            updatedAt: now,
+          },
+        ])
+      );
+
+    const rejectedUpdateQuery = createThenableQuery([] as unknown[]);
+    rejectedUpdateQuery.returning = vi.fn(() => Promise.reject({ code: "42703" }));
+
+    const downgradedUpdateQuery = createThenableQuery([
+      {
+        id: 1,
+        siteTitle: "Updated Title",
+        allowGlobalUsageView: false,
+        currencyDisplay: "USD",
+        billingModelSource: "original",
+        enableAutoCleanup: false,
+        cleanupRetentionDays: 30,
+        cleanupSchedule: "0 2 * * *",
+        cleanupBatchSize: 10000,
+        enableClientVersionCheck: false,
+        verboseProviderError: false,
+        enableHttp2: false,
+        interceptAnthropicWarmupRequests: false,
+        createdAt: now,
+        updatedAt: now,
+      },
+    ]);
+
+    const updateMock = vi
+      .fn()
+      .mockReturnValueOnce(rejectedUpdateQuery)
+      .mockReturnValueOnce(downgradedUpdateQuery);
+
+    vi.doMock("@/drizzle/db", () => ({
+      db: {
+        select: selectMock,
+        update: updateMock,
+        insert: vi.fn(() => createThenableQuery([])),
+        execute: vi.fn(async () => ({ count: 0 })),
+      },
+    }));
+
+    const { updateSystemSettings } = await import("@/repository/system-config");
+
+    const result = await updateSystemSettings({
+      siteTitle: "Updated Title",
+      codexPriorityBillingSource: "actual",
+    });
+
+    expect(result.siteTitle).toBe("Updated Title");
+    expect(result.codexPriorityBillingSource).toBe("requested");
+    expect(updateMock).toHaveBeenCalledTimes(2);
+
+    vi.useRealTimers();
+  });
 });