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(models): per-model dynamic execution status in /v1/models (ready/needsKey/exhausted) (#1100) (#1101)
suantea (asuan_suan)85056548ab9c
diff --git a/docs/api/01-rest-api.md b/docs/api/01-rest-api.mdindex f1295b31..d8828f8c 100644--- a/docs/api/01-rest-api.md+++ b/docs/api/01-rest-api.md@@ -8,6 +8,7 @@ Any OpenAI-compatible client works (Anthropic / Claude clients too — see [Anth- [Chat completions](#chat-completions)- [Routing strategies (`auto:*`)](#routing-strategies-auto)+- [Model listing](#model-listing)- [Streaming](#streaming)- [Tool calling](#tool-calling)- [Gemini Google Search grounding](#gemini-google-search-grounding)@@ -92,6 +93,23 @@ curl http://localhost:3001/v1/chat/completions \An unknown profile name returns a clear `400` rather than silently falling back. Profiles are named fallback chains (see [Features](../README.md#features)) — create and switch them from the dashboard; whichever is active is what plain `auto` uses.+## Model listing++`GET /v1/models` lists the whole catalog, including models you cannot call yet, so a client can show what exists as well as what is connected. `?available=true` (aliases `?connected=true`, `?ready=true`) narrows to models that can serve a request now.++Each catalog entry also carries `execution_status`, a live answer to "would a request work right now":++- `ready` — at least one key can actually serve it: enabled, healthy or not yet probed, not scoped away from this model, not on a rate-limit cooldown, and inside its rate and token windows. A key whose `status` is still `unknown` counts as ready, because probing is lazy and a fresh key is usable until something says otherwise.+- `needsKey` — the model is disabled, or no enabled key matches it at all.+- `exhausted` — keys match the model but every one of them is blocked at this moment, so a request would fail immediately. This is the state a burst of 429s produces, and it clears on its own when the cooldowns expire.++`?execution_status=ready` (also `needsKey`, `exhausted`; matched case-insensitively) narrows the catalog rows to one status, so an agent can ask for models it can call without reading the whole list. An unrecognised value filters nothing. Like `?available=`, the filter applies only to catalog rows: `auto`, `fusion` and the `auto:<profile>` chains are router entries rather than models with keys of their own, and are always listed.++```bash+curl "http://localhost:3001/v1/models?execution_status=ready" \+ -H "Authorization: Bearer freellmapi-your-unified-key"+```+## Streaming```pythondiff --git a/server/src/__tests__/routes/proxy-auto-model.test.ts b/server/src/__tests__/routes/proxy-auto-model.test.tsindex 584b9202..68ec89d5 100644--- a/server/src/__tests__/routes/proxy-auto-model.test.ts+++ b/server/src/__tests__/routes/proxy-auto-model.test.ts@@ -126,6 +126,35 @@ describe('Virtual "auto" model', () => {expect(allModels.length).toBeGreaterThan(filteredModels.length);});+ // #1100: every catalog row carries a machine-readable execution_status, and+ // `?execution_status=` narrows to one of them so an agent can ask for models+ // it can call right now without parsing the whole list.+ it('?execution_status= narrows to that status (#1100)', async () => {+ const all = await request(app, 'GET', '/v1/models', undefined, authHeaders());+ expect(all.status).toBe(200);+ const catalog = all.body.data.filter((m: any) => m.execution_status !== undefined);+ expect(catalog.length).toBeGreaterThan(0);+ expect(catalog.every((m: any) => ['ready', 'needsKey', 'exhausted'].includes(m.execution_status))).toBe(true);+ expect(catalog.some((m: any) => m.execution_status === 'ready')).toBe(true);+ expect(catalog.some((m: any) => m.execution_status === 'needsKey')).toBe(true);++ const ready = await request(app, 'GET', '/v1/models?execution_status=ready', undefined, authHeaders());+ const readyModels = ready.body.data.filter((m: any) => m.execution_status !== undefined);+ expect(readyModels.length).toBeGreaterThan(0);+ expect(readyModels.every((m: any) => m.execution_status === 'ready')).toBe(true);+ expect(readyModels.length).toBeLessThan(catalog.length);++ // The value is camelCase but the query is matched case-insensitively.+ const needsKey = await request(app, 'GET', '/v1/models?execution_status=needskey', undefined, authHeaders());+ const needsKeyModels = needsKey.body.data.filter((m: any) => m.execution_status !== undefined);+ expect(needsKeyModels.length).toBeGreaterThan(0);+ expect(needsKeyModels.every((m: any) => m.execution_status === 'needsKey')).toBe(true);++ // An unrecognised value filters nothing rather than emptying the list.+ const bogus = await request(app, 'GET', '/v1/models?execution_status=banana', undefined, authHeaders());+ expect(bogus.body.data.filter((m: any) => m.execution_status !== undefined).length).toBe(catalog.length);+ });+it('marks a fully-disabled model with unavailable_reason "disabled" (#242)', async () => {const db = getDb();const row = db.prepare("SELECT display_name FROM models WHERE platform='groq' AND enabled=1 LIMIT 1").get() as { display_name: string } | undefined;diff --git a/server/src/__tests__/services/model-listing-execution-status.test.ts b/server/src/__tests__/services/model-listing-execution-status.test.tsnew file mode 100644index 00000000..358a365d--- /dev/null+++ b/server/src/__tests__/services/model-listing-execution-status.test.ts@@ -0,0 +1,107 @@+import { describe, it, expect, beforeEach } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { buildModelListing } from '../../services/model-listing.js';+import { setCooldown } from '../../services/ratelimit.js';++// #1100: /v1/models gains a per-model execution_status (ready / needsKey /+// exhausted) derived from whether the router could actually dispatch to the+// model right now, so agents can filter ?execution_status=ready and route+// around exhausted models instead of 429ing.++function seedModel(platform: string, modelId: string, enabled = 1) {+ getDb().prepare(`+ INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, size_label,+ rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, enabled)+ VALUES (?, ?, ?, 5, 5, 'Medium', NULL, NULL, NULL, NULL, '', ?)+ `).run(platform, modelId, modelId, enabled);+}++let keySeq = 0;+function seedKey(platform: string, status: string, enabled = 1, scope: string[] | null = null) {+ keySeq += 1;+ return Number(getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, model_scope_json)+ VALUES (?, ?, 'x', 'x', 'x', ?, ?, ?)+ `).run(platform, `${platform}-${status}-${keySeq}`, status, enabled, scope ? JSON.stringify(scope) : null).lastInsertRowid);+}++function statusFor(modelId: string) {+ const m = buildModelListing().models.find(x => x.id === modelId);+ return m?.executionStatus;+}++describe('buildModelListing execution_status (#1100)', () => {+ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ process.env.UNIFY_MODELS = 'false';+ initDb(':memory:');+ });++ it('marks a model ready when a healthy enabled key exists', () => {+ seedModel('groq', 'ready-model');+ seedKey('groq', 'healthy');+ expect(statusFor('ready-model')).toBe('ready');+ });++ it('treats an unprobed (unknown) key as ready, not exhausted', () => {+ seedModel('groq', 'unknown-model');+ seedKey('groq', 'unknown');+ expect(statusFor('unknown-model')).toBe('ready');+ });++ it('marks a model needsKey when no enabled key exists', () => {+ seedModel('groq', 'nokey-model');+ expect(statusFor('nokey-model')).toBe('needsKey');+ });++ it('marks a model exhausted when every candidate key is rate-limited or invalid', () => {+ seedModel('groq', 'exhausted-model');+ seedKey('groq', 'rate_limited');+ seedKey('groq', 'invalid');+ expect(statusFor('exhausted-model')).toBe('exhausted');+ });++ it('stays ready when at least one of several keys is healthy', () => {+ seedModel('groq', 'mixed-model');+ seedKey('groq', 'rate_limited');+ seedKey('groq', 'healthy');+ expect(statusFor('mixed-model')).toBe('ready');+ });++ it('marks a disabled model needsKey regardless of keys', () => {+ seedModel('groq', 'disabled-model', 0);+ seedKey('groq', 'healthy');+ expect(statusFor('disabled-model')).toBe('needsKey');+ });++ // A live 429 never writes api_keys.status: it writes a per-key cooldown row.+ // Reading status alone therefore called a cooling-down model ready.+ it('marks a model exhausted when its only key is on cooldown', () => {+ seedModel('groq', 'cooling-model');+ const keyId = seedKey('groq', 'healthy');+ setCooldown('groq', 'cooling-model', keyId, 60_000, 'header');+ expect(statusFor('cooling-model')).toBe('exhausted');+ });++ it('stays ready when a sibling key is not on cooldown', () => {+ seedModel('groq', 'sibling-model');+ const cooling = seedKey('groq', 'healthy');+ seedKey('groq', 'healthy');+ setCooldown('groq', 'sibling-model', cooling, 60_000, 'header');+ expect(statusFor('sibling-model')).toBe('ready');+ });++ // #657: a key scoped to other models cannot serve this one, so it must not+ // make the model look ready.+ it('ignores a key scoped away from the model', () => {+ seedModel('groq', 'scoped-out-model');+ seedKey('groq', 'healthy', 1, ['some-other-model']);+ expect(statusFor('scoped-out-model')).toBe('exhausted');+ });++ it('counts a key scoped to the model itself', () => {+ seedModel('groq', 'scoped-in-model');+ seedKey('groq', 'healthy', 1, ['scoped-in-model']);+ expect(statusFor('scoped-in-model')).toBe('ready');+ });+});diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 1c2ad4ef..9c0882d9 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -32,7 +32,7 @@ import { enforceJsonContent } from '../lib/structured-output.js';import type { Platform } from '@freellmapi/shared/types.js';import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';import { isUnifyEnabled, getModelGroups, resolveRequestedIdForDispatch } from '../services/model-groups.js';-import { buildModelListing } from '../services/model-listing.js';+import { buildModelListing, type NormalizedModel } from '../services/model-listing.js';import { claudeFamilyDiscoveryEntries } from '../services/anthropic-map.js';import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';@@ -371,6 +371,20 @@ proxyRouter.get('/models', (req: Request, res: Response) => {})): [];+ // Machine-readable execution filter: `?execution_status=ready` narrows to+ // models a request can actually serve RIGHT NOW (a key that is not scoped+ // away, cooling down or out of window). `ready` implies available;+ // `needsKey`/`exhausted` select the rest. Matched case-insensitively because+ // the value itself is camelCase; an unrecognised value filters nothing, the+ // same way an unrecognised `?available=` does. Like `?available=`, this+ // narrows only the catalog rows: `auto`, `fusion` and the named chains are+ // router entries, not models with keys of their own.+ const esValues: Record<string, NormalizedModel['executionStatus']> = {+ ready: 'ready', needskey: 'needsKey', exhausted: 'exhausted',+ };+ const es = esValues[String(req.query.execution_status ?? '').toLowerCase()];+ const esFiltered = es ? listed.filter(m => m.executionStatus === es) : listed;+res.json({object: 'list',data: [@@ -412,7 +426,7 @@ proxyRouter.get('/models', (req: Request, res: Response) => {available: p.usable === 1,unavailable_reason: p.usable === 1 ? null : 'no_models',})),- ...listed.map(m => ({+ ...esFiltered.map(m => ({id: m.id,object: 'model',created: 0,@@ -423,6 +437,10 @@ proxyRouter.get('/models', (req: Request, res: Response) => {// Non-standard but additive: OpenAI clients ignore unknown fields.available: m.available === 1,unavailable_reason: m.available === 1 ? null : (m.enabled === 1 ? 'no_key' : 'disabled'),+ // Machine-readable dynamic status: 'ready' | 'needsKey' | 'exhausted'+ // (see services/model-listing.ts). Agents can filter with+ // ?execution_status=ready and route around exhausted models.+ execution_status: m.executionStatus,// OpenRouter's field name; agents use it to pick knobs per model. For// a unify group this is the intersection over member platforms — a// param is only advertised when every platform the router might pickdiff --git a/server/src/services/model-listing.ts b/server/src/services/model-listing.tsindex 30ce7896..22886aac 100644--- a/server/src/services/model-listing.ts+++ b/server/src/services/model-listing.ts@@ -1,6 +1,7 @@import type { ModelListRow } from '@freellmapi/shared/types.js';import { getDb } from '../db/index.js';import { isUnifyEnabled, getModelGroups } from './model-groups.js';+import { hasUsableKeyForModel } from './router.js';// Shared catalog-listing logic behind both the OpenAI `GET /v1/models` and the// Anthropic `GET /v1/models` endpoints, so the two wire formats list the exact@@ -20,6 +21,11 @@ export interface NormalizedModel {// `supported_parameters` so agents can pick knobs per model.platforms: string[];supportsTools: boolean;+ // Dynamic execution status for agents: `ready` (a key can serve it right+ // now), `needsKey` (disabled, or no enabled key matches it — available=0's+ // breakdown), or `exhausted` (keys exist but every one is currently blocked,+ // so a request would fail immediately).+ executionStatus: 'ready' | 'needsKey' | 'exhausted';}export interface ModelListing {@@ -31,6 +37,23 @@ export interface ModelListing {autoContextWindow: number | null;}+// `ready` — at least one key could actually serve a request for this model+// right now: enabled, healthy or never probed (probing is lazy, so an unprobed+// key counts as usable), not scoped away from the model (#657), not on+// cooldown, and inside its rate and token windows. `exhausted` — keys match+// the model but every one of them is currently blocked, so a request would+// fail straight away. `needsKey` — nothing matches it at all, or the model is+// disabled.+//+// The gates are the router's own (hasOtherUsableKey), deliberately rather than+// a second reading of api_keys.status: a live 429 never writes that column, it+// writes a cooldown row (see services/ratelimit.ts, lib/fallback-loop.ts), so+// status alone reports a cooling-down model as ready.+function executionStatusFor(modelDbIds: number[], available: number): 'ready' | 'needsKey' | 'exhausted' {+ if (available !== 1) return 'needsKey';+ return modelDbIds.some(id => hasUsableKeyForModel(id)) ? 'ready' : 'exhausted';+}+export function buildModelListing(): ModelListing {const availableExpr = `(CASE WHEN m.enabled = 1 AND EXISTS (@@ -56,16 +79,20 @@ export function buildModelListing(): ModelListing {allListed = getModelGroups().map(g => {const infos = g.members.map(m => byId.get(m.model_db_id)).filter(Boolean) as AvailRow[];const ctxs = infos.map(i => i.context_window).filter((c): c is number => c != null);+ const available = infos.some(i => i.available === 1) ? 1 : 0;return {id: g.canonicalId,name: g.groupLabel,ownedBy: 'freellmapi',- available: infos.some(i => i.available === 1) ? 1 : 0,+ available,enabled: infos.some(i => i.enabled === 1) ? 1 : 0,contextWindow: ctxs.length ? Math.max(...ctxs) : null,intel: infos.length ? Math.min(...infos.map(i => i.intelligence_rank)) : Number.MAX_SAFE_INTEGER,platforms: [...new Set(infos.map(i => i.platform))],supportsTools: infos.some(i => i.supports_tools === 1),+ // A group is ready when ANY member can serve it — that is exactly the+ // choice the router has when it dispatches the group.+ executionStatus: executionStatusFor(g.members.map(m => m.model_db_id), available),};});} else {@@ -91,6 +118,7 @@ export function buildModelListing(): ModelListing {intel: m.intelligence_rank,platforms: [m.platform],supportsTools: m.supports_tools === 1,+ executionStatus: executionStatusFor([m.id], m.available),}));}diff --git a/server/src/services/router.ts b/server/src/services/router.tsindex 785b8cf7..e2c2e0ec 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -1557,6 +1557,18 @@ export function hasOtherUsableKey(modelDbId: number, excludingKeyId: number, skireturn false;}+/**+ * Can ANY key serve this model right now? The same gates hasOtherUsableKey+ * applies — scope (#657), per-key cooldown, and the provider/model rate and+ * token windows — with no key excluded. /v1/models uses it to tell a `ready`+ * model from an `exhausted` one (#1100), so the listing cannot claim a model+ * the router would immediately skip.+ */+export function hasUsableKeyForModel(modelDbId: number): boolean {+ // Key ids are AUTOINCREMENT and start at 1, so -1 excludes nothing.+ return hasOtherUsableKey(modelDbId, -1);+}+/*** Every key that can be ROUTED to this model: enabled + healthy/unknown, not* scoped away from the model (#657), and — for a custom model — belonging to