mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-07 07:42:13 +03:00
* feat(dashboard): add RADAR_ENABLED flag (default off) * feat(db): radar feed cache + settings with encrypted supporter key * feat(radar): signed feed sync with pinned key and version floor - feedSchema.ts: Zod v4 schema mirroring the server feed format (discriminated union on budget.kind, enum constraints, etc.) - pinnedKeys.ts: Ed25519 SPKI-DER pinned key + env override for forks - verify.ts: signature verification over exact wire bytes, never throws - sync.ts: full download/verify/validate/cache pipeline with injectable deps, feature-flag gate, opt-in gate, version floor (numeric compare), and sanitized error reasons (no stack traces) - 40 tests covering: contract hash, key handling, sig verification, schema validation, version compare, all sync paths (disabled, opt_out, invalid_signature, invalid_schema, stale, updated, error), auth header injection, and cache-untouched assertions for every failure mode * feat(radar): read-time overlay merge rules over the free catalog Pure function applyFeed() merges the cached Radar feed over the static baseline catalog at read time, honoring 4 rules: 1. Feed never overwrites a local override field. 2. enabled:false disables the entry with disabledBy:"radar" provenance. 3. User-added entry NOT in the feed survives untouched. 4. User deletion tombstone prevents feed resurrection. getRadarCatalog() accessor in index.ts: flag off / no cache / corrupt payload all fall back to baseline. Valid cache applies the overlay and returns feed metadata (version, tier, fetchedAt). TDD: 19 tests (4 rules + dedup + origin + accessor flag/cache/corrupt/ valid/bad-feed + baselineToMergedEntries converter). * feat(dashboard): radar catalog and guided setup screens - API routes: GET /api/radar/catalog, POST /api/radar/sync, POST /api/radar/settings - All gated on RADAR_ENABLED flag (404 when off) - Error responses via buildErrorBody(), never raw stack/message - Settings never echoes clear supporter key (masked omr_****<last4>) - Sync delegates to syncRadar() server-side, never proxies feed URL - Dashboard pages: - /dashboard/radar: 4 states (flag off, opt-in pending, empty, populated) - /dashboard/radar/setup?provider=X: guided setup with steps, key URL, test connection - Uses existing Card component and next-intl patterns - Sidebar: radar entry in costs group with icon - i18n: pt-BR and en keys for radarPage and radarSetupPage namespaces - Tests: - radar-api-routes.test.ts: 11 tests (flag-off 404, flag-on shape, error sanitization) - radar-page-state.test.ts: 5 tests (pure state logic) - All 90 radar tests pass (including prior 74) * docs(radar): module doc and flag-off inertia test Add docs/frameworks/RADAR.md covering the flag gate, the separate data-sync opt-in and privacy promise, the Ed25519 signature/pinned-key security model, tiers, the read-time overlay merge rules, and the self-hosting env vars — plus index entries in CLAUDE.md/AGENTS.md/docs/README.md/REPOSITORY_MAP.md. Document RADAR_FEED_URL and RADAR_FEED_PUBKEY in .env.example and docs/reference/ENVIRONMENT.md to satisfy check:env-doc-sync, which was failing on this branch since the sync.ts commit added the reads. Add tests/unit/radar-inertia.test.ts as the single canonical place asserting the "RADAR_ENABLED off => zero behavioral delta" claim end to end: the three /api/radar/* routes 404, the flag resolves to the definition default with no override, getRadarCatalog() returns exactly the baseline without touching the cache, and computeFreeModelTotals() keeps its pinned values with the Radar module imported alongside it. * fix(db): renumber radar migration to 135 after collision with 134 The base branch introduced 134_proxy_logs_egress_ip while this branch carried 134_radar_cache_settings; the migration runner rejects duplicate numeric prefixes. This migration has never been applied to a real database (the PR is unmerged), so no retroactive isSchemaAlreadyApplied guard is needed. * i18n(radar): translate radar catalog and setup strings to all locales The UI-coverage ratchet measures (present - placeholder) / total_en, so the __MISSING__ sentinels that i18n:sync-ui writes do not count as covered — only real translations restore the metric. Scoped to this PR's namespaces (radarPage, radarSetupPage, sidebar.radar*) instead of a bulk sync, which would have pulled ~978 unrelated pending keys into this diff. Placeholders and code identifiers verified preserved across all 1682 strings. * fix(radar): trust the served-tier header instead of the signed body field The signed feed body always carries tier:"live" by design (one signed artifact per version — rewriting the field server-side per request would break the exact-bytes Ed25519 signature). The server now returns the tier ACTUALLY served via the x-omniroute-feed-tier response header, so free users on a delayed community snapshot no longer see "Ao vivo (tempo real)" in the UI. sync.ts now reads and validates that header (falling back to the body's tier only when the header is absent or holds an unrecognized value) and stores the served tier in the cache; index.ts already surfaces cache.tier to the UI unchanged. * test(combo): shorten an assert message that exceeded the line limit The assertion added by #9507 was 104 chars, so prettier reformatted it into five lines on the next commit that touched the file, pushing it past its frozen size (3449) and failing check:file-size. The message is shortened (the issue reference stays in the comment directly above); the assertion itself is unchanged, and the file is back to 3448 lines and prettier-clean. * i18n(radar): use the canonical zh-TW glossary terms The machine translation produced retired renderings the glossary gate blocks: 供應商 for provider (canonical 提供者) and 文檔 for documentation (canonical 文件). Fixed across the 11 affected radar strings; tests/unit/i18n-glossary-consistency-check.test.ts is back to 17/17. * fix(radar): point the default feed URL at the domain that exists radar.omniroute.dev was a placeholder for a domain that was never registered, so an out-of-the-box sync would fail DNS resolution for every user. The live feed is served from radar.omniroute.online (the subdomain the design always specified), now behind Cloudflare TLS. Forks still override it via RADAR_FEED_URL. --------- Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
228 lines
8.8 KiB
JavaScript
228 lines
8.8 KiB
JavaScript
/**
|
|
* omniroute setup-claude — Remote-aware Claude Code profile generator.
|
|
*
|
|
* Claude Code has no native profile files (unlike Codex). The idiomatic way to
|
|
* keep multiple named configs is `CLAUDE_CONFIG_DIR` — a separate config dir per
|
|
* profile (its own settings.json, credentials, history, cache). This command
|
|
* fetches the live /v1/models catalog from a (possibly remote) OmniRoute and
|
|
* writes `~/.claude/profiles/<name>/settings.json` for each supported model,
|
|
* reusing the SAME profile names as `setup-codex` (glm52, kimi-k27, …).
|
|
*
|
|
* Launch a profile with: omniroute launch --profile <name>
|
|
* (which injects ANTHROPIC_AUTH_TOKEN from the active context — the token is
|
|
* never written to disk). Or export ANTHROPIC_AUTH_TOKEN and run:
|
|
* CLAUDE_CONFIG_DIR=~/.claude/profiles/<name> claude
|
|
*
|
|
* Idempotent: re-running overwrites each profile's settings.json in place.
|
|
*/
|
|
|
|
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import os from "node:os";
|
|
import { printHeading, printInfo, printSuccess, printError } from "../io.mjs";
|
|
import {
|
|
categoriseModel,
|
|
isCodexCompatibleTextModel,
|
|
profileNameFromModelId,
|
|
} from "./setup-codex.mjs";
|
|
|
|
/** Map a Codex-style effort to a Claude Code settings.json effortLevel. */
|
|
function effortLevelFor(cfg) {
|
|
// Codex categories use xhigh/high/low/undefined; Claude Code accepts the same
|
|
// names (low|medium|high|xhigh). Pass through, omit for the "simple" tier.
|
|
return cfg.effort || undefined;
|
|
}
|
|
|
|
/**
|
|
* Generic profile for a live-catalog model that `categoriseModel()` doesn't
|
|
* recognize (e.g. any provider added after the hardcoded glm/kimi/mimo/…
|
|
* pattern list was written). Mirrors setup-codex.mjs's fallbackCodexProfile()
|
|
* so setup-claude never silently produces zero profiles for a fresh catalog.
|
|
*/
|
|
export function fallbackClaudeProfile(modelId, model) {
|
|
if (!isCodexCompatibleTextModel(model)) return null;
|
|
return { name: profileNameFromModelId(modelId) };
|
|
}
|
|
|
|
/** Build the settings.json content for one Claude Code profile. */
|
|
export function buildProfileSettings(modelId, baseUrl, cfg) {
|
|
const env = {
|
|
ANTHROPIC_BASE_URL: baseUrl,
|
|
ANTHROPIC_MODEL: modelId,
|
|
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1",
|
|
CLAUDE_CODE_AUTO_COMPACT_WINDOW: "190000",
|
|
};
|
|
const settings = {
|
|
$schema: "https://json.schemastore.org/claude-code-settings.json",
|
|
model: modelId,
|
|
env,
|
|
};
|
|
const effort = effortLevelFor(cfg);
|
|
if (effort) settings.effortLevel = effort;
|
|
// NOTE: ANTHROPIC_AUTH_TOKEN is intentionally NOT written here — `omniroute
|
|
// launch --profile` injects it from the active context, keeping the secret off
|
|
// disk. For direct `CLAUDE_CONFIG_DIR=… claude` use, export it in your shell.
|
|
return JSON.stringify(settings, null, 2) + "\n";
|
|
}
|
|
|
|
/**
|
|
* Generate Claude Code profile files for a live model catalog. Shared by the
|
|
* `setup-claude` CLI command and the post-model-sync auto-sync so both stay
|
|
* behaviorally identical. Writes `<claudeHome>/profiles/<name>/settings.json`
|
|
* (directory-per-profile); never touches the active/default Claude config.
|
|
* @param {Array} models
|
|
* @param {{claudeHome?:string, baseUrl:string, dryRun?:boolean, only?:string, log?:(line:string)=>void}} opts
|
|
* @returns {Promise<{written:number, skipped:number, profiles:Array<{name:string, model:string, filePath:string}>}>}
|
|
*/
|
|
export async function syncClaudeProfilesFromModels(models, opts = {}) {
|
|
const claudeHome = opts.claudeHome || join(os.homedir(), ".claude");
|
|
const profilesRoot = join(claudeHome, "profiles");
|
|
const baseUrl = opts.baseUrl;
|
|
const dryRun = Boolean(opts.dryRun);
|
|
// Injectable dry-run printer (#5959): under the node:test runner, a child
|
|
// process writing multi-byte UTF-8 (the "──" box-drawing heading) to stdout
|
|
// corrupts the runner's V8-serialized event stream ~50% of the time
|
|
// ("Unable to deserialize cloned data due to invalid or unsupported
|
|
// version"). Tests inject a collector; the CLI default stays console.log.
|
|
const log = opts.log ?? console.log;
|
|
const onlyFilter = opts.only ? opts.only.split(",").map((s) => s.trim()) : null;
|
|
|
|
if (!dryRun && !existsSync(profilesRoot)) {
|
|
mkdirSync(profilesRoot, { recursive: true });
|
|
}
|
|
|
|
let written = 0;
|
|
let skipped = 0;
|
|
const profiles = [];
|
|
|
|
for (const m of models) {
|
|
const id = typeof m === "string" ? m : (m.id ?? "");
|
|
if (!id) {
|
|
skipped++;
|
|
continue;
|
|
}
|
|
if (onlyFilter && !onlyFilter.some((f) => id.includes(f))) {
|
|
skipped++;
|
|
continue;
|
|
}
|
|
|
|
const cfg = categoriseModel(id) ?? fallbackClaudeProfile(id, m);
|
|
if (!cfg) {
|
|
skipped++;
|
|
continue;
|
|
}
|
|
|
|
const dir = join(profilesRoot, cfg.name);
|
|
const filePath = join(dir, "settings.json");
|
|
const content = buildProfileSettings(id, baseUrl, cfg);
|
|
|
|
if (dryRun) {
|
|
log(`\n── [dry-run] ${filePath} ──`);
|
|
log(content);
|
|
} else {
|
|
mkdirSync(dir, { recursive: true });
|
|
writeFileSync(filePath, content, "utf8");
|
|
}
|
|
profiles.push({ name: cfg.name, model: id, filePath });
|
|
written++;
|
|
}
|
|
|
|
return { written, skipped, profiles };
|
|
}
|
|
|
|
/**
|
|
* @param {{remote?:string, port?:string, apiKey?:string, claudeHome?:string, dryRun?:boolean, only?:string}} opts
|
|
* @returns {Promise<number>}
|
|
*/
|
|
export async function runSetupClaudeCommand(opts = {}) {
|
|
const port = Number(opts.port ?? process.env.PORT ?? 20128) || 20128;
|
|
const baseUrl = (opts.remote ?? `http://localhost:${port}`)
|
|
.replace(/\/+$/, "")
|
|
.replace(/\/v1$/, "");
|
|
const apiKey = opts.apiKey ?? opts["api-key"] ?? process.env.OMNIROUTE_API_KEY ?? "";
|
|
const claudeHome = opts.claudeHome ?? opts["claude-home"] ?? join(os.homedir(), ".claude");
|
|
const profilesRoot = join(claudeHome, "profiles");
|
|
const dryRun = Boolean(opts.dryRun ?? opts["dry-run"]);
|
|
|
|
printHeading("OmniRoute → Claude Code profile generator");
|
|
printInfo(`Connecting to ${baseUrl} …`);
|
|
|
|
// ── Fetch model catalog ───────────────────────────────────────────────────
|
|
let models;
|
|
try {
|
|
const headers = { "Content-Type": "application/json" };
|
|
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
|
|
const res = await fetch(`${baseUrl}/v1/models`, {
|
|
headers,
|
|
signal: AbortSignal.timeout(10000),
|
|
});
|
|
if (!res.ok) {
|
|
let detail = `HTTP ${res.status}`;
|
|
try {
|
|
const errorBody = await res.json();
|
|
const serverMsg = errorBody?.error?.message || errorBody?.error || errorBody?.message || "";
|
|
if (serverMsg) detail += ` — ${serverMsg}`;
|
|
} catch {}
|
|
throw new Error(detail);
|
|
}
|
|
const body = await res.json();
|
|
models = body.data ?? body.models ?? [];
|
|
} catch (err) {
|
|
printError(`Failed to fetch models: ${err.message}`);
|
|
printInfo(
|
|
"Make sure OmniRoute is running and the --remote URL is correct.\n" +
|
|
"You may also need --api-key if OmniRoute requires authentication."
|
|
);
|
|
return 1;
|
|
}
|
|
|
|
printInfo(`Received ${models.length} models from ${baseUrl}`);
|
|
|
|
const { written, skipped, profiles } = await syncClaudeProfilesFromModels(models, {
|
|
claudeHome,
|
|
baseUrl,
|
|
dryRun,
|
|
only: opts.only,
|
|
});
|
|
|
|
if (!dryRun) {
|
|
for (const profile of profiles) {
|
|
printSuccess(` ✓ profiles/${profile.name}/settings.json (${profile.model})`);
|
|
}
|
|
console.log("");
|
|
printSuccess(`${written} Claude Code profiles written to ${profilesRoot}`);
|
|
if (skipped > 0) printInfo(`${skipped} models skipped (no matching profile pattern)`);
|
|
console.log("\nTo use a profile:");
|
|
console.log(" omniroute launch --profile <name> # e.g. omniroute launch --profile glm52");
|
|
console.log(
|
|
" # or: CLAUDE_CONFIG_DIR=~/.claude/profiles/<name> claude (export ANTHROPIC_AUTH_TOKEN first)"
|
|
);
|
|
} else {
|
|
console.log(`\n[dry-run] ${written} profiles would be written (${skipped} skipped)`);
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
export function registerSetupClaude(program) {
|
|
program
|
|
.command("setup-claude")
|
|
.description(
|
|
"Fetch the live model catalog from OmniRoute (local or remote VPS) and generate " +
|
|
"~/.claude/profiles/<name>/ Claude Code profiles (CLAUDE_CONFIG_DIR) for each model"
|
|
)
|
|
.option("--port <port>", "Local OmniRoute port (ignored when --remote is set)", "20128")
|
|
.option("--remote <url>", "Remote OmniRoute URL, e.g. http://192.168.0.15:20128")
|
|
.option("--api-key <key>", "OmniRoute API key (defaults to OMNIROUTE_API_KEY env var)")
|
|
.option("--claude-home <dir>", "Claude home dir (default: ~/.claude)")
|
|
.option(
|
|
"--only <patterns>",
|
|
"Comma-separated substrings — only matching model IDs (e.g. glm,kimi)"
|
|
)
|
|
.option("--dry-run", "Print what would be written without touching the filesystem")
|
|
.action(async (opts) => {
|
|
const exitCode = await runSetupClaudeCommand(opts);
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
}
|