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): BeatAPI decisions and SerpSearch (v0.16.1) (#1571)
Tashfeen2c506ea99949
diff --git a/client/src/components/keys/shared.tsx b/client/src/components/keys/shared.tsxindex a5e731a4..bb79b055 100644--- a/client/src/components/keys/shared.tsx+++ b/client/src/components/keys/shared.tsx@@ -30,6 +30,7 @@ export const PLATFORMS: { value: Platform; label: string; url: string; keyless?:{ 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: 'auray', label: 'Auray (50 shared monthly credits)', url: 'https://app.auray.ai' },+ { value: 'beatapi', label: 'BeatAPI (JEV decisions; temporary free offer)', url: 'https://beatapi.io' },{ value: 'typhoon', label: 'Typhoon (free research API)', url: 'https://playground.opentyphoon.ai' },{ value: 'plugsky', label: 'Plugsky (free chat aliases)', url: 'https://plugsky.com/dashboard' },{ value: 'inferbase', label: 'Inferbase (shared monthly and daily allowance)', url: 'https://inferbase.ai' },diff --git a/client/src/lib/routing.ts b/client/src/lib/routing.tsindex 4717a243..36b85ae9 100644--- a/client/src/lib/routing.ts+++ b/client/src/lib/routing.ts@@ -465,6 +465,8 @@ export const platformColors: Record<string, string> = {firecrawl: '#ef4444',linkup: '#10b981',parallel: '#0ea5e9',+ serpsearch: '#2563eb',+ beatapi: '#8b5cf6',}// ── Grouped (unified) rendering ──────────────────────────────────────────────diff --git a/client/src/lib/search.ts b/client/src/lib/search.tsindex a7739a8d..406bb157 100644--- a/client/src/lib/search.ts+++ b/client/src/lib/search.ts@@ -8,7 +8,7 @@ import type { SearchPlatform as SharedSearchPlatform } from '@freellmapi/shared/// Mirrors SEARCH_PLATFORMS in shared/types.ts. The client only imports types// from shared, so the list is repeated here; the two assertions below fail the// typecheck if either side gains a platform the other lacks.-export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel'] as const+export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch'] as constexport type SearchPlatform = (typeof SEARCH_PLATFORMS)[number]const sharedCoversClient: SharedSearchPlatform = '' as SearchPlatformconst clientCoversShared: SearchPlatform = '' as SharedSearchPlatform@@ -28,6 +28,7 @@ export const SEARCH_PROVIDERS: { value: SearchPlatform; label: string; url: stri{ value: 'firecrawl', label: 'Firecrawl (1,000 credits/month)', url: 'https://www.firecrawl.dev/app/api-keys' },{ value: 'linkup', label: 'Linkup (€5 credits/month)', url: 'https://app.linkup.so/api-keys' },{ value: 'parallel', label: 'Parallel (no key needed)', url: 'https://platform.parallel.ai', keyless: true },+ { value: 'serpsearch', label: 'SerpSearch (1,000 searches/month)', url: 'https://serpsearch.com/dashboard/api-keys' },]/** Short provider name for chips and badges ("Tavily", not the full label). */diff --git a/desktop/package-lock.json b/desktop/package-lock.jsonindex ea456e95..97c9eee6 100644--- a/desktop/package-lock.json+++ b/desktop/package-lock.json@@ -1,12 +1,12 @@{"name": "freellmapi-desktop",- "version": "0.16.0",+ "version": "0.16.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "freellmapi-desktop",- "version": "0.16.0",+ "version": "0.16.1","dependencies": {"better-sqlite3": "^12.10.0","electron-updater": "^6.8.9"diff --git a/desktop/package.json b/desktop/package.jsonindex 4198c363..3d8925a1 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -1,6 +1,6 @@{"name": "freellmapi-desktop",- "version": "0.16.0",+ "version": "0.16.1","description": "FreeLLMAPI menu-bar app — local OpenAI-compatible LLM router","author": {"name": "tashfeenahmed",diff --git a/docs/BEATAPI-SERPSEARCH.md b/docs/BEATAPI-SERPSEARCH.mdnew file mode 100644index 00000000..741c2487--- /dev/null+++ b/docs/BEATAPI-SERPSEARCH.md@@ -0,0 +1,43 @@+# BeatAPI decisions and SerpSearch++These integrations add credential and request handling only. Model/engine rows+are delivered by the signed catalog, retaining Premium access immediately and+Free access after the existing 30-day promotion gate. No bundled seeds or+release-gate changes are included.++## BeatAPI++- Add a `beatapi` key in the dashboard, or import `BEATAPI_API_KEY`.+- JEV decision requests use `POST https://api.beatapi.io/v1/systemone` with+ Bearer authentication and `{ model, state, questions }`.+- The adapter supports the existing decision question types: `choice`, `noul`,+ and `score`. It does not expose chat or JEV image-box questions.+- Validation uses authenticated `GET /v1/models`, never inference.+- `jev-1.13-free` and `jev-1.14-free` returned valid decisions in live tests on+ October 18, 2026. They are **temporary free offers**, not recurring monthly+ credits. Before any top-up they share one successful request/minute/account.+ The catalog carries these terms; a paid top-up is not required to use them.+- Response model identity and typed answers are checked. HTTP rate limits and+ stated retry hints use the existing decision router's cooldown/failover.++Sources: [decision API](https://docs.beatapi.io/decisions),+[free-model terms](https://docs.beatapi.io/free-models),+[pricing](https://beatapi.io/pricing).++## SerpSearch++- Add a `serpsearch` key under search providers, or import `SERPSEARCH_API_KEY`.+- Bearer-authenticated `GET https://api.serpsearch.com/api/v1/search?query=...`+ maps organic results to the unified search response. `topic: "news"` uses+ `/api/v1/news` and flattens article groups. It does not invent summaries or+ convert image/video search into generation models.+- The Free plan shares 1,000 requests/month across endpoints, without a card;+ live response headers confirmed the allowance and one request/second.+- Key validation omits `query`. A valid key returns a missing-query HTTP 400+ with quota headers, an invalid key returns 401. Both were live checked, and+ the valid probe did not decrement quota. Unexpected responses are inconclusive.+- The adapter follows the existing no-hits fallback policy and result limit.+ It does not paginate automatically or consume extra credits to fill results.++Sources: [API documentation](https://serpsearch.com/docs),+[pricing](https://serpsearch.com/pricing), [FAQ](https://serpsearch.com/faq).diff --git a/server/src/__tests__/providers/beatapi-serpsearch.test.ts b/server/src/__tests__/providers/beatapi-serpsearch.test.tsnew file mode 100644index 00000000..7b71022c--- /dev/null+++ b/server/src/__tests__/providers/beatapi-serpsearch.test.ts@@ -0,0 +1,63 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { BeatApiProvider } from '../../providers/beatapi.js';+import { SerpSearchProvider } from '../../providers/serpsearch.js';+import { getProvider } from '../../providers/index.js';+import { AUTH_JSON_PROVIDER_MAP, parseKeysFromFile } from '../../lib/key-parser.js';++const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers });+afterEach(() => vi.restoreAllMocks());++describe.each([+ { platform: 'beatapi' as const, provider: new BeatApiProvider(), url: 'https://api.beatapi.io/v1/models' },+ { platform: 'serpsearch' as const, provider: new SerpSearchProvider(), url: 'https://api.serpsearch.com/api/v1/search' },+])('$platform credentials', ({ platform, provider, url }) => {+ it('registers and imports explicitly named keys', () => {+ expect(getProvider(platform)).toBeInstanceOf(provider.constructor);+ expect(parseKeysFromFile(`${platform.toUpperCase()}_API_KEY=unit-test-only`, 'keys.env').keys[0].platform).toBe(platform);+ expect(AUTH_JSON_PROVIDER_MAP[platform]).toBe(platform);+ });++ it('validates without spending search or inference quota', async () => {+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(platform === 'beatapi'+ ? json({ data: [{ id: 'jev-1.14-free' }] })+ : new Response('Failed to deserialize query string: missing field `query`', { status: 400, headers: { 'x-quota-limit': '1000' } }));+ expect(await provider.validateKey('unit-test-key')).toBe(true);+ expect(fetch.mock.calls[0][0]).toBe(url);+ const init = fetch.mock.calls[0][1]!;+ expect(init.method).toBe('GET');+ expect(init.body).toBeUndefined();+ expect(init.redirect).toBe('error');+ expect(new Headers(init.headers).get('authorization')).toBe('Bearer unit-test-key');+ });++ it.each([401, 403])('rejects HTTP %s authentication failures', async status => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ error: { message: 'Invalid API key' } }, status));+ await expect(provider.validateKey('invalid')).resolves.toMatchObject({ valid: false });+ });++ it.each([429, 500, 503])('keeps HTTP %s inconclusive with retry hints', async status => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json({}, status, { 'Retry-After': '60' }));+ await expect(provider.validateKey('unit-test-key')).rejects.toMatchObject({ status, retryAfterMs: 60_000 });+ });++ it('rejects ordinary and streaming chat without making a request', async () => {+ const fetch = vi.spyOn(global, 'fetch');+ const base = getProvider(platform)!;+ await expect(base.chatCompletion('k', [], 'm')).rejects.toMatchObject({ status: 422 });+ await expect(base.streamChatCompletion('k', [], 'm').next()).rejects.toMatchObject({ status: 422 });+ expect(fetch).not.toHaveBeenCalled();+ });+});++it.each([null, {}, { data: {} }, { data: [], error: 'failure' }])('rejects malformed BeatAPI lists', async body => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(new BeatApiProvider().validateKey('k')).rejects.toMatchObject({ status: 502 });+});++it.each([+ { body: 'missing field `query`', headers: {} },+ { body: 'unrelated error', headers: { 'x-quota-limit': '1000' } },+])('does not accept unauthenticated or unrelated SerpSearch 400s', async ({ body, headers }) => {+ vi.spyOn(global, 'fetch').mockResolvedValue(new Response(body, { status: 400, headers }));+ await expect(new SerpSearchProvider().validateKey('k')).rejects.toMatchObject({ status: 400 });+});diff --git a/server/src/__tests__/services/beatapi-serpsearch.test.ts b/server/src/__tests__/services/beatapi-serpsearch.test.tsnew file mode 100644index 00000000..1cd7cc24--- /dev/null+++ b/server/src/__tests__/services/beatapi-serpsearch.test.ts@@ -0,0 +1,122 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { runDecision, DECISION_PLATFORMS } from '../../services/decision.js';+import { runSearch, SEARCH_ENGINE_PLATFORMS } from '../../services/search.js';+import { clearAllCooldowns } from '../../services/ratelimit.js';+import { applyCatalog } from '../../services/catalog-sync.js';++const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers });+const request = { state: 'Invoice charged twice', questions: { billing: { type: 'noul' as const, instructions: 'Billing issue?' } } };+const answers = { billing: { type: 'noul', noul: 0.98 } };+function seed(platform: string, id: string, modality: string) {+ const { encrypted, iv, authTag } = 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, encrypted, iv, authTag);+ getDb().prepare(`INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label) VALUES (?, ?, ?, ?, 0, 1, 'test')`)+ .run(platform, id, id, modality);+}+beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ clearAllCooldowns(Number.MAX_SAFE_INTEGER);+});+afterEach(() => vi.restoreAllMocks());++describe('BeatAPI decision dispatch', () => {+ it.each(['jev-1.13-free', 'jev-1.14-free'])('uses the tested System One contract for %s', async model => {+ seed('beatapi', model, 'decision');+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ model, answers, usage: { input_tokens: 335, output_tokens: 47 } }));+ expect(DECISION_PLATFORMS.has('beatapi')).toBe(true);+ expect(await runDecision(request, { model })).toEqual({ provider: 'beatapi', model, answers, usage: { input_tokens: 335, output_tokens: 47 } });+ const [url, init] = fetch.mock.calls[0];+ expect(url).toBe('https://api.beatapi.io/v1/systemone');+ expect(JSON.parse(String(init?.body))).toEqual({ model, ...request });+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer unit-test-key');+ expect(getDb().prepare("SELECT COUNT(*) AS n FROM models WHERE platform = 'beatapi'").get()).toEqual({ n: 0 });+ });++ it.each([+ { model: 'other', answers }, { answers }, { model: 'jev-1.14-free', answers: {} },+ { model: 'jev-1.14-free', answers: { billing: { type: 'noul', noul: 'yes' } } },+ { model: 'jev-1.14-free', answers, error: { message: 'failed' } },+ ])('fails closed on substituted, incomplete or malformed decisions', async body => {+ seed('beatapi', 'jev-1.14-free', 'decision');+ vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(runDecision(request, { model: 'jev-1.14-free' })).rejects.toMatchObject({ status: 502 });+ });++ it('preserves BeatAPI body-stated account throttling', async () => {+ seed('beatapi', 'jev-1.14-free', 'decision');+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ error: { retry_after_seconds: 60 } }, 429));+ await expect(runDecision(request, { model: 'jev-1.14-free' })).rejects.toMatchObject({ status: 429, retryAfterMs: 60_000 });+ });+});++describe('SerpSearch dispatch', () => {+ beforeEach(() => seed('serpsearch', 'serpsearch-search', 'search'));++ it('encodes the query, normalizes organic results and respects maxResults', async () => {+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ organic_results: [+ { title: 'A & B', url: 'https://example.com/a', description: 'snippet' },+ { title: 'Unsafe', url: 'javascript:alert(1)' },+ { title: 'C', url: 'https://example.com/c' },+ ] }));+ const result = await runSearch('cats & dogs #1', { engine: 'serpsearch-search', maxResults: 1 });+ expect(SEARCH_ENGINE_PLATFORMS.has('serpsearch')).toBe(true);+ expect(result.results).toEqual([{ title: 'A & B', url: 'https://example.com/a', content: 'snippet', score: 1 }]);+ const [url, init] = fetch.mock.calls[0];+ expect(new URL(String(url)).searchParams.get('query')).toBe('cats & dogs #1');+ expect(new URL(String(url)).pathname).toBe('/api/v1/search');+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer unit-test-key');+ expect(init?.method).toBe('GET');+ expect(init?.body).toBeUndefined();+ });++ it('flattens news groups without inventing summaries', async () => {+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json([{ group_name: 'Ungrouped', articles: [{ title: 'News', url: 'https://example.com/news', created_at: 1792145760 }] }]));+ const out = await runSearch('AI', { engine: 'serpsearch-search', topic: 'news' });+ expect(String(fetch.mock.calls[0][0])).toContain('/api/v1/news?query=AI');+ expect(out.results[0]).toEqual({ title: 'News', url: 'https://example.com/news', content: '', score: 1 });+ });++ it.each([null, { error: 'failed' }, { organic_results: 'bad' }])('rejects malformed successful responses', async body => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(runSearch('AI', { engine: 'serpsearch-search' })).rejects.toMatchObject({ status: 502 });+ });++ it('passes an empty SERP to the existing no-hits fallback policy', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ search_info: { total_results: '0' } }));+ await expect(runSearch('no results', { engine: 'serpsearch-search' })).rejects.toThrow('upstream returned no valid search hits');+ });++ it('honors the one-second upstream retry hint', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ error: { code: 'RATE_LIMIT_EXCEEDED' } }, 429, { 'Retry-After': '1' }));+ await expect(runSearch('AI', { engine: 'serpsearch-search' })).rejects.toMatchObject({ status: 429, retryAfterMs: 1000 });+ });+});++it('loads new modalities only from the catalog, idempotently preserving premiumSince', () => {+ const db = getDb();+ expect(db.prepare("SELECT COUNT(*) n FROM media_models WHERE platform IN ('beatapi', 'serpsearch')").get()).toEqual({ n: 0 });+ const premiumSince = '2026-10-18T12:00:00.000Z';+ const catalog = {+ version: '2099.01.01', generatedAt: premiumSince, tier: 'live' as const, models: [], quirks: [],+ decisionModels: ['jev-1.13-free', 'jev-1.14-free'].map(modelId => ({+ platform: 'beatapi', modelId, displayName: modelId, priority: 10, enabled: true,+ quotaLabel: 'Temporary free offer', contextWindow: 32768, premiumSince,+ })),+ searchEngines: [{ platform: 'serpsearch', engineId: 'serpsearch-search', displayName: 'SerpSearch',+ priority: 10, enabled: true, quotaLabel: '1,000 requests/month', creditsPerQuery: 1,+ features: { news: true, answer: false, fullContent: false }, premiumSince }],+ };+ expect(applyCatalog(db, catalog).skippedUnknownPlatform).toBe(0);+ expect(applyCatalog(db, catalog).inserted).toBe(0);+ const rows = db.prepare("SELECT platform, modality, meta_json FROM media_models WHERE platform IN ('beatapi', 'serpsearch')").all() as Array<{ platform: string; modality: string; meta_json: string }>;+ expect(rows).toHaveLength(3);+ for (const row of rows) {+ expect(row.modality).toBe(row.platform === 'beatapi' ? 'decision' : 'search');+ expect(JSON.parse(row.meta_json).premiumSince).toBe(premiumSince);+ }+ expect(db.prepare("SELECT COUNT(*) n FROM models WHERE platform IN ('beatapi', 'serpsearch')").get()).toEqual({ n: 0 });+});diff --git a/server/src/__tests__/services/decision.test.ts b/server/src/__tests__/services/decision.test.tsindex 904e7b20..bed9f871 100644--- a/server/src/__tests__/services/decision.test.ts+++ b/server/src/__tests__/services/decision.test.ts@@ -63,8 +63,8 @@ describe('decision service', () => {vi.restoreAllMocks();});- it('has adapters for exactly the launch platforms', () => {- expect([...DECISION_PLATFORMS].sort()).toEqual(['cloudflare', 'openrouter']);+ it('has adapters for the supported decision platforms', () => {+ expect([...DECISION_PLATFORMS].sort()).toEqual(['beatapi', 'cloudflare', 'openrouter']);});it('calls Cloudflare ai/run with the account from the key and the short model selector', async () => {diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex 078062c7..b514a2ee 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -47,6 +47,10 @@ export const PREFIX_MAP: Record<string, string> = {ACLIDE_: 'aclide',SPEKA_: 'speka',AURAY_: 'auray',+ BEATAPI_: 'beatapi',+ BEAT_API_: 'beatapi',+ SERPSEARCH_: 'serpsearch',+ SERP_SEARCH_: 'serpsearch',TYPHOON_: 'typhoon',PLUGSKY_: 'plugsky',INFERBASE_: 'inferbase',@@ -158,6 +162,8 @@ export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {aclide: 'aclide',speka: 'speka',auray: 'auray',+ beatapi: 'beatapi',+ serpsearch: 'serpsearch',typhoon: 'typhoon',plugsky: 'plugsky',inferbase: 'inferbase',diff --git a/server/src/lib/search-platforms.ts b/server/src/lib/search-platforms.tsindex 422b7721..03957c60 100644--- a/server/src/lib/search-platforms.ts+++ b/server/src/lib/search-platforms.ts@@ -3,7 +3,7 @@ import type { SearchPlatform } from '@freellmapi/shared/types.js';// Runtime copy of shared/types.ts SEARCH_PLATFORMS. The server only ever// imports types from @freellmapi/shared (it is not compiled into dist), so the// list lives here too; a test pins the two together.-export const SEARCH_PLATFORMS: readonly SearchPlatform[] = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel'];+export const SEARCH_PLATFORMS: readonly SearchPlatform[] = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch'];const SEARCH_PLATFORM_SET = new Set<string>(SEARCH_PLATFORMS);diff --git a/server/src/providers/beatapi.ts b/server/src/providers/beatapi.tsnew file mode 100644index 00000000..138d3adb--- /dev/null+++ b/server/src/providers/beatapi.ts@@ -0,0 +1,33 @@+import type { ChatCompletionChunk, ChatCompletionResponse } from '@freellmapi/shared/types.js';+import { BaseProvider, providerHttpError, type KeyValidationResult } from './base.js';++export const BEATAPI_BASE_URL = 'https://api.beatapi.io/v1';++/** Decision-only integration. Model availability and promotional terms live+ * in the signed catalog, not bundled seeds or the chat router. */+export class BeatApiProvider extends BaseProvider {+ readonly platform = 'beatapi' as const;+ readonly name = 'BeatAPI';++ async validateKey(apiKey: string): Promise<KeyValidationResult> {+ const res = await this.fetchWithTimeout(`${BEATAPI_BASE_URL}/models`, {+ method: 'GET', redirect: 'error', headers: { Authorization: `Bearer ${apiKey}` },+ }, 10_000, { timeoutBounds: 'request' });+ if ([401, 403].includes(res.status)) return this.validationResult(res);+ if (!res.ok) throw providerHttpError(res, 'BeatAPI key validation is inconclusive');+ const body = await res.json().catch(() => null) as { data?: unknown; error?: unknown } | null;+ if (!Array.isArray(body?.data) || body?.error) {+ throw Object.assign(new Error('BeatAPI returned an invalid model list'), { status: 502 });+ }+ return true;+ }++ async chatCompletion(): Promise<ChatCompletionResponse> {+ throw Object.assign(new Error('BeatAPI integration supports /v1/decisions, not chat completions'), { status: 422 });+ }++ // eslint-disable-next-line require-yield+ async *streamChatCompletion(): AsyncGenerator<ChatCompletionChunk> {+ throw Object.assign(new Error('BeatAPI integration supports /v1/decisions, not chat completions'), { status: 422 });+ }+}diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex 42ebcc1d..5a74884b 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -38,6 +38,8 @@ import { DreamPromptingProvider } from './dreamprompting.js';import { WaterfallProvider } from './waterfall.js';import { LogfareProvider } from './logfare.js';import { AurayProvider } from './auray.js';+import { BeatApiProvider } from './beatapi.js';+import { SerpSearchProvider } from './serpsearch.js';const providers = new Map<Platform, BaseProvider>();@@ -82,6 +84,8 @@ register(new GizmoProvider());register(new BlockRunProvider());register(new MoondreamProvider());register(new AurayProvider());+register(new BeatApiProvider());+register(new SerpSearchProvider());// Free-plan grants are shared wallets, not free credits per model. Eligibility// and tested model rows belong in Oracle, never in bundled DB migrations.diff --git a/server/src/providers/serpsearch.ts b/server/src/providers/serpsearch.tsnew file mode 100644index 00000000..7cdfd551--- /dev/null+++ b/server/src/providers/serpsearch.ts@@ -0,0 +1,25 @@+import { providerHttpError, type KeyValidationResult } from './base.js';+import { SearchOnlyProvider } from './search-only.js';++export const SERPSEARCH_BASE_URL = 'https://api.serpsearch.com/api/v1';++export class SerpSearchProvider extends SearchOnlyProvider {+ readonly platform = 'serpsearch' as const;+ readonly name = 'SerpSearch';++ async validateKey(apiKey: string): Promise<KeyValidationResult> {+ // Authentication runs before query validation: a valid key gets 400 with+ // quota headers, an invalid key gets 401. No query means no credit spent.+ // Live checked against both cases; do not turn this into a real search.+ const res = await this.fetchWithTimeout(`${SERPSEARCH_BASE_URL}/search`, {+ method: 'GET', redirect: 'error', headers: { Authorization: `Bearer ${apiKey}` },+ }, 10_000, { timeoutBounds: 'request' });+ if ([401, 403].includes(res.status)) return this.validationResult(res);+ const quota = res.headers.get('x-quota-limit');+ if (res.status === 400 && quota !== null && /^\d+$/.test(quota)) {+ const text = await res.text();+ if (/missing field [`'"]?query|INVALID_QUERY/i.test(text)) return true;+ }+ throw providerHttpError(res, 'SerpSearch key validation is inconclusive');+ }+}diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 37523715..31cc529d 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -55,6 +55,8 @@ const PLATFORMS = ['gizmo','blockrun','moondream',+ 'beatapi',+ 'serpsearch','freeai','google', 'groq', 'cerebras', 'sail', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare', 'bai', 'radeon', 'nvidia', 'mistral','openrouter', 'cohere', 'tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'cloudflare', 'zhipu', 'ollama',diff --git a/server/src/services/decision.ts b/server/src/services/decision.tsindex aa4a1c75..58fc4ac4 100644--- a/server/src/services/decision.ts+++ b/server/src/services/decision.ts@@ -1,4 +1,5 @@import { getDb } from '../db/index.js';+import { BEATAPI_BASE_URL } from '../providers/beatapi.js';import { parseRetryAfterMs, parseStatedRetryMs } from '../providers/base.js';import { RetryHintTracker } from '../lib/retry-hint.js';import { getClientContext } from '../lib/client-context.js';@@ -177,6 +178,27 @@ function cloudflareKey(key: string): { accountId: string; token: string } {}const ADAPTERS: Record<string, Adapter> = {+ beatapi: async (cred, modelId, body, signal) => {+ const json = await upstream(`${BEATAPI_BASE_URL}/systemone`, 'beatapi', {+ method: 'POST', redirect: 'error',+ headers: { Authorization: `Bearer ${cred.key}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ model: modelId, state: body.state, questions: body.questions }),+ }, signal) as { model?: string; answers?: unknown; usage?: unknown; error?: unknown } | null;+ if (!json || json.error || json.model !== modelId) {+ throw new DecisionError('beatapi returned an error or a different decision model', 502);+ }+ const answers = answersOf(json.answers, 'beatapi');+ for (const [id, question] of Object.entries(body.questions)) {+ const answer = answers[id] as { type?: unknown; choice?: unknown; noul?: unknown; score?: unknown } | null;+ const value = answer?.[question.type];+ if (!answer || answer.type !== question.type || (question.type === 'choice'+ ? typeof value !== 'string'+ : typeof value !== 'number' || !Number.isFinite(value))) {+ throw new DecisionError('beatapi returned a missing or invalid typed answer', 502);+ }+ }+ return { answers, usage: usageOf(json.usage) };+ },// Workers AI runs Clef through ai/run, with a short `model` selector// ("clef-flash") inside the body. Response: { result: { answers, usage } }.cloudflare: async (cred, modelId, body, signal) => {diff --git a/server/src/services/search.ts b/server/src/services/search.tsindex 2c6d5e88..c795a136 100644--- a/server/src/services/search.ts+++ b/server/src/services/search.ts@@ -5,6 +5,7 @@ import { getClientContext } from '../lib/client-context.js';import { proxyFetch } from '../lib/proxy.js';import { isSearchPlatform } from '../lib/search-platforms.js';import { TAVILY_BASE_URL } from '../providers/tavily.js';+import { SERPSEARCH_BASE_URL } from '../providers/serpsearch.js';import { EXA_BASE_URL } from '../providers/exa.js';import { FIRECRAWL_BASE_URL } from '../providers/firecrawl.js';import { LINKUP_BASE_URL } from '../providers/linkup.js';@@ -285,6 +286,33 @@ async function tavilyShaped(url: string, platform: string, cred: ReservedProvide}const ADAPTERS: Record<string, Adapter> = {+ serpsearch: async (cred, query, opts, n) => {+ const news = opts.topic === 'news';+ const url = new URL(`${SERPSEARCH_BASE_URL}/${news ? 'news' : 'search'}`);+ url.searchParams.set('query', query);+ const parsed = await upstream(url.toString(), 'serpsearch', {+ method: 'GET', redirect: 'error', headers: { Authorization: `Bearer ${cred.key}` },+ }, opts.signal);+ let rows: unknown[];+ if (news) {+ if (!Array.isArray(parsed) || parsed.some(g => !g || !Array.isArray(g.articles))) {+ throw new SearchError('SerpSearch returned invalid news results', 502);+ }+ rows = parsed.flatMap(g => g.articles);+ } else {+ const result = parsed as { organic_results?: unknown; error?: unknown } | null;+ if (!result || typeof result !== 'object' || Array.isArray(result) || result.error ||+ (result.organic_results !== undefined && !Array.isArray(result.organic_results))) {+ throw new SearchError('SerpSearch returned invalid search results', 502);+ }+ // A valid SERP may omit organic_results entirely (e.g. no matches).+ rows = (result.organic_results ?? []) as unknown[];+ }+ const hits = rows.filter((r): r is Record<string, unknown> => !!r && typeof r === 'object').map(r => ({+ title: str(r.title), url: str(r.url), content: str(r.description),+ }));+ return { results: keepHits(hits).slice(0, n) };+ },tavily: (cred, query, opts, n) => tavilyShaped(`${TAVILY_BASE_URL}/search`, 'tavily', cred, query, opts, n),custom: (cred, query, opts, n) => {diff --git a/shared/types.ts b/shared/types.tsindex f48fb04a..02e04df9 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -74,6 +74,8 @@ export type Platform =| 'speka'// Built-in chat and embeddings share free monthly credits; catalog only.| 'auray'+ // Decision-only JEV adapter; promotional availability is catalog-managed.+ | 'beatapi'// Ongoing free research API for chat and speech recognition; catalog only.| 'typhoon'// Permanent free chat aliases, shared fair-use quota; signed catalog only.@@ -136,6 +138,7 @@ export type Platform =| 'firecrawl'| 'linkup'| 'parallel'+ | 'serpsearch'| 'cloudflare'| 'zhipu'| 'ollama'@@ -264,7 +267,7 @@ export type Platform =* web_search tools), never chat. Search engine rows arrive through the* catalog's `searchEngines` registry. The server keeps its own runtime copy in* server/src/lib/search-platforms.ts (shared is type-only on the server). */-export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel'] as const;+export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch'] as const;export type SearchPlatform = (typeof SEARCH_PLATFORMS)[number];export function isSearchPlatform(platform: string): platform is SearchPlatform {