mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-04 22:32:12 +03:00
* 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).
191 lines
6.3 KiB
TypeScript
191 lines
6.3 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { z } from "zod";
|
|
import { isAuthenticated } from "@/shared/utils/apiAuth";
|
|
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
|
|
import { FEATURE_FLAG_DEFINITIONS } from "@/shared/constants/featureFlagDefinitions";
|
|
import {
|
|
getFeatureFlagOverrides,
|
|
setFeatureFlagOverride,
|
|
removeFeatureFlagOverride,
|
|
clearAllFeatureFlagOverrides,
|
|
} from "@/lib/db/featureFlags";
|
|
import { resolveAllFeatureFlags } from "@/shared/utils/featureFlags";
|
|
import { getCcAliasGlobalState } from "@/lib/db/ccDiscoveryAliases";
|
|
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
|
|
|
|
const ACTIVE_VALUES = new Set(["true", "1", "yes"]);
|
|
const CC_DISCOVERY_ALIASES_FLAG_KEY = "EXPOSE_CC_DISCOVERY_ALIASES";
|
|
|
|
function isActive(value: string): boolean {
|
|
return ACTIVE_VALUES.has(value);
|
|
}
|
|
|
|
/**
|
|
* GET /api/settings/feature-flags
|
|
* Returns all feature flags with their effective values and a summary.
|
|
*/
|
|
export async function GET(request: NextRequest) {
|
|
if (!(await isAuthenticated(request))) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const resolved = resolveAllFeatureFlags();
|
|
|
|
const flags = resolved.map(({ key, effectiveValue, source, definition }) => {
|
|
// EXPOSE_CC_DISCOVERY_ALIASES resolves with env-wins-over-db precedence
|
|
// (see db/ccDiscoveryAliases.ts::getCcAliasGlobalState) — the opposite of
|
|
// resolveAllFeatureFlags' generic db-wins-over-env order. Override the
|
|
// reported effectiveValue/source with the gate's own resolution so the
|
|
// dashboard never shows a source that doesn't match actual gate behavior.
|
|
if (key === CC_DISCOVERY_ALIASES_FLAG_KEY) {
|
|
const gateState = getCcAliasGlobalState();
|
|
return {
|
|
key,
|
|
label: definition.label,
|
|
description: definition.description,
|
|
category: definition.category,
|
|
type: definition.type,
|
|
enumValues: definition.enumValues ?? null,
|
|
defaultValue: definition.defaultValue,
|
|
effectiveValue: gateState.enabled ? "true" : "false",
|
|
source: gateState.source,
|
|
requiresRestart: definition.requiresRestart,
|
|
warningLevel: definition.warningLevel,
|
|
};
|
|
}
|
|
|
|
return {
|
|
key,
|
|
label: definition.label,
|
|
description: definition.description,
|
|
category: definition.category,
|
|
type: definition.type,
|
|
enumValues: definition.enumValues ?? null,
|
|
defaultValue: definition.defaultValue,
|
|
effectiveValue,
|
|
source,
|
|
requiresRestart: definition.requiresRestart,
|
|
warningLevel: definition.warningLevel,
|
|
};
|
|
});
|
|
|
|
const total = flags.length;
|
|
const active = flags.filter((f) => isActive(f.effectiveValue)).length;
|
|
const inactive = total - active;
|
|
const overriddenByDb = flags.filter((f) => f.source === "db").length;
|
|
const overriddenByEnv = flags.filter((f) => f.source === "env").length;
|
|
|
|
return NextResponse.json({
|
|
flags,
|
|
summary: { total, active, inactive, overriddenByDb, overriddenByEnv },
|
|
});
|
|
} catch (error) {
|
|
return NextResponse.json({ error: sanitizeErrorMessage(error) }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
const putFeatureFlagSchema = z.object({
|
|
key: z.string().min(1),
|
|
value: z.string().optional(),
|
|
});
|
|
|
|
/**
|
|
* PUT /api/settings/feature-flags
|
|
* Set or remove a feature flag override.
|
|
* Body: { key: string; value?: string }
|
|
* If value is omitted, the override is removed.
|
|
*/
|
|
export async function PUT(request: NextRequest) {
|
|
if (!(await isAuthenticated(request))) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
let rawBody: unknown;
|
|
try {
|
|
rawBody = await request.json();
|
|
} catch {
|
|
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
|
}
|
|
|
|
const validation = validateBody(putFeatureFlagSchema, rawBody);
|
|
if (isValidationFailure(validation)) {
|
|
return NextResponse.json({ error: validation.error }, { status: 400 });
|
|
}
|
|
|
|
const { key, value } = validation.data;
|
|
|
|
// Validate key against known definitions
|
|
const definition = FEATURE_FLAG_DEFINITIONS.find((d) => d.key === key);
|
|
if (!definition) {
|
|
return NextResponse.json({ error: `Unknown feature flag key: ${key}` }, { status: 400 });
|
|
}
|
|
|
|
// Validate enum values
|
|
if (value !== undefined && definition.type === "enum" && definition.enumValues) {
|
|
if (!definition.enumValues.includes(value)) {
|
|
return NextResponse.json(
|
|
{
|
|
error: `Invalid value "${value}" for enum flag ${key}. Allowed: ${definition.enumValues.join(", ")}`,
|
|
},
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
}
|
|
|
|
try {
|
|
// Capture previous state before modifying
|
|
const allFlagsBefore = resolveAllFeatureFlags();
|
|
const prevFlag = allFlagsBefore.find((f) => f.key === key);
|
|
const previousValue = prevFlag?.effectiveValue ?? definition.defaultValue;
|
|
const previousSource = prevFlag?.source ?? "default";
|
|
|
|
if (value === undefined) {
|
|
removeFeatureFlagOverride(key);
|
|
} else {
|
|
setFeatureFlagOverride(key, value);
|
|
}
|
|
|
|
// After write — get new effective value
|
|
const allFlagsAfter = resolveAllFeatureFlags();
|
|
const updatedFlag = allFlagsAfter.find((f) => f.key === key);
|
|
const newEffectiveValue = updatedFlag?.effectiveValue ?? definition.defaultValue;
|
|
const newSource = updatedFlag?.source ?? "default";
|
|
|
|
return NextResponse.json({
|
|
key,
|
|
effectiveValue: newEffectiveValue,
|
|
source: newSource,
|
|
previousValue,
|
|
previousSource,
|
|
requiresRestart: definition.requiresRestart,
|
|
});
|
|
} catch (error) {
|
|
return NextResponse.json({ error: sanitizeErrorMessage(error) }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
/**
|
|
* DELETE /api/settings/feature-flags
|
|
* Clear all feature flag overrides.
|
|
*/
|
|
export async function DELETE(request: NextRequest) {
|
|
if (!(await isAuthenticated(request))) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const overrides = getFeatureFlagOverrides();
|
|
const count = Object.keys(overrides).length;
|
|
|
|
clearAllFeatureFlagOverrides();
|
|
|
|
return NextResponse.json({
|
|
cleared: count,
|
|
message: `Cleared ${count} feature flag override${count !== 1 ? "s" : ""}`,
|
|
});
|
|
} catch (error) {
|
|
return NextResponse.json({ error: sanitizeErrorMessage(error) }, { status: 500 });
|
|
}
|
|
}
|