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: add Kenari free routes and Mistral transcription (#1703)
Tashfeen22b7ec74a098
diff --git a/client/src/components/keys/shared.tsx b/client/src/components/keys/shared.tsxindex 9815478a..f55165f9 100644--- a/client/src/components/keys/shared.tsx+++ b/client/src/components/keys/shared.tsx@@ -32,6 +32,7 @@ export function GetKeyLink({ url }: { url: string }) {export const PLATFORMS: { value: Platform; label: string; url: string; keyless?: boolean; hidden?: boolean }[] = [{ value: 'aclide', label: 'ACLIDE (shared monthly credits)', url: 'https://aclide.com/en/dashboard/api-keys' },{ value: 'speka', label: 'Speka ($1 shared monthly credits)', url: 'https://speka.me/dashboard/keys' },+ { value: 'kenari', label: 'Kenari (shared daily free chat and images)', url: 'https://kenari.id' },{ value: 'beatapi', label: 'BeatAPI (JEV decisions; temporary free offer)', url: 'https://beatapi.io' },{ value: 'apinex', label: 'APINex (shared daily free chat and decisions)', url: 'https://apinex.bond/keys' },{ value: 'onomeo', label: 'onomeo (30 free calls / 5 hours, shared)', url: 'https://onomeo.com/dashboard' },diff --git a/client/src/lib/routing.ts b/client/src/lib/routing.tsindex e9b9161e..31bc1228 100644--- a/client/src/lib/routing.ts+++ b/client/src/lib/routing.ts@@ -422,6 +422,7 @@ export const platformColors: Record<string, string> = {sail: '#0ea5e9',aclide: '#6366f1',speka: '#0d9488',+ kenari: '#d97706',typhoon: '#e11d48',plugsky: '#0284c7',inferbase: '#2563eb',diff --git a/desktop/package-lock.json b/desktop/package-lock.jsonindex 4853d26f..01dc620d 100644--- a/desktop/package-lock.json+++ b/desktop/package-lock.json@@ -1,12 +1,12 @@{"name": "freellmapi-desktop",- "version": "0.16.9",+ "version": "0.16.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "freellmapi-desktop",- "version": "0.16.9",+ "version": "0.16.10","dependencies": {"better-sqlite3": "^12.10.0","electron-updater": "^6.8.9"diff --git a/desktop/package.json b/desktop/package.jsonindex ed7adb94..2eeabb6a 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -1,6 +1,6 @@{"name": "freellmapi-desktop",- "version": "0.16.9",+ "version": "0.16.10","description": "FreeLLMAPI menu-bar app — local OpenAI-compatible LLM router","author": {"name": "tashfeenahmed",diff --git a/server/src/__tests__/providers/kenari.test.ts b/server/src/__tests__/providers/kenari.test.tsnew file mode 100644index 00000000..de8280f8--- /dev/null+++ b/server/src/__tests__/providers/kenari.test.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { KenariProvider } from '../../providers/kenari.js';+import { initDb, getDb } from '../../db/index.js';+import { getProvider } from '../../providers/index.js';+import { isBuiltinDiscoveryEligible } from '../../services/builtin-model-discovery.js';++const model = 'qwen3-8-omni-flash:free';+const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers });+const completion = (content: string | null = 'OK', returned = model) => ({+ id: 'test', object: 'chat.completion', created: 1, model: returned,+ choices: [{ index: 0, message: { role: 'assistant', content }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+});+const frame = (delta: object, returned = model) => ({ id: 'test', object: 'chat.completion.chunk', created: 1,+ model: returned, choices: [{ index: 0, delta, finish_reason: null }] });+const stream = (...events: unknown[]) => new Response(events.map(x => `data: ${JSON.stringify(x)}\n\n`).join('') + 'data: [DONE]\n\n');++beforeEach(() => { process.env.ENCRYPTION_KEY = '0'.repeat(64); initDb(':memory:'); });+afterEach(() => { vi.restoreAllMocks(); getDb().close(); });++describe('Kenari provider', () => {+ it('is registered without bundled models or free-tier discovery bypass', () => {+ expect(getProvider('kenari')).toBeInstanceOf(KenariProvider);+ expect(getDb().prepare("SELECT COUNT(*) n FROM models WHERE platform='kenari'").get()).toEqual({ n: 0 });+ expect(isBuiltinDiscoveryEligible(getDb(), 'kenari')).toBe(false);+ });+ it('validates a zero balance through the authenticated account endpoint, not public models', async () => {+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ object: 'account.balance', available_micro_idr: 0 }));+ await expect(new KenariProvider().validateKey('unit-test')).resolves.toBe(true);+ expect(fetch.mock.calls[0][0]).toBe('https://kenari.id/v1/account/balance');+ expect(new Headers(fetch.mock.calls[0][1]?.headers).get('authorization')).toBe('Bearer unit-test');+ expect(fetch.mock.calls[0][1]?.redirect).toBe('error');+ });+ it('rejects invalid credentials', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json({}, 401));+ await expect(new KenariProvider().validateKey('invalid')).resolves.toMatchObject({ valid: false });+ });+ it.each([403, 429, 500])('leaves HTTP %s credential checks inconclusive', async status => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json({}, status, { 'Retry-After': '20' }));+ await expect(new KenariProvider().validateKey('unit-test')).rejects.toMatchObject({ status, retryAfterMs: 20_000 });+ });+ it.each([null, {}, { object: 'account.balance', available_micro_idr: '0' }])('rejects malformed balance %j', async body => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(new KenariProvider().validateKey('unit-test')).rejects.toMatchObject({ status: 502 });+ });+ it('preserves the exact free route and sampling options', async () => {+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json(completion()));+ await expect(new KenariProvider().chatCompletion('unit-test', [{ role: 'user', content: 'OK' }], model, { max_tokens: 64 })).resolves.toMatchObject({ model });+ expect(fetch.mock.calls[0][0]).toBe('https://kenari.id/v1/chat/completions');+ expect(JSON.parse(String(fetch.mock.calls[0][1]?.body))).toMatchObject({ model, max_tokens: 64 });+ });+ it.each(['', 'another-model'])('rejects missing or substituted identity %s', async returned => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json(completion('OK', returned)));+ await expect(new KenariProvider().chatCompletion('unit-test', [], model)).rejects.toMatchObject({ status: 502 });+ });+ it('rejects an empty completion but permits tool-only answers', async () => {+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValueOnce(json(completion('')));+ await expect(new KenariProvider().chatCompletion('unit-test', [], model)).rejects.toMatchObject({ status: 502 });+ fetch.mockResolvedValue(json({ ...completion(null), choices: [{ index: 0, message: { role: 'assistant', content: null,+ tool_calls: [{ id: 't', type: 'function', function: { name: 'lookup', arguments: '{}' } }] }, finish_reason: 'tool_calls' }] }));+ await expect(new KenariProvider().chatCompletion('unit-test', [], model)).resolves.toMatchObject({ model });+ });+ it('rejects a paid ID without any request', async () => {+ const fetch = vi.spyOn(global, 'fetch');+ await expect(new KenariProvider().chatCompletion('unit-test', [], 'qwen3-8-omni-flash')).rejects.toMatchObject({ status: 400 });+ await expect(new KenariProvider().streamChatCompletion('unit-test', [], 'qwen3-8-omni-flash').next()).rejects.toMatchObject({ status: 400 });+ expect(fetch).not.toHaveBeenCalled();+ });+ it('holds an empty stream before yielding so failover remains possible', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue(stream(frame({ role: 'assistant' }), frame({ content: '' })));+ await expect(new KenariProvider().streamChatCompletion('unit-test', [], model).next()).rejects.toMatchObject({ status: 502 });+ });+ it('streams exact-route content and a model-less usage trailer', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue(stream(frame({ role: 'assistant' }), frame({ content: 'OK' }), { choices: [], usage: { total_tokens: 2 } }));+ const chunks = [];+ for await (const chunk of new KenariProvider().streamChatCompletion('unit-test', [], model)) chunks.push(chunk);+ expect(chunks).toHaveLength(3);+ expect(chunks[1].choices[0].delta.content).toBe('OK');+ });+ it.each([frame({ content: 'OK' }, 'other'), { error: { message: 'failed' } }])('rejects invalid SSE before content is committed', async event => {+ vi.spyOn(global, 'fetch').mockResolvedValue(stream(frame({ role: 'assistant' }), event));+ await expect(new KenariProvider().streamChatCompletion('unit-test', [], model).next()).rejects.toMatchObject({ status: 502 });+ });+ it.each([402, 429, 503])('preserves HTTP %s without a paid-alias retry', async status => {+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ error: { message: 'unavailable' } }, status, { 'Retry-After': '15' }));+ await expect(new KenariProvider().chatCompletion('unit-test', [], model)).rejects.toMatchObject({ status, retryAfterMs: 15_000 });+ expect(fetch).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/src/__tests__/services/kenari-mistral-media.test.ts b/server/src/__tests__/services/kenari-mistral-media.test.tsnew file mode 100644index 00000000..2e21b580--- /dev/null+++ b/server/src/__tests__/services/kenari-mistral-media.test.ts@@ -0,0 +1,88 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { runImageGeneration, runTranscription, MEDIA_PLATFORMS, TRANSCRIPTION_PLATFORMS } from '../../services/media.js';+import { applyCatalog } from '../../services/catalog-sync.js';+import { clearAllCooldowns } from '../../services/ratelimit.js';++const imageModel = 'agnes-image-2-5-flash:free';+const sttModels = ['voxtral-mini-transcribe-3', 'voxtral-small-transcribe-3'];+const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers });+const audio = Buffer.from('RIFFfakewavbytes');+const params = { file: audio, filename: 'speech.wav', mimeType: 'audio/wav', responseFormat: 'json' };+beforeEach(() => { process.env.ENCRYPTION_KEY = '0'.repeat(64); initDb(':memory:'); clearAllCooldowns(Number.MAX_SAFE_INTEGER); });+afterEach(() => { vi.restoreAllMocks(); getDb().close(); });++function seed(platform: string, model: string, modality: string) {+ const key = encrypt('unit-test-key');+ getDb().prepare("INSERT INTO api_keys (platform,label,encrypted_key,iv,auth_tag,status,enabled) VALUES (?,'test',?,?,?,'healthy',1)").run(platform, key.encrypted, key.iv, key.authTag);+ getDb().prepare("INSERT INTO media_models (platform,model_id,display_name,modality,priority,enabled,quota_label) VALUES (?,?,?,?,1,1,'shared free allowance')").run(platform, model, model, modality);+}++describe('Kenari images', () => {+ it('uses exact :free ID and tested OpenAI image payload', async () => {+ seed('kenari', imageModel, 'image');+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ data: [{ b64_json: 'aW1hZ2U=' }] }));+ expect(await runImageGeneration(imageModel, { prompt: 'blue circle' })).toEqual({ platform: 'kenari', modelId: imageModel, images: [{ b64_json: 'aW1hZ2U=' }] });+ const [url, init] = fetch.mock.calls[0];+ expect(url).toBe('https://kenari.id/v1/images/generations');+ expect(init?.redirect).toBe('error');+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer unit-test-key');+ expect(JSON.parse(String(init?.body))).toEqual({ model: imageModel, prompt: 'blue circle', n: 1, size: '1024x1024', response_format: 'b64_json' });+ });+ it.each([null, {}, { data: [] }, { data: [null] }, { data: [{ b64_json: '' }] }, { data: [{ url: 'https://example.com/image' }] }])('rejects malformed/empty images %j', async body => {+ seed('kenari', imageModel, 'image');+ vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(runImageGeneration(imageModel, { prompt: 'blue circle' })).rejects.toMatchObject({ status: 502 });+ });+ it('does not retry a paid alias on quota exhaustion', async () => {+ seed('kenari', imageModel, 'image');+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ error: 'quota' }, 429, { 'Retry-After': '30' }));+ await expect(runImageGeneration(imageModel, { prompt: 'blue circle' })).rejects.toMatchObject({ status: 429, retryAfterMs: 30_000 });+ expect(fetch).toHaveBeenCalledTimes(1);+ });+});++describe('Mistral transcription', () => {+ it.each(sttModels)('dispatches %s using documented multipart fields', async model => {+ seed('mistral', model, 'transcription');+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ model, text: 'สวัสดี', language: 'th', segments: [] }));+ expect(await runTranscription(model, { ...params, language: 'th', temperature: 0.2, prompt: 'Do not send this Whisper field' })).toEqual({ platform: 'mistral', modelId: model, text: 'สวัสดี', language: 'th', segments: [] });+ const [url, init] = fetch.mock.calls[0];+ expect(url).toBe('https://api.mistral.ai/v1/audio/transcriptions');+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer unit-test-key');+ expect(new Headers(init?.headers).has('content-type')).toBe(false);+ const form = init?.body as FormData;+ expect([...form.keys()]).toEqual(['file', 'model', 'language', 'temperature']);+ expect(form.get('model')).toBe(model);+ expect(Buffer.from(await (form.get('file') as File).arrayBuffer())).toEqual(audio);+ });+ it.each([null, {}, { text: 1 }, { text: 'bad', error: 'failed' }])('rejects malformed transcription %j', async body => {+ seed('mistral', sttModels[0], 'transcription');+ vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(runTranscription(sttModels[0], params)).rejects.toMatchObject({ status: 502 });+ });+ it('preserves retry-after and does not claim native VTT', async () => {+ seed('mistral', sttModels[0], 'transcription');+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({}, 429, { 'Retry-After': '20' }));+ await expect(runTranscription(sttModels[0], { ...params, responseFormat: 'vtt' })).rejects.toMatchObject({ status: 400 });+ expect(fetch).not.toHaveBeenCalled();+ await expect(runTranscription(sttModels[0], params)).rejects.toMatchObject({ status: 429, retryAfterMs: 20_000 });+ });+});++it('ingests catalog-only chat, image and transcription rows idempotently into separate registries', () => {+ expect(MEDIA_PLATFORMS.has('kenari')).toBe(true);+ expect(TRANSCRIPTION_PLATFORMS.has('mistral')).toBe(true);+ const catalog = { version: '2099.01.01', generatedAt: '2099-01-01T00:00:00Z', tier: 'live' as const, quirks: [],+ models: ['chat', 'image'].map(modality => ({ platform: 'kenari', modelId: modality === 'image' ? imageModel : 'qwen3-8-omni-flash:free', displayName: modality,+ ...(modality === 'image' ? { modality: 'image' as const } : {}), intelligenceRank: 50, speedRank: 10, sizeLabel: '', limits: { rpm: null, rpd: null, tpm: null, tpd: null }, monthlyTokenBudget: 'Shared daily allowance', contextWindow: null, enabled: true, supportsVision: false, supportsTools: false })),+ transcriptionModels: sttModels.map(modelId => ({ platform: 'mistral', modelId, displayName: modelId, priority: 1, enabled: true, premiumSince: '2099-01-01T00:00:00Z' })),+ };+ expect(applyCatalog(getDb(), catalog).skippedUnknownPlatform).toBe(0);+ expect(applyCatalog(getDb(), catalog).inserted).toBe(0);+ expect(getDb().prepare("SELECT model_id FROM models WHERE platform='kenari'").all()).toEqual([{ model_id: 'qwen3-8-omni-flash:free' }]);+ expect(getDb().prepare("SELECT model_id,modality FROM media_models WHERE platform IN ('kenari','mistral') ORDER BY platform,model_id").all()).toEqual([+ { model_id: imageModel, modality: 'image' }, ...sttModels.map(model_id => ({ model_id, modality: 'transcription' })),+ ]);+});diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex d853f96f..08e8f449 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -46,6 +46,7 @@ export interface ParseResult {export const PREFIX_MAP: Record<string, string> = {ACLIDE_: 'aclide',SPEKA_: 'speka',+ KENARI_: 'kenari',BEATAPI_: 'beatapi',APINEX_: 'apinex',ONOMEO_: 'onomeo',@@ -166,6 +167,7 @@ export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {sail: 'sail',aclide: 'aclide',speka: 'speka',+ kenari: 'kenari',beatapi: 'beatapi',apinex: 'apinex',onomeo: 'onomeo',diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex dcb6c7c3..5ec43e36 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -17,6 +17,7 @@ import { ZhipuProvider } from './zhipu.js';import { SailProvider } from './sail.js';import { AclideProvider } from './aclide.js';import { SpekaProvider } from './speka.js';+import { KenariProvider } from './kenari.js';import { TyphoonProvider } from './typhoon.js';import { PlugskyProvider } from './plugsky.js';import { InferbaseProvider } from './inferbase.js';@@ -79,6 +80,7 @@ register(new OpenAICompatProvider({register(new SailProvider());register(new AclideProvider());register(new SpekaProvider());+register(new KenariProvider());register(new TyphoonProvider());register(new PlugskyProvider());register(new InferbaseProvider());diff --git a/server/src/providers/kenari.ts b/server/src/providers/kenari.tsnew file mode 100644index 00000000..550bab17--- /dev/null+++ b/server/src/providers/kenari.ts@@ -0,0 +1,90 @@+import type { ChatCompletionChunk, ChatCompletionResponse, ChatMessage } from '@freellmapi/shared/types.js';+import { providerHttpError, type CompletionOptions, type KeyValidationResult, type ProviderFetchOptions } from './base.js';+import { OpenAICompatProvider } from './openai-compat.js';+import type { QuotaObservationContext } from '../services/provider-quota.js';++export const KENARI_BASE_URL = 'https://kenari.id/v1';++function upstreamError(message: string): Error {+ return Object.assign(new Error(`Kenari ${message}`), { status: 502 });+}++export function requireKenariFreeModel(modelId: string): void {+ if (!modelId.endsWith(':free')) {+ throw Object.assign(new Error('Kenari requires an explicit :free model route'), { status: 400 });+ }+}++function checkModel(requested: string, returned: unknown): void {+ if (returned !== requested) throw upstreamError('returned a different or missing model identity');+}++/** Named :free routes share the account's renewable daily quota. Never strip+ * the suffix, discover the paid roster, or retry a paid route. Model rows are+ * delivered only by the signed catalog. Docs: https://kenari.id/en/docs. */+export class KenariProvider extends OpenAICompatProvider {+ constructor() {+ super({ platform: 'kenari', name: 'Kenari', baseUrl: KENARI_BASE_URL,+ validateUrl: `${KENARI_BASE_URL}/account/balance`, timeoutMs: 90_000 });+ }++ protected override fetchWithTimeout(url: string, init: RequestInit, timeoutMs?: number,+ options?: ProviderFetchOptions): Promise<Response> {+ return super.fetchWithTimeout(url, { ...init, redirect: 'error' }, timeoutMs, options);+ }++ protected override async validationResult(response: Response): Promise<KeyValidationResult> {+ if (response.status === 401) return super.validationResult(response);+ // Restricted/shared keys cannot read account balance (403); this is not+ // proof the key is invalid. Quota failures and outages are inconclusive too.+ if (!response.ok) throw providerHttpError(response, 'Kenari key validation is temporarily inconclusive');+ const body = await response.json().catch(() => null) as {+ object?: unknown; available_micro_idr?: unknown; error?: unknown;+ } | null;+ if (body?.object !== 'account.balance' || body.error ||+ typeof body.available_micro_idr !== 'number' || !Number.isFinite(body.available_micro_idr)) {+ throw upstreamError('returned an invalid account balance');+ }+ return true; // A zero balance is valid for :free models.+ }++ override async chatCompletion(apiKey: string, messages: ChatMessage[], modelId: string,+ options?: CompletionOptions, quotaContext?: QuotaObservationContext): Promise<ChatCompletionResponse> {+ requireKenariFreeModel(modelId);+ const response = await super.chatCompletion(apiKey, messages, modelId, options, quotaContext);+ checkModel(modelId, response.model);+ if (!response.choices?.some(c =>+ (typeof c.message?.content === 'string' && c.message.content.trim()) || c.message?.tool_calls?.length)) {+ throw upstreamError('returned an empty completion');+ }+ return response;+ }++ override async *streamChatCompletion(apiKey: string, messages: ChatMessage[], modelId: string,+ options?: CompletionOptions, quotaContext?: QuotaObservationContext): AsyncGenerator<ChatCompletionChunk> {+ requireKenariFreeModel(modelId);+ let started = false;+ const preamble: ChatCompletionChunk[] = [];+ for await (const chunk of super.streamChatCompletion(apiKey, messages, modelId, options, quotaContext)) {+ if ('error' in chunk || !Array.isArray(chunk.choices)) throw upstreamError('returned a malformed stream event');+ // A usage-only terminal event may omit model; every other event must+ // retain the exact requested route before any bytes reach the client.+ if (chunk.model || chunk.choices.length) checkModel(modelId, chunk.model);+ if (!started) {+ preamble.push(chunk);+ const usable = chunk.choices.some(c =>+ (typeof c.delta?.content === 'string' && c.delta.content.trim()) || c.delta?.tool_calls?.length);+ if (!usable) {+ if (preamble.length >= 64) throw upstreamError('returned an empty stream preamble');+ continue;+ }+ started = true;+ yield* preamble;+ preamble.length = 0;+ } else yield chunk;+ }+ // Empty 200 streams were observed live. Do not commit their role/finish+ // frames, so the normal router can still fail over to another route.+ if (!started) throw upstreamError('returned an empty completion stream');+ }+}diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 0dbe2843..791b44b7 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -54,6 +54,7 @@ const UNLISTED_PLATFORMS = new Set<string>();const PLATFORMS = ['aclide','speka',+ 'kenari','typhoon','plugsky','inferbase',diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex 2cf2a303..3c1e9d32 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -23,10 +23,11 @@ import { SPEECHIFY_BASE_URL, SPEECHIFY_VERSION } from '../providers/speechify.jsimport { TYPHOON_BASE_URL } from '../providers/typhoon.js';import { ELECTRONHUB_BASE_URL } from '../providers/electronhub.js';import { FREEAI_BASE_URL, freeAiAudioUrl } from '../providers/freeai.js';+import { KENARI_BASE_URL, requireKenariFreeModel } from '../providers/kenari.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', 'speechify', 'electronhub', 'freeai']);+export const MEDIA_PLATFORMS = new Set(['nvidia', 'pollinations', 'cloudflare', 'siliconflow', 'google', 'speechify', 'electronhub', 'freeai', 'kenari']);/** Video uses a dedicated optional catalog registry so binaries that predate* this modality ignore the rows instead of accidentally ingesting them as@@ -39,7 +40,7 @@ const KEYLESS_CAPABLE = new Set(['pollinations']);/** Platforms with a speech-to-text adapter below. catalog-sync gates the* catalog's `transcriptionModels` entries on this, the way MEDIA_PLATFORMS* gates the generative-media rows. */-export const TRANSCRIPTION_PLATFORMS = new Set(['groq', 'cloudflare', 'typhoon']);+export const TRANSCRIPTION_PLATFORMS = new Set(['groq', 'cloudflare', 'typhoon', 'mistral']);// 'transcription' rows live in media_models like the other modalities; they// arrive via the catalog's dedicated `transcriptionModels` array (see@@ -358,6 +359,22 @@ async function callImageProvider(const key = credential.key;const [w, h] = parseSize(p.size);switch (row.platform) {+ case 'kenari': {+ requireKenariFreeModel(row.model_id);+ const r = await mediaFetch(`${KENARI_BASE_URL}/images/generations`, 'kenari', 'image', {+ method: 'POST',+ redirect: 'error',+ headers: { 'Content-Type': 'application/json', ...bearerAuthHeader(key) },+ body: JSON.stringify({ model: row.model_id, prompt: p.prompt, n: p.n ?? 1,+ size: p.size ?? '1024x1024', response_format: 'b64_json' }),+ });+ const j = await r.json() as { data?: { b64_json?: unknown }[]; error?: unknown } | null;+ if (j?.error || !Array.isArray(j?.data) || !j.data.length ||+ j.data.some(i => !i || typeof i.b64_json !== 'string' || !i.b64_json.trim())) {+ throw new MediaError('kenari returned no image data', 502);+ }+ return j.data.map(i => ({ b64_json: i.b64_json as string }));+ }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 };@@ -1077,6 +1094,22 @@ async function callTranscriptionProvider(): Promise<Omit<TranscriptionResult, 'platform' | 'modelId'>> {const key = credential.key;switch (m.platform) {+ case 'mistral': {+ // Voxtral accepts multipart file/model, language and temperature, not+ // Whisper's prompt or response_format. Normalize JSON/text locally.+ const form = new FormData();+ form.append('file', new Blob([p.file], { type: p.mimeType || 'application/octet-stream' }), p.filename);+ form.append('model', m.modelId);+ if (p.language) form.append('language', p.language);+ if (p.temperature !== undefined) form.append('temperature', String(p.temperature));+ const r = await mediaFetch('https://api.mistral.ai/v1/audio/transcriptions', 'mistral', 'transcription', {+ method: 'POST', redirect: 'error', headers: { ...bearerAuthHeader(key) }, body: form,+ });+ const j = await r.json() as { text?: unknown; language?: unknown; segments?: unknown; error?: unknown } | null;+ if (j?.error || typeof j?.text !== 'string') throw new MediaError('mistral returned no transcription text', 502);+ return { text: j.text, language: typeof j.language === 'string' ? j.language : undefined,+ segments: Array.isArray(j.segments) ? j.segments : undefined };+ }case 'typhoon': {// The tested API accepts file + model and returns {text, usage}.// Do not forward Whisper-only options or claim native subtitle support.diff --git a/shared/types.ts b/shared/types.tsindex 19bb7587..a79aaec3 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -72,6 +72,8 @@ export type Platform =| 'aclide'// OpenAI-compatible chat and embeddings; one shared $1 monthly allowance.| 'speka'+ // Named free chat/image routes share one renewable daily account allowance.+ | 'kenari'// Decision-only JEV adapter; promotional availability is catalog-managed.| 'beatapi'// Free-category chat and decisions share one weighted daily allowance.