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>