feat(router): smart routers and per-member rate limits (#9)

Add smart routers: virtual models that score each request and route it to admin-defined model tiers. A retryable failure moves the request to a higher tier. The classifier v2 extracts prose, finds the original ask in long tool loops, adds an uncertainty margin and reads tool-output failures. Sessions, outcome signals, bounded calibration, adaptive selection within a tier, gated saturation downgrade, a first-byte timeout and an opt-in timeout fallback are included. Every new feature is off by default.

Add per-member group limits, a tokensPerMinute window that counts uncached input and output, rate-limit headers in three dialects, soft pacing before the hard limit, and a limitExemptKinds list so embedding and reranking traffic never counts toward or hits a limit.

Fix yaegi named-result state that made smartContentSize grow between calls.
This commit is contained in:
2026-11-25 00:40:30 +00:00
committed by GitHub
parent 6fb048b599
commit 4c61d19a72
154 changed files with 73356 additions and 286 deletions
+7 -4
View File
@@ -5,12 +5,13 @@ import GrantForm from '@/components/forms/GrantForm.vue'
import LimitsForm from '@/components/forms/LimitsForm.vue'
import ModelMetaForm from '@/components/forms/ModelMetaForm.vue'
import PricingForm from '@/components/forms/PricingForm.vue'
import RouterForm from '@/components/forms/RouterForm.vue'
import UserForm from '@/components/forms/UserForm.vue'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useNavStore } from '@/stores/nav'
/** HELPER_IDS mirrors the Config page's own `helper` hash param (redesign-plan.md section 3.1: `helper=limits|grant|pricing|model|user`) — the single source of truth for which tab is selected and which form renders. */
const HELPER_IDS = ['limits', 'grant', 'pricing', 'model', 'user'] as const
/** HELPER_IDS mirrors the Config page's own `helper` hash param (redesign-plan.md section 3.1: `helper=limits|grant|pricing|model|router|user`) — the single source of truth for which tab is selected and which form renders. */
const HELPER_IDS = ['limits', 'grant', 'pricing', 'model', 'router', 'user'] as const
type HelperId = (typeof HELPER_IDS)[number]
const HELPER_LABEL: Record<HelperId, string> = {
@@ -18,13 +19,14 @@ const HELPER_LABEL: Record<HelperId, string> = {
grant: 'Access grant',
pricing: 'Pricing',
model: 'Model metadata',
router: 'Smart router',
user: 'New user',
}
/**
* ChangeHelper (redesign-plan.md section 3.4) is the Config page's
* snippet-building surface: five forms (LimitsForm, GrantForm,
* PricingForm, ModelMetaForm, UserForm), each producing a paste-ready
* snippet-building surface: six forms (LimitsForm, GrantForm,
* PricingForm, ModelMetaForm, RouterForm, UserForm), each producing a paste-ready
* YAML/users.json fragment via lib/snippets.ts, switched by the page's own
* `helper` hash param so a shared link opens the same tab.
*/
@@ -58,6 +60,7 @@ function setHelper(next: unknown): void {
<GrantForm v-else-if="helper === 'grant'" :group-names="props.groupNames" :user-names="props.userNames" />
<PricingForm v-else-if="helper === 'pricing'" />
<ModelMetaForm v-else-if="helper === 'model'" />
<RouterForm v-else-if="helper === 'router'" />
<UserForm v-else :group-names="props.groupNames" />
</div>
</template>
+2 -1
View File
@@ -412,7 +412,8 @@ function groupsCsv(): string {
</DetailField>
</dl>
<dl class="mb-3 grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm sm:grid-cols-4">
<DetailField label="Limits">{{ formatLimits(row.original.limits) }}</DetailField>
<DetailField label="Limits">{{ formatLimits(row.original.limits, row.original.limitSources) }}</DetailField>
<DetailField v-if="row.original.memberLimits" label="Member limits">{{ formatLimits(row.original.memberLimits) }}</DetailField>
<DetailField label="req/min" numeric>
<template v-if="row.original.storeDown">?</template>
<CompactNumber v-else :value="row.original.requestsPerMinute" />
@@ -0,0 +1,224 @@
import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { describe, expect, it } from 'vitest'
import SmartRoutersCard from '@/components/SmartRoutersCard.vue'
import type { AdminRouterView } from '@/types/api'
const router: AdminRouterView = {
name: 'auto',
defaultTier: 'small',
selection: 'hash',
maxAttempts: 3,
contextEscalation: false,
shadowEnabled: false,
classifier: 'v1',
riskZ: 128,
calibration: { mode: 'off', delta: [], maxLower: 150, maxRaise: 0, freeze: false },
saturationDowngrade: false,
downgradeBand: 100,
downgraded: 0,
timeoutFallback: false,
fellBack: 0,
tiers: [
{ name: 'small', minScore: 0, models: ['openai/gpt-5-mini'] },
{ name: 'big', minScore: 400, models: ['anthropic/claude-opus', 'openai/gpt-5'] },
],
keywordRules: [{ tier: 'big', keywords: ['prove', 'audit'] }],
contextTokens: 262144,
stats: {
scope: 'shared',
requests: 4,
tiers: [
{ name: 'small', count: 1 },
{ name: 'big', count: 3 },
],
reasons: [
{ name: 'keyword', count: 1 },
{ name: 'score', count: 3 },
],
escalations: [{ from: 'small', to: 'big', count: 2 }],
shadow: [],
outcomes: [],
},
}
function render(routers: AdminRouterView[]): Promise<string> {
return renderToString(createSSRApp(SmartRoutersCard, { routers }))
}
describe('SmartRoutersCard', () => {
it('shows an empty message with no routers', async () => {
expect(await render([])).toContain('None configured.')
})
it('shows calibration, adaptive selection and downgrade settings', async () => {
const live: AdminRouterView = {
...router,
selection: 'adaptive',
adaptive: { explorePct: 5, windowHours: 6, latencyWeightPct: 30 },
calibration: { mode: 'shadow', delta: [{ tier: 'big', delta: 25 }], maxLower: 150, maxRaise: 0, freeze: false },
saturationDowngrade: true,
downgradeBand: 100,
downgraded: 7,
}
const html = await render([live])
expect(html).toContain('selection: adaptive')
expect(html).toContain('explore 5%, window 6h')
expect(html).toContain('calibration: shadow')
expect(html).toContain('offsets (not applied): big -25')
expect(html).toContain('saturation downgrade: on, band 100')
expect(html).toContain('downgraded: 7')
const off = await render([router])
expect(off).toContain('calibration: off')
expect(off).toContain('saturation downgrade: off')
expect(off).not.toContain('offsets')
expect(off).not.toContain('explore')
expect(off).not.toContain('downgraded:')
})
it('shows the timeout fallback flag and its count only when on', async () => {
const on = await render([{ ...router, timeoutFallback: true, fellBack: 3 }])
expect(on).toContain('timeout fallback: on')
expect(on).toContain('fell back: 3')
const off = await render([router])
expect(off).toContain('timeout fallback: off')
expect(off).not.toContain('fell back:')
})
it('renders router settings, tiers and keyword rules', async () => {
const html = await render([router])
expect(html).toContain('Smart routers')
expect(html).toContain('auto')
expect(html).toContain('default tier: small')
expect(html).toContain('selection: hash')
expect(html).toContain('max attempts: 3')
expect(html).toContain('context escalation: off')
expect(html).toContain('from score 400')
expect(html).toContain('anthropic/claude-opus, openai/gpt-5')
expect(html).toContain('prove, audit')
})
it('shows the first byte timeout only when set', async () => {
expect(await render([{ ...router, firstByteTimeout: '40s' }])).toContain('first byte timeout: 40s')
expect(await render([router])).not.toContain('first byte timeout')
})
it('shows the tools min tier only when set', async () => {
expect(await render([{ ...router, toolsMinTier: 'big' }])).toContain('tools min tier: big')
expect(await render([router])).not.toContain('tools min tier')
})
it('shows the classifier and the risk margin only when v2 is involved', async () => {
const plain = await render([router])
expect(plain).toContain('classifier: v1')
expect(plain).not.toContain('risk z')
expect(plain).not.toContain('shadow classifier')
const shadowed = await render([{ ...router, shadowEnabled: true, shadowClassifier: 'v2', riskZ: 90 }])
expect(shadowed).toContain('shadow classifier: v2')
expect(shadowed).toContain('risk z: 90')
expect(await render([{ ...router, classifier: 'v2' }])).toContain('risk z: 128')
})
it('renders the shadow agreement matrix only when shadow weights are set', async () => {
const shadowed: AdminRouterView = {
...router,
shadowEnabled: true,
stats: {
...router.stats!,
shadow: [
{ live: 'small', shadow: 'small', count: 6 },
{ live: 'big', shadow: 'small', count: 2 },
{ live: 'big', shadow: 'big', count: 2 },
],
},
}
const html = await render([shadowed])
expect(html).toContain('Shadow weights')
expect(html).toContain('aria-label="Shadow agreement matrix for auto"')
expect(html).toContain('agreement: 80%')
expect(html).toMatch(/<th[^>]*>small<\/th>/)
expect(html).toMatch(/data-cell="big:small"[^>]*>2</)
expect(html).toMatch(/data-cell="small:big"[^>]*>0</)
expect(await render([router])).not.toContain('Shadow weights')
})
it('shows an empty shadow matrix without NaN', async () => {
const html = await render([{ ...router, shadowEnabled: true }])
expect(html).toContain('Shadow weights')
expect(html).toContain('agreement: 0%')
expect(html).not.toContain('NaN')
})
it('renders outcome counts per tier summed over reasons', async () => {
const withOutcomes: AdminRouterView = {
...router,
stats: {
...router.stats!,
outcomes: [
{ tier: 'small', reason: 'score', outcome: 'ok', count: 3 },
{ tier: 'small', reason: 'keyword', outcome: 'ok', count: 1 },
{ tier: 'small', reason: 'score', outcome: 'escalated', count: 2 },
{ tier: 'big', reason: 'score', outcome: 'error', count: 1 },
{ tier: 'big', reason: 'score', outcome: 'bad', count: 2 },
{ tier: 'big', reason: 'score', outcome: 'slow', count: 5 },
{ tier: 'big', reason: 'keyword', outcome: 'slow', count: 1 },
],
},
}
const html = await render([withOutcomes])
expect(html).toContain('aria-label="Outcomes for auto"')
expect(html).toMatch(/data-cell="small:ok"[^>]*>4</)
expect(html).toMatch(/data-cell="small:escalated"[^>]*>2</)
expect(html).toMatch(/data-cell="big:error"[^>]*>1</)
expect(html).toMatch(/data-cell="big:bad"[^>]*>2</)
expect(html).toMatch(/<th[^>]*>slow<\/th>/)
expect(html).toMatch(/data-cell="big:slow"[^>]*>6</)
expect(html).toMatch(/data-cell="small:slow"[^>]*>0</)
expect(await render([router])).not.toContain('Outcomes for')
})
it('labels shadow and outcome scope like the other counts', async () => {
const html = await render([{ ...router, shadowEnabled: true, stats: { ...router.stats!, scope: 'instance' } }])
expect(html).toContain('This gateway instance, since start')
})
it('shows the context window, per-tier counts and shares, reasons and escalations', async () => {
const html = await render([router])
expect(html).toContain('context window: 256k')
expect(html).toContain('requests: 4')
expect(html).toContain('1 req (25%)')
expect(html).toContain('3 req (75%)')
expect(html).toContain('width:75%')
expect(html).toContain('keyword: 1')
expect(html).toContain('score: 3')
expect(html).toMatch(/Escalated[\s\S]*small[\s\S]*to[\s\S]*big[\s\S]*: 2/)
expect(html).toContain('All replicas, this month (UTC)')
})
it('labels per-instance counts when Redis is not shared', async () => {
const html = await render([{ ...router, stats: { ...router.stats!, scope: 'instance' } }])
expect(html).toContain('This gateway instance, since start')
expect(html).not.toContain('All replicas')
})
it('renders zero counts and no window without stats', async () => {
const { contextTokens: _c, stats: _s, ...bare } = router
const html = await render([bare])
expect(html).not.toContain('context window:')
expect(html).toContain('requests: 0')
expect(html).toContain('0 req (0%)')
expect(html).not.toContain('Routing reasons')
expect(html).not.toContain('Escalated')
})
it('handles zero-filled stats without dividing by zero', async () => {
const zero: AdminRouterView = {
...router,
stats: { scope: 'instance', requests: 0, tiers: [{ name: 'small', count: 0 }, { name: 'big', count: 0 }], reasons: [], escalations: [], shadow: [], outcomes: [] },
}
const html = await render([zero])
expect(html).toContain('0 req (0%)')
expect(html).not.toContain('NaN')
})
})
+180
View File
@@ -0,0 +1,180 @@
<script setup lang="ts">
import { computed } from 'vue'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { formatContextWindow } from '@/lib/format'
import type { AdminRouterView } from '@/types/api'
/**
* SmartRoutersCard is the Models page's read-only view of every configured
* smart router (admin_routers.go): tiers cheapest first with their score
* floor and models, plus selection, attempt cap and keyword rules. Config
* lives in the plugin config; use the Config page's router helper to build a
* snippet. Counts are fleet-wide per month with Redis, else per process.
*/
const props = defineProps<{
routers: AdminRouterView[]
}>()
const scopeLabel = computed(() =>
props.routers.some((r) => r.stats?.scope === 'shared') ? 'Counts: All replicas, this month (UTC)' : 'Counts: This gateway instance, since start',
)
const OUTCOMES = ['ok', 'escalated', 'error', 'bad', 'slow'] as const
function shadowCount(router: AdminRouterView, live: string, shadow: string): number {
return router.stats?.shadow.find((c) => c.live === live && c.shadow === shadow)?.count ?? 0
}
function shadowAgreement(router: AdminRouterView): number {
const cells = router.stats?.shadow ?? []
const total = cells.reduce((sum, c) => sum + c.count, 0)
const same = cells.filter((c) => c.live === c.shadow).reduce((sum, c) => sum + c.count, 0)
return share(same, total)
}
function outcomeCount(router: AdminRouterView, tier: string, outcome: string): number {
return (router.stats?.outcomes ?? []).filter((o) => o.tier === tier && o.outcome === outcome).reduce((sum, o) => sum + o.count, 0)
}
function deltaLabel(router: AdminRouterView): string {
return router.calibration.delta.map((d) => `${d.tier} -${d.delta}`).join(', ')
}
function share(count: number, total: number): number {
return total > 0 ? Math.round((count / total) * 100) : 0
}
</script>
<template>
<Card>
<CardHeader>
<CardTitle>Smart routers</CardTitle>
<CardDescription>Virtual models that pick a tier by request complexity and escalate on failure. {{ scopeLabel }}.</CardDescription>
</CardHeader>
<CardContent class="flex flex-col gap-4">
<p v-if="routers.length === 0" class="text-sm text-muted-foreground">None configured.</p>
<section v-for="router in routers" :key="router.name" class="flex flex-col gap-2" :aria-label="`Router ${router.name}`">
<div class="flex flex-wrap items-center gap-2">
<span class="font-mono text-sm font-medium">{{ router.name }}</span>
<Badge variant="outline" class="font-normal">default tier: {{ router.defaultTier }}</Badge>
<Badge v-if="router.toolsMinTier" variant="outline" class="font-normal">tools min tier: {{ router.toolsMinTier }}</Badge>
<Badge variant="outline" class="font-normal">classifier: {{ router.classifier }}</Badge>
<Badge v-if="router.shadowClassifier" variant="outline" class="font-normal">shadow classifier: {{ router.shadowClassifier }}</Badge>
<Badge v-if="router.classifier === 'v2' || router.shadowClassifier" variant="outline" class="font-normal">risk z: {{ router.riskZ }}</Badge>
<Badge variant="outline" class="font-normal">selection: {{ router.selection }}</Badge>
<Badge v-if="router.adaptive" variant="outline" class="font-normal">
explore {{ router.adaptive.explorePct }}%, window {{ router.adaptive.windowHours }}h
</Badge>
<Badge variant="outline" class="font-normal">calibration: {{ router.calibration.mode }}</Badge>
<Badge v-if="router.calibration.mode !== 'off' && router.calibration.freeze" variant="outline" class="font-normal">
calibration frozen
</Badge>
<Badge v-if="router.calibration.mode !== 'off'" variant="outline" class="font-normal">
offsets{{ router.calibration.mode === 'shadow' ? ' (not applied)' : '' }}: {{ deltaLabel(router) }}
</Badge>
<Badge variant="outline" class="font-normal">
saturation downgrade: {{ router.saturationDowngrade ? `on, band ${router.downgradeBand}` : 'off' }}
</Badge>
<Badge v-if="router.saturationDowngrade" variant="secondary" class="font-normal">downgraded: {{ router.downgraded }}</Badge>
<Badge variant="outline" class="font-normal">timeout fallback: {{ router.timeoutFallback ? 'on' : 'off' }}</Badge>
<Badge v-if="router.timeoutFallback" variant="secondary" class="font-normal">fell back: {{ router.fellBack }}</Badge>
<Badge variant="outline" class="font-normal">max attempts: {{ router.maxAttempts }}</Badge>
<Badge v-if="router.firstByteTimeout" variant="outline" class="font-normal">
first byte timeout: {{ router.firstByteTimeout }}
</Badge>
<Badge variant="outline" class="font-normal">context escalation: {{ router.contextEscalation ? 'on' : 'off' }}</Badge>
<Badge v-if="router.contextTokens" variant="outline" class="font-normal">
context window: {{ formatContextWindow(router.contextTokens) }}
</Badge>
<Badge variant="secondary" class="font-normal">requests: {{ router.stats?.requests ?? 0 }}</Badge>
</div>
<ol class="flex flex-col gap-1 text-sm">
<li v-for="(tier, index) in router.tiers" :key="tier.name" class="flex flex-col gap-1">
<div class="flex flex-wrap items-baseline gap-2">
<span class="font-medium">{{ tier.name }}</span>
<span class="text-xs text-muted-foreground">from score {{ tier.minScore }}</span>
<span class="font-mono text-xs break-all">{{ tier.models.join(', ') }}</span>
<span class="ml-auto text-xs tabular-nums text-muted-foreground">
{{ router.stats?.tiers[index]?.count ?? 0 }} req ({{ share(router.stats?.tiers[index]?.count ?? 0, router.stats?.requests ?? 0) }}%)
</span>
</div>
<div class="h-1.5 w-full overflow-hidden rounded-full bg-muted" aria-hidden="true">
<div
class="h-full rounded-full bg-primary"
:style="{ width: `${share(router.stats?.tiers[index]?.count ?? 0, router.stats?.requests ?? 0)}%` }"
/>
</div>
</li>
</ol>
<p v-if="router.stats && router.stats.reasons.length > 0" class="flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
Routing reasons:
<Badge v-for="reason in router.stats.reasons" :key="reason.name" variant="outline" class="font-normal">
{{ reason.name }}: {{ reason.count }}
</Badge>
</p>
<ul v-if="router.stats && router.stats.escalations.length > 0" class="flex flex-col gap-0.5 text-xs text-muted-foreground">
<li v-for="esc in router.stats.escalations" :key="`${esc.from}>${esc.to}`">
Escalated <span class="font-medium">{{ esc.from }}</span> to <span class="font-medium">{{ esc.to }}</span>:
{{ esc.count }}
</li>
</ul>
<div v-if="router.shadowEnabled" class="flex flex-col gap-1">
<p class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span class="font-medium">Shadow weights</span>
<span>Live tier (rows) against shadow tier (columns). No effect on routing.</span>
<Badge variant="outline" class="font-normal">agreement: {{ shadowAgreement(router) }}%</Badge>
</p>
<table class="w-fit text-xs tabular-nums" :aria-label="`Shadow agreement matrix for ${router.name}`">
<thead>
<tr>
<th class="px-2 py-0.5" />
<th v-for="col in router.tiers" :key="col.name" scope="col" class="px-2 py-0.5 text-right font-medium">{{ col.name }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in router.tiers" :key="row.name">
<th scope="row" class="px-2 py-0.5 text-left font-medium">{{ row.name }}</th>
<td
v-for="col in router.tiers"
:key="col.name"
:data-cell="`${row.name}:${col.name}`"
class="px-2 py-0.5 text-right"
:class="row.name === col.name ? 'bg-muted font-medium' : 'text-muted-foreground'"
>
{{ shadowCount(router, row.name, col.name) }}
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="router.stats && router.stats.outcomes.length > 0" class="flex flex-col gap-1">
<p class="text-xs text-muted-foreground">
<span class="font-medium">Outcomes</span> by first attempted tier. Escalated means a higher tier served it; error means a final non-2xx; slow means an attempt missed the first-byte timeout.
</p>
<table class="w-fit text-xs tabular-nums" :aria-label="`Outcomes for ${router.name}`">
<thead>
<tr>
<th class="px-2 py-0.5" />
<th v-for="outcome in OUTCOMES" :key="outcome" scope="col" class="px-2 py-0.5 text-right font-medium">{{ outcome }}</th>
</tr>
</thead>
<tbody>
<tr v-for="tier in router.tiers" :key="tier.name">
<th scope="row" class="px-2 py-0.5 text-left font-medium">{{ tier.name }}</th>
<td v-for="outcome in OUTCOMES" :key="outcome" :data-cell="`${tier.name}:${outcome}`" class="px-2 py-0.5 text-right">
{{ outcomeCount(router, tier.name, outcome) }}
</td>
</tr>
</tbody>
</table>
</div>
<p v-for="(rule, index) in router.keywordRules" :key="index" class="text-xs text-muted-foreground">
Keywords to <span class="font-medium">{{ rule.tier }}</span
>: <span class="font-mono">{{ rule.keywords.join(', ') }}</span>
</p>
</section>
</CardContent>
</Card>
</template>
+4 -1
View File
@@ -187,11 +187,14 @@ const runOutDate = computed(() => {
</CardContent>
<CardContent v-else class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
<StatItem label="Requests/day"><CompactNumber :value="entry.requestsPerDay" /></StatItem>
<StatItem v-if="entry.exemptRequestsPerMonth" label="Exempt requests/month">
<CompactNumber :value="entry.exemptRequestsPerMonth" />
</StatItem>
<StatItem label="Cost/day">{{ formatCostDisplay(entry.costPerDayMicroUsd) }}</StatItem>
<StatItem label="Cost/month">{{ formatCostDisplay(entry.costPerMonthMicroUsd) }}</StatItem>
<div>
<p class="text-muted-foreground">Limits</p>
<p class="text-sm">{{ formatLimits(entry.limits) }}</p>
<p class="text-sm">{{ formatLimits(entry.limits, entry.limitSources) }}</p>
</div>
</CardContent>
</Card>
+21 -10
View File
@@ -1,13 +1,13 @@
<script setup lang="ts">
import { computed, reactive } from 'vue'
import { computed, reactive, ref } from 'vue'
import TargetPicker from '@/components/forms/TargetPicker.vue'
import SnippetBlock from '@/components/SnippetBlock.vue'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Input } from '@/components/ui/input'
import { useTargetPicker } from '@/composables/useTargetPicker'
import { groupLimitsSnippet, isValidNonNegative, isValidNonNegativeInt, userLimitsJsonFragment } from '@/lib/snippets'
import type { LimitsConfig } from '@/types/api'
import { groupLimitsSnippet, groupMemberLimitsSnippet, isValidNonNegative, isValidNonNegativeInt, userLimitsJsonFragment } from '@/lib/snippets'
import type { LimitKey, LimitsConfig } from '@/types/api'
/**
* LimitsForm (ChangeHelper, redesign-plan.md section 3.4) builds a
@@ -29,25 +29,27 @@ const { targetKind, targetName, targetNames, nameValid, snippetLabel } = useTarg
)
/** INTEGER_FIELDS is every LimitsConfig field Go decodes as `int64` (llmgateway.go) — requestsPerMinute/requestsPerDay/tokensPerDay/tokensPerMonth reject a fractional value like "1.5" at json.Unmarshal outright (P2 item 12), unlike costPerDayUSD/costPerMonthUSD, which are `float64`. */
const INTEGER_FIELDS = new Set<keyof LimitsConfig>(['requestsPerMinute', 'requestsPerDay', 'tokensPerDay', 'tokensPerMonth'])
const INTEGER_FIELDS = new Set<LimitKey>(['requestsPerMinute', 'requestsPerDay', 'tokensPerMinute', 'tokensPerDay', 'tokensPerMonth'])
/** fieldValid applies isValidNonNegativeInt to the four int64 fields and isValidNonNegative (fractions allowed) to the two float64 cost fields — the ONE gate both invalidFields and limits below share, so they can never disagree on which fields are int-only. */
function fieldValid(key: keyof LimitsConfig, value: number): boolean {
function fieldValid(key: LimitKey, value: number): boolean {
return INTEGER_FIELDS.has(key) ? isValidNonNegativeInt(value) : isValidNonNegative(value)
}
const FIELDS: { key: keyof LimitsConfig; label: string }[] = [
const FIELDS: { key: LimitKey; label: string }[] = [
{ key: 'requestsPerMinute', label: 'Requests/minute' },
{ key: 'requestsPerDay', label: 'Requests/day' },
{ key: 'tokensPerMinute', label: 'Tokens/minute (in+out)' },
{ key: 'tokensPerDay', label: 'Tokens/day (in+out)' },
{ key: 'tokensPerMonth', label: 'Tokens/month (in+out)' },
{ key: 'costPerDayUSD', label: 'Cost/day (USD)' },
{ key: 'costPerMonthUSD', label: 'Cost/month (USD)' },
]
const raw = reactive<Record<keyof LimitsConfig, string>>({
const raw = reactive<Record<LimitKey, string>>({
requestsPerMinute: '',
requestsPerDay: '',
tokensPerMinute: '',
tokensPerDay: '',
tokensPerMonth: '',
costPerDayUSD: '',
@@ -78,12 +80,16 @@ const limits = computed<LimitsConfig>(() => {
return out
})
/** perMember emits the group's values as `memberLimits` (one counter per member user) instead of the shared aggregate `limits`; only meaningful for a group target. */
const perMember = ref(false)
const snippet = computed<string | null>(() => {
if (!nameValid.value || invalidFields.value.length > 0) return null
if (Object.keys(limits.value).length === 0) return null
return targetKind.value === 'group'
? groupLimitsSnippet(targetName.value.trim(), limits.value)
: userLimitsJsonFragment(limits.value)
if (targetKind.value !== 'group') return userLimitsJsonFragment(limits.value)
return perMember.value
? groupMemberLimitsSnippet(targetName.value.trim(), limits.value)
: groupLimitsSnippet(targetName.value.trim(), limits.value)
})
</script>
@@ -98,6 +104,11 @@ const snippet = computed<string | null>(() => {
@update:target-name="targetName = $event"
/>
<label v-if="targetKind === 'group'" class="flex items-center gap-2 text-sm">
<input id="limits-per-member" v-model="perMember" type="checkbox" />
Per member (each user gets their own counter) instead of one shared group total
</label>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
<div v-for="field in FIELDS" :key="field.key" class="flex flex-col gap-1">
<label :for="`limits-${field.key}`" class="text-xs font-medium text-muted-foreground">{{ field.label }}</label>
+124
View File
@@ -0,0 +1,124 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import SnippetBlock from '@/components/SnippetBlock.vue'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Input } from '@/components/ui/input'
import { isValidName, parseList, routerSnippet, validateRouter } from '@/lib/snippets'
import type { RouterInput } from '@/lib/snippets'
/**
* RouterForm (ChangeHelper) builds one `smartRouters` entry
* (SmartRouterConfig, smart_router.go): up to three tiers, cheapest first,
* and one optional keyword rule. A tier row with an empty name is ignored.
* Validation lives in lib/snippets.ts's validateRouter, which mirrors the
* gateway's own startup checks.
*/
const TIER_ROWS = 3
interface TierRow {
name: string
minScore: string
models: string
}
const routerName = ref('')
const tierRows = ref<TierRow[]>(
Array.from({ length: TIER_ROWS }, (_, i) => ({ name: '', minScore: i === 0 ? '0' : '', models: '' })),
)
const ruleTier = ref('')
const ruleKeywords = ref('')
const selection = ref<'ordered' | 'hash'>('ordered')
const maxAttemptsRaw = ref('')
const contextEscalation = ref(true)
const nameValid = computed(() => isValidName(routerName.value.trim()))
const router = computed<RouterInput>(() => ({
tiers: tierRows.value
.filter((row) => row.name.trim() !== '')
.map((row) => ({
name: row.name.trim(),
minScore: row.minScore.trim() === '' ? Number.NaN : Number(row.minScore),
models: parseList(row.models),
})),
keywordRules: ruleTier.value.trim() === '' && ruleKeywords.value.trim() === '' ? [] : [{ tier: ruleTier.value.trim(), keywords: parseList(ruleKeywords.value) }],
selection: selection.value,
maxAttempts: maxAttemptsRaw.value.trim() === '' ? 0 : Number(maxAttemptsRaw.value),
contextEscalation: contextEscalation.value,
}))
const errors = computed(() => {
const out: string[] = []
if (routerName.value.trim() !== '' && !nameValid.value) out.push('Router name may only use letters, digits, dot, underscore and hyphen.')
if (router.value.tiers.length > 0) out.push(...validateRouter(router.value))
return out
})
const snippet = computed<string | null>(() => {
if (!nameValid.value || router.value.tiers.length === 0 || errors.value.length > 0) return null
return routerSnippet(routerName.value.trim(), router.value)
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-1">
<label for="router-name" class="text-xs font-medium text-muted-foreground">Router name (the model clients request)</label>
<Input id="router-name" v-model="routerName" placeholder="auto" class="font-mono" />
</div>
<div v-for="(row, index) in tierRows" :key="index" class="grid grid-cols-1 gap-3 sm:grid-cols-[1fr_8rem_2fr]">
<div class="flex flex-col gap-1">
<label :for="`router-tier-name-${index}`" class="text-xs font-medium text-muted-foreground">Tier {{ index + 1 }} name</label>
<Input :id="`router-tier-name-${index}`" v-model="row.name" :placeholder="['small', 'medium', 'large'][index]" />
</div>
<div class="flex flex-col gap-1">
<label :for="`router-tier-score-${index}`" class="text-xs font-medium text-muted-foreground">Min score (0-1000)</label>
<Input :id="`router-tier-score-${index}`" v-model="row.minScore" type="number" min="0" max="1000" step="1" />
</div>
<div class="flex flex-col gap-1">
<label :for="`router-tier-models-${index}`" class="text-xs font-medium text-muted-foreground">Models (comma-separated)</label>
<Input :id="`router-tier-models-${index}`" v-model="row.models" placeholder="openai/gpt-5-mini, gx10/current" class="font-mono" />
</div>
</div>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-[1fr_2fr]">
<div class="flex flex-col gap-1">
<label for="router-rule-tier" class="text-xs font-medium text-muted-foreground">Keyword rule tier (optional)</label>
<Input id="router-rule-tier" v-model="ruleTier" placeholder="large" />
</div>
<div class="flex flex-col gap-1">
<label for="router-rule-keywords" class="text-xs font-medium text-muted-foreground">Keywords (comma-separated)</label>
<Input id="router-rule-keywords" v-model="ruleKeywords" placeholder="prove, architecture review" />
</div>
</div>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3 sm:items-end">
<div class="flex flex-col gap-1">
<label for="router-selection" class="text-xs font-medium text-muted-foreground">Selection within a tier</label>
<select id="router-selection" v-model="selection" class="h-9 rounded-md border border-input bg-transparent px-3 text-sm">
<option value="ordered">ordered</option>
<option value="hash">hash</option>
</select>
</div>
<div class="flex flex-col gap-1">
<label for="router-max-attempts" class="text-xs font-medium text-muted-foreground">Max attempts (blank = 4)</label>
<Input id="router-max-attempts" v-model="maxAttemptsRaw" type="number" min="0" step="1" placeholder="4" />
</div>
<div class="flex items-center gap-2">
<input id="router-context-escalation" v-model="contextEscalation" type="checkbox" class="size-4 rounded border-input" />
<label for="router-context-escalation" class="text-xs font-medium text-muted-foreground">Skip models with too small a context window</label>
</div>
</div>
<Alert v-if="errors.length" id="router-errors" variant="destructive">
<AlertDescription>
<p v-for="(error, index) in errors" :key="index">{{ error }}</p>
</AlertDescription>
</Alert>
<SnippetBlock v-if="snippet" label="Paste into middleware.yaml" :text="snippet" />
<p v-else class="text-sm text-muted-foreground">Enter a router name and at least one tier with models to build a snippet.</p>
</div>
</template>
+27 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLatencyMs, formatModelCostHover, formatPercentAxis, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLimits, formatLatencyMs, formatModelCostHover, formatPercentAxis, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
describe('refreshLabel', () => {
it('reads "discovery off" when discovery is disabled, regardless of lastRefresh', () => {
@@ -300,3 +300,29 @@ describe('formatPercentAxis', () => {
expect(formatPercentAxis(rate)).toBe(want)
})
})
describe('formatLimits', () => {
it('returns none when unset or empty', () => {
expect(formatLimits(undefined)).toBe('none')
expect(formatLimits({})).toBe('none')
})
it('renders tokens per minute', () => {
expect(formatLimits({ tokensPerMinute: 500 })).toBe('tok/min 500')
})
it('renders pacing with its source', () => {
expect(formatLimits({ pacing: { startPct: 80, maxDelay: '10s' } }, { pacing: 'memberLimits:friends' })).toBe(
'pace from 80% up to 10s (memberLimits:friends)',
)
})
it('appends each field source when given', () => {
expect(
formatLimits(
{ requestsPerMinute: 9, tokensPerMinute: 100 },
{ requestsPerMinute: 'user', tokensPerMinute: 'memberLimits:friends' },
),
).toBe('req/min 9 (user), tok/min 100 (memberLimits:friends)')
})
})
+15 -8
View File
@@ -1,4 +1,4 @@
import type { HistoryWindow, LimitsConfig } from '@/types/api'
import type { HistoryWindow, LimitSources, LimitsConfig } from '@/types/api'
/** ZERO_TIME is Go's zero time.Time value in its default JSON (RFC 3339) encoding — the unset-timestamp sentinel every admin API "never happened yet" field marshals as, and every formatter/test below treats as absent. */
export const ZERO_TIME = '0001-01-01T00:00:00Z'
@@ -368,15 +368,22 @@ export function refreshDetailLabel(discoveryEnabled: boolean, lastRefresh: strin
}
/** formatLimits renders a LimitsConfig as a short comma-joined summary, or "none" when unset. */
export function formatLimits(limits: LimitsConfig | undefined): string {
export function formatLimits(limits: LimitsConfig | undefined, sources?: LimitSources): string {
if (!limits) return 'none'
const parts: string[] = []
if (limits.requestsPerMinute) parts.push(`req/min ${limits.requestsPerMinute}`)
if (limits.requestsPerDay) parts.push(`req/day ${limits.requestsPerDay}`)
if (limits.tokensPerDay) parts.push(`tok/day ${limits.tokensPerDay}`)
if (limits.tokensPerMonth) parts.push(`tok/month ${limits.tokensPerMonth}`)
if (limits.costPerDayUSD) parts.push(`cost/day $${limits.costPerDayUSD}`)
if (limits.costPerMonthUSD) parts.push(`cost/month $${limits.costPerMonthUSD}`)
const add = (key: keyof LimitsConfig, text: string) => {
if (!limits[key]) return
const source = sources?.[key]
parts.push(source ? `${text} (${source})` : text)
}
add('requestsPerMinute', `req/min ${limits.requestsPerMinute}`)
add('requestsPerDay', `req/day ${limits.requestsPerDay}`)
add('tokensPerMinute', `tok/min ${limits.tokensPerMinute}`)
add('tokensPerDay', `tok/day ${limits.tokensPerDay}`)
add('tokensPerMonth', `tok/month ${limits.tokensPerMonth}`)
add('costPerDayUSD', `cost/day $${limits.costPerDayUSD}`)
add('costPerMonthUSD', `cost/month $${limits.costPerMonthUSD}`)
if (limits.pacing) add('pacing', `pace from ${limits.pacing.startPct}% up to ${limits.pacing.maxDelay}`)
return parts.length ? parts.join(', ') : 'none'
}
+25
View File
@@ -256,3 +256,28 @@ describe('modelCatalogColumns: p50/p95/error rate columns', () => {
expect(accessor(testRow({ attempts: 10, failures: 0 }), 0)).toBe(0)
})
})
describe('buildModelCatalogRows: router targets', () => {
it('carries a model routers list and defaults to empty', () => {
const catalog = {
providers: [
{
name: 'openai',
type: 'openai',
lastRefresh: '',
openUntil: '',
healthState: 'closed',
discoveryEnabled: false,
models: [
{ id: 'openai/a', model: 'a', priceSource: 'unpriced', routers: ['auto'] },
{ id: 'openai/b', model: 'b', priceSource: 'unpriced' },
],
},
],
aliases: [],
routers: [],
} as unknown as AdminCatalogResponse
const rows = buildModelCatalogRows(catalog, { models: [] } as unknown as AdminUsageModelsResponse, { rows: [] } as unknown as AdminPerfResponse)
expect(rows.map((r) => r.routers)).toEqual([['auto'], []])
})
})
+18
View File
@@ -43,6 +43,8 @@ export interface ModelCatalogRow {
/** True for a ':free' suffix model — display-only; priceSource carries the real billing truth regardless (types/api.ts's own AdminCatalogModel doc comment). */
displayFree?: boolean
aliases: string[]
/** Smart routers that target this model. */
routers?: string[]
requests: number
tokensIn: number
tokensOut: number
@@ -83,6 +85,7 @@ export function buildModelCatalogRows(
priceSource: m.priceSource,
displayFree: m.displayFree,
aliases: m.aliases ?? [],
routers: m.routers ?? [],
requests: usage?.requests ?? 0,
tokensIn: usage?.tokensIn ?? 0,
tokensOut: usage?.tokensOut ?? 0,
@@ -194,6 +197,21 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
)
},
},
{
id: 'routers',
header: 'Routers',
enableSorting: false,
accessorFn: (r) => (r.routers ?? []).join(', '),
cell: ({ row }) => {
const routers = row.original.routers ?? []
if (routers.length === 0) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
return h(
'div',
{ class: 'flex flex-wrap gap-1' },
routers.map((r) => h(Badge, { key: r, as: 'span', variant: 'secondary', class: 'font-mono font-normal', title: 'Smart router target' }, () => r)),
)
},
},
// reuse-audit.md F9: requests/tokensIn/tokensOut share the shared
// usageMetricColumns factory; 'cost' stays hand-written below since
// this table's cost cell has an extra free-priced-model badge case
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import { routerSnippet, validateRouter } from './snippets'
import type { RouterInput } from './snippets'
const base: RouterInput = {
tiers: [
{ name: 'small', minScore: 0, models: ['openai/gpt-5-mini'] },
{ name: 'big', minScore: 400, models: ['anthropic/claude-opus', 'openai/gpt-5'] },
],
keywordRules: [],
selection: 'ordered',
maxAttempts: 0,
contextEscalation: true,
}
describe('routerSnippet: golden YAML, spec.plugin.llmgateway.smartRouters.<name>', () => {
it('omits every default', () => {
expect(routerSnippet('auto', base)).toBe(
[
'spec:',
' plugin:',
' llmgateway:',
' smartRouters:',
' auto:',
' tiers:',
' - {"name":"small","minScore":0,"models":["openai/gpt-5-mini"]}',
' - {"name":"big","minScore":400,"models":["anthropic/claude-opus","openai/gpt-5"]}',
].join('\n'),
)
})
it('states non-default selection, attempts, escalation and keyword rules', () => {
const out = routerSnippet('auto', {
...base,
selection: 'hash',
maxAttempts: 3,
contextEscalation: false,
keywordRules: [{ tier: 'big', keywords: ['prove'] }],
})
expect(out).toContain('keywordRules:')
expect(out).toContain('selection: hash')
expect(out).toContain('maxAttempts: 3')
expect(out).toContain('contextEscalation: false')
expect(out).toContain('"keywords":["prove"]')
})
})
describe('validateRouter', () => {
it('accepts a valid router', () => {
expect(validateRouter(base)).toEqual([])
})
it('rejects no tiers', () => {
expect(validateRouter({ ...base, tiers: [] })).toEqual(['Add at least one tier.'])
})
it('requires first minScore 0 and rising scores', () => {
const errs = validateRouter({
...base,
tiers: [
{ name: 'a', minScore: 100, models: ['m1'] },
{ name: 'b', minScore: 100, models: ['m2'] },
],
})
expect(errs.join(' ')).toContain('must have minScore 0')
expect(errs.join(' ')).toContain('greater than the previous')
})
it('rejects overlapping models, duplicate tiers and empty tiers', () => {
const errs = validateRouter({
...base,
tiers: [
{ name: 'a', minScore: 0, models: ['m1'] },
{ name: 'a', minScore: 10, models: ['m1'] },
{ name: 'c', minScore: 20, models: [] },
],
})
expect(errs.join(' ')).toContain('used twice')
expect(errs.join(' ')).toContain('must be disjoint')
expect(errs.join(' ')).toContain('needs at least one model')
})
it('rejects a keyword rule for an unknown tier', () => {
expect(validateRouter({ ...base, keywordRules: [{ tier: 'nope', keywords: ['x'] }] }).join(' ')).toContain('is not a tier')
})
})
+22
View File
@@ -5,6 +5,7 @@ import {
generateApiKey,
groupGrantSnippet,
groupLimitsSnippet,
groupMemberLimitsSnippet,
isValidName,
isValidNonNegative,
isValidNonNegativeInt,
@@ -337,3 +338,24 @@ describe('generateApiKey / API_KEY_PLACEHOLDER', () => {
expect(generateApiKey()).not.toBe(generateApiKey())
})
})
describe('groupMemberLimitsSnippet: golden YAML, spec.plugin.llmgateway.groups.<name>.memberLimits', () => {
it('renders memberLimits with tokensPerMinute in field order', () => {
expect(groupMemberLimitsSnippet('friends', { tokensPerMinute: 1000, requestsPerMinute: 2 })).toBe(
[
'spec:',
' plugin:',
' llmgateway:',
' groups:',
' friends:',
' memberLimits:',
' requestsPerMinute: 2',
' tokensPerMinute: 1000',
].join('\n'),
)
})
it('emits tokensPerMinute in a user limits fragment', () => {
expect(userLimitsJsonFragment({ tokensPerMinute: 50 })).toBe('"limits": {"tokensPerMinute": 50}')
})
})
+88 -2
View File
@@ -19,7 +19,7 @@
// authorizedProviders is computed first and gates model resolution).
import { emitConfigSnippet, emitYamlFlowMap, emitYamlKey, emitYamlScalar } from '@/lib/yaml-emit'
import type { YamlValue } from '@/lib/yaml-emit'
import type { LimitsConfig } from '@/types/api'
import type { LimitKey, LimitsConfig } from '@/types/api'
/** NAME_PATTERN is the operator-facing name rule every provider/group id must satisfy — letters, digits, dot, underscore, hyphen, matching every real name in middleware.yaml (anthropic, gx10-embed, macstudio-rerank, friends, ...) and mirroring the plugin's own path.Match glob-safe charset. */
export const NAME_PATTERN = /^[a-zA-Z0-9._-]+$/
@@ -109,9 +109,10 @@ export function validatePersonalGrant(providers: string[], models: string[]): st
}
/** LIMITS_FIELD_ORDER is LimitsConfig's own field order (types/api.ts) — the single source of truth every limits snippet (YAML block or JSON fragment) below renders in, so the two never drift relative to each other. */
const LIMITS_FIELD_ORDER: (keyof LimitsConfig)[] = [
const LIMITS_FIELD_ORDER: (LimitKey)[] = [
'requestsPerMinute',
'requestsPerDay',
'tokensPerMinute',
'tokensPerDay',
'tokensPerMonth',
'costPerDayUSD',
@@ -135,6 +136,13 @@ export function groupLimitsSnippet(groupName: string, limits: LimitsConfig): str
return emitConfigSnippet(['groups', groupName], { limits: body })
}
/** groupMemberLimitsSnippet builds a group's per-member YAML block at spec.plugin.llmgateway.groups.<name>.memberLimits — each member user gets their own counter with these values. */
export function groupMemberLimitsSnippet(groupName: string, limits: LimitsConfig): string {
const body: { [key: string]: YamlValue | undefined } = {}
for (const [key, value] of limitsEntries(limits)) body[key] = value
return emitConfigSnippet(['groups', groupName], { memberLimits: body })
}
function jsonString(s: string): string {
return JSON.stringify(s)
}
@@ -305,3 +313,81 @@ export function userJsonLine(user: UserSnippetInput): string {
if (user.admin) parts.push(`"admin": ${emitYamlScalar(true)}`)
return `{${parts.join(', ')}}`
}
/** ROUTER_MAX_MIN_SCORE mirrors smart_router.go's maxSmartMinScore: tier scores are per-mille. */
export const ROUTER_MAX_MIN_SCORE = 1000
export interface RouterTierInput {
name: string
minScore: number
models: string[]
}
export interface RouterKeywordRuleInput {
tier: string
keywords: string[]
}
export interface RouterInput {
tiers: RouterTierInput[]
keywordRules: RouterKeywordRuleInput[]
selection: 'ordered' | 'hash'
/** 0 means the gateway default. */
maxAttempts: number
contextEscalation: boolean
}
/**
* validateRouter mirrors smart_router.go's validateSmartRouters rules: at
* least one tier, unique tier names, first minScore 0, strictly rising
* scores, models required and disjoint across tiers, keyword rules naming a
* real tier. Returns every problem, empty when the router is valid.
*/
export function validateRouter(router: RouterInput): string[] {
const errors: string[] = []
if (router.tiers.length === 0) errors.push('Add at least one tier.')
const names = new Set<string>()
const modelTier = new Map<string, string>()
let prev = -1
router.tiers.forEach((tier, i) => {
if (names.has(tier.name)) errors.push(`Tier name "${tier.name}" is used twice.`)
names.add(tier.name)
if (!Number.isInteger(tier.minScore) || tier.minScore < 0 || tier.minScore > ROUTER_MAX_MIN_SCORE) {
errors.push(`Tier "${tier.name}" minScore must be a whole number from 0 to ${ROUTER_MAX_MIN_SCORE}.`)
} else if (i === 0 && tier.minScore !== 0) {
errors.push(`First tier "${tier.name}" must have minScore 0.`)
} else if (i > 0 && tier.minScore <= prev) {
errors.push(`Tier "${tier.name}" minScore must be greater than the previous tier's.`)
}
prev = tier.minScore
if (tier.models.length === 0) errors.push(`Tier "${tier.name}" needs at least one model.`)
for (const model of tier.models) {
const other = modelTier.get(model)
if (other !== undefined) errors.push(`Model "${model}" is in tier "${other}" and tier "${tier.name}"; tiers must be disjoint.`)
else modelTier.set(model, tier.name)
}
})
for (const rule of router.keywordRules) {
if (!names.has(rule.tier)) errors.push(`Keyword rule tier "${rule.tier}" is not a tier of this router.`)
if (rule.keywords.length === 0) errors.push(`Keyword rule for tier "${rule.tier}" needs at least one keyword.`)
}
if (!Number.isInteger(router.maxAttempts) || router.maxAttempts < 0) errors.push('Max attempts must be a non-negative whole number.')
return errors
}
/**
* routerSnippet builds one `smartRouters.<name>` YAML entry
* (SmartRouterConfig, smart_router.go). Defaults stay out: selection
* "ordered", maxAttempts 0 and contextEscalation true are omitted, so the
* snippet only states what differs from the gateway.
*/
export function routerSnippet(name: string, router: RouterInput): string {
const body: { [key: string]: YamlValue | undefined } = {
tiers: router.tiers.map((t) => ({ name: t.name, minScore: t.minScore, models: t.models })),
}
if (router.keywordRules.length > 0) body.keywordRules = router.keywordRules.map((r) => ({ tier: r.tier, keywords: r.keywords }))
if (router.selection !== 'ordered') body.selection = router.selection
if (router.maxAttempts > 0) body.maxAttempts = router.maxAttempts
if (!router.contextEscalation) body.contextEscalation = false
return emitConfigSnippet(['smartRouters', name], body)
}
+2
View File
@@ -5,6 +5,7 @@ import ErrorState from '@/components/ErrorState.vue'
import KpiTile from '@/components/KpiTile.vue'
import LoadStateView from '@/components/LoadStateView.vue'
import SkeletonKpiTile from '@/components/SkeletonKpiTile.vue'
import SmartRoutersCard from '@/components/SmartRoutersCard.vue'
import TopList from '@/components/TopList.vue'
import type { TopListItem } from '@/components/TopList.vue'
import TryLongerRangeButton from '@/components/TryLongerRangeButton.vue'
@@ -504,5 +505,6 @@ onUnmounted(() => {
</LoadStateView>
</CardContent>
</Card>
<SmartRoutersCard v-if="(dashboard.overview?.routers?.length ?? 0) > 0" :routers="dashboard.overview?.routers ?? []" />
</div>
</template>
+2
View File
@@ -3,6 +3,7 @@ import { computed, onMounted, watch } from 'vue'
import ModelCatalogTable from '@/components/ModelCatalogTable.vue'
import ProviderHealthPanel from '@/components/ProviderHealthPanel.vue'
import SmartRoutersCard from '@/components/SmartRoutersCard.vue'
import { useFiltersStore } from '@/stores/filters'
import { useModelsStore } from '@/stores/models'
import { useNavStore } from '@/stores/nav'
@@ -54,6 +55,7 @@ watch(
<template>
<div class="flex flex-col gap-6">
<ProviderHealthPanel />
<SmartRoutersCard v-if="models.routers.length > 0" :routers="models.routers" />
<!-- verify-ui-states-2.md #8: shown only for a BACKGROUND failure
(rows already on screen) — a first-load failure already renders via
ModelCatalogTable's own ErrorState below, and showing both duplicated
+4 -1
View File
@@ -6,7 +6,7 @@ import type { ModelCatalogRow } from '@/lib/model-table-columns'
import { useCatalogStore } from '@/stores/catalog'
import { useFiltersStore } from '@/stores/filters'
import { hourOrDayWindow } from '@/stores/reliability'
import type { AdminPerfResponse, AdminPerfRow, AdminUsageModelsResponse, HistoryWindow } from '@/types/api'
import type { AdminPerfResponse, AdminPerfRow, AdminRouterView, AdminUsageModelsResponse, HistoryWindow } from '@/types/api'
/**
* useModelsStore fetches the Models page's own catalog table (redesign-
@@ -29,6 +29,8 @@ import type { AdminPerfResponse, AdminPerfRow, AdminUsageModelsResponse, History
export const useModelsStore = defineStore('models', {
state: () => ({
rows: [] as ModelCatalogRow[],
/** The catalog's configured smart routers, shown read-only by SmartRoutersCard.vue. */
routers: [] as AdminRouterView[],
/** GET /admin/api/performance?kind=provider's own rows (fleet p50/p95, attempts/failures, timeouts, failovers per provider) — ProviderHealthPanel.vue's own doc comment. Keyed by provider name at read time, not here, so this store stays a plain array like `rows` above. */
providerPerf: [] as AdminPerfRow[],
/** The hour/day window + span hourOrDayWindow actually resolved for both performance requests — ProviderHealthPanel.vue's badge titles read this rather than filters.window/span directly whenever a month-range clamp was applied. */
@@ -66,6 +68,7 @@ export const useModelsStore = defineStore('models', {
if (requestId !== this.reqId) return
this.rows = buildModelCatalogRows(catalog.data, rankingRes, perfRes)
this.routers = catalog.data.routers ?? []
this.providerPerf = providerPerfRes.rows ?? []
this.perfWindow = perfWindow
this.latencyEnabled = perfRes.latencyEnabled
+138
View File
@@ -6,12 +6,26 @@
export interface LimitsConfig {
requestsPerMinute?: number
requestsPerDay?: number
tokensPerMinute?: number
tokensPerDay?: number
tokensPerMonth?: number
costPerDayUSD?: number
costPerMonthUSD?: number
pacing?: PacingConfig
}
/** LimitKey is the numeric LimitsConfig fields — everything except the nested pacing block. */
export type LimitKey = Exclude<keyof LimitsConfig, 'pacing'>
/** Mirrors Go's PacingConfig: requests wait up to maxDelay (a Go duration) as minute usage rises from startPct to 100%. */
export interface PacingConfig {
startPct: number
maxDelay: string
}
/** Maps a LimitsConfig field name to where its effective value came from: "user" or "memberLimits:<group>". */
export type LimitSources = Partial<Record<keyof LimitsConfig, string>>
/**
* One upstream model's current-window attempt/failure counters within its
* provider (admin.go: adminModelRateView) — Feature A, v0.22 per-model
@@ -210,6 +224,118 @@ export interface AdminGroupView {
memberCount: number
}
/** One tier of a smart router (admin_routers.go: adminRouterTierView). */
export interface AdminRouterTierView {
name: string
models: string[]
minScore: number
}
/** One keyword rule of a smart router (admin_routers.go: adminRouterRuleView). */
export interface AdminRouterRuleView {
tier: string
keywords: string[]
}
/** A named request count (admin_routers.go: adminRouterCountView). */
export interface AdminRouterCountView {
name: string
count: number
}
/** One tier-to-tier escalation count (admin_routers.go: adminRouterEscalationView). */
export interface AdminRouterEscalationView {
from: string
to: string
count: number
}
/** One live-tier by shadow-tier matrix cell (admin_routers.go: adminRouterShadowView). */
export interface AdminRouterShadowView {
live: string
shadow: string
count: number
}
/** Finished requests by first attempted tier, routing reason and outcome (admin_routers.go: adminRouterOutcomeView). */
export interface AdminRouterOutcomeView {
tier: string
reason: string
outcome: 'ok' | 'error' | 'escalated' | 'bad' | 'slow'
count: number
}
/** Router counters (admin_routers.go: adminRouterStatsView); scope "shared" sums all gateway instances this month, "instance" is this process since start. */
export interface AdminRouterStatsView {
scope: 'shared' | 'instance'
requests: number
tiers: AdminRouterCountView[]
reasons: AdminRouterCountView[]
escalations: AdminRouterEscalationView[]
/** Non-zero cells of the live-by-shadow tier matrix; empty without shadowWeights. */
shadow: AdminRouterShadowView[]
outcomes: AdminRouterOutcomeView[]
}
/** One tier's calibration offset: points its threshold sits below the configured minScore. */
export interface AdminRouterDeltaView {
tier: string
delta: number
}
/** Calibration state of one router (admin_routers.go: adminRouterCalibrationView). Shadow offsets are computed, not applied. */
export interface AdminRouterCalibrationView {
mode: 'off' | 'shadow' | 'live'
delta: AdminRouterDeltaView[]
maxLower: number
maxRaise: number
freeze: boolean
}
/** Settings of adaptive selection; present only when selection is "adaptive". */
export interface AdminRouterAdaptiveView {
explorePct: number
windowHours: number
latencyWeightPct: number
}
/** One configured smart router, read-only (admin_routers.go: adminRouterView). */
export interface AdminRouterView {
name: string
defaultTier: string
/** Floor tier for requests with tools; absent when unset. */
toolsMinTier?: string
/** True when the router has shadowWeights or shadowClassifier, so the matrix is meaningful even when empty. */
shadowEnabled: boolean
/** Live classifier: "v1" or "v2". */
classifier: string
/** "v2" when the router scores each request with v2 beside a v1 live classifier; absent otherwise. */
shadowClassifier?: string
/** v2 risk margin in hundredths of a sigma. */
riskZ: number
/** Go duration after which a slow upstream attempt escalates; absent when unset. */
firstByteTimeout?: string
selection: string
adaptive?: AdminRouterAdaptiveView
calibration: AdminRouterCalibrationView
/** True when a saturated tier starts score-routed requests one tier lower. */
saturationDowngrade: boolean
downgradeBand: number
/** Requests started one tier lower because their tier was saturated. */
downgraded: number
/** True when a router whose every attempt was slow tries one tier below its first attempted tier. */
timeoutFallback: boolean
/** Requests that took the extra timeout-fallback attempt. */
fellBack: number
tiers: AdminRouterTierView[]
keywordRules: AdminRouterRuleView[]
maxAttempts: number
contextEscalation: boolean
/** Advertised context window in tokens; absent when no target declares one. */
contextTokens?: number
stats?: AdminRouterStatsView
}
export interface AdminAliasView {
alias: string
target: string
@@ -275,6 +401,7 @@ export interface AdminOverviewResponse {
providers: AdminProviderView[]
groups: AdminGroupView[]
aliases: AdminAliasView[]
routers?: AdminRouterView[]
redis: AdminRedisView
cache: AdminCacheView
retry: AdminRetryView
@@ -284,6 +411,10 @@ export interface AdminOverviewResponse {
export interface AdminUsageEntryView {
limits?: LimitsConfig
/** Users only: each set limits field's origin, "user" or "memberLimits:<group>" (admin.go: adminUsageEntryView.LimitSources). */
limitSources?: LimitSources
/** Groups only: the per-member default each member user inherits. */
memberLimits?: LimitsConfig
kind: string
id: string
groupName?: string
@@ -328,6 +459,8 @@ export interface AdminUsageEntryView {
* path already paid, so this field costs nothing extra to read).
*/
rejectionsPerDay: number
/** Limit-exempt requests this month (limitExemptKinds); they count in no limit. */
exemptRequestsPerMonth?: number
storeDown?: boolean
/**
* Unix seconds this scope last made a request, fleet-wide (admin.go:
@@ -707,6 +840,8 @@ export interface AdminCatalogModel {
/** True for a pseudo-model row built from a `pathBaseUrls` key — not a routable model, never priced. */
endpoint?: boolean
aliases?: string[]
/** Smart routers that list this model as a target (admin_catalog.go: adminCatalogModel.Routers). */
routers?: string[]
}
/** One provider's full catalog listing (admin.go: adminCatalogProvider — phase 2 redesign), on-demand only (never part of the 5s overview poll). */
@@ -724,6 +859,7 @@ export interface AdminCatalogProvider {
export interface AdminCatalogResponse {
providers: AdminCatalogProvider[]
aliases: AdminAliasView[]
routers?: AdminRouterView[]
}
/**
@@ -735,6 +871,7 @@ export interface AdminCatalogResponse {
*/
export interface AdminConsumerUser {
limits?: LimitsConfig
limitSources?: LimitSources
name: string
source: 'inline' | 'file'
groups: string[]
@@ -757,6 +894,7 @@ export interface AdminModelAccessCount {
*/
export interface AdminConsumerGroup {
limits?: LimitsConfig
memberLimits?: LimitsConfig
name: string
providers?: string[]
models?: string[]