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: generative media — image generation + audio/TTS endpoints (#358)
Tashfeen9f7bd8ca8b92
diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex 2d975a71..093a0df7 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -56,6 +56,7 @@ const PLATFORMS: { value: Platform; label: string; url: string; keyless?: boolea{ value: 'opencode', label: 'OpenCode Zen (free key)', url: 'https://opencode.ai/auth' },{ value: 'agnes', label: 'Agnes AI (free key)', url: 'https://platform.agnes-ai.com' },{ value: 'reka', label: 'Reka (free key)', url: 'https://platform.reka.ai' },+ { value: 'siliconflow', label: 'SiliconFlow (image + TTS)', url: 'https://siliconflow.com' },]// 'custom' is configured through its own form (base URL + model), not thediff --git a/server/src/__tests__/services/media.test.ts b/server/src/__tests__/services/media.test.tsnew file mode 100644index 00000000..26809c44--- /dev/null+++ b/server/src/__tests__/services/media.test.ts@@ -0,0 +1,165 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { runImageGeneration, runSpeech, MediaError } from '../../services/media.js';++const realFetch = globalThis.fetch;++function addKey(platform: string, raw = `${platform}-test-key`) {+ const { encrypted, iv, authTag } = encrypt(raw);+ getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES (?, 'test', ?, ?, ?, 'healthy', 1)+ `).run(platform, encrypted, iv, authTag);+}++function addMedia(platform: string, modelId: string, modality: 'image' | 'audio', priority = 1) {+ getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)+ VALUES (?, ?, ?, ?, ?, 1, '')+ `).run(platform, modelId, modelId, modality, priority);+}++function jsonResponse(body: unknown) {+ return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });+}++describe('media service', () => {+ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('migration creates the media_models table', () => {+ 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');+ });++ describe('image generation', () => {+ it('NVIDIA: maps artifacts[].base64 → b64_json', async () => {+ addMedia('nvidia', 'black-forest-labs/flux.1-schnell', 'image');+ addKey('nvidia');+ globalThis.fetch = vi.fn(async () => jsonResponse({ artifacts: [{ base64: 'AAAA' }] })) as any;+ const r = await runImageGeneration('black-forest-labs/flux.1-schnell', { prompt: 'a cat' });+ expect(r.platform).toBe('nvidia');+ expect(r.images[0].b64_json).toBe('AAAA');+ });++ it('Pollinations: keyless GET, raw bytes → b64_json (no api key needed)', async () => {+ addMedia('pollinations', 'flux', 'image');+ globalThis.fetch = vi.fn(async () =>+ new Response(Buffer.from('PNGDATA'), { status: 200, headers: { 'content-type': 'image/jpeg' } })) as any;+ const r = await runImageGeneration('flux', { prompt: 'a cat' });+ expect(r.platform).toBe('pollinations');+ expect(r.images[0].b64_json).toBe(Buffer.from('PNGDATA').toString('base64'));+ });++ it('Cloudflare: JSON {result.image} → b64_json', async () => {+ addMedia('cloudflare', '@cf/black-forest-labs/flux-1-schnell', 'image');+ addKey('cloudflare', 'acct123:token456');+ globalThis.fetch = vi.fn(async () => jsonResponse({ result: { image: 'CFB64' }, success: true })) as any;+ const r = await runImageGeneration('@cf/black-forest-labs/flux-1-schnell', { prompt: 'x' });+ expect(r.images[0].b64_json).toBe('CFB64');+ });++ it('Cloudflare: binary SDXL response → b64_json', async () => {+ addMedia('cloudflare', '@cf/stabilityai/stable-diffusion-xl-base-1.0', 'image');+ addKey('cloudflare', 'acct123:token456');+ globalThis.fetch = vi.fn(async () =>+ new Response(Buffer.from('SDXLPNG'), { status: 200, headers: { 'content-type': 'image/png' } })) as any;+ const r = await runImageGeneration('@cf/stabilityai/stable-diffusion-xl-base-1.0', { prompt: 'x' });+ expect(r.images[0].b64_json).toBe(Buffer.from('SDXLPNG').toString('base64'));+ });++ it('SiliconFlow: images[].url → url', async () => {+ addMedia('siliconflow', 'black-forest-labs/FLUX.1-schnell', 'image');+ addKey('siliconflow');+ globalThis.fetch = vi.fn(async () => jsonResponse({ images: [{ url: 'https://x/y.png' }] })) as any;+ const r = await runImageGeneration('black-forest-labs/FLUX.1-schnell', { prompt: 'x' });+ expect(r.images[0].url).toBe('https://x/y.png');+ });++ it('unknown model id → 400', async () => {+ addMedia('nvidia', 'real-model', 'image');+ addKey('nvidia');+ await expect(runImageGeneration('does-not-exist', { prompt: 'x' })).rejects.toMatchObject({ status: 400 });+ });++ it('no providers configured → 503', async () => {+ await expect(runImageGeneration('auto', { prompt: 'x' })).rejects.toMatchObject({ status: 503 });+ });++ it('fails over to the next provider on error (auto)', async () => {+ addMedia('nvidia', 'flux-n', 'image', 1);+ addKey('nvidia');+ addMedia('siliconflow', 'flux-s', 'image', 2);+ addKey('siliconflow');+ globalThis.fetch = vi.fn(async (url: any) => {+ if (String(url).includes('nvidia')) return new Response('upstream boom', { status: 500 });+ return jsonResponse({ images: [{ url: 'ok' }] });+ }) as any;+ const r = await runImageGeneration('auto', { prompt: 'x' });+ expect(r.platform).toBe('siliconflow');+ expect(r.images[0].url).toBe('ok');+ });++ it('skips a provider with no key, uses the one that has it (auto)', async () => {+ addMedia('nvidia', 'flux-n', 'image', 1); // no key added+ addMedia('siliconflow', 'flux-s', 'image', 2);+ addKey('siliconflow');+ globalThis.fetch = vi.fn(async () => jsonResponse({ images: [{ url: 'ok' }] })) as any;+ const r = await runImageGeneration('auto', { prompt: 'x' });+ expect(r.platform).toBe('siliconflow');+ });+ });++ describe('text-to-speech', () => {+ it('Cloudflare MeloTTS: base64 audio → audio/mpeg bytes', async () => {+ addMedia('cloudflare', '@cf/myshell-ai/melotts', 'audio');+ addKey('cloudflare', 'acct:tok');+ globalThis.fetch = vi.fn(async () => jsonResponse({ result: { audio: Buffer.from('MP3').toString('base64') } })) as any;+ const r = await runSpeech('@cf/myshell-ai/melotts', { input: 'hi' });+ expect(r.contentType).toBe('audio/mpeg');+ expect(r.audio.toString()).toBe('MP3');+ });++ it('SiliconFlow CosyVoice: raw audio bytes', async () => {+ addMedia('siliconflow', 'FunAudioLLM/CosyVoice2-0.5B', 'audio');+ addKey('siliconflow');+ globalThis.fetch = vi.fn(async () =>+ new Response(Buffer.from('COSY'), { status: 200, headers: { 'content-type': 'audio/mpeg' } })) as any;+ const r = await runSpeech('FunAudioLLM/CosyVoice2-0.5B', { input: 'hi' });+ expect(r.contentType).toBe('audio/mpeg');+ expect(r.audio.toString()).toBe('COSY');+ });++ it('Pollinations openai-audio: message.audio.data → bytes (keyless)', async () => {+ addMedia('pollinations', 'openai-audio', 'audio');+ globalThis.fetch = vi.fn(async () =>+ jsonResponse({ choices: [{ message: { audio: { data: Buffer.from('POLLY').toString('base64') } } }] })) as any;+ const r = await runSpeech('openai-audio', { input: 'hi' });+ expect(r.audio.toString()).toBe('POLLY');+ });++ it('Gemini TTS: base64 PCM wrapped as WAV (RIFF header)', async () => {+ addMedia('google', 'gemini-2.5-flash-preview-tts', 'audio');+ addKey('google');+ const pcm = Buffer.from([1, 2, 3, 4]);+ globalThis.fetch = vi.fn(async () => jsonResponse({+ candidates: [{ content: { parts: [{ inlineData: { mimeType: 'audio/L16;codec=pcm;rate=24000', data: pcm.toString('base64') } }] } }],+ })) as any;+ const r = await runSpeech('gemini-2.5-flash-preview-tts', { input: 'hi' });+ expect(r.contentType).toBe('audio/wav');+ expect(r.audio.subarray(0, 4).toString()).toBe('RIFF');+ expect(r.audio.subarray(8, 12).toString()).toBe('WAVE');+ // header (44) + 4 PCM bytes+ expect(r.audio.length).toBe(48);+ });+ });+});diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.tsindex d315e50a..0f659aba 100644--- a/server/src/db/migrations.ts+++ b/server/src/db/migrations.ts@@ -44,6 +44,7 @@ export function migrateDbSchema(db: Database.Database) {// (drives the realistic "Est. savings" analytics stat).applyModelPricing(db);migrateEmbeddingsV1(db);+ migrateMediaV1(db);migrateQuirksV1(db);ensureUnifiedKey(db);migrateProfilesInit(db);@@ -1967,6 +1968,35 @@ function migrateEmbeddingsV1(db: Database.Database) {}}+/**+ * Media (image + audio/TTS) models V1 (June 2026): SCHEMA ONLY.+ *+ * Generative-media models live in their OWN table — exactly like embeddings —+ * so they never enter the chat router's candidate pool (a chat request can't+ * misroute to an image model) and never pollute the chat token budget. This is+ * schema only: per the no-model-data-in-migrations rule (see migrateDbSchema),+ * the rows are maintained in the published catalog and arrive via catalog-sync+ * (premium on the live tier within ~12h, free at the monthly promote). `modality`+ * is 'image' | 'audio'; `quota_label` mirrors the catalog's display note. The+ * request_type column (added by migrateEmbeddingsV1) tags media traffic 'image'+ * / 'audio' so it stays out of the chat budget math.+ */+function migrateMediaV1(db: Database.Database) {+ db.exec(`+ CREATE TABLE IF NOT EXISTS media_models (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ platform TEXT NOT NULL,+ model_id TEXT NOT NULL,+ display_name TEXT NOT NULL,+ modality TEXT NOT NULL,+ priority INTEGER NOT NULL DEFAULT 0,+ enabled INTEGER NOT NULL DEFAULT 1,+ quota_label TEXT NOT NULL DEFAULT '',+ UNIQUE(platform, model_id)+ );+ `);+}+/*** Quirks V1 (June 2026): promote the catalog's free-form "quirks" out of code* comments into structured, reusable data so the catalog server can ship them.diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex 471307bc..7e213caa 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -218,6 +218,17 @@ register(new OpenAICompatProvider({baseUrl: 'https://api.reka.ai/v1',}));+// SiliconFlow — OpenAI-compatible (api.siliconflow.com/v1). Registered mainly+// for its FREE generative-media models (FLUX.1-schnell image, CosyVoice2 TTS),+// which route via services/media.ts; OpenAI-compatible chat is supported too.+// Key from siliconflow.com, no card; validateKey uses GET /v1/models (200 with+// a valid key). Catalog rows live in the catalog (premium → age into free).+register(new OpenAICompatProvider({+ platform: 'siliconflow',+ name: 'SiliconFlow',+ baseUrl: 'https://api.siliconflow.com/v1',+}));+// Placeholder so getProvider('custom')/hasProvider('custom')/getAllProviders()// behave — but the real instance is built per-key by resolveProvider(), since// a custom provider's base URL is user-supplied and lives on the api_keys row.diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 45860d97..a48bacef 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -14,7 +14,7 @@ export const keysRouter = Router();const PLATFORMS = ['google', 'groq', 'cerebras', 'nvidia', 'mistral','openrouter', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama',- 'kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'ovh', 'agnes', 'reka', 'custom',+ 'kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'ovh', 'agnes', 'reka', 'siliconflow', 'custom',] as const;// `key` is optional so keyless providers (Kilo's anonymous gateway) can be addeddiff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 744f62f5..ea3737e5 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -6,6 +6,7 @@ import type { ChatMessage, ModelListRow } from '@freellmapi/shared/types.js';import { routeRequest, resolveRoutingChain, resolveModelGroupCandidates, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, hasEnabledToolsModel, type RouteResult, type ResolvedChain, type ChainRow } from '../services/router.js';import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit, PAYMENT_REQUIRED_COOLDOWN_MS, MODEL_FORBIDDEN_COOLDOWN_MS, learnLimitFromError } from '../services/ratelimit.js';import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';+import { runImageGeneration, runSpeech, MediaError } from '../services/media.js';import { getDb, getUnifiedApiKey } from '../db/index.js';import { contentToString, messageHasImage, normalizeOutboundContent, sanitizeResponse } from '../lib/content.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';@@ -502,6 +503,89 @@ proxyRouter.post('/embeddings', async (req: Request, res: Response) => {}});+// OpenAI-compatible image generation. Routed through the media catalog (its own+// table, never the chat router): `model: "auto"` (or omitted) tries every enabled+// image provider in order; a provider model id pins to that one. Failover is+// across providers, never across modalities. See services/media.ts.+const ImageBody = z.object({+ model: z.string().optional(),+ prompt: z.string().min(1),+ n: z.number().int().positive().max(4).optional(),+ size: z.string().optional(),+ response_format: z.enum(['url', 'b64_json']).optional(),+});++function mediaErrorType(status: number): string {+ if (status === 400) return 'invalid_request_error';+ if (status === 401) return 'authentication_error';+ if (status === 429) return 'rate_limit_error';+ return 'server_error';+}++proxyRouter.post('/images/generations', async (req: Request, res: Response) => {+ const token = extractApiToken(req);+ const unifiedKey = getUnifiedApiKey();+ if (!token || !timingSafeStringEqual(token, unifiedKey)) {+ res.status(401).json({ error: { message: 'Invalid API key', type: 'authentication_error' } });+ return;+ }+ const parsed = ImageBody.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: 'Invalid request: `prompt` is required', type: 'invalid_request_error' } });+ return;+ }+ try {+ const result = await runImageGeneration(parsed.data.model, {+ prompt: parsed.data.prompt, n: parsed.data.n, size: parsed.data.size,+ });+ res.json({+ created: Math.floor(Date.now() / 1000),+ data: result.images,+ model: result.modelId,+ provider: result.platform,+ });+ } catch (err: any) {+ const status = err instanceof MediaError ? err.status : 502;+ const httpStatus = status >= 400 && status < 600 ? status : 502;+ res.status(httpStatus).json({ error: { message: `image generation error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status) } });+ }+});++// OpenAI-compatible text-to-speech. Returns raw audio bytes (OpenAI's /audio/speech+// shape). Same media-catalog routing as images.+const SpeechBody = z.object({+ model: z.string().optional(),+ input: z.string().min(1),+ voice: z.string().optional(),+ response_format: z.string().optional(),+});++proxyRouter.post('/audio/speech', async (req: Request, res: Response) => {+ const token = extractApiToken(req);+ const unifiedKey = getUnifiedApiKey();+ if (!token || !timingSafeStringEqual(token, unifiedKey)) {+ res.status(401).json({ error: { message: 'Invalid API key', type: 'authentication_error' } });+ return;+ }+ const parsed = SpeechBody.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: 'Invalid request: `input` is required', type: 'invalid_request_error' } });+ return;+ }+ try {+ const result = await runSpeech(parsed.data.model, {+ input: parsed.data.input, voice: parsed.data.voice, format: parsed.data.response_format,+ });+ res.setHeader('Content-Type', result.contentType);+ res.setHeader('X-Provider', result.platform);+ res.send(result.audio);+ } catch (err: any) {+ const status = err instanceof MediaError ? err.status : 502;+ const httpStatus = status >= 400 && status < 600 ? status : 502;+ res.status(httpStatus).json({ error: { message: `speech error: ${err?.message ?? 'unknown'}`, type: mediaErrorType(status) } });+ }+});+proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {const start = Date.now();const requestGroupId = getRequestGroupId(req);diff --git a/server/src/services/catalog-sync.ts b/server/src/services/catalog-sync.tsindex 59e48154..e1ad036e 100644--- a/server/src/services/catalog-sync.ts+++ b/server/src/services/catalog-sync.ts@@ -2,8 +2,13 @@ import crypto from 'crypto';import type DatabaseType from 'better-sqlite3';import { getDb, getSetting, setSetting } from '../db/index.js';import { hasProvider } from '../providers/index.js';+import { MEDIA_PLATFORMS } from './media.js';import type { Platform } from '@freellmapi/shared/types.js';+// Generative-media modalities are routed into the separate media_models table+// (see services/media.ts), never into the chat `models` table.+const MEDIA_MODALITIES = new Set(['image', 'audio']);+/*** catalog-sync — keeps the local model catalog in step with the published one.*@@ -88,6 +93,11 @@ interface CatalogModel {enabled: boolean;supportsVision: boolean;supportsTools: boolean;+ /** 'text' (default/absent) routes to the chat `models` table; 'image'/'audio'+ * route to the separate `media_models` table. */+ modality?: string;+ /** Short display note for media models (e.g. "Keyless - up to 1024x1024"). */+ mediaNote?: string;}interface Catalog {@@ -164,10 +174,51 @@ export function applyCatalog(db: DatabaseType.Database, catalog: Catalog): NonNu@enabled, @supportsVision, @supportsTools)`);+ // Generative-media models go to their own table (never the chat router's pool).+ const selectMedia = db.prepare('SELECT id, enabled FROM media_models WHERE platform = ? AND model_id = ?');+ const updateMedia = db.prepare(`+ UPDATE media_models SET+ display_name = @displayName, modality = @modality, priority = @priority,+ quota_label = @quotaLabel, enabled = @enabled+ WHERE id = @id+ `);+ const insertMedia = db.prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)+ VALUES (@platform, @modelId, @displayName, @modality, @priority, @enabled, @quotaLabel)+ `);+const apply = db.transaction(() => {const inCatalog = new Set<string>();+ const inMediaCatalog = new Set<string>();for (const m of catalog.models) {+ // Media modalities are gated on MEDIA_PLATFORMS (decoupled from the chat+ // provider registry) and routed to media_models, then skip the chat path.+ const modality = m.modality ?? 'text';+ if (MEDIA_MODALITIES.has(modality)) {+ if (!MEDIA_PLATFORMS.has(m.platform)) {+ counts.skippedUnknownPlatform++;+ continue;+ }+ inMediaCatalog.add(`${m.platform}:${m.modelId}`);+ const mrow = selectMedia.get(m.platform, m.modelId) as { id: number; enabled: number } | undefined;+ const mfields = {+ displayName: m.displayName,+ modality,+ priority: m.intelligenceRank ?? 0,+ quotaLabel: m.mediaNote ?? '',+ };+ if (mrow) {+ const enabled = m.enabled ? mrow.enabled : 0; // catalog disable wins; local disable wins+ updateMedia.run({ ...mfields, id: mrow.id, enabled });+ counts.updated++;+ } else {+ insertMedia.run({ ...mfields, platform: m.platform, modelId: m.modelId, enabled: m.enabled ? 1 : 0 });+ counts.inserted++;+ }+ continue;+ }+if (m.platform === 'custom' || !hasProvider(m.platform as Platform)) {// An older binary may receive models for providers it cannot route yet;// skip them — they will appear after the user updates the app.@@ -229,6 +280,19 @@ export function applyCatalog(db: DatabaseType.Database, catalog: Catalog): NonNu}}+ // Remove media models the catalog no longer lists (own table, no fallback_config).+ const mediaCandidates = db+ .prepare('SELECT id, platform, model_id FROM media_models')+ .all() as { id: number; platform: string; model_id: string }[];+ const deleteMedia = db.prepare('DELETE FROM media_models WHERE id = ?');+ for (const c of mediaCandidates) {+ if (!MEDIA_PLATFORMS.has(c.platform)) continue; // not media-managed by this binary+ if (!inMediaCatalog.has(`${c.platform}:${c.model_id}`)) {+ deleteMedia.run(c.id);+ counts.removed++;+ }+ }+// Quirks are pure content: replace wholesale.db.prepare('DELETE FROM quirk_targets').run();db.prepare('DELETE FROM quirks').run();diff --git a/server/src/services/media.ts b/server/src/services/media.tsnew file mode 100644index 00000000..229048d3--- /dev/null+++ b/server/src/services/media.ts@@ -0,0 +1,357 @@+// Generative-media routing (image generation + audio/TTS).+//+// Self-contained, exactly like embeddings: media models live in their OWN+// `media_models` table so they can NEVER enter the chat router's candidate pool+// (a chat request can't misroute to an image model) and never pollute the chat+// token budget. Each platform has a small adapter here; routing fails over+// across the providers serving the same modality. The rows are maintained in the+// published catalog and arrive via catalog-sync (premium on the live tier within+// ~12h, free at the monthly promote) — never seeded by migrations.+import { getDb } from '../db/index.js';+import { decrypt } from '../lib/crypto.js';+import { proxyFetch } from '../lib/proxy.js';++/** Platforms with a media adapter below. catalog-sync gates media rows on this+ * (decoupled from the chat provider registry — e.g. SiliconFlow is media-only). */+export const MEDIA_PLATFORMS = new Set(['nvidia', 'pollinations', 'cloudflare', 'siliconflow', 'google']);++/** Platforms whose free media path needs no API key (anonymous). */+const KEYLESS_CAPABLE = new Set(['pollinations']);++export type MediaModality = 'image' | 'audio';++export interface MediaModelRow {+ id: number;+ platform: string;+ model_id: string;+ display_name: string;+ modality: MediaModality;+ priority: number;+ enabled: number;+ quota_label: string;+}++export class MediaError extends Error {+ status: number;+ constructor(message: string, status: number) {+ super(message);+ this.status = status;+ }+}++export interface ImageResult {+ platform: string;+ modelId: string;+ images: Array<{ b64_json?: string; url?: string }>;+}+export interface SpeechResult {+ platform: string;+ modelId: string;+ audio: Buffer;+ contentType: string;+}+export interface ImageParams { prompt: string; n?: number; size?: string }+export interface SpeechParams { input: string; voice?: string; format?: string }++// Media generations are slower than chat — a cold FLUX/SDXL run can take 30-60s.+const FETCH_TIMEOUT_MS = 60_000;++export function listMediaModels(modality: MediaModality): MediaModelRow[] {+ return getDb()+ .prepare('SELECT * FROM media_models WHERE modality = ? AND enabled = 1 ORDER BY priority, id')+ .all(modality) 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;+ try {+ return decrypt(row.encrypted_key, row.iv, row.auth_tag);+ } catch {+ return null;+ }+}++async function mediaFetch(url: string, platform: string, init: RequestInit): Promise<Response> {+ const r = await proxyFetch(url, { ...init, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }, platform);+ if (!r.ok) {+ const body = await r.text().catch(() => '');+ throw new MediaError(`${platform} ${r.status}: ${body.slice(0, 200)}`, r.status);+ }+ return r;+}++function parseSize(size?: string): [number, number] {+ if (size && /^\d+x\d+$/.test(size)) {+ const [w, h] = size.split('x').map(Number);+ return [w, h];+ }+ return [1024, 1024];+}++function parseCfKey(key: string | null): { accountId: string; token: string } {+ if (!key) throw new MediaError('cloudflare key required (account_id:token)', 401);+ const sep = key.indexOf(':');+ if (sep === -1) throw new MediaError('cloudflare key is not in account_id:token form', 500);+ return { accountId: key.slice(0, sep), token: key.slice(sep + 1) };+}++function contentTypeFor(fmt: string): string {+ switch (fmt) {+ case 'wav': return 'audio/wav';+ case 'opus': return 'audio/ogg';+ case 'aac': return 'audio/aac';+ case 'flac': return 'audio/flac';+ case 'pcm': return 'audio/L16';+ case 'mp3':+ default: return 'audio/mpeg';+ }+}++function parseRate(mime?: string): number | undefined {+ const m = mime?.match(/rate=(\d+)/);+ return m ? Number(m[1]) : undefined;+}++/** Wrap raw 16-bit mono PCM (what Gemini TTS returns) in a WAV header so any+ * client can play it without knowing the sample rate out of band. */+function wrapPcmAsWav(pcm: Buffer, sampleRate: number): Buffer {+ const numChannels = 1;+ const bitsPerSample = 16;+ const byteRate = (sampleRate * numChannels * bitsPerSample) / 8;+ const blockAlign = (numChannels * bitsPerSample) / 8;+ const header = Buffer.alloc(44);+ header.write('RIFF', 0);+ header.writeUInt32LE(36 + pcm.length, 4);+ header.write('WAVE', 8);+ header.write('fmt ', 12);+ header.writeUInt32LE(16, 16);+ header.writeUInt16LE(1, 20); // PCM+ header.writeUInt16LE(numChannels, 22);+ header.writeUInt32LE(sampleRate, 24);+ header.writeUInt32LE(byteRate, 28);+ header.writeUInt16LE(blockAlign, 32);+ header.writeUInt16LE(bitsPerSample, 34);+ header.write('data', 36);+ header.writeUInt32LE(pcm.length, 40);+ return Buffer.concat([header, pcm]);+}++async function callImageProvider(+ row: MediaModelRow,+ key: string | null,+ p: ImageParams,+): Promise<Array<{ b64_json?: string; url?: string }>> {+ const [w, h] = parseSize(p.size);+ switch (row.platform) {+ case 'nvidia': {+ // NVIDIA NIM image models live at ai.api.nvidia.com/v1/genai/{model};+ // response is { artifacts: [{ base64 }] }.+ const r = await mediaFetch(`https://ai.api.nvidia.com/v1/genai/${row.model_id}`, 'nvidia', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: 'application/json', Authorization: `Bearer ${key}` },+ body: JSON.stringify({ prompt: p.prompt, mode: 'base', steps: 4, width: w, height: h }),+ });+ const j = (await r.json()) as { artifacts?: { base64?: string }[] };+ return (j.artifacts ?? []).map(a => ({ b64_json: a.base64 }));+ }+ case 'pollinations': {+ // Keyless GET image endpoint returns raw image bytes.+ const url = `https://image.pollinations.ai/prompt/${encodeURIComponent(p.prompt)}?width=${w}&height=${h}&nologo=true&model=${encodeURIComponent(row.model_id)}`;+ const r = await mediaFetch(url, 'pollinations', { method: 'GET' });+ const buf = Buffer.from(await r.arrayBuffer());+ return [{ b64_json: buf.toString('base64') }];+ }+ 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', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({ prompt: p.prompt, width: w, height: h }),+ });+ // FLUX returns JSON { result: { image: <b64> } }; SDXL returns raw PNG bytes.+ const ct = r.headers.get('content-type') ?? '';+ if (ct.includes('application/json')) {+ const j = (await r.json()) as { result?: { image?: string } };+ const b64 = j.result?.image;+ if (!b64) throw new MediaError('cloudflare returned no image', 502);+ return [{ b64_json: b64 }];+ }+ const buf = Buffer.from(await r.arrayBuffer());+ return [{ b64_json: buf.toString('base64') }];+ }+ case 'siliconflow': {+ const r = await mediaFetch('https://api.siliconflow.com/v1/images/generations', 'siliconflow', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },+ body: JSON.stringify({ model: row.model_id, prompt: p.prompt, image_size: `${w}x${h}` }),+ });+ const j = (await r.json()) as { images?: { url?: string }[]; data?: { url?: string }[] };+ return (j.images ?? j.data ?? []).map(i => ({ url: i.url }));+ }+ default:+ throw new MediaError(`no image adapter for platform '${row.platform}'`, 500);+ }+}++async function callSpeechProvider(+ row: MediaModelRow,+ key: string | null,+ p: SpeechParams,+): Promise<{ audio: Buffer; contentType: string }> {+ switch (row.platform) {+ 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', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({ prompt: p.input, lang: p.voice ?? 'en' }),+ });+ const j = (await r.json()) as { result?: { audio?: string } };+ const b64 = j.result?.audio;+ if (!b64) throw new MediaError('cloudflare returned no audio', 502);+ return { audio: Buffer.from(b64, 'base64'), contentType: 'audio/mpeg' };+ }+ case 'siliconflow': {+ const fmt = p.format ?? 'mp3';+ const r = await mediaFetch('https://api.siliconflow.com/v1/audio/speech', 'siliconflow', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },+ body: JSON.stringify({ model: row.model_id, input: p.input, voice: p.voice ?? `${row.model_id}:alex`, response_format: fmt }),+ });+ return { audio: Buffer.from(await r.arrayBuffer()), contentType: contentTypeFor(fmt) };+ }+ case 'pollinations': {+ // OpenAI-shaped chat-completions with the audio modality returns b64 audio.+ // The anonymous tier needs no key; only send one when it's a real sk_ token.+ const realKey = key && key.startsWith('sk_') ? key : null;+ const r = await mediaFetch('https://gen.pollinations.ai/v1/chat/completions', 'pollinations', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...(realKey ? { Authorization: `Bearer ${realKey}` } : {}) },+ body: JSON.stringify({+ model: row.model_id,+ modalities: ['text', 'audio'],+ audio: { voice: p.voice ?? 'alloy', format: p.format ?? 'mp3' },+ messages: [{ role: 'user', content: p.input }],+ }),+ });+ const j = (await r.json()) as { choices?: { message?: { audio?: { data?: string } } }[] };+ const b64 = j.choices?.[0]?.message?.audio?.data;+ if (!b64) throw new MediaError('pollinations returned no audio', 502);+ return { audio: Buffer.from(b64, 'base64'), contentType: contentTypeFor(p.format ?? 'mp3') };+ }+ case 'google': {+ // Gemini TTS via generateContent (AUDIO modality) returns base64 PCM+ // (L16, mono, ~24kHz); wrap it in a WAV header so clients can play it.+ const r = await mediaFetch(+ `https://generativelanguage.googleapis.com/v1beta/models/${row.model_id}:generateContent?key=${encodeURIComponent(key ?? '')}`,+ 'google',+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ contents: [{ parts: [{ text: p.input }] }],+ generationConfig: {+ responseModalities: ['AUDIO'],+ speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: p.voice ?? 'Kore' } } },+ },+ }),+ },+ );+ const j = (await r.json()) as {+ candidates?: { content?: { parts?: { inlineData?: { data?: string; mimeType?: string } }[] } }[];+ };+ const part = j.candidates?.[0]?.content?.parts?.find(pt => pt.inlineData?.data);+ const b64 = part?.inlineData?.data;+ if (!b64) throw new MediaError('gemini returned no audio', 502);+ const rate = parseRate(part?.inlineData?.mimeType) ?? 24000;+ return { audio: wrapPcmAsWav(Buffer.from(b64, 'base64'), rate), contentType: 'audio/wav' };+ }+ default:+ throw new MediaError(`no speech adapter for platform '${row.platform}'`, 500);+ }+}++/** Map the request's `model` to a candidate chain within one modality:+ * 'auto'/empty → every enabled provider for the modality (failover order),+ * a provider model id → just that row. */+function resolveMediaChain(model: string | undefined, modality: MediaModality): MediaModelRow[] {+ const rows = listMediaModels(modality);+ if (rows.length === 0) {+ throw new MediaError(`No enabled ${modality} providers configured.`, 503);+ }+ if (!model || model === 'auto') return rows;+ const matches = rows.filter(r => r.model_id === model);+ if (matches.length === 0) {+ throw new MediaError(`Unknown ${modality} model '${model}'. Use 'auto' or a provider model id.`, 400);+ }+ return matches;+}++function logMedia(row: MediaModelRow, 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);+ } catch (e) {+ console.error('Failed to log media request:', e);+ }+}++function chainError(modality: MediaModality, lastError: MediaError | null): MediaError {+ return new MediaError(+ `All ${modality} providers failed${lastError ? ` (last: ${lastError.message.slice(0, 160)})` : ' (no usable keys)'}.`,+ lastError && lastError.status === 429 ? 429 : 502,+ );+}++/** Generate image(s), failing over across providers serving the modality. */+export async function runImageGeneration(model: string | undefined, params: ImageParams): Promise<ImageResult> {+ const 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 started = Date.now();+ try {+ const images = await callImageProvider(row, key, 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);+ 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));+ lastError = e;+ }+ }+ throw chainError('image', lastError);+}++/** Synthesize speech, failing over across providers serving the modality. */+export async function runSpeech(model: string | undefined, params: SpeechParams): Promise<SpeechResult> {+ 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 started = Date.now();+ try {+ const out = await callSpeechProvider(row, key, params);+ if (!out.audio.length) throw new MediaError('upstream returned no audio', 502);+ logMedia(row, '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));+ lastError = e;+ }+ }+ throw chainError('audio', lastError);+}diff --git a/shared/types.ts b/shared/types.tsindex 82979ade..dba39844 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -37,6 +37,10 @@ export type Platform =// image/video); free via a recurring monthly credit grant, key from// platform.reka.ai (no card).| 'reka'+ // SiliconFlow — OpenAI-compatible. Registered for its FREE generative-media+ // models (FLUX.1-schnell image, CosyVoice2 TTS) routed via services/media.ts;+ // chat is supported too. Key from siliconflow.com (no card).+ | 'siliconflow'// User-configured OpenAI-compatible endpoint (llama.cpp, LM Studio, vLLM,// Ollama, any base_url). The endpoint URL lives on the api_keys row; see #117.| 'custom';