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: support custom provider modalities (#229)
long2ice3511d20c4ff6
diff --git a/README.md b/README.mdindex a05306b6..4b848aa2 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@**One OpenAI-compatible endpoint. Sixteen free LLM providers. ~1.7B tokens per month.**-Aggregate the free tiers from Google, Groq, Cerebras, NVIDIA, Mistral, OpenRouter, GitHub Models, Cohere, Cloudflare, HuggingFace, Z.ai (Zhipu), Ollama, Kilo, Pollinations, LLM7, OVH AI Endpoints, and OpenCode Zen — plus any custom OpenAI-compatible endpoint (llama.cpp, LM Studio, vLLM, local Ollama) — behind a single `/v1/chat/completions` endpoint. Keys are stored encrypted. A router picks the best available model for each request, falls over to the next provider when one is rate-limited, and tracks per-key usage so you stay under every free-tier cap.+Aggregate the free tiers from Google, Groq, Cerebras, NVIDIA, Mistral, OpenRouter, GitHub Models, Cohere, Cloudflare, HuggingFace, Z.ai (Zhipu), Ollama, Kilo, Pollinations, LLM7, OVH AI Endpoints, and OpenCode Zen — plus custom OpenAI-compatible chat, embedding, image, and audio endpoints — behind a single `/v1` API. Keys are stored encrypted. A router picks the best available model for each request, falls over to the next provider when one is rate-limited, and tracks per-key usage so you stay under every free-tier cap.[](https://github.com/tashfeenahmed/freellmapi/actions/workflows/ci.yml)[](./LICENSE)@@ -80,17 +80,17 @@ The problem is that stacking them by hand is painful: seventeen different SDKs,</tr></table>-Plus a **custom** provider — point at any OpenAI-compatible endpoint (llama.cpp, LM Studio, vLLM, a local Ollama, or a remote gateway) from the Keys page.+Plus a **custom** provider — point chat, embedding, image, or audio models at any OpenAI-compatible endpoint (llama.cpp, LM Studio, vLLM, a local Ollama, or a remote gateway) from the Keys page.## Features- **OpenAI-compatible** — `POST /v1/chat/completions` and `GET /v1/models` work with the official OpenAI SDKs and any OpenAI-compatible client (LangChain, LlamaIndex, Continue, Hermes, etc.). Just change `base_url`.- **Responses API** — `POST /v1/responses` (the wire format current Codex CLI versions require) is implemented as a translating shim over the same router, with full streaming events and tool calls.- **Anthropic Messages API** — `POST /v1/messages` (plus `/v1/messages/count_tokens`) speaks Anthropic's wire format over the same router, so **Claude Code** and the official Anthropic SDKs run against your free pool. `GET /v1/models` is content-negotiated (Anthropic shape when the client sends `anthropic-version`, OpenAI shape otherwise), and Claude families (`opus` / `sonnet` / `haiku` / `default`) map to `auto` or a pinned model on the Keys page. See [Anthropic / Claude clients](#anthropic--claude-clients).-- **Image generation & text-to-speech** — `POST /v1/images/generations` and `POST /v1/audio/speech` route across the providers that serve media models. Browse and toggle them on the dashboard's **Models → Image / Audio** tabs.+- **Image generation & text-to-speech** — `POST /v1/images/generations` and `POST /v1/audio/speech` route across the providers that serve media models, including custom OpenAI-compatible media endpoints. Browse and toggle them on the dashboard's **Models → Image / Audio** tabs.- **Streaming and non-streaming** — Server-Sent Events for `stream: true`, JSON response otherwise. Every provider adapter implements both.- **Tool calling** — OpenAI-style `tools` / `tool_choice` requests are passed through, and assistant `tool_calls` + `tool` role follow-up messages round-trip across providers.-- **Embeddings** — `/v1/embeddings` with family-based routing: failover only ever happens between providers serving the *same* model (vectors from different models are incompatible), never across models. See [Embeddings](#embeddings).+- **Embeddings** — `/v1/embeddings` with family-based routing, including custom OpenAI-compatible embedding endpoints: failover only ever happens between providers serving the *same* model (vectors from different models are incompatible), never across models. See [Embeddings](#embeddings).- **Automatic fallover** — If the chosen provider returns a 429, 5xx, or times out, the router skips it, puts the key on a short cooldown, and retries on the next model in your fallback chain (up to 20 attempts).- **Per-key rate tracking** — RPM, RPD, TPM, and TPD counters per `(platform, model, key)` so the router always picks a key that's under its caps.- **Sticky sessions** — Multi-turn conversations keep talking to the same model for 30 minutes to avoid the hallucination spike that comes from mid-conversation model switches.@@ -587,6 +587,7 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full migration CLI and workflow<a href="https://github.com/zhangyu1324"><img src="https://images.weserv.nl/?url=github.com/zhangyu1324.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@zhangyu1324" /></a><a href="https://github.com/chongjiazhen"><img src="https://images.weserv.nl/?url=github.com/chongjiazhen.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@chongjiazhen" /></a><a href="https://github.com/vjsai"><img src="https://images.weserv.nl/?url=github.com/vjsai.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@vjsai" /></a>+<a href="https://github.com/long2ice"><img src="https://images.weserv.nl/?url=github.com/long2ice.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@long2ice" /></a><a href="https://github.com/hodlmybeer69-bit"><img src="https://images.weserv.nl/?url=github.com/hodlmybeer69-bit.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@hodlmybeer69-bit" /></a><a href="https://github.com/phoenixikkifullstack"><img src="https://images.weserv.nl/?url=github.com/phoenixikkifullstack.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@phoenixikkifullstack" /></a><a href="https://github.com/jtbrennan-git"><img src="https://images.weserv.nl/?url=github.com/jtbrennan-git.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@jtbrennan-git" /></a>diff --git a/client/src/components/media-models.tsx b/client/src/components/media-models.tsxindex 4cdd6097..03e35dd6 100644--- a/client/src/components/media-models.tsx+++ b/client/src/components/media-models.tsx@@ -2,6 +2,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { Link } from 'react-router-dom'import { apiFetch } from '@/lib/api'import { Switch } from '@/components/ui/switch'+import { Button } from '@/components/ui/button'import { PageHeader } from '@/components/page-header'import { ModelsTabs } from '@/components/models-tabs'import { useI18n } from '@/i18n'@@ -15,6 +16,7 @@ export interface MediaModel {enabled: booleanquotaLabel: stringkeyCount: number+ isCustom?: boolean}interface MediaData { models: MediaModel[] }@@ -60,6 +62,11 @@ export function MediaModelsView({ modality }: { modality: 'image' | 'audio' }) {onSuccess: () => queryClient.invalidateQueries({ queryKey: ['media'] }),})+ const deleteCustom = useMutation({+ mutationFn: (id: number) => apiFetch(`/api/media/custom/${id}`, { method: 'DELETE' }),+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['media'] }),+ })+const groups = groupMedia((data?.models ?? []).filter(m => m.modality === modality))const title = modality === 'image' ? t('models.imageTitle') : t('models.audioTitle')const description = modality === 'image' ? t('models.imageDesc') : t('models.audioDesc')@@ -116,6 +123,17 @@ export function MediaModelsView({ modality }: { modality: 'image' | 'audio' }) {checked={m.enabled}onCheckedChange={(c) => toggle.mutate({ id: m.id, enabled: c })}/>+ {m.isCustom && (+ <Button+ variant="ghost"+ size="xs"+ className="text-muted-foreground hover:text-destructive"+ onClick={() => deleteCustom.mutate(m.id)}+ disabled={deleteCustom.isPending}+ >+ {t('common.remove')}+ </Button>+ )}</div>))}</div>diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex dda40efd..dafb52a5 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -202,15 +202,26 @@"savingProxy": "Saving…","proxyLoadFailed": "Could not load proxy settings.","addCustom": "Add a custom OpenAI-compatible model",- "addCustomDescription": "Point at any OpenAI-compatible endpoint: llama.cpp, LM Studio, vLLM, a local Ollama, or a remote gateway. List one model per line (or comma-separated) to add several at once; they all share the one endpoint. The API key is optional (most local servers don't need one).",+ "addCustomDescription": "Point chat, embedding, image, or audio models at any OpenAI-compatible endpoint. The API key is optional for local servers.",+ "customType": "Type",+ "customTypeChat": "Chat",+ "customTypeEmbedding": "Embedding",+ "customTypeImage": "Image",+ "customTypeAudio": "Audio","customBaseUrl": "Base URL","customModels": "Models",+ "customModel": "Model","customDisplayName": "Display name","customDisplayNamePerModel": "per-model","customDisplayNameOptional": "optional",+ "customFamily": "Family",+ "customFamilyPlaceholder": "defaults to model id","customApiKey": "API key","addModel": "Add model","addModels": "Add {count} models",+ "addEmbeddingModel": "Add embedding",+ "addImageModel": "Add image model",+ "addAudioModel": "Add audio model","addingCustom": "Adding…","getApiKey": "Get API key","deleteKeyConfirm": "Delete this key? This cannot be undone.",diff --git a/client/src/pages/EmbeddingsPage.tsx b/client/src/pages/EmbeddingsPage.tsxindex c842648d..70fa24d6 100644--- a/client/src/pages/EmbeddingsPage.tsx+++ b/client/src/pages/EmbeddingsPage.tsx@@ -19,6 +19,7 @@ interface ProviderEntry {enabled: booleanquotaLabel: stringkeyCount: number+ isCustom?: boolean}interface Family {@@ -73,6 +74,15 @@ export default function EmbeddingsPage() {},})+ const deleteCustom = useMutation({+ mutationFn: (id: number) => apiFetch(`/api/embeddings/custom/${id}`, { method: 'DELETE' }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['embeddings'] })+ queryClient.invalidateQueries({ queryKey: ['embeddings', 'usage'] })+ setLocalFamilies(null)+ },+ })+const families = localFamilies ?? data?.families ?? []const defaultFamily = localDefault ?? data?.defaultFamily ?? ''const hasChanges = localFamilies !== null || localDefault !== null@@ -201,6 +211,17 @@ export default function EmbeddingsPage() {checked={p.enabled}onCheckedChange={(c) => updateProvider(f.family, p.id, { enabled: c })}/>+ {p.isCustom && (+ <Button+ variant="ghost"+ size="xs"+ className="text-muted-foreground hover:text-destructive"+ onClick={() => deleteCustom.mutate(p.id)}+ disabled={deleteCustom.isPending}+ >+ {t('common.remove')}+ </Button>+ )}</div>))}</div>diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex 4021687e..a994bb25 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -353,40 +353,86 @@ function parseModelList(raw: string): string[] {function CustomProviderSection() {const { t } = useI18n()const queryClient = useQueryClient()+ const [customType, setCustomType] = useState<'chat' | 'embedding' | 'image' | 'audio'>('chat')const [baseUrl, setBaseUrl] = useState('')const [model, setModel] = useState('')const [displayName, setDisplayName] = useState('')+ const [family, setFamily] = useState('')const [apiKey, setApiKey] = useState('')- const models = parseModelList(model)- const multiple = models.length > 1+ const models = customType === 'chat' ? parseModelList(model) : [model.trim()].filter(Boolean)+ const multiple = customType === 'chat' && models.length > 1++ const { data: embeddingsData } = useQuery<{ families: { family: string }[] }>({+ queryKey: ['embeddings'],+ queryFn: () => apiFetch('/api/embeddings'),+ })const addCustom = useMutation({- mutationFn: (body: { baseUrl: string; models: string[]; displayName?: string; apiKey?: string }) =>- apiFetch('/api/keys/custom', { method: 'POST', body: JSON.stringify(body) }),+ mutationFn: ({ path, body }: { path: string; body: Record<string, unknown> }) =>+ apiFetch(path, { method: 'POST', body: JSON.stringify(body) }),onSuccess: () => {queryClient.invalidateQueries({ queryKey: ['keys'] })queryClient.invalidateQueries({ queryKey: ['health'] })queryClient.invalidateQueries({ queryKey: ['fallback'] })queryClient.invalidateQueries({ queryKey: ['models'] })+ queryClient.invalidateQueries({ queryKey: ['embeddings'] })+ queryClient.invalidateQueries({ queryKey: ['media'] })setModel('')setDisplayName('')+ setFamily('')},})const submit = (e: React.FormEvent) => {e.preventDefault()if (!baseUrl || models.length === 0) return- // A single display name only makes sense for a lone model; with several- // ids the server names each model after its own id.- addCustom.mutate({+ const common = {baseUrl,- models,+ model: models[0],displayName: !multiple ? (displayName || undefined) : undefined,apiKey: apiKey || undefined,+ }+ if (customType === 'chat') {+ addCustom.mutate({+ path: '/api/keys/custom',+ body: {+ baseUrl,+ models,+ displayName: !multiple ? (displayName || undefined) : undefined,+ apiKey: apiKey || undefined,+ },+ })+ return+ }+ if (customType === 'embedding') {+ addCustom.mutate({+ path: '/api/embeddings/custom',+ body: { ...common, family: family || undefined },+ })+ return+ }+ addCustom.mutate({+ path: '/api/media/custom',+ body: { ...common, modality: customType },})}+ const modelPlaceholder = customType === 'chat'+ ? 'qwen3:4b\nllama3:8b'+ : customType === 'embedding'+ ? 'text-embedding-3-small'+ : customType === 'image'+ ? 'gpt-image-1'+ : 'gpt-4o-mini-tts'+ const addLabel = customType === 'chat'+ ? (multiple ? t('keys.addModels', { count: models.length }) : t('keys.addModel'))+ : customType === 'embedding'+ ? t('keys.addEmbeddingModel')+ : customType === 'image'+ ? t('keys.addImageModel')+ : t('keys.addAudioModel')+return (<section><h2 className="text-sm font-medium mb-1">{t('keys.addCustom')}</h2>@@ -394,6 +440,20 @@ function CustomProviderSection() {{t('keys.addCustomDescription')}</p><form onSubmit={submit} className="flex flex-wrap items-end gap-3 rounded-3xl border p-4 bg-card">+ <div className="space-y-1.5">+ <Label className="text-xs">{t('keys.customType')}</Label>+ <Select value={customType} onValueChange={(v) => setCustomType(v as typeof customType)}>+ <SelectTrigger className="w-[160px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="chat">{t('keys.customTypeChat')}</SelectItem>+ <SelectItem value="embedding">{t('keys.customTypeEmbedding')}</SelectItem>+ <SelectItem value="image">{t('keys.customTypeImage')}</SelectItem>+ <SelectItem value="audio">{t('keys.customTypeAudio')}</SelectItem>+ </SelectContent>+ </Select>+ </div><div className="space-y-1.5 flex-1 min-w-[240px]"><Label className="text-xs">{t('keys.customBaseUrl')}</Label><Input@@ -404,12 +464,12 @@ function CustomProviderSection() {/></div><div className="space-y-1.5">- <Label className="text-xs">{t('keys.customModels')}</Label>+ <Label className="text-xs">{customType === 'chat' ? t('keys.customModels') : t('keys.customModel')}</Label><Textareavalue={model}onChange={e => setModel(e.target.value)}- placeholder={'qwen3:4b\nllama3:8b'}- rows={2}+ placeholder={modelPlaceholder}+ rows={customType === 'chat' ? 2 : 1}className="w-[200px] font-mono text-xs"/></div>@@ -423,6 +483,17 @@ function CustomProviderSection() {className="w-[150px]"/></div>+ {customType === 'embedding' && (+ <div className="space-y-1.5">+ <Label className="text-xs">{t('keys.customFamily')}</Label>+ <Input+ value={family}+ onChange={e => setFamily(e.target.value)}+ placeholder={embeddingsData?.families?.[0]?.family ?? t('keys.customFamilyPlaceholder')}+ className="w-[190px] font-mono text-xs"+ />+ </div>+ )}<div className="space-y-1.5"><Label className="text-xs">{t('keys.customApiKey')}</Label><Input@@ -434,7 +505,7 @@ function CustomProviderSection() {/></div><Button type="submit" size="sm" disabled={!baseUrl || models.length === 0 || addCustom.isPending}>- {addCustom.isPending ? t('keys.addingCustom') : multiple ? t('keys.addModels', { count: models.length }) : t('keys.addModel')}+ {addCustom.isPending ? t('keys.addingCustom') : addLabel}</Button></form>{addCustom.isError && (diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex 5d33ec36..e2bd473a 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -5,6 +5,7 @@ import { getMigrationStatuses, runMigrations } from '../../../db/migrate/runner.import { up as runLegacyBaseline } from '../../../db/migrations/20260101_000000_legacy_baseline.js';const LEGACY_BASELINE_FILENAME = '20260101_000000_legacy_baseline.ts';+const CUSTOM_PROVIDER_MODALITIES_FILENAME = '20260627_000001_custom_provider_modalities.ts';interface SchemaRow {type: string;@@ -54,7 +55,10 @@ describe('migration round trip', () => {await runMigrations(db, 'up');expect(getEnabledZenDeadPromoCount(db)).toBe(0);- expect(getAppliedMigrationNames(db)).toEqual([LEGACY_BASELINE_FILENAME]);+ expect(getAppliedMigrationNames(db)).toEqual([+ LEGACY_BASELINE_FILENAME,+ CUSTOM_PROVIDER_MODALITIES_FILENAME,+ ]);} finally {db.close();}diff --git a/server/src/__tests__/routes/custom-modalities.test.ts b/server/src/__tests__/routes/custom-modalities.test.tsnew file mode 100644index 00000000..d3acca71--- /dev/null+++ b/server/src/__tests__/routes/custom-modalities.test.ts@@ -0,0 +1,178 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb } from '../../db/index.js';+import { decrypt } from '../../lib/crypto.js';+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';++const realFetch = globalThis.fetch;++let dashToken = '';++async function post(app: Express, path: string, body: unknown) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await realFetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),+ },+ body: JSON.stringify(body),+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++async function del(app: Express, path: string) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await realFetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'DELETE',+ headers: isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {},+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}++function embeddingResponse(dimensions: number) {+ return new Response(JSON.stringify({+ data: [{ index: 0, embedding: Array(dimensions).fill(0.1) }],+ usage: { prompt_tokens: 1 },+ }), { status: 200, headers: { 'content-type': 'application/json' } });+}++describe('custom provider modalities', () => {+ let app: Express;++ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ dashToken = mintDashboardToken();+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('registers a custom embedding provider after probing dimensions', async () => {+ const fetchMock = vi.fn(async () => embeddingResponse(3));+ globalThis.fetch = fetchMock as any;++ const { status, body } = await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8181/v1/',+ model: 'local-embed',+ family: 'local-family',+ displayName: 'Local Embed',+ apiKey: 'embed-secret',+ });++ expect(status).toBe(201);+ expect(body.dimensions).toBe(3);+ expect(body.baseUrl).toBe('http://127.0.0.1:8181/v1');+ expect(String(fetchMock.mock.calls[0][0])).toBe('http://127.0.0.1:8181/v1/embeddings');++ const row = getDb().prepare(`+ SELECT em.family, em.model_id, em.display_name, em.dimensions, k.base_url, k.encrypted_key, k.iv, k.auth_tag+ FROM embedding_models em+ JOIN api_keys k ON k.id = em.key_id+ WHERE em.platform = 'custom' AND em.model_id = 'local-embed'+ `).get() as any;+ expect(row.family).toBe('local-family');+ expect(row.display_name).toBe('Local Embed');+ expect(row.dimensions).toBe(3);+ expect(row.base_url).toBe('http://127.0.0.1:8181/v1');+ expect(decrypt(row.encrypted_key, row.iv, row.auth_tag)).toBe('embed-secret');+ });++ it('rejects a custom embedding provider with mismatched family dimensions', async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(embeddingResponse(3))+ .mockResolvedValueOnce(embeddingResponse(2));+ globalThis.fetch = fetchMock as any;++ expect((await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8181/v1',+ model: 'local-embed-a',+ family: 'shared-family',+ })).status).toBe(201);++ const { status, body } = await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8282/v1',+ model: 'local-embed-b',+ family: 'shared-family',+ });++ expect(status).toBe(400);+ expect(body.error.message).toMatch(/Use a new family name/);+ });++ it('registers custom image and audio models against one endpoint key', async () => {+ const image = await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8383/v1',+ model: 'local-image',+ modality: 'image',+ apiKey: 'media-secret',+ label: 'Local media',+ });+ const audio = await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8383/v1',+ model: 'local-tts',+ modality: 'audio',+ });++ expect(image.status).toBe(201);+ expect(audio.status).toBe(201);+ expect(audio.body.keyId).toBe(image.body.keyId);++ const keys = getDb().prepare("SELECT * FROM api_keys WHERE platform = 'custom' AND base_url = 'http://127.0.0.1:8383/v1'").all() as any[];+ expect(keys).toHaveLength(1);+ expect(decrypt(keys[0].encrypted_key, keys[0].iv, keys[0].auth_tag)).toBe('media-secret');++ const rows = getDb().prepare(`+ SELECT model_id, modality, key_id+ FROM media_models+ WHERE platform = 'custom'+ ORDER BY model_id+ `).all() as { model_id: string; modality: string; key_id: number }[];+ expect(rows).toEqual([+ { model_id: 'local-image', modality: 'image', key_id: image.body.keyId },+ { model_id: 'local-tts', modality: 'audio', key_id: image.body.keyId },+ ]);+ });++ it('deleting a custom endpoint key removes bound embedding and media models', async () => {+ const fetchMock = vi.fn(async () => embeddingResponse(3));+ globalThis.fetch = fetchMock as any;++ const embedding = await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8484/v1',+ model: 'local-embed',+ family: 'local-delete-family',+ apiKey: 'delete-secret',+ });+ expect(embedding.status).toBe(201);++ const media = await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8484/v1',+ model: 'local-image',+ modality: 'image',+ });+ expect(media.status).toBe(201);+ expect(media.body.keyId).toBe(embedding.body.keyId);++ getDb().prepare("UPDATE settings SET value = 'local-delete-family' WHERE key = 'embeddings_default_family'").run();++ const removed = await del(app, `/api/keys/${embedding.body.keyId}`);+ expect(removed.status).toBe(200);++ expect((getDb().prepare("SELECT COUNT(*) AS n FROM embedding_models WHERE platform = 'custom'").get() as { n: number }).n).toBe(0);+ expect((getDb().prepare("SELECT COUNT(*) AS n FROM media_models WHERE platform = 'custom'").get() as { n: number }).n).toBe(0);+ const def = getDb().prepare("SELECT value FROM settings WHERE key = 'embeddings_default_family'").get() as { value: string };+ expect(def.value).not.toBe('local-delete-family');+ });+});diff --git a/server/src/__tests__/routes/custom-provider.test.ts b/server/src/__tests__/routes/custom-provider.test.tsindex d1fc8d17..91840f87 100644--- a/server/src/__tests__/routes/custom-provider.test.ts+++ b/server/src/__tests__/routes/custom-provider.test.ts@@ -3,6 +3,7 @@ import http from 'node:http';import type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { decrypt } from '../../lib/crypto.js';import { routeRequest } from '../../services/router.js';import { resolveProvider, getProvider } from '../../providers/index.js';import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';@@ -118,6 +119,33 @@ describe('Custom Provider Endpoints', () => {expect(custom.baseUrl).toBe('http://127.0.0.1:11434/v1');});+ it('does not overwrite an existing endpoint key when a later submit omits apiKey', async () => {+ const first = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:7777/v1',+ model: 'secret-model-a',+ apiKey: 'keep-this-key',+ });+ expect(first.status).toBe(201);++ const second = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:7777/v1',+ model: 'secret-model-b',+ });+ expect(second.status).toBe(201);++ const key = getDb().prepare(`+ SELECT id, encrypted_key, iv, auth_tag+ FROM api_keys+ WHERE platform = 'custom' AND base_url = 'http://127.0.0.1:7777/v1'+ `).get() as { id: number; encrypted_key: string; iv: string; auth_tag: string };+ expect(decrypt(key.encrypted_key, key.iv, key.auth_tag)).toBe('keep-this-key');++ const db = getDb();+ db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom' AND key_id = ?)").run(key.id);+ db.prepare("DELETE FROM models WHERE platform = 'custom' AND key_id = ?").run(key.id);+ db.prepare('DELETE FROM api_keys WHERE id = ?').run(key.id);+ });+it('routes a request to the custom model through its base URL', () => {// The seeded built-in models have no keys, so the only routable model is// the custom one we registered above.diff --git a/server/src/__tests__/services/embeddings.test.ts b/server/src/__tests__/services/embeddings.test.tsindex 4e8bd626..0af54528 100644--- a/server/src/__tests__/services/embeddings.test.ts+++ b/server/src/__tests__/services/embeddings.test.ts@@ -14,6 +14,15 @@ function addKey(platform: string, raw = `${platform}-test-key`) {`).run(platform, encrypted, iv, authTag);}+function addCustomKey(baseUrl: string, raw = 'custom-test-key'): number {+ const { encrypted, iv, authTag } = encrypt(raw);+ const row = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)+ VALUES ('custom', 'test', ?, ?, ?, 'healthy', 1, ?)+ `).run(encrypted, iv, authTag, baseUrl);+ return Number(row.lastInsertRowid);+}+function okEmbeddingResponse(dims: number, count = 1) {return new Response(JSON.stringify({data: Array.from({ length: count }, (_, i) => ({ index: i, embedding: Array(dims).fill(0.1) })),@@ -53,6 +62,11 @@ describe('embeddings service', () => {).all();expect(dims).toHaveLength(1);});++ it('adds key_id for custom embedding endpoint binding', () => {+ const cols = (getDb().prepare('PRAGMA table_info(embedding_models)').all() as { name: string }[]).map(c => c.name);+ expect(cols).toContain('key_id');+ });});describe('resolveFamily', () => {@@ -194,6 +208,29 @@ describe('embeddings service', () => {expect(chatUsed.used).toBe(0);});+ it('routes custom embeddings through the model-bound endpoint key', async () => {+ const keyId = addCustomKey('http://127.0.0.1:8181/v1', 'custom-embed-key');+ getDb().prepare(`+ INSERT INTO embedding_models+ (family, platform, model_id, display_name, dimensions, max_input_tokens, priority, enabled, quota_label, key_id)+ VALUES ('local-embed', 'custom', 'local-embed-v1', 'Local Embed', 3, NULL, 1, 1, '', ?)+ `).run(keyId);+ const fetchMock = vi.fn(async () => okEmbeddingResponse(3));+ globalThis.fetch = fetchMock as any;++ const result = await runEmbeddings('local-embed', ['hello']);++ expect(result.platform).toBe('custom');+ expect(String(fetchMock.mock.calls[0][0])).toBe('http://127.0.0.1:8181/v1/embeddings');+ const init = fetchMock.mock.calls[0][1] as RequestInit;+ const headers = init.headers as Record<string, string>;+ expect(headers.Authorization).toBe('Bearer custom-embed-key');+ const body = JSON.parse(String(init.body));+ expect(body.model).toBe('local-embed-v1');+ const log = getDb().prepare("SELECT key_id FROM requests WHERE request_type = 'embedding' ORDER BY id DESC LIMIT 1").get() as { key_id: number };+ expect(log.key_id).toBe(keyId);+ });+describe('dimensions parameter (MRL truncation)', () => {// Typed fetch mock so .mock.calls is properly indexed without `as any`.// The cast on assignment to globalThis.fetch is unavoidable becausediff --git a/server/src/__tests__/services/media.test.ts b/server/src/__tests__/services/media.test.tsindex 26809c44..655722a5 100644--- a/server/src/__tests__/services/media.test.ts+++ b/server/src/__tests__/services/media.test.ts@@ -13,11 +13,20 @@ function addKey(platform: string, raw = `${platform}-test-key`) {`).run(platform, encrypted, iv, authTag);}-function addMedia(platform: string, modelId: string, modality: 'image' | 'audio', priority = 1) {+function addCustomKey(baseUrl: string, raw = 'custom-media-key'): number {+ const { encrypted, iv, authTag } = encrypt(raw);+ const row = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)+ VALUES ('custom', 'test', ?, ?, ?, 'healthy', 1, ?)+ `).run(encrypted, iv, authTag, baseUrl);+ return Number(row.lastInsertRowid);+}++function addMedia(platform: string, modelId: string, modality: 'image' | 'audio', priority = 1, keyId: number | null = null) {getDb().prepare(`- INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)- VALUES (?, ?, ?, ?, ?, 1, '')- `).run(platform, modelId, modelId, modality, priority);+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id)+ VALUES (?, ?, ?, ?, ?, 1, '', ?)+ `).run(platform, modelId, modelId, modality, priority, keyId);}function jsonResponse(body: unknown) {@@ -39,6 +48,7 @@ describe('media service', () => {const cols = (getDb().prepare('PRAGMA table_info(media_models)').all() as { name: string }[]).map(c => c.name);expect(cols).toContain('modality');expect(cols).toContain('quota_label');+ expect(cols).toContain('key_id');});describe('image generation', () => {@@ -117,6 +127,26 @@ describe('media service', () => {const r = await runImageGeneration('auto', { prompt: 'x' });expect(r.platform).toBe('siliconflow');});++ it('custom image models call the bound OpenAI-compatible endpoint', async () => {+ const keyId = addCustomKey('http://127.0.0.1:8282/v1', 'custom-image-key');+ addMedia('custom', 'local-image', 'image', 1, keyId);+ const fetchMock = vi.fn(async () => jsonResponse({ data: [{ url: 'https://example.test/image.png' }] }));+ globalThis.fetch = fetchMock as any;++ const r = await runImageGeneration('local-image', { prompt: 'a cat', n: 2, size: '512x512' });++ expect(r.platform).toBe('custom');+ expect(r.images[0].url).toBe('https://example.test/image.png');+ expect(String(fetchMock.mock.calls[0][0])).toBe('http://127.0.0.1:8282/v1/images/generations');+ const init = fetchMock.mock.calls[0][1] as RequestInit;+ const headers = init.headers as Record<string, string>;+ expect(headers.Authorization).toBe('Bearer custom-image-key');+ const body = JSON.parse(String(init.body));+ expect(body).toMatchObject({ model: 'local-image', prompt: 'a cat', n: 2, size: '512x512' });+ const log = getDb().prepare("SELECT key_id FROM requests WHERE request_type = 'image' ORDER BY id DESC LIMIT 1").get() as { key_id: number };+ expect(log.key_id).toBe(keyId);+ });});describe('text-to-speech', () => {@@ -161,5 +191,26 @@ describe('media service', () => {// header (44) + 4 PCM bytesexpect(r.audio.length).toBe(48);});++ it('custom audio models call the bound OpenAI-compatible endpoint', async () => {+ const keyId = addCustomKey('http://127.0.0.1:8383/v1', 'custom-audio-key');+ addMedia('custom', 'local-tts', 'audio', 1, keyId);+ const fetchMock = vi.fn(async () =>+ new Response(Buffer.from('MP3'), { status: 200, headers: { 'content-type': 'audio/mpeg' } })) as any;+ globalThis.fetch = fetchMock as any;++ const r = await runSpeech('local-tts', { input: 'hi', voice: 'alloy', format: 'mp3' });++ expect(r.platform).toBe('custom');+ expect(r.audio.toString()).toBe('MP3');+ expect(String(fetchMock.mock.calls[0][0])).toBe('http://127.0.0.1:8383/v1/audio/speech');+ const init = fetchMock.mock.calls[0][1] as RequestInit;+ const headers = init.headers as Record<string, string>;+ expect(headers.Authorization).toBe('Bearer custom-audio-key');+ const body = JSON.parse(String(init.body));+ expect(body).toMatchObject({ model: 'local-tts', input: 'hi', voice: 'alloy', response_format: 'mp3' });+ const log = getDb().prepare("SELECT key_id FROM requests WHERE request_type = 'audio' ORDER BY id DESC LIMIT 1").get() as { key_id: number };+ expect(log.key_id).toBe(keyId);+ });});});diff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex 0d35b62f..52f7909b 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -1,5 +1,6 @@import type Database from 'better-sqlite3';import * as legacyBaseline from '../migrations/20260101_000000_legacy_baseline.js';+import * as customProviderModalities from '../migrations/20260627_000001_custom_provider_modalities.js';export interface MigrationModule {up(db: Database.Database): void;@@ -12,7 +13,9 @@ export interface DefaultMigration {}export const LEGACY_BASELINE_FILENAME = '20260101_000000_legacy_baseline.ts';+export const CUSTOM_PROVIDER_MODALITIES_FILENAME = '20260627_000001_custom_provider_modalities.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },+ { filename: CUSTOM_PROVIDER_MODALITIES_FILENAME, module: customProviderModalities },];diff --git a/server/src/db/migrations/20260627_000001_custom_provider_modalities.ts b/server/src/db/migrations/20260627_000001_custom_provider_modalities.tsnew file mode 100644index 00000000..3d035317--- /dev/null+++ b/server/src/db/migrations/20260627_000001_custom_provider_modalities.ts@@ -0,0 +1,32 @@+import type Database from 'better-sqlite3';++function hasColumn(db: Database.Database, table: string, column: string): boolean {+ const columns = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];+ return columns.some(col => col.name === column);+}++function addKeyIdColumn(db: Database.Database, table: string): void {+ if (!hasColumn(db, table, 'key_id')) {+ db.prepare(`ALTER TABLE ${table} ADD COLUMN key_id INTEGER`).run();+ }+}++function dropKeyIdColumn(db: Database.Database, table: string): void {+ if (hasColumn(db, table, 'key_id')) {+ db.prepare(`ALTER TABLE ${table} DROP COLUMN key_id`).run();+ }+}++export function up(db: Database.Database): void {+ addKeyIdColumn(db, 'embedding_models');+ addKeyIdColumn(db, 'media_models');+ db.prepare('CREATE INDEX IF NOT EXISTS idx_embedding_models_key_id ON embedding_models(key_id)').run();+ db.prepare('CREATE INDEX IF NOT EXISTS idx_media_models_key_id ON media_models(key_id)').run();+}++export function down(db: Database.Database): void {+ db.prepare('DROP INDEX IF EXISTS idx_embedding_models_key_id').run();+ db.prepare('DROP INDEX IF EXISTS idx_media_models_key_id').run();+ dropKeyIdColumn(db, 'media_models');+ dropKeyIdColumn(db, 'embedding_models');+}diff --git a/server/src/routes/embeddings.ts b/server/src/routes/embeddings.tsindex ddbb5280..8e37b08e 100644--- a/server/src/routes/embeddings.ts+++ b/server/src/routes/embeddings.ts@@ -2,7 +2,14 @@ import { Router } from 'express';import type { Request, Response } from 'express';import { z } from 'zod';import { getDb, setSetting } from '../db/index.js';-import { listEmbeddingModels, getDefaultFamily, type EmbeddingModelRow } from '../services/embeddings.js';+import { encrypt, decrypt, maskKey } from '../lib/crypto.js';+import {+ listEmbeddingModels,+ getDefaultFamily,+ probeEmbeddingDimensions,+ EmbeddingsError,+ type EmbeddingModelRow,+} from '../services/embeddings.js';export const embeddingsRouter = Router();@@ -14,6 +21,11 @@ embeddingsRouter.get('/', (_req: Request, res: Response) => {"SELECT platform, COUNT(*) AS n FROM api_keys WHERE enabled = 1 AND status IN ('healthy', 'unknown') GROUP BY platform",).all() as { platform: string; n: number }[]).map(r => [r.platform, r.n]),);+ const customKeyIds = new Set(+ (db.prepare(+ "SELECT id FROM api_keys WHERE platform = 'custom' AND enabled = 1 AND status IN ('healthy', 'unknown')",+ ).all() as { id: number }[]).map(r => r.id),+ );const byFamily = new Map<string, EmbeddingModelRow[]>();for (const row of listEmbeddingModels()) {@@ -38,12 +50,176 @@ embeddingsRouter.get('/', (_req: Request, res: Response) => {priority: r.priority,enabled: r.enabled === 1,quotaLabel: r.quota_label,- keyCount: keyCounts.get(r.platform) ?? 0,+ keyCount: r.platform === 'custom' && r.key_id != null+ ? (customKeyIds.has(r.key_id) ? 1 : 0)+ : keyCounts.get(r.platform) ?? 0,+ isCustom: r.platform === 'custom',})),})),});});+const customEmbeddingSchema = z.object({+ baseUrl: z.string().url('baseUrl must be a valid URL'),+ model: z.string().min(1),+ displayName: z.string().optional(),+ family: z.string().optional(),+ apiKey: z.string().optional(),+ label: z.string().optional(),+ quotaLabel: z.string().optional(),+ maxInputTokens: z.number().int().positive().optional(),+});++function decryptExistingKey(row: { encrypted_key: string; iv: string; auth_tag: string } | undefined): string | null {+ if (!row) return null;+ try {+ return decrypt(row.encrypted_key, row.iv, row.auth_tag);+ } catch {+ return null;+ }+}++embeddingsRouter.post('/custom', async (req: Request, res: Response) => {+ const parsed = customEmbeddingSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });+ return;+ }++ const db = getDb();+ const baseUrl = parsed.data.baseUrl.trim().replace(/\/+$/, '');+ const modelId = parsed.data.model.trim();+ if (!modelId) {+ res.status(400).json({ error: { message: 'model is required' } });+ return;+ }+ const displayName = parsed.data.displayName?.trim() || modelId;+ const family = parsed.data.family?.trim() || modelId;+ const providedKey = parsed.data.apiKey?.trim() || undefined;+ const label = parsed.data.label?.trim() || undefined;+ const quotaLabel = parsed.data.quotaLabel?.trim() || 'custom endpoint';++ const existingKey = db.prepare(`+ SELECT id, encrypted_key, iv, auth_tag+ FROM api_keys+ WHERE platform = 'custom' AND base_url = ?+ LIMIT 1+ `).get(baseUrl) as { id: number; encrypted_key: string; iv: string; auth_tag: string } | undefined;+ const probeKey = providedKey ?? decryptExistingKey(existingKey) ?? 'no-key';++ let dimensions: number;+ try {+ dimensions = await probeEmbeddingDimensions(baseUrl, probeKey, modelId);+ } catch (err: any) {+ const status = err instanceof EmbeddingsError ? err.status : 502;+ res.status(status >= 400 && status < 600 ? status : 502).json({+ error: { message: `custom embedding probe failed: ${err?.message ?? 'unknown error'}` },+ });+ return;+ }++ const sibling = db.prepare(`+ SELECT dimensions+ FROM embedding_models+ WHERE family = ?+ AND NOT (platform = 'custom' AND model_id = ?)+ LIMIT 1+ `).get(family, modelId) as { dimensions: number } | undefined;+ if (sibling && sibling.dimensions !== dimensions) {+ res.status(400).json({+ error: {+ message: `Embedding family '${family}' is ${sibling.dimensions} dimensions, but '${modelId}' returned ${dimensions}. Use a new family name.`,+ },+ });+ return;+ }++ const upsert = db.transaction(() => {+ let keyId: number;+ let storedKeyForMask = probeKey;+ if (existingKey) {+ keyId = existingKey.id;+ if (providedKey) {+ const { encrypted, iv, authTag } = encrypt(providedKey);+ db.prepare(`+ UPDATE api_keys+ SET label = COALESCE(?, label),+ encrypted_key = ?,+ iv = ?,+ auth_tag = ?,+ status = 'unknown',+ enabled = 1+ WHERE id = ?+ `).run(label ?? null, encrypted, iv, authTag, keyId);+ storedKeyForMask = providedKey;+ } else {+ db.prepare(`+ UPDATE api_keys+ SET label = COALESCE(?, label), status = 'unknown', enabled = 1+ WHERE id = ?+ `).run(label ?? null, keyId);+ }+ } else {+ const keyToStore = providedKey ?? 'no-key';+ const { encrypted, iv, authTag } = encrypt(keyToStore);+ const key = db.prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)+ VALUES ('custom', ?, ?, ?, ?, 'unknown', 1, ?)+ `).run(label ?? 'Custom', encrypted, iv, authTag, baseUrl);+ keyId = Number(key.lastInsertRowid);+ storedKeyForMask = keyToStore;+ }++ const existingModel = db.prepare(`+ SELECT id, priority+ FROM embedding_models+ WHERE platform = 'custom' AND model_id = ?+ LIMIT 1+ `).get(modelId) as { id: number; priority: number } | undefined;+ const priority = existingModel?.priority ?? (+ (db.prepare('SELECT COALESCE(MAX(priority), 0) AS maxPriority FROM embedding_models WHERE family = ?')+ .get(family) as { maxPriority: number }).maxPriority + 1+ );++ if (existingModel) {+ db.prepare(`+ UPDATE embedding_models+ SET family = ?,+ display_name = ?,+ dimensions = ?,+ max_input_tokens = ?,+ priority = ?,+ enabled = 1,+ quota_label = ?,+ key_id = ?+ WHERE id = ?+ `).run(family, displayName, dimensions, parsed.data.maxInputTokens ?? null, priority, quotaLabel, keyId, existingModel.id);+ return { modelDbId: existingModel.id, keyId, storedKeyForMask };+ }++ const model = db.prepare(`+ INSERT INTO embedding_models+ (family, platform, model_id, display_name, dimensions, max_input_tokens, priority, enabled, quota_label, key_id)+ VALUES (?, 'custom', ?, ?, ?, ?, ?, 1, ?, ?)+ `).run(family, modelId, displayName, dimensions, parsed.data.maxInputTokens ?? null, priority, quotaLabel, keyId);+ return { modelDbId: Number(model.lastInsertRowid), keyId, storedKeyForMask };+ });++ const result = upsert();+ res.status(201).json({+ success: true,+ keyId: result.keyId,+ modelDbId: result.modelDbId,+ platform: 'custom',+ baseUrl,+ model: modelId,+ displayName,+ family,+ dimensions,+ maskedKey: maskKey(result.storedKeyForMask),+ });+});+const updateSchema = z.object({defaultFamily: z.string().optional(),providers: z.array(z.object({@@ -81,6 +257,28 @@ embeddingsRouter.put('/', (req: Request, res: Response) => {res.json({ success: true });});+embeddingsRouter.delete('/custom/:id', (req: Request, res: Response) => {+ const id = Number(req.params.id);+ if (!Number.isInteger(id)) {+ res.status(400).json({ error: { message: 'Invalid id' } });+ return;+ }++ const db = getDb();+ const row = db.prepare("SELECT family FROM embedding_models WHERE id = ? AND platform = 'custom'").get(id) as { family: string } | undefined;+ if (!row) {+ res.status(404).json({ error: { message: `Unknown custom embedding model ${id}` } });+ return;+ }++ db.prepare("DELETE FROM embedding_models WHERE id = ? AND platform = 'custom'").run(id);+ if (getDefaultFamily() === row.family) {+ const replacement = db.prepare('SELECT family FROM embedding_models ORDER BY family, priority LIMIT 1').get() as { family: string } | undefined;+ if (replacement) setSetting('embeddings_default_family', replacement.family);+ }+ res.json({ success: true });+});+// Per-family usage: requests today (most embedding quotas are daily/RPM) and// tokens this calendar month, from the tagged request log.embeddingsRouter.get('/usage', (_req: Request, res: Response) => {diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 8a1778ce..61370e6c 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -154,8 +154,8 @@ keysRouter.post('/custom', (req: Request, res: Response) => {const baseUrl = parsed.data.baseUrl.trim().replace(/\/+$/, '');// Local servers often need no key; keep a sentinel so there's always a bearer.- const rawKey = parsed.data.apiKey?.trim() || 'no-key';- const label = parsed.data.label ?? 'Custom';+ const providedKey = parsed.data.apiKey?.trim() || undefined;+ const label = parsed.data.label?.trim() || undefined;// Flatten singular + plural inputs into one list, dedupe by model id, drop// blanks. The singular `displayName` only applies to a lone `model` (it can't@@ -183,22 +183,37 @@ keysRouter.post('/custom', (req: Request, res: Response) => {const upsert = db.transaction(() => {// One 'custom' key row PER ENDPOINT (matched on base_url). Re-submitting// the same endpoint updates its key/label; a new base_url gets its own- // row instead of clobbering the previous provider. (#212)- const existing = db.prepare("SELECT id FROM api_keys WHERE platform = 'custom' AND base_url = ? LIMIT 1")- .get(baseUrl) as { id: number } | undefined;+// row instead of clobbering the previous provider. (#212) Re-submitting with a+// blank key preserves the stored key; only a provided key updates credentials.+ const existing = db.prepare("SELECT id, encrypted_key, iv, auth_tag FROM api_keys WHERE platform = 'custom' AND base_url = ? LIMIT 1")+ .get(baseUrl) as { id: number; encrypted_key: string; iv: string; auth_tag: string } | undefined;let keyId: number;+ let storedKeyForMask = providedKey ?? 'no-key';if (existing) {- const { encrypted, iv, authTag } = encrypt(rawKey);- db.prepare("UPDATE api_keys SET label = ?, encrypted_key = ?, iv = ?, auth_tag = ?, status = 'unknown', enabled = 1 WHERE id = ?")- .run(label, encrypted, iv, authTag, existing.id);keyId = existing.id;+ if (providedKey) {+ const { encrypted, iv, authTag } = encrypt(providedKey);+ db.prepare("UPDATE api_keys SET label = COALESCE(?, label), encrypted_key = ?, iv = ?, auth_tag = ?, status = 'unknown', enabled = 1 WHERE id = ?")+ .run(label ?? null, encrypted, iv, authTag, existing.id);+ storedKeyForMask = providedKey;+ } else {+ try {+ storedKeyForMask = decrypt(existing.encrypted_key, existing.iv, existing.auth_tag);+ } catch {+ storedKeyForMask = 'no-key';+ }+ db.prepare("UPDATE api_keys SET label = COALESCE(?, label), status = 'unknown', enabled = 1 WHERE id = ?")+ .run(label ?? null, existing.id);+ }} else {- const { encrypted, iv, authTag } = encrypt(rawKey);+ const keyToStore = providedKey ?? 'no-key';+ const { encrypted, iv, authTag } = encrypt(keyToStore);const r = db.prepare(`INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)VALUES ('custom', ?, ?, ?, ?, 'unknown', 1, ?)- `).run(label, encrypted, iv, authTag, baseUrl);+ `).run(label ?? 'Custom', encrypted, iv, authTag, baseUrl);keyId = Number(r.lastInsertRowid);+ storedKeyForMask = keyToStore;}const registered: { modelDbId: number; model: string; displayName: string }[] = [];@@ -228,10 +243,10 @@ keysRouter.post('/custom', (req: Request, res: Response) => {registered.push({ modelDbId: modelRow.id, model: modelId, displayName });}- return { keyId, registered };+ return { keyId, registered, storedKeyForMask };});- const { keyId, registered } = upsert();+ const { keyId, registered, storedKeyForMask } = upsert();// `model`/`displayName`/`modelDbId` echo the first model for older clients;// `models` carries the full set registered in this call.const first = registered[0]!;@@ -244,7 +259,7 @@ keysRouter.post('/custom', (req: Request, res: Response) => {model: first.model,displayName: first.displayName,models: registered,- maskedKey: maskKey(rawKey),+ maskedKey: maskKey(storedKeyForMask),});});@@ -271,12 +286,26 @@ keysRouter.delete('/:id', (req: Request, res: Response) => {// theirs. Legacy rows (key_id NULL) are swept once no custom keys remain,// so they never linger in the fallback chain forever (#189).if (row.platform === 'custom') {+ const defaultEmbedding = db.prepare("SELECT value FROM settings WHERE key = 'embeddings_default_family'").get() as { value: string } | undefined;db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom' AND key_id = ?)").run(id);db.prepare("DELETE FROM models WHERE platform = 'custom' AND key_id = ?").run(id);+ db.prepare("DELETE FROM embedding_models WHERE platform = 'custom' AND key_id = ?").run(id);+ db.prepare("DELETE FROM media_models WHERE platform = 'custom' AND key_id = ?").run(id);const remaining = db.prepare("SELECT COUNT(*) AS n FROM api_keys WHERE platform = 'custom'").get() as { n: number };if (remaining.n === 0) {db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom')").run();db.prepare("DELETE FROM models WHERE platform = 'custom'").run();+ db.prepare("DELETE FROM embedding_models WHERE platform = 'custom'").run();+ db.prepare("DELETE FROM media_models WHERE platform = 'custom'").run();+ }+ if (defaultEmbedding) {+ const stillExists = db.prepare('SELECT 1 FROM embedding_models WHERE family = ? LIMIT 1').get(defaultEmbedding.value);+ if (!stillExists) {+ const replacement = db.prepare('SELECT family FROM embedding_models ORDER BY family, priority LIMIT 1').get() as { family: string } | undefined;+ if (replacement) {+ db.prepare("UPDATE settings SET value = ? WHERE key = 'embeddings_default_family'").run(replacement.family);+ }+ }}}});diff --git a/server/src/routes/media.ts b/server/src/routes/media.tsindex e2a06161..7bff2889 100644--- a/server/src/routes/media.ts+++ b/server/src/routes/media.ts@@ -2,6 +2,7 @@ import { Router } from 'express';import type { Request, Response } from 'express';import { z } from 'zod';import { getDb } from '../db/index.js';+import { encrypt, decrypt, maskKey } from '../lib/crypto.js';import { listAllMediaModels } from '../services/media.js';export const mediaRouter = Router();@@ -16,6 +17,11 @@ mediaRouter.get('/', (_req: Request, res: Response) => {"SELECT platform, COUNT(*) AS n FROM api_keys WHERE enabled = 1 AND status IN ('healthy', 'unknown') GROUP BY platform",).all() as { platform: string; n: number }[]).map(r => [r.platform, r.n]),);+ const customKeyIds = new Set(+ (db.prepare(+ "SELECT id FROM api_keys WHERE platform = 'custom' AND enabled = 1 AND status IN ('healthy', 'unknown')",+ ).all() as { id: number }[]).map(r => r.id),+ );res.json({models: listAllMediaModels().map(r => ({@@ -26,11 +32,135 @@ mediaRouter.get('/', (_req: Request, res: Response) => {modality: r.modality,enabled: r.enabled === 1,quotaLabel: r.quota_label,- keyCount: keyCounts.get(r.platform) ?? 0,+ keyCount: r.platform === 'custom' && r.key_id != null+ ? (customKeyIds.has(r.key_id) ? 1 : 0)+ : keyCounts.get(r.platform) ?? 0,+ isCustom: r.platform === 'custom',})),});});+const customMediaSchema = z.object({+ baseUrl: z.string().url('baseUrl must be a valid URL'),+ model: z.string().min(1),+ displayName: z.string().optional(),+ modality: z.enum(['image', 'audio']),+ apiKey: z.string().optional(),+ label: z.string().optional(),+ quotaLabel: z.string().optional(),+});++mediaRouter.post('/custom', (req: Request, res: Response) => {+ const parsed = customMediaSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });+ return;+ }++ const db = getDb();+ const baseUrl = parsed.data.baseUrl.trim().replace(/\/+$/, '');+ const modelId = parsed.data.model.trim();+ if (!modelId) {+ res.status(400).json({ error: { message: 'model is required' } });+ return;+ }+ const displayName = parsed.data.displayName?.trim() || modelId;+ const label = parsed.data.label?.trim() || undefined;+ const providedKey = parsed.data.apiKey?.trim() || undefined;+ const quotaLabel = parsed.data.quotaLabel?.trim() || 'custom endpoint';++ const upsert = db.transaction(() => {+ const existingKey = db.prepare(`+ SELECT id, encrypted_key, iv, auth_tag+ FROM api_keys+ WHERE platform = 'custom' AND base_url = ?+ LIMIT 1+ `).get(baseUrl) as { id: number; encrypted_key: string; iv: string; auth_tag: string } | undefined;+ let keyId: number;+ let storedKeyForMask = providedKey ?? 'no-key';+ if (existingKey) {+ keyId = existingKey.id;+ if (providedKey) {+ const { encrypted, iv, authTag } = encrypt(providedKey);+ db.prepare(`+ UPDATE api_keys+ SET label = COALESCE(?, label),+ encrypted_key = ?,+ iv = ?,+ auth_tag = ?,+ status = 'unknown',+ enabled = 1+ WHERE id = ?+ `).run(label ?? null, encrypted, iv, authTag, keyId);+ storedKeyForMask = providedKey;+ } else {+ try {+ storedKeyForMask = decrypt(existingKey.encrypted_key, existingKey.iv, existingKey.auth_tag);+ } catch {+ storedKeyForMask = 'no-key';+ }+ db.prepare(`+ UPDATE api_keys+ SET label = COALESCE(?, label), status = 'unknown', enabled = 1+ WHERE id = ?+ `).run(label ?? null, keyId);+ }+ } else {+ const { encrypted, iv, authTag } = encrypt(providedKey ?? 'no-key');+ const key = db.prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)+ VALUES ('custom', ?, ?, ?, ?, 'unknown', 1, ?)+ `).run(label ?? 'Custom', encrypted, iv, authTag, baseUrl);+ keyId = Number(key.lastInsertRowid);+ }++ const existingModel = db.prepare(`+ SELECT id, modality, priority+ FROM media_models+ WHERE platform = 'custom' AND model_id = ?+ LIMIT 1+ `).get(modelId) as { id: number; modality: string; priority: number } | undefined;+ const priority = existingModel && existingModel.modality === parsed.data.modality+ ? existingModel.priority+ : (db.prepare('SELECT COALESCE(MAX(priority), 0) AS maxPriority FROM media_models WHERE modality = ?')+ .get(parsed.data.modality) as { maxPriority: number }).maxPriority + 1;++ if (existingModel) {+ db.prepare(`+ UPDATE media_models+ SET display_name = ?,+ modality = ?,+ priority = ?,+ enabled = 1,+ quota_label = ?,+ key_id = ?+ WHERE id = ?+ `).run(displayName, parsed.data.modality, priority, quotaLabel, keyId, existingModel.id);+ return { modelDbId: existingModel.id, keyId, storedKeyForMask };+ }++ const model = db.prepare(`+ INSERT INTO media_models+ (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id)+ VALUES ('custom', ?, ?, ?, ?, 1, ?, ?)+ `).run(modelId, displayName, parsed.data.modality, priority, quotaLabel, keyId);+ return { modelDbId: Number(model.lastInsertRowid), keyId, storedKeyForMask };+ });++ const result = upsert();+ res.status(201).json({+ success: true,+ keyId: result.keyId,+ modelDbId: result.modelDbId,+ platform: 'custom',+ baseUrl,+ model: modelId,+ displayName,+ modality: parsed.data.modality,+ maskedKey: maskKey(result.storedKeyForMask),+ });+});+const updateSchema = z.object({ enabled: z.boolean() });mediaRouter.put('/:id', (req: Request, res: Response) => {@@ -51,3 +181,18 @@ mediaRouter.put('/:id', (req: Request, res: Response) => {}res.json({ success: true });});++mediaRouter.delete('/custom/:id', (req: Request, res: Response) => {+ const id = Number(req.params.id);+ if (!Number.isInteger(id)) {+ res.status(400).json({ error: { message: 'Invalid id' } });+ return;+ }++ const info = getDb().prepare("DELETE FROM media_models WHERE id = ? AND platform = 'custom'").run(id);+ if (info.changes === 0) {+ res.status(404).json({ error: { message: `Unknown custom media model ${id}` } });+ return;+ }+ res.json({ success: true });+});diff --git a/server/src/routes/models.ts b/server/src/routes/models.tsindex 91c921ba..2e9e3590 100644--- a/server/src/routes/models.ts+++ b/server/src/routes/models.ts@@ -5,6 +5,28 @@ import { hasProvider } from '../providers/index.js';export const modelsRouter = Router();+modelsRouter.delete('/custom/:id', (req: Request, res: Response) => {+ const id = Number(req.params.id);+ if (!Number.isInteger(id)) {+ res.status(400).json({ error: { message: 'Invalid id' } });+ return;+ }++ const db = getDb();+ const row = db.prepare("SELECT id FROM models WHERE id = ? AND platform = 'custom'").get(id);+ if (!row) {+ res.status(404).json({ error: { message: `Unknown custom model ${id}` } });+ return;+ }++ const remove = db.transaction(() => {+ db.prepare('DELETE FROM fallback_config WHERE model_db_id = ?').run(id);+ db.prepare("DELETE FROM models WHERE id = ? AND platform = 'custom'").run(id);+ });+ remove();+ res.json({ success: true });+});+// List all models with availability infomodelsRouter.get('/', (_req: Request, res: Response) => {const db = getDb();diff --git a/server/src/services/embeddings.ts b/server/src/services/embeddings.tsindex 6cc8ea92..84642941 100644--- a/server/src/services/embeddings.ts+++ b/server/src/services/embeddings.ts@@ -22,6 +22,7 @@ export interface EmbeddingModelRow {priority: number;enabled: number;quota_label: string;+ key_id: number | null;}export interface EmbeddingsResult {@@ -61,13 +62,40 @@ export function resolveFamily(model: string | undefined): string | null {return byModelId?.family ?? null;}-function getPlatformKey(platform: string): string | null {- const row = getDb().prepare(- "SELECT encrypted_key, iv, auth_tag FROM api_keys WHERE platform = ? AND enabled = 1 AND status IN ('healthy', 'unknown') ORDER BY id LIMIT 1",- ).get(platform) as { encrypted_key: string; iv: string; auth_tag: string } | undefined;- if (!row) return null;+interface ProviderCredential {+ id: number;+ key: string;+ 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 id 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 decrypt(row.encrypted_key, row.iv, row.auth_tag);+ return {+ id: keyRow.id,+ key: decrypt(keyRow.encrypted_key, keyRow.iv, keyRow.auth_tag),+ baseUrl: keyRow.base_url?.trim().replace(/\/+$/, '') ?? null,+ };} catch {return null;}@@ -121,8 +149,21 @@ async function openAiStyleEmbed(};}-async function callProvider(row: EmbeddingModelRow, key: string, inputs: string[], dimensions?: number): Promise<ProviderCallResult> {+export async function probeEmbeddingDimensions(baseUrl: string, key: string, modelId: string): Promise<number> {+ const out = await openAiStyleEmbed(`${baseUrl.trim().replace(/\/+$/, '')}/embeddings`, key, modelId, ['dimension probe']);+ const vector = out.vectors[0];+ if (!Array.isArray(vector) || vector.length === 0) {+ throw new EmbeddingsError('upstream returned malformed embeddings', 502);+ }+ return vector.length;+}++async function callProvider(row: EmbeddingModelRow, credential: ProviderCredential, inputs: string[], dimensions?: number): Promise<ProviderCallResult> {+ const { key } = credential;switch (row.platform) {+ case 'custom':+ if (!credential.baseUrl) throw new EmbeddingsError('custom embedding provider is missing base_url', 500);+ return openAiStyleEmbed(`${credential.baseUrl}/embeddings`, key, row.model_id, inputs, {}, dimensions);case 'google':return openAiStyleEmbed('https://generativelanguage.googleapis.com/v1beta/openai/embeddings', key, row.model_id, inputs, {}, dimensions);case 'nvidia':@@ -184,6 +225,7 @@ async function callProvider(row: EmbeddingModelRow, key: string, inputs: string[function logEmbeddingRequest(row: EmbeddingModelRow,+ keyId: number | null,status: 'success' | 'error',inputTokens: number,latencyMs: number,@@ -192,8 +234,8 @@ function logEmbeddingRequest(try {getDb().prepare(`INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, request_type)- VALUES (?, ?, NULL, ?, ?, 0, ?, ?, 'embedding')- `).run(row.platform, row.model_id, status, inputTokens, latencyMs, error);+ VALUES (?, ?, ?, ?, ?, 0, ?, ?, 'embedding')+ `).run(row.platform, row.model_id, keyId, status, inputTokens, latencyMs, error);} catch (e) {console.error('Failed to log embedding request:', e);}@@ -225,16 +267,16 @@ export async function runEmbeddings(model: string | undefined, inputs: string[],let lastError: EmbeddingsError | null = null;for (const row of chain) {- const key = getPlatformKey(row.platform);- if (!key) continue; // no usable key for this provider — try the next one+ const credential = getProviderCredential(row);+ if (!credential) continue; // no usable key for this provider — try the next oneconst started = Date.now();try {- const out = await callProvider(row, key, inputs, dimensions);+ const out = await callProvider(row, credential, inputs, dimensions);if (out.vectors.length !== inputs.length || out.vectors.some(v => !Array.isArray(v) || v.length === 0)) {throw new EmbeddingsError('upstream returned malformed embeddings', 502);}const tokens = out.inputTokens ?? estimateTokens(inputs);- logEmbeddingRequest(row, 'success', tokens, Date.now() - started, null);+ logEmbeddingRequest(row, credential.id, 'success', tokens, Date.now() - started, null);return {family,platform: row.platform,@@ -245,7 +287,7 @@ export async function runEmbeddings(model: string | undefined, inputs: string[],};} catch (err: any) {const e = err instanceof EmbeddingsError ? err : new EmbeddingsError(String(err?.message ?? err), 502);- logEmbeddingRequest(row, 'error', 0, Date.now() - started, e.message.slice(0, 300));+ 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}diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex cd2781ca..fb1bf322 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -29,6 +29,7 @@ export interface MediaModelRow {priority: number;enabled: number;quota_label: string;+ key_id: number | null;}export class MediaError extends Error {@@ -69,13 +70,40 @@ export function listAllMediaModels(): MediaModelRow[] {.all() as MediaModelRow[];}-function getPlatformKey(platform: string): string | null {- const row = getDb()- .prepare("SELECT encrypted_key, iv, auth_tag FROM api_keys WHERE platform = ? AND enabled = 1 AND status IN ('healthy', 'unknown') ORDER BY id LIMIT 1")- .get(platform) as { encrypted_key: string; iv: string; auth_tag: string } | undefined;- if (!row) return null;+interface ProviderCredential {+ id: number | null;+ key: string | null;+ baseUrl: string | null;+}++function getProviderCredential(row: MediaModelRow): 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 id 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 decrypt(row.encrypted_key, row.iv, row.auth_tag);+ return {+ id: keyRow.id,+ key: decrypt(keyRow.encrypted_key, keyRow.iv, keyRow.auth_tag),+ baseUrl: keyRow.base_url?.trim().replace(/\/+$/, '') ?? null,+ };} catch {return null;}@@ -148,11 +176,25 @@ function wrapPcmAsWav(pcm: Buffer, sampleRate: number): Buffer {async function callImageProvider(row: MediaModelRow,- key: string | null,+ credential: ProviderCredential,p: ImageParams,): Promise<Array<{ b64_json?: string; url?: string }>> {+ const key = credential.key;const [w, h] = parseSize(p.size);switch (row.platform) {+ case 'custom': {+ if (!credential.baseUrl) throw new MediaError('custom image provider is missing base_url', 500);+ const body: Record<string, unknown> = { model: row.model_id, prompt: p.prompt };+ if (p.n !== undefined) body.n = p.n;+ if (p.size) body.size = p.size;+ const r = await mediaFetch(`${credential.baseUrl}/images/generations`, 'custom', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key ?? 'no-key'}` },+ body: JSON.stringify(body),+ });+ const j = (await r.json()) as { data?: { b64_json?: string; url?: string }[] };+ return (j.data ?? []).map(i => ({ b64_json: i.b64_json, url: i.url }));+ }case 'nvidia': {// NVIDIA NIM image models live at ai.api.nvidia.com/v1/genai/{model};// response is { artifacts: [{ base64 }] }.@@ -205,10 +247,27 @@ async function callImageProvider(async function callSpeechProvider(row: MediaModelRow,- key: string | null,+ credential: ProviderCredential,p: SpeechParams,): Promise<{ audio: Buffer; contentType: string }> {+ const key = credential.key;switch (row.platform) {+ case 'custom': {+ if (!credential.baseUrl) throw new MediaError('custom audio provider is missing base_url', 500);+ const fmt = p.format ?? 'mp3';+ const body: Record<string, unknown> = { model: row.model_id, input: p.input };+ if (p.voice) body.voice = p.voice;+ if (p.format) body.response_format = p.format;+ const r = await mediaFetch(`${credential.baseUrl}/audio/speech`, 'custom', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key ?? 'no-key'}` },+ body: JSON.stringify(body),+ });+ return {+ audio: Buffer.from(await r.arrayBuffer()),+ contentType: r.headers.get('content-type') ?? contentTypeFor(fmt),+ };+ }case 'cloudflare': {const { accountId, token } = parseCfKey(key);const r = await mediaFetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${row.model_id}`, 'cloudflare', {@@ -297,12 +356,12 @@ function resolveMediaChain(model: string | undefined, modality: MediaModality):return matches;}-function logMedia(row: MediaModelRow, status: 'success' | 'error', latencyMs: number, error: string | null): void {+function logMedia(row: MediaModelRow, keyId: number | null, status: 'success' | 'error', latencyMs: number, error: string | null): void {try {getDb().prepare(`INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, request_type)- VALUES (?, ?, NULL, ?, 0, 0, ?, ?, ?)`)- .run(row.platform, row.model_id, status, latencyMs, error, row.modality);+ VALUES (?, ?, ?, ?, 0, 0, ?, ?, ?)`)+ .run(row.platform, row.model_id, keyId, status, latencyMs, error, row.modality);} catch (e) {console.error('Failed to log media request:', e);}@@ -320,20 +379,21 @@ export async function runImageGeneration(model: string | undefined, params: Imagconst chain = resolveMediaChain(model, 'image');let lastError: MediaError | null = null;for (const row of chain) {- const keyless = KEYLESS_CAPABLE.has(row.platform);- const key = keyless ? null : getPlatformKey(row.platform);- if (!keyless && !key) continue; // no usable key for this provider — try the next+ 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 nextconst started = Date.now();try {- const images = await callImageProvider(row, key, params);+ const images = await callImageProvider(row, credential, params);if (!images.length || images.every(i => !i.b64_json && !i.url)) {throw new MediaError('upstream returned no image', 502);}- logMedia(row, 'success', Date.now() - started, null);+ logMedia(row, credential.id, 'success', Date.now() - started, null);return { platform: row.platform, modelId: row.model_id, images };} catch (err: any) {const e = err instanceof MediaError ? err : new MediaError(String(err?.message ?? err), 502);- logMedia(row, 'error', Date.now() - started, e.message.slice(0, 300));+ logMedia(row, credential.id, 'error', Date.now() - started, e.message.slice(0, 300));lastError = e;}}@@ -345,18 +405,19 @@ 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 keyless = KEYLESS_CAPABLE.has(row.platform);- const key = keyless ? null : getPlatformKey(row.platform);- if (!keyless && !key) continue;+ const credential = KEYLESS_CAPABLE.has(row.platform)+ ? { id: null, key: null, baseUrl: null }+ : getProviderCredential(row);+ if (!credential) continue;const started = Date.now();try {- const out = await callSpeechProvider(row, key, params);+ const out = await callSpeechProvider(row, credential, params);if (!out.audio.length) throw new MediaError('upstream returned no audio', 502);- logMedia(row, 'success', Date.now() - started, null);+ logMedia(row, credential.id, 'success', Date.now() - started, null);return { platform: row.platform, modelId: row.model_id, audio: out.audio, contentType: out.contentType };} catch (err: any) {const e = err instanceof MediaError ? err : new MediaError(String(err?.message ?? err), 502);- logMedia(row, 'error', Date.now() - started, e.message.slice(0, 300));+ logMedia(row, credential.id, 'error', Date.now() - started, e.message.slice(0, 300));lastError = e;}}diff --git a/shared/types.ts b/shared/types.tsindex 41d32057..49dee0d6 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -111,6 +111,7 @@ export interface ApiKey {platform: Platform;label: string;maskedKey: string;+ baseUrl: string | null;status: KeyStatus;enabled: boolean;createdAt: string;