7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(quota): durable per-key monthly budget caps (#1159)
suantea (asuan_suan)0fed6d089d25
diff --git a/docs/en/api/01-rest-api.md b/docs/en/api/01-rest-api.mdindex d7b6e547..7d4d1f51 100644--- a/docs/en/api/01-rest-api.md+++ b/docs/en/api/01-rest-api.md@@ -448,3 +448,31 @@ Endpoints (all behind `requireAuth`):| `DELETE` | `/api/backups/:id` | Delete one backup || `GET` | `/api/backups/tables` | Tables a dump may contain || `GET` / `PUT` | `/api/backups/schedule` | Read / write the backup schedule (HH:mm, interval days, path) |++## Monthly provider-key budgets++Authenticated dashboard clients can set `monthlyRequestCap` and `monthlyTokenCap`+through `PATCH /api/keys/:id`. Both are nonnegative integers; `0` means unlimited.+These limits apply to an upstream provider key across chat, embeddings, and+keyed media requests, and reset at 00:00 UTC on the first of each month. They do+not apply separately to downstream client profiles.++Successful request counts and reported tokens are stored in a durable monthly+ledger. Request-log cleanup does not clear this ledger. Existing retained request+history is backfilled during upgrade; usage already pruned before the upgrade+cannot be reconstructed. In-flight requests reserve capacity until completion,+including long-running streams. Failed attempts release their reservation.++Token reservations use routing estimates. Actual provider token usage can differ,+so the final response can take recorded usage above the configured token cap;+further requests are then rejected. This is a usage guard, not an exact billing+limit. Media requests count toward the request cap; the current media adapters+do not report token usage. Reservations coordinate requests within one gateway+process, not across multiple gateway replicas.++When all otherwise eligible keys have exhausted their monthly budget, standard+chat, embeddings, and media routing returns HTTP `429` with a `Retry-After` header+pointing to the next UTC month. OpenAI-compatible endpoints also return+`error.code: "quota_exceeded"`; other protocol adapters preserve their native+error format. Fusion subcalls obey the caps but retain Fusion's aggregate error+format. If another key has capacity, normal fallback can use it.diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex 34ba764e..afbf8f7b 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -38,6 +38,8 @@ const REQUEST_CALLER_FILENAME = '20260901_000003_request_caller.ts';const ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME = '20260902_000001_analytics_latency_percentile_index.ts';const MCP_ENABLED_DEFAULT_FILENAME = '20260903_000001_mcp_enabled_default.ts';const RESPONSE_CACHE_FILENAME = '20260903_000002_response_cache.ts';+const KEY_MONTHLY_BUDGET_FILENAME = '20260904_000001_key_monthly_budget.ts';+const KEY_MONTHLY_USAGE_FILENAME = '20260914_000001_key_monthly_usage.ts';interface SchemaRow {type: string;@@ -122,6 +124,8 @@ describe('migration round trip', () => {ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME,MCP_ENABLED_DEFAULT_FILENAME,RESPONSE_CACHE_FILENAME,+ KEY_MONTHLY_BUDGET_FILENAME,+ KEY_MONTHLY_USAGE_FILENAME,]);} finally {db.close();diff --git a/server/src/__tests__/routes/backups.test.ts b/server/src/__tests__/routes/backups.test.tsindex 6daab027..7f1b22fc 100644--- a/server/src/__tests__/routes/backups.test.ts+++ b/server/src/__tests__/routes/backups.test.ts@@ -6,7 +6,7 @@ import type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb } from '../../db/index.js';import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';-import { createBackup } from '../../services/backups.js';+import { createBackup, restoreBackup } from '../../services/backups.js';let dashToken = '';let dataDir = '';@@ -90,6 +90,23 @@ describe('Backups API', () => {expect(after.body.items.some((item: { id: number }) => item.id === created.body.backup.id)).toBe(false);});+ it('restores request history without charging the monthly ledger twice', () => {+ const db = getDb();+ const keyId = 851_901;+ const insert = () => db.prepare(`INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms)+ VALUES ('groq', 'backup-ledger-test', ?, 'success', 10, 5, 1)`).run(keyId);+ const usage = () => db.prepare('SELECT requests, tokens FROM key_monthly_usage WHERE key_id = ?').get(keyId);+ insert();+ const full = createBackup(db);+ restoreBackup(db, full.id);+ expect(usage()).toEqual({ requests: 1, tokens: 15 });+ const partial = createBackup(db, { tables: ['requests'] });+ restoreBackup(db, partial.id);+ expect(usage()).toEqual({ requests: 1, tokens: 15 });+ insert();+ expect(usage()).toEqual({ requests: 2, tokens: 30 });+ });+it('round-trips the schedule setting', async () => {const put = await request(app, 'PUT', '/api/backups/schedule', {enabled: true,diff --git a/server/src/__tests__/routes/key-monthly-budget.test.ts b/server/src/__tests__/routes/key-monthly-budget.test.tsnew file mode 100644index 00000000..2fc0d6ad--- /dev/null+++ b/server/src/__tests__/routes/key-monthly-budget.test.ts@@ -0,0 +1,93 @@+import { beforeAll, afterAll, describe, it, expect } from 'vitest';+import { once } from 'node:events';+import type { Server } from 'node:http';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey, setSetting } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { nextMonthResetAt } from '../../services/key-budget.js';++let server: Server;+let baseUrl: string;+let token: string;+let model: string;+beforeAll(async () => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ const db = getDb();+ const secret = encrypt('synthetic-budget-test-key');+ const keyId = Number(db.prepare(`INSERT INTO api_keys (platform, encrypted_key, iv, auth_tag, enabled, status, monthly_request_cap)+ VALUES ('groq', ?, ?, ?, 1, 'healthy', 1)`).run(secret.encrypted, secret.iv, secret.authTag).lastInsertRowid);+ model = (db.prepare("SELECT model_id FROM models WHERE platform = 'groq' LIMIT 1").get() as { model_id: string }).model_id;+ db.prepare(`INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms)+ VALUES ('groq', ?, ?, 'success', 10, 5, 1)`).run(model, keyId);+ db.prepare(`INSERT INTO embedding_models (family, platform, model_id, display_name, dimensions, priority, enabled, quota_label, key_id)+ VALUES ('budget-embedding', 'custom', 'budget-embedding', 'Budget embedding', 2, 1, 1, '', ?)`).run(keyId);+ for (const modality of ['image', 'video', 'audio', 'transcription']) {+ db.prepare(`INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id)+ VALUES ('custom', ?, 'Budget media', ?, 1, 1, '', ?)`).run(`budget-${modality}`, modality, keyId);+ }+ setSetting('ollama_emulation', 'key-required');+ token = getUnifiedApiKey();+ server = createApp().listen(0, '127.0.0.1');+ await once(server, 'listening');+ baseUrl = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+});+afterAll(() => new Promise<void>((resolve, reject) => server.close(err => err ? reject(err) : resolve())));++describe('monthly budget exhaustion on inference endpoints', () => {+ it.each([+ ['/v1/embeddings', { model: 'budget-embedding', input: 'hello' }],+ ['/v1/images/generations', { model: 'budget-image', prompt: 'hello' }],+ ['/v1/videos/generations', { model: 'budget-video', prompt: 'hello' }],+ ['/v1/audio/speech', { model: 'budget-audio', input: 'hello' }],+ ['/api/embed', { model: 'budget-embedding', input: 'hello' }],+ ])('%s also enforces the shared key budget', async (path, body) => {+ const res = await fetch(`${baseUrl}${path}`, {+ method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ expect(res.status).toBe(429);+ if (path !== '/api/embed') expect((await res.json()).error.code).toBe('quota_exceeded');+ expect(Number(res.headers.get('Retry-After'))).toBeGreaterThan(0);+ });++ it('enforces the budget on multipart transcription requests', async () => {+ const body = new FormData();+ body.set('model', 'budget-transcription');+ body.set('file', new Blob(['synthetic audio'], { type: 'audio/wav' }), 'test.wav');+ const res = await fetch(`${baseUrl}/v1/audio/transcriptions`, {+ method: 'POST', headers: { Authorization: `Bearer ${token}` }, body,+ });+ expect(res.status).toBe(429);+ expect((await res.json()).error.code).toBe('quota_exceeded');+ expect(Number(res.headers.get('Retry-After'))).toBeGreaterThan(0);+ });++ it.each(['/v1/chat/completions', '/v1/responses'])('Fusion through %s cannot bypass a capped provider key', async path => {+ const input = path === '/v1/responses' ? { input: 'hello' } : { messages: [{ role: 'user', content: 'hello' }] };+ const before = getDb().prepare('SELECT SUM(requests) AS requests FROM key_monthly_usage').get();+ const res = await fetch(`${baseUrl}${path}`, {+ method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ ...input, model: 'fusion', fusion: { models: [model] }, max_tokens: 20 }),+ });+ expect(res.status).toBe(429);+ expect((await res.json()).error.type).toBe('rate_limit_error');+ expect(getDb().prepare('SELECT SUM(requests) AS requests FROM key_monthly_usage').get()).toEqual(before);+ });++ it.each(['/v1/chat/completions', '/v1/responses', '/v1/messages'])('%s returns quota_exceeded and the month reset header', async path => {+ const input = path === '/v1/responses' ? { input: 'hello' } : { messages: [{ role: 'user', content: 'hello' }] };+ const res = await fetch(`${baseUrl}${path}`, {+ method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ ...input, model, max_tokens: 20 }),+ });+ expect(res.status).toBe(429);+ const body = await res.json();+ // Anthropic translates the error type but keeps the shared retry header.+ if (path !== '/v1/messages') expect(body.error.code).toBe('quota_exceeded');+ const retry = Number(res.headers.get('Retry-After'));+ const expected = Math.ceil((Date.parse(nextMonthResetAt()) - Date.now()) / 1000);+ expect(retry).toBeGreaterThanOrEqual(expected - 1);+ expect(retry).toBeLessThanOrEqual(expected + 1);+ });+});diff --git a/server/src/__tests__/services/embeddings.test.ts b/server/src/__tests__/services/embeddings.test.tsindex 016e90f4..5771d16f 100644--- a/server/src/__tests__/services/embeddings.test.ts+++ b/server/src/__tests__/services/embeddings.test.ts@@ -51,6 +51,26 @@ describe('embeddings service', () => {vi.restoreAllMocks();});+ it('reserves the shared monthly budget across concurrent embeddings and releases failures', async () => {+ const keyId = addCustomKey('https://embeddings.example/v1');+ const db = getDb();+ db.prepare('UPDATE api_keys SET monthly_request_cap = 1 WHERE id = ?').run(keyId);+ db.prepare(`INSERT INTO embedding_models (family, platform, model_id, display_name, dimensions, priority, enabled, quota_label, key_id)+ VALUES ('budget-embed', 'custom', 'budget-embed', 'Budget embedding', 2, 1, 1, '', ?)`).run(keyId);+ let finish!: (response: Response) => void;+ const fetchMock = mockFetch(() => new Promise<Response>(resolve => { finish = resolve; }));+ const first = runEmbeddings('budget-embed', ['hello']);+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));+ await expect(runEmbeddings('budget-embed', ['hello'])).rejects.toMatchObject({ status: 429, code: 'quota_exceeded' });+ finish(new Response('unavailable', { status: 503 }));+ await expect(first).rejects.toMatchObject({ status: 502 });+ fetchMock.mockResolvedValue(okEmbeddingResponse(2));+ await expect(runEmbeddings('budget-embed', ['hello'])).resolves.toMatchObject({ inputTokens: 3 });+ db.prepare('DELETE FROM requests').run();+ await expect(runEmbeddings('budget-embed', ['hello'])).rejects.toMatchObject({ status: 429, code: 'quota_exceeded' });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+describe('migration seed', () => {it('seeds the embedding catalog with families and a default', () => {const rows = getDb().prepare('SELECT DISTINCT family FROM embedding_models').all() as { family: string }[];diff --git a/server/src/__tests__/services/key-budget.test.ts b/server/src/__tests__/services/key-budget.test.tsnew file mode 100644index 00000000..716f08ea--- /dev/null+++ b/server/src/__tests__/services/key-budget.test.ts@@ -0,0 +1,240 @@+import { describe, it, expect, beforeAll, beforeEach } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { pruneRequestAnalytics } from '../../services/request-retention.js';+import { routePinnedModel, routeRequest } from '../../services/router.js';+import { routingExhaustionBody, setExhaustionHeaders } from '../../lib/fallback-loop.js';+import * as ledgerMigration from '../../db/migrations/20260914_000001_key_monthly_usage.js';+import {+ reserveMonthlyBudget,+ getMonthlyBudgetCaps,+ setMonthlyBudgetCaps,+ getMonthlyUsage,+ checkMonthlyBudget,+ secondsUntilNextMonth,+ nextMonthResetAt,+} from '../../services/key-budget.js';++// Per-key monthly budget (#1158): caps are opt-in (0 = unlimited), metering is+// the current UTC month's successful requests, and the rejection carries a+// Retry-After of seconds-until-next-month.++let keyId = 0;++function insertKey(overrides: { status?: string; monthlyRequestCap?: number; monthlyTokenCap?: number } = {}) {+ const { encrypted, iv, authTag } = encrypt('sk-test');+ const result = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, monthly_request_cap, monthly_token_cap)+ VALUES ('groq', 'test', ?, ?, ?, ?, 1, ?, ?)+ `).run(+ encrypted, iv, authTag,+ overrides.status ?? 'healthy',+ overrides.monthlyRequestCap ?? 0,+ overrides.monthlyTokenCap ?? 0,+ );+ keyId = Number(result.lastInsertRowid);+}++function recordSuccess(now: Date) {+ getDb().prepare(+ `INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, created_at)+ VALUES ('groq', 'llama', ?, 'success', 100, 50, 100, NULL, ?)`,+ ).run(keyId, now.toISOString().slice(0, 19).replace('T', ' '));+}++function recordFailure(now: Date) {+ getDb().prepare(+ `INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, created_at)+ VALUES ('groq', 'llama', ?, 'error', 100, 0, 100, 'boom', ?)`,+ ).run(keyId, now.toISOString().slice(0, 19).replace('T', ' '));+}++function inThisMonth(d = new Date()): Date {+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 5, 12, 0, 0));+}++function lastMonth(d = new Date()): Date {+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - 1, 20, 12, 0, 0));+}++describe('key-budget: monthly caps (#1158)', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ beforeEach(() => {+ getDb().prepare('DELETE FROM api_keys').run();+ getDb().prepare('DELETE FROM requests').run();+ keyId = 0;+ });++ it('defaults to unlimited (0 caps) for a fresh key', () => {+ insertKey();+ expect(getMonthlyBudgetCaps(keyId)).toEqual({ requestCap: 0, tokenCap: 0 });+ expect(checkMonthlyBudget(keyId, 100)).toEqual({ allowed: true });+ });++ it('setMonthlyBudgetCaps persists caps', () => {+ insertKey();+ expect(setMonthlyBudgetCaps(keyId, { requestCap: 10, tokenCap: 5000 })).toBe(true);+ expect(getMonthlyBudgetCaps(keyId)).toEqual({ requestCap: 10, tokenCap: 5000 });+ // Patching only one field leaves the other untouched.+ setMonthlyBudgetCaps(keyId, { requestCap: 3 });+ expect(getMonthlyBudgetCaps(keyId)).toEqual({ requestCap: 3, tokenCap: 5000 });+ });++ it('counts only the current month’s successful requests', () => {+ insertKey();+ recordSuccess(inThisMonth()); // counts: 1 req, 150 tokens+ recordSuccess(inThisMonth()); // counts: 2 req, 300 tokens+ recordFailure(inThisMonth()); // excluded (status != success)+ recordSuccess(lastMonth()); // excluded (previous month)++ const usage = getMonthlyUsage(keyId);+ expect(usage.requests).toBe(2);+ expect(usage.tokens).toBe(300);+ });++ it('rejects at the request cap with a next-month Retry-After', () => {+ insertKey({ monthlyRequestCap: 2 });+ recordSuccess(inThisMonth());+ recordSuccess(inThisMonth());++ const verdict = checkMonthlyBudget(keyId, 0);+ expect(verdict.allowed).toBe(false);+ if (!verdict.allowed) {+ expect(verdict.reason).toBe('monthly_request_cap');+ expect(verdict.retryAfterSec).toBeGreaterThan(0);+ // Retry-After should be at most ~32 days out (current month + 1 boundary).+ expect(verdict.retryAfterSec).toBeLessThanOrEqual(32 * 24 * 3600);+ }+ });++ it('rejects at the token cap, counting the estimated tokens of THIS request', () => {+ insertKey({ monthlyTokenCap: 1000 });+ recordSuccess(inThisMonth()); // 150 tokens used++ // 150 + 900 > 1000 → rejected.+ expect(checkMonthlyBudget(keyId, 900).allowed).toBe(false);+ // 150 + 800 <= 1000 → allowed.+ expect(checkMonthlyBudget(keyId, 800)).toEqual({ allowed: true });+ });++ it('blocks requests with no token estimate once the token cap is fully spent', () => {+ insertKey({ monthlyTokenCap: 150 });+ recordSuccess(inThisMonth());+ expect(checkMonthlyBudget(keyId, 0)).toMatchObject({ allowed: false, reason: 'monthly_token_cap' });+ });++ it('does not reject when the cap is hit exactly on the boundary request', () => {+ insertKey({ monthlyRequestCap: 2 });+ recordSuccess(inThisMonth());+ recordSuccess(inThisMonth());+ // usage.requests === cap → rejected (strictly at/over the cap counts spent).+ expect(checkMonthlyBudget(keyId, 0).allowed).toBe(false);+ });++ it('retains spent budgets when request logs are pruned', () => {+ insertKey({ monthlyRequestCap: 2 });+ recordSuccess(inThisMonth()); recordSuccess(inThisMonth());+ expect(checkMonthlyBudget(keyId, 0).allowed).toBe(false);+ const old = process.env.REQUEST_ANALYTICS_MAX_ROWS;+ try {+ process.env.REQUEST_ANALYTICS_MAX_ROWS = '1';+ pruneRequestAnalytics({ force: true });+ expect(getDb().prepare('SELECT COUNT(*) AS n FROM requests').get()).toEqual({ n: 1 });+ expect(getMonthlyUsage(keyId)).toEqual({ requests: 2, tokens: 300 });+ expect(checkMonthlyBudget(keyId, 0).allowed).toBe(false);+ } finally {+ if (old === undefined) delete process.env.REQUEST_ANALYTICS_MAX_ROWS;+ else process.env.REQUEST_ANALYTICS_MAX_ROWS = old;+ }+ });++ it('backfills the ledger once and does not double count when up is rerun', () => {+ insertKey();+ ledgerMigration.down(getDb());+ recordSuccess(inThisMonth());+ ledgerMigration.up(getDb());+ ledgerMigration.up(getDb());+ expect(getMonthlyUsage(keyId)).toEqual({ requests: 1, tokens: 150 });+ recordSuccess(inThisMonth());+ expect(getMonthlyUsage(keyId)).toEqual({ requests: 2, tokens: 300 });+ });++ it('reserves the last request slot and releases it after an unsuccessful attempt', () => {+ insertKey({ monthlyRequestCap: 1 });+ const first = reserveMonthlyBudget(keyId, 100);+ expect(first.allowed).toBe(true);+ expect(reserveMonthlyBudget(keyId, 100).allowed).toBe(false);+ if (!first.allowed) throw new Error('expected a reservation');+ first.release(); first.release();+ expect(checkMonthlyBudget(keyId, 100).allowed).toBe(true);+ const second = reserveMonthlyBudget(keyId, 100);+ if (!second.allowed) throw new Error('expected a reservation');+ recordSuccess(inThisMonth());+ second.release();+ expect(checkMonthlyBudget(keyId, 100).allowed).toBe(false);+ });++ it('keeps token reservations for long streams until explicit release', () => {+ insertKey({ monthlyTokenCap: 1000 });+ const first = reserveMonthlyBudget(keyId, 600);+ if (!first.allowed) throw new Error('expected a reservation');+ expect(checkMonthlyBudget(keyId, 500, Date.now() + 10 * 60_000).allowed).toBe(false);+ const second = reserveMonthlyBudget(keyId, 400);+ expect(second.allowed).toBe(true);+ if (second.allowed) second.release();+ first.release();+ expect(checkMonthlyBudget(keyId, 1000).allowed).toBe(true);+ });++ it('resets completed usage at the next month while retaining active reservations', () => {+ insertKey({ monthlyRequestCap: 2 });+ recordSuccess(inThisMonth());+ const first = reserveMonthlyBudget(keyId, 100);+ if (!first.allowed) throw new Error('expected a reservation');+ expect(checkMonthlyBudget(keyId, 0).allowed).toBe(false);+ const nextMonth = Date.parse(nextMonthResetAt());+ expect(getMonthlyUsage(keyId, nextMonth).requests).toBe(0);+ expect(checkMonthlyBudget(keyId, 0, nextMonth).allowed).toBe(true);+ first.release();+ });++ it('enforces reservations through real route selection and exposes the monthly retry header', () => {+ insertKey({ monthlyRequestCap: 1 });+ const db = getDb();+ const model = db.prepare("SELECT id FROM models WHERE platform = 'groq' LIMIT 1").get() as { id: number };+ db.prepare('UPDATE models SET enabled = 1, rpm_limit = NULL, rpd_limit = NULL, tpm_limit = NULL, tpd_limit = NULL WHERE id = ?').run(model.id);+ const first = routePinnedModel(model.id, 100);+ expect(first).not.toBeNull();+ expect(routePinnedModel(model.id, 100)).toBeNull();+ first?.release?.();+ const second = routePinnedModel(model.id, 100);+ expect(second).not.toBeNull();+ second?.release?.();+ recordSuccess(inThisMonth());+ let error: unknown;+ try { routeRequest(100); } catch (err) { error = err; }+ expect(error).toBeDefined();+ const body = routingExhaustionBody(error);+ expect(body.status).toBe(429);+ expect(body.code).toBe('quota_exceeded');+ expect(body.retryAtMs).toBe(Date.parse(nextMonthResetAt()));+ const headers: Record<string, string> = {};+ setExhaustionHeaders({ setHeader: (name: string, value: string) => { headers[name] = value; } }, body);+ expect(Number(headers['Retry-After'])).toBeGreaterThan(0);+ });++ it('secondsUntilNextMonth lands on the next UTC month boundary', () => {+ const now = Date.UTC(2026, 6, 15, 10, 0, 0); // 2026-07-15+ const secs = secondsUntilNextMonth(now);+ expect(secs).toBeGreaterThan(0);+ const reset = nextMonthResetAt(now);+ expect(reset).toBe('2026-08-01T00:00:00.000Z');+ // seconds until that boundary+ const expected = Math.floor((Date.parse('2026-08-01T00:00:00.000Z') - now) / 1000);+ expect(secs).toBe(expected);+ });+});diff --git a/server/src/__tests__/services/media.test.ts b/server/src/__tests__/services/media.test.tsindex 2dfa68b3..ee972417 100644--- a/server/src/__tests__/services/media.test.ts+++ b/server/src/__tests__/services/media.test.ts@@ -58,6 +58,35 @@ describe('media service', () => {expect(cols).toContain('key_id');});+ it('skips capped provider keys and keeps a reservation until image generation completes', async () => {+ addMedia('nvidia', 'black-forest-labs/flux.1-schnell', 'image');+ addKey('nvidia', 'spent-key');+ addKey('nvidia', 'available-key');+ const db = getDb();+ const keys = db.prepare('SELECT id FROM api_keys ORDER BY id').all() as { id: number }[];+ db.prepare('UPDATE api_keys SET monthly_request_cap = 1').run();+ db.prepare(`INSERT INTO requests (platform, model_id, key_id, status, latency_ms)+ VALUES ('nvidia', 'chat-model', ?, 'success', 1)`).run(keys[0].id);+ let finish!: (response: Response) => void;+ const fetchMock = vi.fn(() => new Promise<Response>(resolve => { finish = resolve; }));+ globalThis.fetch = fetchMock as unknown as typeof fetch;+ const first = runImageGeneration('auto', { prompt: 'a cat' });+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));+ const request = (fetchMock.mock.calls as unknown as [string, RequestInit][])[0][1];+ expect(new Headers(request.headers).get('Authorization')).toBe('Bearer available-key');+ await expect(runImageGeneration('auto', { prompt: 'a cat' })).rejects.toMatchObject({ status: 429, code: 'quota_exceeded' });+ finish(jsonResponse({ artifacts: [{ base64: 'AAAA' }] }));+ await expect(first).resolves.toMatchObject({ platform: 'nvidia' });+ expect(db.prepare('SELECT requests FROM key_monthly_usage WHERE key_id = ?').get(keys[1].id)).toEqual({ requests: 1 });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ // A failed attempt does not consume another request, and cannot leak its reservation.+ db.prepare('UPDATE api_keys SET monthly_request_cap = 2 WHERE id = ?').run(keys[1].id);+ fetchMock.mockResolvedValue(new Response('unavailable', { status: 503 }));+ await expect(runImageGeneration('auto', { prompt: 'a cat' })).rejects.toMatchObject({ status: 502 });+ fetchMock.mockResolvedValue(jsonResponse({ artifacts: [{ base64: 'BBBB' }] }));+ await expect(runImageGeneration('auto', { prompt: 'a cat' })).resolves.toMatchObject({ platform: 'nvidia' });+ });+describe('image generation', () => {it('NVIDIA: maps artifacts[].base64 → b64_json', async () => {addMedia('nvidia', 'black-forest-labs/flux.1-schnell', 'image');diff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex 9c95d1dc..433c0903 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -33,6 +33,8 @@ import * as quotaObservationLookup from '../migrations/20260901_000002_quota_obsimport * as analyticsLatencyPercentileIndex from '../migrations/20260902_000001_analytics_latency_percentile_index.js';import * as mcpEnabledDefault from '../migrations/20260903_000001_mcp_enabled_default.js';import * as responseCache from '../migrations/20260903_000002_response_cache.js';+import * as keyMonthlyBudget from '../migrations/20260904_000001_key_monthly_budget.js';+import * as keyMonthlyUsage from '../migrations/20260914_000001_key_monthly_usage.js';export interface MigrationModule {up(db: Db): void;@@ -78,6 +80,8 @@ export const REQUEST_CALLER_FILENAME = '20260901_000003_request_caller.ts';export const ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME = '20260902_000001_analytics_latency_percentile_index.ts';export const MCP_ENABLED_DEFAULT_FILENAME = '20260903_000001_mcp_enabled_default.ts';export const RESPONSE_CACHE_FILENAME = '20260903_000002_response_cache.ts';+export const KEY_MONTHLY_BUDGET_FILENAME = '20260904_000001_key_monthly_budget.ts';+export const KEY_MONTHLY_USAGE_FILENAME = '20260914_000001_key_monthly_usage.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },@@ -114,4 +118,6 @@ export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME, module: analyticsLatencyPercentileIndex },{ filename: MCP_ENABLED_DEFAULT_FILENAME, module: mcpEnabledDefault },{ filename: RESPONSE_CACHE_FILENAME, module: responseCache },+ { filename: KEY_MONTHLY_BUDGET_FILENAME, module: keyMonthlyBudget },+ { filename: KEY_MONTHLY_USAGE_FILENAME, module: keyMonthlyUsage },];diff --git a/server/src/db/migrations/20260904_000001_key_monthly_budget.ts b/server/src/db/migrations/20260904_000001_key_monthly_budget.tsnew file mode 100644index 00000000..06f5dd9a--- /dev/null+++ b/server/src/db/migrations/20260904_000001_key_monthly_budget.ts@@ -0,0 +1,37 @@+import type { Db } from '../types.js';++/** Guard so the migration can be re-run safely (roundtrip/catalog-sync tests re-run up()). */+function hasColumn(db: Db, table: string, column: string): boolean {+ const columns = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];+ return columns.some(col => col.name === column);+}++/**+ * Per-key monthly budget (#1158): optional request / token caps per api_keys+ * row, counted against the current UTC month's SUCCESSFUL requests. 0 means+ * "no cap" — the pre-existing behaviour, so existing installs are untouched.+ *+ * The columns live on api_keys (the operator-facing budget subject), matching+ * the per-key vocabulary already used for daily limits in ratelimit.ts; the+ * month is derived from requests.created_at (UTC), never wall-clock local.+ */+export function up(db: Db): void {+ if (!hasColumn(db, 'api_keys', 'monthly_request_cap')) {+ db.prepare('ALTER TABLE api_keys ADD COLUMN monthly_request_cap INTEGER NOT NULL DEFAULT 0').run();+ }+ if (!hasColumn(db, 'api_keys', 'monthly_token_cap')) {+ db.prepare('ALTER TABLE api_keys ADD COLUMN monthly_token_cap INTEGER NOT NULL DEFAULT 0').run();+ }+}++export function down(db: Db): void {+ for (const column of ['monthly_request_cap', 'monthly_token_cap']) {+ if (hasColumn(db, 'api_keys', column)) {+ try {+ db.prepare(`ALTER TABLE api_keys DROP COLUMN ${column}`).run();+ } catch {+ // best-effort: some builds pin the table; leaving the column harms nobody+ }+ }+ }+}diff --git a/server/src/db/migrations/20260914_000001_key_monthly_usage.ts b/server/src/db/migrations/20260914_000001_key_monthly_usage.tsnew file mode 100644index 00000000..9900d7e3--- /dev/null+++ b/server/src/db/migrations/20260914_000001_key_monthly_usage.ts@@ -0,0 +1,39 @@+import type { Db } from '../types.js';++/** A durable ledger: pruning analytics must never reopen a spent monthly cap. */+export function up(db: Db): void {+ db.exec(`+ CREATE TABLE IF NOT EXISTS key_monthly_usage (+ key_id INTEGER NOT NULL,+ month TEXT NOT NULL,+ requests INTEGER NOT NULL DEFAULT 0,+ tokens INTEGER NOT NULL DEFAULT 0,+ PRIMARY KEY (key_id, month)+ );+ INSERT INTO key_monthly_usage (key_id, month, requests, tokens)+ SELECT key_id, strftime('%Y-%m', created_at), COUNT(*),+ SUM(MAX(0, input_tokens) + MAX(0, output_tokens))+ FROM requests+ WHERE key_id IS NOT NULL AND status = 'success'+ AND strftime('%Y-%m', created_at) IS NOT NULL+ GROUP BY key_id, strftime('%Y-%m', created_at)+ ON CONFLICT(key_id, month) DO NOTHING;++ CREATE TRIGGER IF NOT EXISTS requests_key_monthly_usage+ AFTER INSERT ON requests+ WHEN NEW.key_id IS NOT NULL AND NEW.status = 'success'+ AND strftime('%Y-%m', NEW.created_at) IS NOT NULL+ BEGIN+ INSERT INTO key_monthly_usage (key_id, month, requests, tokens)+ VALUES (NEW.key_id, strftime('%Y-%m', NEW.created_at), 1,+ MAX(0, NEW.input_tokens) + MAX(0, NEW.output_tokens))+ ON CONFLICT(key_id, month) DO UPDATE SET+ requests = requests + 1,+ tokens = tokens + excluded.tokens;+ END;+ `);+}++export function down(db: Db): void {+ db.exec('DROP TRIGGER IF EXISTS requests_key_monthly_usage; DROP TABLE IF EXISTS key_monthly_usage;');+}diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.tsindex edb2208a..cfbef4f1 100644--- a/server/src/lib/fallback-loop.ts+++ b/server/src/lib/fallback-loop.ts@@ -1,3 +1,4 @@+import { nextMonthResetAt } from '../services/key-budget.js';// One shared provider retry/fallback loop for every OpenAI-, Responses- and// Anthropic-shaped chat surface (routes/proxy.ts legacy /completions and// /chat/completions, routes/responses.ts, routes/anthropic.ts). Each surface@@ -874,15 +875,17 @@ export function exhaustedRetryError(lastError: any, maxRetries?: number, ctx?: E// expiry as retryAtMs.// - anything else (capability filters like vision/tools, mixed reasons) →// the router's status (429) with a generic routing_exhausted code.-type RoutingDiagClass = 'config' | 'too_large' | 'time_bound' | 'other';+type RoutingDiagClass = 'config' | 'too_large' | 'time_bound' | 'monthly_budget' | 'other';function classifyRoutingDiagLine(line: string): RoutingDiagClass {const l = line.toLowerCase();// "< estimated" first: the tpm_limit-too-small line also contains 'tpm',// which would otherwise misread as a transient window.if (l.includes('< estimated')) return 'too_large';+ const monthlyReasons = l.match(/key\(s\) — (.*)$/)?.[1];+ if (monthlyReasons?.split(', ').every(reason => /^monthly-budget-cap:\d+$/.test(reason))) return 'monthly_budget';if (/no provider registered|no enabled\+healthy key|no usable key|decrypt-error|no-resolved-provider|custom-key-mismatch/.test(l)) return 'config';- if (/cooldown|rpm|rpd|tpm|tpd|provider-daily-cap|provider-minute-cap|provider-daily-token-cap|key-concurrency/.test(l)) return 'time_bound';+ if (/cooldown|rpm|rpd|tpm|tpd|provider-daily-cap|provider-minute-cap|provider-daily-token-cap|key-concurrency|monthly-budget-cap/.test(l)) return 'time_bound';return 'other';}@@ -914,6 +917,14 @@ export function routingExhaustionBody(routeErr: any): ExhaustionBody {};}+ if (classes.includes('monthly_budget') && classes.every(c => c === 'monthly_budget' || c === 'config' || c === 'too_large')) {+ return {+ kind: 'rate_limit', status: 429, type: 'rate_limit_error', code: 'quota_exceeded',+ retryAtMs: Date.parse(nextMonthResetAt()),+ message: `Monthly key budget exhausted. Raise the cap or wait until the next UTC month. ${message}`,+ };+ }+if (classes.some(c => c === 'time_bound') && classes.every(c => c !== 'other')) {const retryAtMs = getSoonestCooldownExpiry() ?? undefined;return {diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 23c56dcf..d1e9b8fa 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -10,6 +10,7 @@ import { parseKeysFromFile, stripJsoncComments, stripTrailingCommas } from '../limport { assessProviderUrl } from '../lib/url-guard.js';import { verifyCredentials } from '../services/auth.js';import { getActiveCooldownsForKeys, clearCooldownsForKey } from '../services/ratelimit.js';+import { getMonthlyBudgetCaps } from '../services/key-budget.js';import { resolveCustomEndpointKey, customEndpointKeyIds, siblingEndpointKeyId, endpointHasCredential } from '../services/custom-endpoint.js';import { registerCustomModels, registerCustomChatModels } from '../services/custom-model-register.js';import { registerCustomMediaModel } from '../services/custom-media-register.js';@@ -75,12 +76,13 @@ const updateKeySchema = z.object({modelScope: z.array(z.string().trim().min(1).max(200)).max(100).nullable().optional(),// #590: '' clears the per-key proxy; absent leaves it unchanged.proxyUrl: proxyUrlSchema.optional(),- // Re-entry of a credential without deleting and recreating the row. Like- // POST, the value is trimmed and never echoed back; an absent field leaves- // the encrypted key untouched.+ // Monthly budget caps (#1158): 0 clears the cap (unlimited).+ monthlyRequestCap: z.number().int().min(0).max(1_000_000_000).optional(),+ monthlyTokenCap: z.number().int().min(0).max(1_000_000_000_000).optional(),+ // An absent credential leaves the encrypted key untouched.key: z.string().trim().min(1).optional(),-}).refine(data => data.enabled !== undefined || data.label !== undefined || data.modelScope !== undefined || data.proxyUrl !== undefined || data.key !== undefined, {- message: 'At least one of enabled, label, modelScope, proxyUrl or key must be provided',+}).refine(data => data.enabled !== undefined || data.label !== undefined || data.modelScope !== undefined || data.proxyUrl !== undefined || data.key !== undefined || data.monthlyRequestCap !== undefined || data.monthlyTokenCap !== undefined, {+ message: 'At least one of enabled, label, modelScope, proxyUrl, key, monthlyRequestCap or monthlyTokenCap must be provided',});const importKeySchema = z.object({@@ -313,12 +315,15 @@ keysRouter.get('/', (_req: Request, res: Response) => {}const cooldowns = cooldownsByKeyId.get(Number(row.id)) ?? [];const scope = parseModelScope(row.model_scope_json);+ const budgetCaps = getMonthlyBudgetCaps(Number(row.id));return {id: row.id,platform: row.platform,label: row.label,maskedKey,baseUrl: row.base_url ?? null,+ monthlyRequestCap: budgetCaps.requestCap,+ monthlyTokenCap: budgetCaps.tokenCap,status: row.status,enabled: row.enabled === 1,keyless: resolveProvider(row.platform)?.keyless === true,@@ -1513,7 +1518,7 @@ keysRouter.patch('/:id', (req: Request, res: Response) => {return;}- const { enabled, label, modelScope, proxyUrl, key } = parsed.data;+ const { enabled, label, modelScope, proxyUrl, key, monthlyRequestCap, monthlyTokenCap } = parsed.data;const updates: string[] = [];const values: (string | number | null)[] = [];let changedKey: string | undefined;@@ -1567,6 +1572,15 @@ keysRouter.patch('/:id', (req: Request, res: Response) => {updates.push('proxy_encrypted = ?', 'proxy_iv = ?', 'proxy_auth_tag = ?');values.push(proxy.encrypted, proxy.iv, proxy.authTag);}+ // Monthly budget caps (#1158): 0 = unlimited.+ if (monthlyRequestCap !== undefined) {+ updates.push('monthly_request_cap = ?');+ values.push(monthlyRequestCap);+ }+ if (monthlyTokenCap !== undefined) {+ updates.push('monthly_token_cap = ?');+ values.push(monthlyTokenCap);+ }// Deduped; an empty result stores NULL, which the router reads as "unscoped".const scopeIds = modelScope == null ? [] : [...new Set(modelScope)];if (modelScope !== undefined) {diff --git a/server/src/routes/ollama.ts b/server/src/routes/ollama.tsindex 38fdf7b5..71c0722e 100644--- a/server/src/routes/ollama.ts+++ b/server/src/routes/ollama.ts@@ -9,6 +9,7 @@ import { getSetting, getUnifiedApiKey } from '../db/index.js';import { buildModelListing } from '../services/model-listing.js';import { extractApiToken, timingSafeStringEqual } from './proxy.js';import { runInboundChat, type InboundChatResult, type InboundChatWire } from '../lib/inbound-chat.js';+import { secondsUntilNextMonth } from '../services/key-budget.js';import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';import { validateSession } from '../services/auth.js';@@ -578,6 +579,9 @@ async function handleEmbed(req: Request, res: Response, legacy: boolean): Promis}} catch (error: any) {const status = error instanceof EmbeddingsError ? error.status : 502;+ if (error instanceof EmbeddingsError && error.code === 'quota_exceeded') {+ res.setHeader('Retry-After', secondsUntilNextMonth());+ }res.status(status).json({ error: error.message ?? 'embedding request failed' });}}diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 6b6aab20..288345a3 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -4,6 +4,7 @@ import type { Request, Response } from 'express';import { z } from 'zod';import type { ChatMessage, ChatToolCall, TokenUsage } from '@freellmapi/shared/types.js';import { type RouteResult, type ResolvedChain, type ChainRow, routeRequest, resolveRoutingChain, resolveModelGroupCandidates, resolveStickyPreference, hasEnabledVisionModel, hasEnabledToolsModel, routingReserveTokens } from '../services/router.js';+import { secondsUntilNextMonth } from '../services/key-budget.js';import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';import { runImageGeneration, runVideoGeneration, runSpeech, runTranscription, MediaError, MAX_TRANSCRIPTION_BYTES } from '../services/media.js';import multer from 'multer';@@ -689,8 +690,9 @@ proxyRouter.post('/embeddings', async (req: Request, res: Response) => {});} catch (err: any) {const status = err instanceof EmbeddingsError ? err.status : 502;+ const code = err instanceof EmbeddingsError ? inferenceBudgetCode(err, res) : {};const type = status === 400 ? 'invalid_request_error' : status === 429 ? 'rate_limit_error' : 'server_error';- res.status(status).json({ error: { message: `embedding error: ${err?.message ?? 'unknown'}`, type } });+ res.status(status).json({ error: { message: `embedding error: ${err?.message ?? 'unknown'}`, type, ...code } });}});@@ -706,6 +708,11 @@ const ImageBody = z.object({response_format: z.enum(['url', 'b64_json']).optional(),});+function inferenceBudgetCode(error: { code?: string }, res: Response): { code?: string } {+ if (error.code === 'quota_exceeded') res.setHeader('Retry-After', secondsUntilNextMonth());+ return error.code ? { code: error.code } : {};+}+function mediaErrorType(status: number): string {if (status === 400 || status === 413) return 'invalid_request_error';if (status === 401) return 'authentication_error';@@ -732,8 +739,9 @@ proxyRouter.post('/images/generations', async (req: Request, res: Response) => {});} catch (err: any) {const status = err instanceof MediaError ? err.status : 502;+ const code = err instanceof MediaError ? inferenceBudgetCode(err, res) : {};const httpStatus = status >= 400 && status < 600 ? status : 502;- res.status(httpStatus).json({ error: { message: `image generation error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status) } });+ res.status(httpStatus).json({ error: { message: `image generation error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status), ...code } });}});@@ -789,9 +797,10 @@ proxyRouter.post('/videos/generations', async (req: Request, res: Response) => {// Nothing to report to a socket that is already gone.if (clientAbort.signal.aborted || res.writableEnded) return;const status = err instanceof MediaError ? err.status : 502;+ const code = err instanceof MediaError ? inferenceBudgetCode(err, res) : {};const httpStatus = status >= 400 && status < 600 ? status : 502;res.status(httpStatus).json({- error: { message: `video generation error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status) },+ error: { message: `video generation error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status), ...code },});}});@@ -821,8 +830,9 @@ proxyRouter.post('/audio/speech', async (req: Request, res: Response) => {res.send(result.audio);} catch (err: any) {const status = err instanceof MediaError ? err.status : 502;+ const code = err instanceof MediaError ? inferenceBudgetCode(err, res) : {};const httpStatus = status >= 400 && status < 600 ? status : 502;- res.status(httpStatus).json({ error: { message: `speech error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status) } });+ res.status(httpStatus).json({ error: { message: `speech error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status), ...code } });}});@@ -943,8 +953,8 @@ proxyRouter.post('/audio/transcriptions', (req: Request, res: Response, next) =>res.json({ text: result.text });} catch (err: any) {const status = err instanceof MediaError ? err.status : 502;+ const code = err instanceof MediaError ? inferenceBudgetCode(err, res) : {};const httpStatus = status >= 400 && status < 600 ? status : 502;- const code = err instanceof MediaError && err.code ? { code: err.code } : {};res.status(httpStatus).json({ error: { message: `transcription error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status), ...code } });}});diff --git a/server/src/services/backups.ts b/server/src/services/backups.tsindex 8cfc4ddd..78eca4b5 100644--- a/server/src/services/backups.ts+++ b/server/src/services/backups.ts@@ -467,7 +467,16 @@ export function restoreBackup(db: Db, id: number): RestoreResult {// One transaction for the whole file: better-sqlite3 rolls it back if any// statement throws, so a bad dump leaves the database exactly as it was.db.transaction(() => {+ // Replaying historical log rows is not new provider usage. In a full+ // restore the ledger is restored separately; in a partial log restore+ // the existing ledger remains authoritative. Keep DDL in this same+ // transaction so a failed restore also restores the trigger.+ const usageTrigger = header.tables.includes('requests')+ ? db.prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'requests_key_monthly_usage'").get() as { sql: string } | undefined+ : undefined;+ if (usageTrigger) db.exec('DROP TRIGGER requests_key_monthly_usage');db.exec(sql);+ if (usageTrigger) db.exec(usageTrigger.sql);})();} catch (err) {const reason = err instanceof Error ? err.message : String(err);diff --git a/server/src/services/embeddings.ts b/server/src/services/embeddings.tsindex c3c8e600..599ff21c 100644--- a/server/src/services/embeddings.ts+++ b/server/src/services/embeddings.ts@@ -9,7 +9,7 @@// cross-provider redundancy for free.import { getDb, getSetting } from '../db/index.js';import { getClientContext } from '../lib/client-context.js';-import { decrypt } from '../lib/crypto.js';+import { reserveProviderCredential } from './provider-credential.js';import { proxyFetch } from '../lib/proxy.js';import { customEndpointKeyIds } from './custom-endpoint.js';import type { Db } from '../db/types.js';@@ -39,9 +39,11 @@ export interface EmbeddingsResult {export class EmbeddingsError extends Error {status: number;- constructor(message: string, status: number) {+ code?: string;+ constructor(message: string, status: number, code?: string) {super(message);this.status = status;+ this.code = code;}}@@ -71,39 +73,6 @@ interface ProviderCredential {baseUrl: string | null;}-function getProviderCredential(row: EmbeddingModelRow): ProviderCredential | null {- if (row.key_id != null) {- const keyRow = getDb().prepare(- "SELECT id, encrypted_key, iv, auth_tag, base_url FROM api_keys WHERE id = ? AND enabled = 1 AND status IN ('healthy', 'unknown') LIMIT 1",- ).get(row.key_id) as { id: number; encrypted_key: string; iv: string; auth_tag: string; base_url: string | null } | undefined;- if (!keyRow) return null;- try {- return {- id: keyRow.id,- key: decrypt(keyRow.encrypted_key, keyRow.iv, keyRow.auth_tag),- baseUrl: keyRow.base_url?.trim().replace(/\/+$/, '') ?? null,- };- } catch {- return null;- }- }- if (row.platform === 'custom') return null;-- const keyRow = getDb().prepare(- "SELECT id, encrypted_key, iv, auth_tag, base_url FROM api_keys WHERE platform = ? AND enabled = 1 AND status IN ('healthy', 'unknown') ORDER BY RANDOM() LIMIT 1",- ).get(row.platform) as { id: number; encrypted_key: string; iv: string; auth_tag: string; base_url: string | null } | undefined;- if (!keyRow) return null;- try {- return {- id: keyRow.id,- key: decrypt(keyRow.encrypted_key, keyRow.iv, keyRow.auth_tag),- baseUrl: keyRow.base_url?.trim().replace(/\/+$/, '') ?? null,- };- } catch {- return null;- }-}-// Rough token estimate when the provider doesn't report usage (~4 chars/token).function estimateTokens(inputs: string[]): number {return Math.ceil(inputs.reduce((n, s) => n + s.length, 0) / 4);@@ -363,8 +332,11 @@ export async function runEmbeddings(model: string | undefined, inputs: string[],let lastError: EmbeddingsError | null = null;for (const row of chain) {- const credential = getProviderCredential(row);- if (!credential) continue; // no usable key for this provider — try the next one+ const { credential, budgetBlocked } = reserveProviderCredential(row, estimateTokens(inputs));+ if (!credential) {+ if (budgetBlocked) lastError = new EmbeddingsError('Monthly key budget exhausted', 429, 'quota_exceeded');+ continue;+ }const started = Date.now();try {const out = await callProvider(row, credential, inputs, dimensions);@@ -386,11 +358,14 @@ export async function runEmbeddings(model: string | undefined, inputs: string[],logEmbeddingRequest(row, credential.id, 'error', 0, Date.now() - started, e.message.slice(0, 300));lastError = e;// fall through to the next provider in the family+ } finally {+ credential.release();}}throw new EmbeddingsError(`All providers for embedding family '${family}' failed${lastError ? ` (last: ${lastError.message.slice(0, 160)})` : ' (no usable keys)'}.`,lastError && lastError.status === 429 ? 429 : 502,+ lastError?.code,);}diff --git a/server/src/services/key-budget.ts b/server/src/services/key-budget.tsnew file mode 100644index 00000000..3b5854fb--- /dev/null+++ b/server/src/services/key-budget.ts@@ -0,0 +1,136 @@+/**+ * Per-key monthly budget (#1158): optional request/token caps per api_keys row,+ * enforced against the CURRENT UTC month's successful requests. A key at its+ * cap returns `quota_exceeded` (429) with a Retry-After of "seconds until the+ * next month" — the semantic GateLLM-style rejection so an agent knows when the+ * window resets instead of hammering a 429.+ *+ * Successful usage is retained in key_monthly_usage independently of analytics+ * retention. Active requests reserve their estimated tokens until their route+ * is released. Actual provider usage is settled by the request-log transaction;+ * token estimates are an admission guard, not an exact upstream billing cap.+ * Caps are opt-in (0 = unlimited) and reset on UTC month boundaries.+ */+import { getDb } from '../db/index.js';++export interface MonthlyBudgetCaps {+ /** 0 = unlimited (the default, unchanged behaviour). */+ requestCap: number;+ /** 0 = unlimited. */+ tokenCap: number;+}++export interface MonthlyUsage {+ /** Successful requests in the current UTC month. */+ requests: number;+ /** Sum of (input_tokens + output_tokens) over those successes. */+ tokens: number;+}++export type BudgetVerdict =+ | { allowed: true }+ | { allowed: false; reason: 'monthly_request_cap' | 'monthly_token_cap'; retryAfterSec: number };++function utcNextMonthStartMs(now = Date.now()): number {+ const d = new Date(now);+ const month = d.getUTCMonth() + 1;+ return Date.UTC(d.getUTCFullYear() + Math.floor(month / 12), month % 12, 1);+}++interface Reservation { keyId: number; tokens: number }+// These requests belong to this process and remain reserved until completion,+// even if a stream outlives the short rate-limit lease timeout. A restarted+// process has no active requests; completed usage remains in SQLite.+const reservations = new WeakMap<ReturnType<typeof getDb>, Set<Reservation>>();++function activeReservations(): Set<Reservation> {+ const db = getDb();+ let active = reservations.get(db);+ if (!active) { active = new Set(); reservations.set(db, active); }+ return active;+}++export function getMonthlyBudgetCaps(keyId: number): MonthlyBudgetCaps {+ const row = getDb().prepare(+ 'SELECT monthly_request_cap, monthly_token_cap FROM api_keys WHERE id = ?',+ ).get(keyId) as { monthly_request_cap: number; monthly_token_cap: number } | undefined;+ if (!row) return { requestCap: 0, tokenCap: 0 };+ return { requestCap: row.monthly_request_cap, tokenCap: row.monthly_token_cap };+}++export function setMonthlyBudgetCaps(+ keyId: number,+ patch: Partial<MonthlyBudgetCaps>,+): boolean {+ const sets: string[] = [];+ const values: number[] = [];+ if (patch.requestCap !== undefined) {+ sets.push('monthly_request_cap = ?');+ values.push(patch.requestCap);+ }+ if (patch.tokenCap !== undefined) {+ sets.push('monthly_token_cap = ?');+ values.push(patch.tokenCap);+ }+ if (sets.length === 0) return false;+ const result = getDb().prepare(`UPDATE api_keys SET ${sets.join(', ')} WHERE id = ?`).run(...values, keyId);+ return result.changes > 0;+}++export function getMonthlyUsage(keyId: number, now = Date.now()): MonthlyUsage {+ const row = getDb().prepare(`+ SELECT requests, tokens FROM key_monthly_usage WHERE key_id = ? AND month = ?+ `).get(keyId, new Date(now).toISOString().slice(0, 7)) as MonthlyUsage | undefined;+ return { requests: Number(row?.requests ?? 0), tokens: Number(row?.tokens ?? 0) };+}++/**+ * Check a key against its monthly caps, taking the current month's successful+ * usage plus the tokens THIS request would add. Returns allowed when both caps+ * are 0 (unlimited) or neither would be exceeded.+ */+export function checkMonthlyBudget(+ keyId: number,+ estimatedTokens: number,+ now = Date.now(),+): BudgetVerdict {+ const caps = getMonthlyBudgetCaps(keyId);+ if (caps.requestCap <= 0 && caps.tokenCap <= 0) return { allowed: true };++ const usage = getMonthlyUsage(keyId, now);+ for (const reservation of activeReservations()) {+ if (reservation.keyId !== keyId) continue;+ usage.requests++;+ usage.tokens += reservation.tokens;+ }+ if (caps.requestCap > 0 && usage.requests >= caps.requestCap) {+ return { allowed: false, reason: 'monthly_request_cap', retryAfterSec: secondsUntilNextMonth(now) };+ }+ if (caps.tokenCap > 0 && (usage.tokens >= caps.tokenCap || usage.tokens + Math.max(0, estimatedTokens) > caps.tokenCap)) {+ return { allowed: false, reason: 'monthly_token_cap', retryAfterSec: secondsUntilNextMonth(now) };+ }+ return { allowed: true };+}++/** Check and reserve synchronously before dispatch; release on every terminal path. */+export function reserveMonthlyBudget(+ keyId: number,+ estimatedTokens: number,+): { allowed: true; release: () => void } | Extract<BudgetVerdict, { allowed: false }> {+ const verdict = checkMonthlyBudget(keyId, estimatedTokens);+ if (!verdict.allowed) return verdict;+ const active = activeReservations();+ const reservation = { keyId, tokens: Math.max(0, estimatedTokens) };+ active.add(reservation);+ return { allowed: true, release: () => { active.delete(reservation); } };+}++/** Seconds from `now` until the next UTC month boundary — the Retry-After value. */+export function secondsUntilNextMonth(now = Date.now()): number {+ return Math.max(1, Math.floor((utcNextMonthStartMs(now) - now) / 1000));+}++/** ISO timestamp of the next UTC month boundary (for headers / diagnostics). */+export function nextMonthResetAt(now = Date.now()): string {+ return new Date(utcNextMonthStartMs(now)).toISOString();+}diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex afc43908..5353e648 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -9,7 +9,7 @@// ~12h, free once each model is 30 days old) — never seeded by migrations.import { getDb } from '../db/index.js';import { getClientContext } from '../lib/client-context.js';-import { decrypt } from '../lib/crypto.js';+import { reserveProviderCredential } from './provider-credential.js';import { proxyFetch } from '../lib/proxy.js';import { assessProviderUrl } from '../lib/url-guard.js';import { isOnCooldown, setCooldown } from './ratelimit.js';@@ -209,44 +209,12 @@ export function listAllMediaModels(): MediaModelRow[] {}interface ProviderCredential {+ release?: () => void;id: number | null;key: string | null;baseUrl: string | null;}-function getProviderCredential(row: Pick<MediaModelRow, 'platform' | 'key_id'>): ProviderCredential | null {- if (row.key_id != null) {- const keyRow = getDb()- .prepare("SELECT id, encrypted_key, iv, auth_tag, base_url FROM api_keys WHERE id = ? AND enabled = 1 AND status IN ('healthy', 'unknown') LIMIT 1")- .get(row.key_id) as { id: number; encrypted_key: string; iv: string; auth_tag: string; base_url: string | null } | undefined;- if (!keyRow) return null;- try {- return {- id: keyRow.id,- key: decrypt(keyRow.encrypted_key, keyRow.iv, keyRow.auth_tag),- baseUrl: keyRow.base_url?.trim().replace(/\/+$/, '') ?? null,- };- } catch {- return null;- }- }- if (row.platform === 'custom') return null;-- const keyRow = getDb()- .prepare("SELECT id, encrypted_key, iv, auth_tag, base_url FROM api_keys WHERE platform = ? AND enabled = 1 AND status IN ('healthy', 'unknown') ORDER BY RANDOM() LIMIT 1")- .get(row.platform) as { id: number; encrypted_key: string; iv: string; auth_tag: string; base_url: string | null } | undefined;- if (!keyRow) return null;- try {- return {- id: keyRow.id,- key: decrypt(keyRow.encrypted_key, keyRow.iv, keyRow.auth_tag),- baseUrl: keyRow.base_url?.trim().replace(/\/+$/, '') ?? null,- };- } catch {- return null;- }-}-async function mediaFetch(url: string,platform: string,@@ -771,6 +739,7 @@ function chainError(modality: MediaModality, lastError: MediaError | null): Medireturn new MediaError(`All ${modality} providers failed${lastError ? ` (last: ${lastError.message.slice(0, 160)})` : ' (no usable keys)'}.`,status,+ lastError?.code,);}@@ -779,10 +748,13 @@ export async function runImageGeneration(model: string | undefined, params: Imagconst chain = resolveMediaChain(model, 'image');let lastError: MediaError | null = null;for (const row of chain) {- const credential = KEYLESS_CAPABLE.has(row.platform)- ? { id: null, key: null, baseUrl: null }- : getProviderCredential(row);- if (!credential) continue; // no usable key for this provider — try the next+ const { credential, budgetBlocked } = KEYLESS_CAPABLE.has(row.platform)+ ? { credential: { id: null, key: null, baseUrl: null, release: () => {} }, budgetBlocked: false }+ : reserveProviderCredential(row, 0);+ if (!credential) {+ if (budgetBlocked) lastError = new MediaError('Monthly key budget exhausted', 429, 'quota_exceeded');+ continue;+ }const started = Date.now();try {const images = await callImageProvider(row, credential, params);@@ -795,6 +767,8 @@ export async function runImageGeneration(model: string | undefined, params: Imagconst e = err instanceof MediaError ? err : new MediaError(String(err?.message ?? err), 502);logMedia(row, credential.id, 'error', Date.now() - started, e.message.slice(0, 300));lastError = e;+ } finally {+ credential.release();}}throw chainError('image', lastError);@@ -812,9 +786,12 @@ export async function runVideoGeneration(let lastError: MediaError | null = null;for (const row of chain) {throwIfClientGone(clientSignal);- const credential = getProviderCredential(row);- if (!credential) continue;- if (credential.id != null && isOnCooldown(row.platform, row.model_id, credential.id)) continue;+ const { credential, budgetBlocked } = reserveProviderCredential(row, 0,+ keyId => isOnCooldown(row.platform, row.model_id, keyId));+ if (!credential) {+ if (budgetBlocked) lastError = new MediaError('Monthly key budget exhausted', 429, 'quota_exceeded');+ continue;+ }const started = Date.now();try {const out = await callVideoProvider(row, credential, params, clientSignal);@@ -828,6 +805,8 @@ export async function runVideoGeneration(lastError = e;// A caller that hung up gets no second generation charged to its account.throwIfClientGone(clientSignal);+ } finally {+ credential.release();}}throw chainError('video', lastError);@@ -873,7 +852,7 @@ interface SttCandidate {platform: string;modelId: string;/** The api_keys row this model is bound to, or null to pick any healthy key- * for the platform. Custom endpoints ALWAYS carry one: getProviderCredential+ * for the platform. Custom endpoints ALWAYS carry one: reserveProviderCredential* refuses to guess a key for platform 'custom', so dropping this here would* silently skip every custom STT row. */keyId: number | null;@@ -1078,9 +1057,12 @@ export async function runTranscription(model: string | undefined, p: Transcripti}let lastError: MediaError | null = null;for (const m of usable) {- const credential = getProviderCredential({ platform: m.platform, key_id: m.keyId });- if (!credential) continue; // no usable key for this provider — try the next- if (credential.id != null && isOnCooldown(m.platform, m.modelId, credential.id)) continue;+ const { credential, budgetBlocked } = reserveProviderCredential({ platform: m.platform, key_id: m.keyId }, 0,+ keyId => isOnCooldown(m.platform, m.modelId, keyId));+ if (!credential) {+ if (budgetBlocked) lastError = new MediaError('Monthly key budget exhausted', 429, 'quota_exceeded');+ continue;+ }const logRow = { platform: m.platform, model_id: m.modelId, modality: 'transcription' as const };const started = Date.now();try {@@ -1097,6 +1079,8 @@ export async function runTranscription(model: string | undefined, p: TranscriptisetCooldown(m.platform, m.modelId, credential.id);}lastError = e;+ } finally {+ credential.release();}}throw chainError('transcription', lastError);@@ -1107,10 +1091,13 @@ export async function runSpeech(model: string | undefined, params: SpeechParams)const chain = resolveMediaChain(model, 'audio');let lastError: MediaError | null = null;for (const row of chain) {- const credential = KEYLESS_CAPABLE.has(row.platform)- ? { id: null, key: null, baseUrl: null }- : getProviderCredential(row);- if (!credential) continue;+ const { credential, budgetBlocked } = KEYLESS_CAPABLE.has(row.platform)+ ? { credential: { id: null, key: null, baseUrl: null, release: () => {} }, budgetBlocked: false }+ : reserveProviderCredential(row, 0);+ if (!credential) {+ if (budgetBlocked) lastError = new MediaError('Monthly key budget exhausted', 429, 'quota_exceeded');+ continue;+ }const started = Date.now();try {const out = await callSpeechProvider(row, credential, params);@@ -1121,6 +1108,8 @@ export async function runSpeech(model: string | undefined, params: SpeechParams)const e = err instanceof MediaError ? err : new MediaError(String(err?.message ?? err), 502);logMedia(row, credential.id, 'error', Date.now() - started, e.message.slice(0, 300));lastError = e;+ } finally {+ credential.release();}}throw chainError('audio', lastError);diff --git a/server/src/services/provider-credential.ts b/server/src/services/provider-credential.tsnew file mode 100644index 00000000..0ee89917--- /dev/null+++ b/server/src/services/provider-credential.ts@@ -0,0 +1,57 @@+import { getDb } from '../db/index.js';+import { decrypt } from '../lib/crypto.js';+import { reserveMonthlyBudget } from './key-budget.js';++export interface ReservedProviderCredential {+ id: number;+ key: string;+ baseUrl: string | null;+ release: () => void;+}++interface KeyRow {+ id: number;+ encrypted_key: string;+ iv: string;+ auth_tag: string;+ base_url: string | null;+}++/** Select and reserve a credential for the independent embeddings/media routers.+ * Bound custom models stay on their own key; ordinary providers may use any+ * healthy key with room in its budget. Callers release after logging the result.+ */+export function reserveProviderCredential(+ row: { platform: string; key_id: number | null },+ estimatedTokens: number,+ skip: (keyId: number) => boolean = () => false,+): { credential: ReservedProviderCredential | null; budgetBlocked: boolean } {+ if (row.platform === 'custom' && row.key_id == null) return { credential: null, budgetBlocked: false };+ const bound = row.key_id != null;+ const keys = getDb().prepare(`+ SELECT id, encrypted_key, iv, auth_tag, base_url FROM api_keys+ WHERE ${bound ? 'id' : 'platform'} = ? AND enabled = 1+ AND status IN ('healthy', 'unknown') ORDER BY RANDOM()+ `).all(bound ? row.key_id : row.platform) as KeyRow[];+ let budgetBlocked = false;+ for (const keyRow of keys) {+ if (skip(keyRow.id)) continue;+ let key: string;+ try {+ key = decrypt(keyRow.encrypted_key, keyRow.iv, keyRow.auth_tag);+ } catch {+ continue;+ }+ const reservation = reserveMonthlyBudget(keyRow.id, estimatedTokens);+ if (!reservation.allowed) { budgetBlocked = true; continue; }+ return {+ credential: {+ id: keyRow.id, key,+ baseUrl: keyRow.base_url?.trim().replace(/\/+$/, '') ?? null,+ release: reservation.release,+ },+ budgetBlocked,+ };+ }+ return { credential: null, budgetBlocked };+}diff --git a/server/src/services/router.ts b/server/src/services/router.tsindex ee22bc40..7dba046a 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -27,6 +27,7 @@ import {type HeadroomThresholds,} from './scoring.js';import { TIMEOUT_ERROR_MARKERS } from '../lib/error-classify.js';+import { checkMonthlyBudget, reserveMonthlyBudget } from './key-budget.js';import { applyModelWeightOverride, getModelWeightOverrides } from './model-weight-overrides.js';import { modelsWithOverriddenField } from './model-state.js';import { parseBudget } from '../lib/budget.js';@@ -1499,6 +1500,11 @@ function selectKeyForModel(entry: ChainRow, estimatedTokens: number, skipKeys?:if (!canMakeRequest(entry.platform, entry.model_id, key.id, limits)) { note('rpm/rpd-limit'); continue; }if (!canUseTokens(entry.platform, entry.model_id, key.id, estimatedTokens, limits)) { note('tpm/tpd-limit'); continue; }if (!canUseProviderTokens(entry.platform, key.id, entry.model_id, estimatedTokens)) { note('provider-daily-token-cap'); continue; }+ // Monthly budget (#1158): a key whose request/token caps are spent for the+ // current UTC month is not a candidate — same skip semantics as the daily+ // gates above. The Retry-After (next-month boundary) surfaces through the+ // fallback exhaustion path rather than blocking here.+ if (!checkMonthlyBudget(key.id, estimatedTokens).allowed) { note('monthly-budget-cap'); continue; }let decryptedKey: string;try {@@ -1518,6 +1524,9 @@ function selectKeyForModel(entry: ChainRow, estimatedTokens: number, skipKeys?:roundRobinIndex.set(rrKey, idx);// Taken only once the key has cleared every gate and is definitely being// returned, so a rejected candidate never consumes concurrency budget.+ const proxyUrl = decryptProxyUrl(key);+ const budget = reserveMonthlyBudget(key.id, estimatedTokens);+ if (!budget.allowed) { note('monthly-budget-cap'); continue; }const leaseId = acquireLease(entry.platform, entry.model_id, key.id, estimatedTokens);return {provider: resolvedProvider,@@ -1527,13 +1536,13 @@ function selectKeyForModel(entry: ChainRow, estimatedTokens: number, skipKeys?:keyId: key.id,keyLabel: key.label || null,// Decrypted once here, at the point the row is already in hand (#590).- proxyUrl: decryptProxyUrl(key),+ proxyUrl,platform: entry.platform,displayName: entry.display_name,endpointScope: entry.endpoint_scope ?? '',rpdLimit: limits.rpd,tpdLimit: limits.tpd,- release: () => releaseLease(leaseId),+ release: () => { releaseLease(leaseId); budget.release(); },};}