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(server): tier selectors in the Claude family model map (#1444)
suantea (asuan_suan)f1708ffa29a3
diff --git a/server/src/__tests__/services/anthropic-map.test.ts b/server/src/__tests__/services/anthropic-map.test.tsindex ba3fd85f..3be05c49 100644--- a/server/src/__tests__/services/anthropic-map.test.ts+++ b/server/src/__tests__/services/anthropic-map.test.ts@@ -1,5 +1,11 @@-import { describe, it, expect } from 'vitest';-import { classifyClaudeFamily } from '../../services/anthropic-map.js';+import { describe, it, expect, beforeEach } from 'vitest';+import { classifyClaudeFamily, parseTierSelector, setClaudeModelMap, resolveAnthropicModel } from '../../services/anthropic-map.js';+import { initDb, getDb } from '../../db/index.js';++beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+});// classifyClaudeFamily maps a requested model alias to a Claude family (or null// for a concrete catalog id). Claude Code's planning alias `opusplan` is@@ -29,3 +35,55 @@ describe('classifyClaudeFamily', () => {expect(classifyClaudeFamily('llama-3.1-70b')).toBeNull();});});++// Tier selectors (`tier:pro|mid|normal`) map a Claude family onto the V17+// intelligence tiers (size_label) instead of one pinned model, so the family+// routes over the whole capability band.+describe('tier selectors in the anthropic model map', () => {+ it('parses tier selector values and rejects other strings', () => {+ expect(parseTierSelector('tier:pro')).toBe('tier:pro');+ expect(parseTierSelector('tier:normal')).toBe('tier:normal');+ expect(parseTierSelector('tier:huge')).toBeNull();+ expect(parseTierSelector('auto')).toBeNull();+ });++ it('accepts tier selector values in the map', () => {+ const map = setClaudeModelMap({ opus: 'tier:pro', sonnet: 'tier:mid', haiku: 'tier:normal' });+ expect(map.opus).toBe('tier:pro');+ expect(map.sonnet).toBe('tier:mid');+ expect(map.haiku).toBe('tier:normal');+ });++ it('resolves a tier family to the whole tier pool, unpinned', () => {+ setClaudeModelMap({ opus: 'tier:pro' });+ const resolved = resolveAnthropicModel('claude-opus-4-5');+ expect(resolved.pinned).toBe(false);+ expect(resolved.tierDbIds).toBeDefined();+ expect(resolved.tierDbIds!.length).toBeGreaterThan(0);+ // The whole Frontier tier is one pool: no single model is preferred.+ expect(resolved.preferredModelDbId).toBeUndefined();+ });++ it('normal absorbs Medium and Small so the smallest providers stay reachable', () => {+ setClaudeModelMap({ haiku: 'tier:normal' });+ const resolved = resolveAnthropicModel('claude-haiku-4-5');+ expect(resolved.tierDbIds).toBeDefined();+ expect(resolved.tierDbIds!.length).toBeGreaterThanOrEqual(2);+ });++ it('degrades to auto when the tier pool is empty', () => {+ getDb().prepare(`UPDATE models SET size_label = 'Frontier'`).run();+ setClaudeModelMap({ sonnet: 'tier:mid' });+ const resolved = resolveAnthropicModel('claude-sonnet-4-5');+ expect(resolved).toEqual({ pinned: false });+ });++ it('still pins a concrete catalog model over a tier value', () => {+ const row = getDb().prepare(`SELECT id, model_id FROM models WHERE enabled = 1 LIMIT 1`).get() as { id: number; model_id: string };+ setClaudeModelMap({ opus: row.model_id });+ const resolved = resolveAnthropicModel('claude-opus-4-5');+ expect(resolved.pinned).toBe(true);+ expect(resolved.preferredModelDbId).toBe(row.id);+ expect(resolved.tierDbIds).toBeUndefined();+ });+});diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.tsindex 2144b438..43578f49 100644--- a/server/src/routes/anthropic.ts+++ b/server/src/routes/anthropic.ts@@ -592,7 +592,11 @@ export async function handleMessages(req: Request, res: Response): Promise<void>//// Only the pinned paths change. A Claude family alias mapped to 'auto' (the// default for opus/sonnet/haiku/default) resolves to no model at all and- // keeps auto-routing over the full chain exactly as before.+ // keeps auto-routing over the full chain exactly as before. A tier selector+ // (`tier:pro|mid|normal`) resolves to the tier's whole enabled pool and+ // routes over it as a chain, so the tier acts as a capability band the+ // router scores inside — failover stays within the band instead of falling+ // off to an unrelated model.let groupChain: ChainRow[] | undefined;// Sticky scope for a group-pinned request: bucket by the pinned catalog id so// the session prefers its last successful provider of THIS model without@@ -611,6 +615,16 @@ export async function handleMessages(req: Request, res: Response): Promise<void>stickyScope = resolved.modelId;}}+ } else if (resolved.tierDbIds && resolved.tierDbIds.length > 0) {+ const chain = resolveModelGroupCandidates(resolved.tierDbIds);+ if (chain.length > 0) {+ groupChain = chain;+ // Scoped per tier, not per model: a session on tier:sonnet keeps its+ // provider affinity when the operator re-points the family at another+ // tier selector only if the scope follows the tier. Use the family's+ // first tier id — stable per tier selector, distinct from any model id.+ stickyScope = `tier:${resolved.tierDbIds[0]}`;+ }}let preferredModel = resolved.preferredModelDbId;diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.tsindex d459a42b..74b70467 100644--- a/server/src/routes/settings.ts+++ b/server/src/routes/settings.ts@@ -162,7 +162,9 @@ settingsRouter.get('/anthropic-map', (_req: Request, res: Response) => {});// Update the Claude Code model map. Partial: send just the families you want to-// change; each value is 'auto' or a catalog model_id.+// change; each value is 'auto', a catalog model_id, or a tier selector+// (`tier:pro` | `tier:mid` | `tier:normal`) that routes over the whole+// capability tier instead of one model.settingsRouter.put('/anthropic-map', (req: Request, res: Response) => {try {res.json({ map: setClaudeModelMap(req.body) });diff --git a/server/src/services/anthropic-map.ts b/server/src/services/anthropic-map.tsindex 75f35c8e..13607afc 100644--- a/server/src/services/anthropic-map.ts+++ b/server/src/services/anthropic-map.ts@@ -16,7 +16,8 @@ const SETTING_KEY = 'anthropic_model_map';export const CLAUDE_FAMILIES = ['default', 'opus', 'sonnet', 'haiku'] as const;export type ClaudeFamily = (typeof CLAUDE_FAMILIES)[number];-// Each value is either the sentinel 'auto' or a catalog model_id.+// Each value is either the sentinel 'auto', a catalog model_id, or a tier+// selector `tier:pro|mid|normal` (see resolveTierModel below).export type AnthropicModelMap = Record<ClaudeFamily, string>;const DEFAULT_MAP: AnthropicModelMap = { default: 'auto', opus: 'auto', sonnet: 'auto', haiku: 'auto' };@@ -28,6 +29,25 @@ export const anthropicModelMapSchema = z.object({haiku: z.string().min(1).optional(),}).strict();+// Tier selectors reuse the V17 intelligence tiers (size_label) as the+// capability axis: pro → Frontier, mid → Large, normal → Medium+Small.+export const TIER_SELECTORS = ['tier:pro', 'tier:mid', 'tier:normal'] as const;+export type TierSelector = (typeof TIER_SELECTORS)[number];++const TIER_SIZE_LABELS: Record<Exclude<TierSelector, never>, string[]> = {+ 'tier:pro': ['Frontier'],+ 'tier:mid': ['Large'],+ // normal deliberately absorbs Small too: the bottom of the free pool is+ // still a valid "cheap tier" target, and excluding it would strand the+ // smallest providers.+ 'tier:normal': ['Medium', 'Small'],+};++export function parseTierSelector(value: string): TierSelector | null {+ const v = value.trim().toLowerCase();+ return (TIER_SELECTORS as readonly string[]).includes(v) ? (v as TierSelector) : null;+}+export function getClaudeModelMap(): AnthropicModelMap {const raw = getSetting(SETTING_KEY);if (!raw) return { ...DEFAULT_MAP };@@ -83,6 +103,26 @@ export interface ResolvedAnthropicModel {modelId?: string;// True when we resolved to a specific model (for analytics/pinned labels).pinned: boolean;+ // When a tier selector matched, the db ids of EVERY enabled model in that+ // tier. The caller routes over this pool as a chain (tier order, then the+ // usual score order inside it) instead of the full catalog.+ tierDbIds?: number[];+}++// Resolve the db ids of every enabled model whose size_label belongs to the+// tier, ordered by the same chain priority the rest of the router uses.+function lookupTierDbIds(tier: TierSelector): number[] {+ const labels = TIER_SIZE_LABELS[tier];+ const placeholders = labels.map(() => '?').join(', ');+ const db = getDb();+ const rows = db.prepare(`+ SELECT m.id as id+ FROM models m+ LEFT JOIN fallback_config fc ON fc.model_db_id = m.id+ WHERE m.enabled = 1 AND m.size_label IN (${placeholders})+ ORDER BY COALESCE(fc.priority, 0) ASC, m.id ASC+ `).all(...labels) as { id: number }[];+ return rows.map(r => r.id);}// Resolve the model a `/v1/messages` request should route to, honoring the@@ -108,6 +148,16 @@ export function resolveAnthropicModel(model?: string): ResolvedAnthropicModel {const family = classifyClaudeFamily(model);if (family) {const target = getClaudeModelMap()[family];+ // A tier selector routes over the whole tier pool rather than pinning one+ // model: `pinned` stays false (it is not a single model), and the caller+ // restricts the chain to tierDbIds.+ const tier = target ? parseTierSelector(target) : null;+ if (tier) {+ const tierDbIds = lookupTierDbIds(tier);+ // An empty tier (operator re-labeled everything, or labels not yet+ // seeded) degrades gracefully to auto rather than failing the request.+ return tierDbIds.length ? { pinned: false, tierDbIds } : { pinned: false };+ }if (!target || target === 'auto') return { pinned: false };const row = lookupEnabled(target);// A pinned-but-now-disabled/removed target degrades gracefully to auto.