Skip to content

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(providers): add Free.ai Kokoro speech adapter (#1467)

Tashfeen65ec96df6450
diff --git a/client/src/components/keys/shared.tsx b/client/src/components/keys/shared.tsx
index b51ef726..4dd659a9 100644
--- a/client/src/components/keys/shared.tsx
+++ b/client/src/components/keys/shared.tsx
@@ -47,6 +47,7 @@ export const PLATFORMS: { value: Platform; label: string; url: string; keyless?:
{ value: 'septor', label: 'Septor Labs (daily free-model quota)', url: 'https://septorlabs.com/dashboard' },
{ value: 'clod', label: 'CLōD (shared daily free requests)', url: 'https://newapp.clod.io' },
{ value: 'speechify', label: 'Speechify (monthly free TTS characters)', url: 'https://platform.speechify.ai' },
+ { value: 'freeai', label: 'Free.ai (shared daily free TTS tokens)', url: 'https://free.ai/account/#api-keys' },
{ value: 'blaze', label: 'BlazeAPI (daily free tokens; Discord verification)', url: 'https://blazeapi.org/dashboard' },
{ value: 'lucidity', label: 'Lucidity Composite (daily free-model requests)', url: 'https://composite.lucidity.sh' },
{ value: 'airforce', label: 'Api.Airforce (daily free requests; 1 per minute)', url: 'https://api.airforce' },
diff --git a/client/src/lib/routing.ts b/client/src/lib/routing.ts
index a1f33be8..b72a93a3 100644
--- a/client/src/lib/routing.ts
+++ b/client/src/lib/routing.ts
@@ -419,6 +419,7 @@ export const platformColors: Record<string, string> = {
septor: '#0891b2',
clod: '#16a34a',
speechify: '#7c3aed',
+ freeai: '#16a34a',
blaze: '#f97316',
lucidity: '#6366f1',
airforce: '#0ea5e9',
diff --git a/docs/providers/freeai.md b/docs/providers/freeai.md
new file mode 100644
index 00000000..c26d9086
--- /dev/null
+++ b/docs/providers/freeai.md
@@ -0,0 +1,41 @@
+# Free.ai
+
+The Free.ai integration currently supports **Kokoro text-to-speech only** through
+`POST /v1/audio/speech`. Model rows are distributed by the signed catalog; there
+are no bundled seeds or changes to premium/free catalog timing.
+
+Get a key at <https://free.ai/account/#api-keys>. The confirmed free account tier
+has 30,000 shared internal tokens per day and 1,000 API requests per month, without
+a card. These are account allowances, not a grant per model. Premium external
+models require purchased tokens and are not included by this adapter.
+
+Use model `kokoro`, voice `af_heart` and `response_format: "wav"`. If the format is
+omitted, WAV is returned. Standard OpenAI voice names map to `af_heart`; native
+voice names pass through. Other audio formats and untested models are rejected
+before generation. The adapter calls Free.ai's native `/v1/tts/`, then retrieves
+the WAV from its fixed output host without forwarding the credential or following
+redirects. It checks the output bytes before returning them.
+
+Free.ai can queue requests under load. This adapter reports those as a temporary
+502 (`upstream_queued`), not successful audio. It does not follow
+the browser-session queue URL or resubmit the generation automatically. Check
+the provider's account history before retrying a queued request.
+
+## Credential health
+
+Live controls on 2026-10-11 found that the model roster, invalid-payload errors,
+invalid-model errors **and even a successful Kokoro synthesis** returned the same
+status for valid and bogus credentials. Those endpoints cannot prove that a key
+is valid. Automatic health validation therefore stays inconclusive and spends no
+quota. Existing health behavior preserves the key's unknown/healthy status, so
+configured keys remain usable for inference. The supplied key is still sent on
+actual generation requests; this integration does not advertise anonymous access.
+
+Kokoro generated valid WAV files during live testing. Two tested Qwen aliases
+returned the same backend identity under conflicting advertised names; the other
+chat, image, translation and transcription candidates failed or timed out. None
+of those routes is included here.
+
+References: <https://free.ai/api/> and <https://free.ai/developer/>. Some older
+pricing text conflicts with these pages; the logged-in free account explicitly
+confirmed the shared daily pool and monthly API cap, with zero purchased tokens.
diff --git a/server/src/__tests__/providers/freeai.test.ts b/server/src/__tests__/providers/freeai.test.ts
new file mode 100644
index 00000000..81064658
--- /dev/null
+++ b/server/src/__tests__/providers/freeai.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { FreeAiProvider, freeAiAudioUrl } from '../../providers/freeai.js';
+import { hasProvider } from '../../providers/index.js';
+import { initDb, getDb } from '../../db/index.js';
+import { encrypt } from '../../lib/crypto.js';
+import { checkKeyHealth } from '../../services/health.js';
+
+const audioUrl = 'https://api.free.ai/static/outputs/1bcc722e-4ddf-4e15-995a-b274000f99e5.wav';
+
+describe('Free.ai', () => {
+ afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); });
+
+ it('registers a TTS-only provider without inventing a chat endpoint', async () => {
+ expect(hasProvider('freeai')).toBe(true);
+ const fetch = vi.spyOn(globalThis, 'fetch');
+ const provider = new FreeAiProvider();
+ await expect(provider.chatCompletion()).rejects.toMatchObject({ status: 400 });
+ await expect(provider.streamChatCompletion().next()).rejects.toMatchObject({ status: 400 });
+ await expect(provider.validateKey('')).resolves.toMatchObject({ valid: false });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('leaves credential validity inconclusive without spending quota on public probes', async () => {
+ const fetch = vi.spyOn(globalThis, 'fetch');
+ const provider = new FreeAiProvider();
+ for (const key of ['test-key', 'invalid-freeai-control']) {
+ await expect(provider.validateKey(key)).rejects.toThrow('key validity is unknown');
+ }
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unverified configured key routable during health checks without falsely validating it', async () => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ const { encrypted, iv, authTag } = encrypt('test-key');
+ const id = Number(getDb().prepare("INSERT INTO api_keys (platform,label,encrypted_key,iv,auth_tag,status,enabled) VALUES ('freeai','test',?,?,?,'unknown',1)").run(encrypted, iv, authTag).lastInsertRowid);
+ const fetch = vi.spyOn(globalThis, 'fetch');
+ await expect(checkKeyHealth(id)).resolves.toBe('unknown');
+ expect(getDb().prepare('SELECT status, enabled, last_health_error FROM api_keys WHERE id=?').get(id)).toMatchObject({
+ status: 'unknown', enabled: 1, last_health_error: expect.stringContaining('key validity is unknown'),
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it.each([null, {}, { audio_url: 'https://evil.example/a.wav' },
+ { audio_url: 'http://api.free.ai/static/outputs/1bcc722e-4ddf-4e15-995a-b274000f99e5.wav' },
+ { audio_url: 'https://[email protected]/a.wav' }, { audio_url: `${audioUrl}?redirect=1` },
+ { audio_url: 'https://api.free.ai/admin/' }, { audio_url: 'https://[email protected]/static/outputs/1bcc722e-4ddf-4e15-995a-b274000f99e5.wav' },
+ ])('rejects unsafe or missing audio URLs', body => { expect(freeAiAudioUrl(body)).toBeNull(); });
+});
diff --git a/server/src/__tests__/routes/keys.test.ts b/server/src/__tests__/routes/keys.test.ts
index ece83c3b..0992719c 100644
--- a/server/src/__tests__/routes/keys.test.ts
+++ b/server/src/__tests__/routes/keys.test.ts
@@ -217,7 +217,7 @@ describe('Keys API', () => {
expect(status).toBe(400);
});
- it.each(['inferbase', 'simplellm', 'aclide', 'speka', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare'])('accepts a %s key without seeding gated model rows', async platform => {
+ it.each(['freeai', 'inferbase', 'simplellm', 'aclide', 'speka', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare'])('accepts a %s key without seeding gated model rows', async platform => {
const { status, body } = await request(app, 'POST', '/api/keys', {
platform, key: 'not-a-real-test-key-12345', label: 'Gateway test',
});
diff --git a/server/src/__tests__/services/catalog-sync.test.ts b/server/src/__tests__/services/catalog-sync.test.ts
index 39af3ee1..1789e806 100644
--- a/server/src/__tests__/services/catalog-sync.test.ts
+++ b/server/src/__tests__/services/catalog-sync.test.ts
@@ -254,6 +254,15 @@ describe('applyCatalog', () => {
expect(getDb().prepare("SELECT model_id, modality, enabled FROM media_models WHERE platform = 'speechify'").get()).toEqual({ model_id: 'test-simba', modality: 'audio', enabled: 1 });
});
+ it('imports Free.ai speech only from the catalog, never as a chat model or bundled seed', () => {
+ expect(getDb().prepare("SELECT id FROM media_models WHERE platform='freeai'").get()).toBeUndefined();
+ const catalog = catalogOf([...existingAsCatalogModels(), baseModel({ platform: 'freeai', modelId: 'kokoro', modality: 'audio' })]);
+ applyCatalog(getDb(), catalog);
+ applyCatalog(getDb(), catalog);
+ expect(getDb().prepare("SELECT id FROM models WHERE platform='freeai'").get()).toBeUndefined();
+ expect(getDb().prepare("SELECT model_id, modality, enabled FROM media_models WHERE platform='freeai'").all()).toEqual([{ model_id: 'kokoro', modality: 'audio', enabled: 1 }]);
+ });
+
it('adds Speka chat and embedding rows only when the signed catalog supplies them', () => {
expect(getDb().prepare("SELECT id FROM models WHERE platform = 'speka'").get()).toBeUndefined();
expect(getDb().prepare("SELECT id FROM embedding_models WHERE platform = 'speka'").get()).toBeUndefined();
diff --git a/server/src/__tests__/services/media.test.ts b/server/src/__tests__/services/media.test.ts
index fac9a4c1..d4a947b0 100644
--- a/server/src/__tests__/services/media.test.ts
+++ b/server/src/__tests__/services/media.test.ts
@@ -472,6 +472,81 @@ describe('media service', () => {
});
describe('text-to-speech', () => {
+ const freeAiUrl = 'https://api.free.ai/static/outputs/1bcc722e-4ddf-4e15-995a-b274000f99e5.wav';
+ const freeAiWav = () => { const b = Buffer.alloc(48); b.write('RIFF'); b.write('WAVE', 8); return b; };
+
+ it('Free.ai maps OpenAI fields to Kokoro and downloads verified WAV without credentials', async () => {
+ addMedia('freeai', 'kokoro', 'audio'); addKey('freeai');
+ const wav = freeAiWav();
+ const fetchMock = vi.spyOn(globalThis, 'fetch')
+ .mockResolvedValueOnce(jsonResponse({ audio_url: freeAiUrl }))
+ .mockResolvedValueOnce(new Response(wav, { headers: { 'Content-Type': 'audio/wav' } }));
+ const result = await runSpeech('kokoro', { input: 'Hello', voice: 'alloy' });
+ expect(result.audio).toEqual(wav);
+ expect(result.contentType).toBe('audio/wav');
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://api.free.ai/v1/tts/');
+ expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer freeai-test-key');
+ expect(JSON.parse(String(init?.body))).toEqual({ model: 'kokoro', text: 'Hello', voice: 'af_heart' });
+ expect(fetchMock.mock.calls[1][0]).toBe(freeAiUrl);
+ expect(new Headers(fetchMock.mock.calls[1][1]?.headers).has('Authorization')).toBe(false);
+ for (const [, request] of fetchMock.mock.calls) expect(request?.redirect).toBe('error');
+ });
+
+ it('Free.ai preserves native voices and explicit WAV requests', async () => {
+ addMedia('freeai', 'kokoro', 'audio'); addKey('freeai');
+ const fetchMock = vi.spyOn(globalThis, 'fetch')
+ .mockResolvedValueOnce(jsonResponse({ audio_url: freeAiUrl }))
+ .mockResolvedValueOnce(new Response(freeAiWav()));
+ await runSpeech('kokoro', { input: 'Hello', voice: 'af_heart', format: 'wav' });
+ expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body)).voice).toBe('af_heart');
+ });
+
+ it.each(['mp3', 'pcm', 'flac', 'opus'])('Free.ai rejects unsupported %s before generating', async format => {
+ addMedia('freeai', 'kokoro', 'audio'); addKey('freeai');
+ const fetchMock = vi.spyOn(globalThis, 'fetch');
+ await expect(runSpeech('kokoro', { input: 'Hello', format })).rejects.toThrow('supports wav');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('Free.ai never sends untested or premium model IDs', async () => {
+ addMedia('freeai', 'premium/voice', 'audio'); addKey('freeai');
+ const fetchMock = vi.spyOn(globalThis, 'fetch');
+ await expect(runSpeech('premium/voice', { input: 'Hello' })).rejects.toThrow('only the tested Kokoro');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each([{}, { audio_url: 'http://169.254.169.254/latest/meta-data/' }, { audio_url: 'https://example.com/test.wav' }])('Free.ai never downloads unsafe output', async body => {
+ addMedia('freeai', 'kokoro', 'audio'); addKey('freeai');
+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse(body));
+ await expect(runSpeech('kokoro', { input: 'Hello' })).rejects.toThrow('unsafe audio URL');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('Free.ai rejects JSON and oversized output instead of labelling them audio', async () => {
+ addMedia('freeai', 'kokoro', 'audio'); addKey('freeai');
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(jsonResponse({ audio_url: freeAiUrl }))
+ .mockResolvedValueOnce(jsonResponse({ error: 'not audio' }))
+ .mockResolvedValueOnce(jsonResponse({ audio_url: freeAiUrl }))
+ .mockResolvedValueOnce(new Response(freeAiWav(), { headers: { 'Content-Length': String(21 * 1024 * 1024) } }));
+ await expect(runSpeech('kokoro', { input: 'Hello' })).rejects.toThrow('recognized WAV');
+ await expect(runSpeech('kokoro', { input: 'Hello' })).rejects.toThrow('too large');
+ });
+
+ it('Free.ai preserves quota backoff without retrying a paid model', async () => {
+ addMedia('freeai', 'kokoro', 'audio'); addKey('freeai');
+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('quota', { status: 429, headers: { 'Retry-After': '30' } }));
+ await expect(runSpeech('kokoro', { input: 'Hello' })).rejects.toMatchObject({ status: 429, retryAfterMs: 30000 });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('Free.ai reports queued work without following a poll URL or resubmitting generation', async () => {
+ addMedia('freeai', 'kokoro', 'audio'); addKey('freeai');
+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ queued: true, job_id: 'test', poll_url: 'https://example.com/private' }));
+ await expect(runSpeech('kokoro', { input: 'Hello' })).rejects.toMatchObject({ status: 502, code: 'upstream_queued' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
it.each(['simba-3.0', 'simba-3.2'])('Speechify %s sends native fields and decodes JSON audio', async model => {
addMedia('speechify', model, 'audio');
addKey('speechify');
diff --git a/server/src/providers/freeai.ts b/server/src/providers/freeai.ts
new file mode 100644
index 00000000..3f08e28a
--- /dev/null
+++ b/server/src/providers/freeai.ts
@@ -0,0 +1,41 @@
+import type { ChatCompletionChunk, ChatCompletionResponse } from '@freellmapi/shared/types.js';
+import { BaseProvider, type KeyValidationResult } from './base.js';
+
+export const FREEAI_BASE_URL = 'https://api.free.ai';
+
+/** Only download the output shape exercised live, not arbitrary upstream URLs. */
+export function freeAiAudioUrl(body: unknown): string | null {
+ if (!body || typeof body !== 'object' || !('audio_url' in body) || typeof body.audio_url !== 'string') return null;
+ try {
+ const url = new URL(body.audio_url);
+ if (url.origin !== FREEAI_BASE_URL || url.username || url.password || url.search || url.hash
+ || !/^\/static\/outputs\/[0-9a-f-]{36}\.wav$/i.test(url.pathname)) return null;
+ return url.href;
+ } catch { return null; }
+}
+
+/** TTS-only until the mismatched chat aliases are resolved. Free accounts share
+ * 30K tokens/day and 1K API requests/month (no card; verified 2026-10-11).
+ * https://free.ai/api/ — model rows belong only in the signed catalog. */
+export class FreeAiProvider extends BaseProvider {
+ readonly platform = 'freeai' as const;
+ readonly name = 'Free.ai';
+ async validateKey(apiKey: string): Promise<KeyValidationResult> {
+ if (!apiKey.trim()) return { valid: false, error: 'Free.ai API key is required' };
+ // Live controls (2026-10-11): /models, invalid-model errors and even Kokoro
+ // synthesis returned the same status with valid and bogus credentials.
+ // None proves authentication. Do not burn quota or mark a bogus key valid.
+ // The existing health service preserves unknown/healthy state on an
+ // inconclusive probe, so a configured key can still serve normal requests.
+ throw new Error('Free.ai has no verified credential-validation endpoint; key validity is unknown (no quota spent)');
+ }
+
+ async chatCompletion(): Promise<ChatCompletionResponse> {
+ throw Object.assign(new Error('Free.ai currently supports /v1/audio/speech, not chat completions'), { status: 400 });
+ }
+
+ // eslint-disable-next-line require-yield
+ async *streamChatCompletion(): AsyncGenerator<ChatCompletionChunk> {
+ throw Object.assign(new Error('Free.ai currently supports /v1/audio/speech, not chat completions'), { status: 400 });
+ }
+}
diff --git a/server/src/providers/index.ts b/server/src/providers/index.ts
index c72be456..21e611c0 100644
--- a/server/src/providers/index.ts
+++ b/server/src/providers/index.ts
@@ -25,6 +25,7 @@ import { Router9Provider } from './router9.js';
import { SeptorProvider } from './septor.js';
import { ClodProvider } from './clod.js';
import { SpeechifyProvider } from './speechify.js';
+import { FreeAiProvider } from './freeai.js';
import { BlazeProvider } from './blaze.js';
import { LucidityProvider } from './lucidity.js';
import { AirforceProvider } from './airforce.js';
@@ -86,6 +87,7 @@ register(new Router9Provider());
register(new SeptorProvider());
register(new ClodProvider());
register(new SpeechifyProvider());
+register(new FreeAiProvider());
register(new BlazeProvider());
// Five more OpenAI-compatible gateways. Each pins the response model to the
// requested route (502 on substitution); rows stay in the hosted catalog.
diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.ts
index 6494f660..ab6f0851 100644
--- a/server/src/routes/keys.ts
+++ b/server/src/routes/keys.ts
@@ -52,6 +52,7 @@ const PLATFORMS = [
'gizmo',
'blockrun',
'moondream',
+ 'freeai',
'google', 'groq', 'cerebras', 'sail', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare', 'bai', 'radeon', 'nvidia', 'mistral',
'openrouter', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama',
'kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'ovh', 'agnes', 'reka', 'siliconflow',
diff --git a/server/src/services/media.ts b/server/src/services/media.ts
index e2af8fab..7276fe49 100644
--- a/server/src/services/media.ts
+++ b/server/src/services/media.ts
@@ -20,10 +20,11 @@ import { isOnCooldown, setCooldown } from './ratelimit.js';
import { SPEECHIFY_BASE_URL, SPEECHIFY_VERSION } from '../providers/speechify.js';
import { TYPHOON_BASE_URL } from '../providers/typhoon.js';
import { ELECTRONHUB_BASE_URL } from '../providers/electronhub.js';
+import { FREEAI_BASE_URL, freeAiAudioUrl } from '../providers/freeai.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']);
+export const MEDIA_PLATFORMS = new Set(['nvidia', 'pollinations', 'cloudflare', 'siliconflow', 'google', 'speechify', 'electronhub', 'freeai']);
/** Video uses a dedicated optional catalog registry so binaries that predate
* this modality ignore the rows instead of accidentally ingesting them as
@@ -595,6 +596,54 @@ async function callSpeechProvider(
): Promise<{ audio: Buffer; contentType: string }> {
const key = credential.key;
switch (row.platform) {
+ case 'freeai': {
+ if (!key) throw new MediaError('Free.ai API key required', 401);
+ if (row.model_id !== 'kokoro') throw new MediaError('Free.ai currently supports only the tested Kokoro speech route', 400);
+ if (p.format && p.format !== 'wav') throw new MediaError('Free.ai Kokoro supports wav output through this adapter', 400);
+ const standardVoices = new Set(['alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'nova', 'onyx', 'sage', 'shimmer', 'verse', 'marin', 'cedar']);
+ const voice = !p.voice || standardVoices.has(p.voice.toLowerCase()) ? 'af_heart' : p.voice;
+ const r = await mediaFetch(`${FREEAI_BASE_URL}/v1/tts/`, 'freeai', 'audio', {
+ method: 'POST', redirect: 'error',
+ headers: { 'Content-Type': 'application/json', ...bearerAuthHeader(key) },
+ body: JSON.stringify({ model: row.model_id, text: p.input, voice }),
+ });
+ const body: unknown = await r.json();
+ if (body && typeof body === 'object' && 'queued' in body && body.queued === true) {
+ // The website uses session-based polling for queued jobs; its
+ // API status endpoint did not expose our tested job. Never follow an
+ // arbitrary poll_url or submit the same generation again automatically.
+ throw new MediaError('Free.ai queued this speech job; audio is not yet available. Check the Free.ai account history before retrying.', 502, 'upstream_queued');
+ }
+ const url = freeAiAudioUrl(body);
+ if (!url) throw new MediaError('Free.ai returned a missing or unsafe audio URL', 502);
+ // Output is public on the same fixed host. Never forward the credential,
+ // follow redirects or download arbitrary URLs supplied by an upstream.
+ const output = await mediaFetch(url, 'freeai', 'audio', { method: 'GET', redirect: 'error' });
+ const maxBytes = 20 * 1024 * 1024;
+ if (Number(output.headers.get('content-length')) > maxBytes || !output.body) {
+ await output.body?.cancel();
+ throw new MediaError('Free.ai speech output is missing or too large', 502);
+ }
+ const reader = output.body.getReader(), chunks: Buffer[] = [];
+ let size = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.length;
+ if (size > maxBytes) {
+ await reader.cancel();
+ throw new MediaError('Free.ai speech output is too large', 502);
+ }
+ chunks.push(Buffer.from(value));
+ }
+ } finally { reader.releaseLock(); }
+ const audio = Buffer.concat(chunks);
+ if (audio.length <= 44 || audio.toString('ascii', 0, 4) !== 'RIFF' || audio.toString('ascii', 8, 12) !== 'WAVE') {
+ throw new MediaError('Free.ai returned no recognized WAV audio', 502);
+ }
+ return { audio, contentType: 'audio/wav' };
+ }
case 'speechify': {
const fmt = p.format ?? 'mp3';
// Speechify exposes ogg, not OpenAI's opus name. Do not silently return
diff --git a/shared/types.ts b/shared/types.ts
index 24a9eb1f..3514ce0b 100644
--- a/shared/types.ts
+++ b/shared/types.ts
@@ -97,6 +97,9 @@ export type Platform =
| 'septor'
| 'clod'
| 'speechify'
+ // Self-hosted TTS: shared 30K tokens/day and 1K API requests/month, no card.
+ // Model rows arrive only through the signed, freshness-gated catalog.
+ | 'freeai'
| 'blaze'
// Lucidity Composite, Api.Airforce and DreamPrompting expose daily free
// allowances; Waterfall and Logfare publish community / fair-use tiers.