Files
OmniRoute/src/lib/db/ccDiscoveryMetrics.ts
Diego Rodrigues de Sa e Souza cd9a631464 feat: Claude Code discovery aliases (surface non-Claude models in the /model picker) (#8666)
* feat(db): cc discovery alias gate storage + EXPOSE_CC_DISCOVERY_ALIASES flag

Adds the gate for claude/<provider>/<model> discovery-alias mirror ids on
the /v1/models catalog: a new runtime feature flag (env forces on and wins
over the dashboard DB override), per-provider and per-model "on"/"off"/null
overrides stored in key_value under the ccDiscoveryAliases namespace, and a
pure precedence resolver (model > provider > global). Catalog wiring is a
separate follow-up task; this only lands the gate + storage.

* feat(sse): synthesize claude/ discovery aliases for the model catalog

* feat(api): advertise cc discovery aliases on /v1/models behind the 3-level gate

* feat(sse): resolve claude/ discovery aliases on the request path

* fix(sse): import getComboByName from db/combos, not the localDb barrel

* fix(sse): cover custom-node prefixes and the Codex WS bridge in cc discovery alias resolution

* feat(dashboard): cc discovery alias toggles + flag-screen env warning

Adds the operator-facing UI/API layer for the Claude Code discovery-alias
gate (claude/<provider>/<model> mirror ids on /v1/models): REST endpoint
for provider/model overrides, a provider-detail card with 3-state
(inherit/on/off) toggles, an info button on the Claude Code tool card
linking to Feature Flags, and an env-source warning on the
EXPOSE_CC_DISCOVERY_ALIASES flag card when it's forced on via env.

* feat(api): cc discovery usage metrics

* fix(api): record cc alias metric in the production wrapper + atomic counter upsert

* docs: document cc discovery aliases (Claude Code guide + feature flag catalog)

* fix(sse): don't mirror built-in auto/* combos as discovery aliases (advertised-but-unroutable)

* i18n(vi): translate the discovery-alias strings instead of shipping placeholders

vi is the one locale with a strict "no internal missing markers" test, so the 17
__MISSING__ entries this branch added (the provider ccAlias panel, the info
button, the feature-flag description and the env warning) would have turned that
test red the moment the base itself was repaired. Translated, keeping every ICU
placeholder ({modelId}, {error}) and the literal claude/<provider>/<model> id
shape intact.

* chore(quality): raise the frozen caps this feature legitimately grows

catalog.ts 1615 -> 1639: the alias synthesis is wired into the catalog builder,
which is where the per-key-filtered list is assembled — the only place the mirror
entries can be appended after model hiding has been applied.

localDb.ts 808 -> 810: two re-export lines for the new ccDiscoveryAliases db
module, which is exactly what the "Adding a New DB Module" recipe prescribes.

* refactor(dashboard,api): keep the complexity ratchets flat

The feature added four cyclomatic violations and one cognitive one, which the
ratchets reject — the baseline only moves when a metric improves. Split the new
code instead:

- appendCcDiscoveryAliases: the four skip-guards become isMirrorableId().
- resolveCcDiscoveryAliasStripWith: alias parsing and gate resolution become
  parseCcAliasTarget() and resolveGateFor(), replacing a chain of ternaries that
  each re-tested isComboAlias.
- FeatureFlagCard: the env-precedence warning becomes its own component instead
  of a conditional branch inside an already-large render.
- ProviderCcAliasSection: the loader moves to useCcAliasData(), and the override
  list and add-row become ModelOverrideList / AddOverrideRow, bringing both
  oversized functions back under the 80-line rule.

Behavior unchanged — the 74 discovery-alias tests pass untouched. Both ratchets
now sit exactly at baseline (2188 / 971).
2026-07-26 17:19:19 -03:00

114 lines
3.9 KiB
TypeScript

/**
* cc-discovery usage metrics — aggregate counters for the Claude Code
* discovery-alias feature (see src/lib/ccDiscoveryAliasResolve.ts and
* src/app/api/v1/models/catalog.ts).
*
* Tracks:
* - how many requests were served after resolving a `claude/…` mirror id
* back to its real model/combo (per-total and per-model breakdown)
* - how many `GET /v1/models` catalog hits came from a Claude Code client
* (detected by the `claude-cli` User-Agent substring, the same signal
* open-sse/utils/bypassHandler.ts already uses)
*
* Deliberately reuses the generic `key_value` namespace/key store (the same
* pattern as src/lib/db/sessionAccountAffinity.ts) instead of a dedicated
* migration — this is a v1 aggregate-counter feature, not a per-event log,
* so no new table is warranted.
*
* Every write is best-effort: a DB hiccup here must never break the request
* it is instrumenting (mirrors src/lib/db/pluginMetrics.ts).
*/
import { getDbInstance } from "./core";
const NAMESPACE = "ccDiscoveryMetrics";
const TOTAL_KEY = "req:total";
const HIT_KEY = "discovery:hits";
const MODEL_KEY_PREFIX = "req:model:";
export interface CcDiscoveryMetrics {
aliasRequests: number;
discoveryHits: number;
byModel: Record<string, number>;
}
function modelKey(realModelId: string): string {
return `${MODEL_KEY_PREFIX}${realModelId}`;
}
function incrementCounter(key: string): void {
// Atomic upsert increment — a single statement so two concurrent requests
// never lose a count the way a read-then-write pair would. `value` is TEXT, so
// CAST it to INTEGER for the arithmetic; an absent row starts at '1' via the
// INSERT branch, and a non-numeric prior value CASTs to 0 → 1 on update.
getDbInstance()
.prepare(
`INSERT INTO key_value (namespace, key, value) VALUES (?, ?, '1')
ON CONFLICT(namespace, key)
DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`
)
.run(NAMESPACE, key);
}
/**
* Record one request served via a resolved `claude/…` discovery alias.
* `realModelId` is the id AFTER stripping (e.g. `kimi/kimi-k2.6`, `my-combo`).
* Never throws — a metrics failure must not affect the request it instruments.
*/
export function incrementCcAliasRequestCount(realModelId: string): void {
try {
incrementCounter(TOTAL_KEY);
if (typeof realModelId === "string" && realModelId.length > 0) {
incrementCounter(modelKey(realModelId));
}
} catch {
// Best-effort: DB hiccup should never break the request it instruments.
}
}
/**
* Record one `GET /v1/models` hit whose User-Agent identified it as a
* Claude Code discovery request.
*/
export function incrementCcDiscoveryHitCount(): void {
try {
incrementCounter(HIT_KEY);
} catch {
// Best-effort — same rationale as incrementCcAliasRequestCount.
}
}
/**
* Read the aggregated cc-discovery metrics. Never throws — returns the
* zero-value shape on any DB failure so a monitoring read never 500s.
*/
export function getCcDiscoveryMetrics(): CcDiscoveryMetrics {
try {
const db = getDbInstance();
const rows = db
.prepare("SELECT key, value FROM key_value WHERE namespace = ?")
.all(NAMESPACE) as Array<{ key?: unknown; value?: unknown }>;
let aliasRequests = 0;
let discoveryHits = 0;
const byModel: Record<string, number> = {};
for (const row of rows) {
if (typeof row.key !== "string") continue;
const value = typeof row.value === "string" ? parseInt(row.value, 10) : Number(row.value);
const count = Number.isFinite(value) && value >= 0 ? value : 0;
if (row.key === TOTAL_KEY) {
aliasRequests = count;
} else if (row.key === HIT_KEY) {
discoveryHits = count;
} else if (row.key.startsWith(MODEL_KEY_PREFIX)) {
byModel[row.key.slice(MODEL_KEY_PREFIX.length)] = count;
}
}
return { aliasRequests, discoveryHits, byModel };
} catch {
return { aliasRequests: 0, discoveryHits: 0, byModel: {} };
}
}