Files
OmniRoute/bin/cli/commands/config.mjs
Diego Rodrigues de Sa e Souza 75d9a83c25 Release v3.8.3 (#2617)
* chore(config): ignore additional agent workflow command files

Add newly introduced agent workflow and Claude command files to
.gitignore so proprietary automation assets are not committed.

* feat(deepseek-web): fix auth to use userToken + WASM PoW solver

Rewrite deepseek-web executor from broken cookie auth to userToken
Bearer flow (like Chat2API). Replace pure JS Keccak PoW with WASM
solver (5.8s → 86ms). Add 14 models, validation, and dashboard UX.

* fix(deepseek-web): update target_path to use challenge property

* refactor(deepseek-web): streamline token handling and implement cache eviction

* fix(deepseek-web): fix SSE parser, prompt format, and error handling

- Handle all 3 DeepSeek SSE stream formats: initial fragments,
  APPEND operations, and bare string tokens (fixes truncated responses)
- Simplify prompt builder to send system + last user message only
  (DeepSeek web API is single-turn, full history caused marker leakage)
- Check json.code before token extraction (fixes "did not return
  access token: Authorization" on code 40003 with HTTP 200)
- Clear session cache alongside token cache on auth errors
- Add dev origin for remote testing

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: ignore memory-bank and cursor agent rules from tracking

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: enhance documentation and configuration for Fumadocs integration

- Added Fumadocs MDX support in the Next.js configuration.
- Updated transpile packages to include fumadocs-ui and fumadocs-core.
- Implemented a comprehensive set of redirects for documentation paths to improve navigation.
- Removed the generate-docs-index script as it is no longer needed.
- Updated various documentation titles for consistency and clarity.
- Enhanced global styles to incorporate Fumadocs UI themes and styles.

* refactor(docs): cleanup fumadocs PR — revert deepseek, add i18n fallback, restore LanguageSelector

- Revert unrelated deepseek-web.ts changes (should be separate PR)
- Add .source/ to .gitignore (Fumadocs generated files)
- Remove contributor IP from allowedDevOrigins
- Add i18n runtime fallback: reads NEXT_LOCALE cookie, loads translated
  .md from docs/i18n/<locale>/docs/ (preserves existing translation pipeline)
- Restore LanguageSelector in Fumadocs layout nav
- Restore SEO metadata (title template, description, robots)

* fix(codex): use allowlist to strip non-Responses-API fields in non-passthrough path (#2608) (#2615)

Integrated into release/v3.8.3 — fix(codex): allowlist-based sanitization for gpt-5.5 Responses API

* fix(deepseek-web): fix SSE parser, prompt format, error handling, and cache keys (#2616)

Integrated into release/v3.8.3 — fix(deepseek-web): SSE parser (APPEND + bare tokens), prompt builder, error handling, session cache cleanup

* chore(config): ignore additional agent workflow command files

Add newly introduced agent workflow and Claude command files to
.gitignore so proprietary automation assets are not committed.

* feat(docs): migrate /docs to Fumadocs MDX with nested routes (#2614)

Integrated into release/v3.8.3 — Fumadocs MDX migration with nested routes, search API, and 50+ URL redirects

* fix(catalog): skip static PROVIDER_MODELS when synced models exist (#2625)

Integrated into release/v3.8.3

* fix(qoder): Cosy auth fallback for PAT tokens + vision support for qwen3-vl-plus (#2629)

Integrated into release/v3.8.3

* fix(cli): register tsx loader and add opencode config subcommand (#2631)

Integrated into release/v3.8.3

* feat(dashboard): add search and filters to /dashboard/api-manager (#2628)

Integrated into release/v3.8.3

* fix(claude): improve Pi and OpenCode compatibility (#2621)

Integrated into release/v3.8.3

* fix: restore semantic passthrough system-role-only extraction instead of full normalization (#2620)

Integrated into release/v3.8.3

* fix(kiro): stabilize conversationId across prompt compression (#2630)

Integrated into release/v3.8.3

* fix(deepseek-web): SSE thinking/search routing and session lifecycle (#2624)

Integrated into release/v3.8.3 — DeepSeek Web SSE thinking/search routing overhaul

* feat(dashboard): free-tier grouping with symbolic link in /providers (#2632)

Integrated into release/v3.8.3

* fix: close implementation gaps — t3-chat-web, stream_options, combo_strategy, batch config (#2634)

Integrated into release/v3.8.3

* feat(dashboard): risk notice modal for sensitive providers (#2633)

Integrated into release/v3.8.3

* fix(reasoning): extend reasoning_content injection to Kimi K2 and other replay models (#2639)

Integrated into release/v3.8.3

* fix(cli): Linux autostart via systemd user service (fixes #2627) (#2635)

Integrated into release/v3.8.3

* Refactor/providers free tier (#2640)

Integrated into release/v3.8.3

* fix(tests): remove duplicate assertion in schema coercion & fix(cli): ignore system vars in env check

* fix(combo): preserve omniModel tag in streaming output for round-trip context pinning (#2646)

Integrated into release/v3.8.3

* feat(dashboard): media providers pages + Web Fetch category (#2645)

Integrated into release/v3.8.3

* Feature provider adapta org com tutorial de conexão em modal (#2643)

Integrated into release/v3.8.3

* fix(rtk): skip content-based filter matching for non-shell tool results (#2642)

Integrated into release/v3.8.3

* fix(translator): enable Claude extended thinking for Copilot Responses-API requests (#2647)

Integrated into release/v3.8.3

* feat(dashboard): add search and filters to /dashboard/api-manager (#2641)

Integrated into release/v3.8.3

* feat(dashboard): risk notice modal for sensitive providers (#2638)

Integrated into release/v3.8.3

* feat(dashboard): mini-playground inline (Phase 4) (#2648)

Integrated into release/v3.8.3

* fix(settings): fix Require Login modal Cancel button text and dismissal (#2649)

Integrated into release/v3.8.3

* feat(combos): universal context handoff for cross-model conversation continuity (#2653)

Integrated into release/v3.8.3

* chore(release): bump to v3.8.3 — changelog, docs, version sync

* feat(i18n): complete zh-CN translations for 1220 missing keys (#2655)

Integrated into release/v3.8.3

* chore(release): include electron package changes in v3.8.3

* docs(changelog): integrate PR #2655 into v3.8.3

* feat(i18n): translate 377 additional zh-CN entries (81 new keys + 296 same-as-en) (#2659)

Integrated into release/v3.8.3

* feat(dashboard): add Cmd+K / Ctrl+K command palette for sidebar navigation (#2656)

Integrated into release/v3.8.3

* docs: update changelog for PR integrations under v3.8.3

* feat(cli): integrate native updates, autostart and headless CLI mode (#2662)

Integrated into release/v3.8.3

* fix(proxy): save dashboard custom proxies in registry (#2661)

Integrated into release/v3.8.3

* feat(dashboard): chat-first test slide-over (Option A) (#2660)

Integrated into release/v3.8.3

* docs: update changelog with Batch 2 PR merges for v3.8.3

* fix: add xhigh+max to effortLevel schema; add opencode-plugin publish job (#2666)

Integrated into release/v3.8.3

* docs: update changelog with Batch 3 PR #2666 merge for v3.8.3

* feat(quota+providers): card-grid layout, provider group headers, Codex race fix (#2667)

Integrated into release/v3.8.3

* feat(dashboard): real-time live WebSocket monitoring (#2668)

Integrated into release/v3.8.3

* feat(copilot): AI assistant with CodeGraph + CLI + knowledge base (#2669)

Integrated into release/v3.8.3

* feat(pipeline): pre-request middleware hooks (#2670)

Integrated into release/v3.8.3

* feat(resilience): credential health check + adaptive circuit breaker (#2671)

Integrated into release/v3.8.3

* feat(playground): combo routing visual simulator (#2672)

Integrated into release/v3.8.3

* feat(auth): API key groups with model-level permissions (#2673)

Integrated into release/v3.8.3

* feat(pwa): enhanced manifest + push notification support (#2674)

Integrated into release/v3.8.3

* feat(proxy): serverless relay endpoints with rate limiting (#2675)

Integrated into release/v3.8.3

* docs(changelog): update changelog for PRs 2667-2675 & fix: resolve typescript compile-time errors

* fix(db): remove transactions from migrations

Remove explicit transaction wrappers from recent migrations and correct
the API key groups migration metadata. Also fix codegraph path resolution
for ESM environments and refresh generated fumadocs source output.

---------

Co-authored-by: Ömer Vehbe <ovehbe@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Mr. Meowgi <mr@meowgi.dev>
Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
Co-authored-by: amogus22877769 <y.lev357@gmail.com>
Co-authored-by: Halil Tezcan KARABULUT <info@hlltzcnkb.com>
Co-authored-by: Tentoxa <53821604+Tentoxa@users.noreply.github.com>
Co-authored-by: HALDRO <121296348+HALDRO@users.noreply.github.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: janeza2 <49841619+janeza2@users.noreply.github.com>
Co-authored-by: df4p <38404+df4p@users.noreply.github.com>
Co-authored-by: ivan-mezentsev <ivan@mezentsev.me>
Co-authored-by: Chewji <126886556+Chewji9875@users.noreply.github.com>
Co-authored-by: L-aros <107354918+L-aros@users.noreply.github.com>
Co-authored-by: M.M <mr.maatoug@gmail.com>
Co-authored-by: Benson K B <bensonkbmca@gmail.com>
Co-authored-by: terence71-glitch <mcdowellterence71@gmail.com>
2026-05-24 18:05:58 -03:00

352 lines
12 KiB
JavaScript

import { printHeading, printInfo, printSuccess, printError } from "../io.mjs";
import { t } from "../i18n.mjs";
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import { resolveDataDir } from "../data-dir.mjs";
import { registerContexts } from "./contexts.mjs";
function ensureBackup(configPath) {
if (!fs.existsSync(configPath)) return;
const backupDir = path.join(path.dirname(configPath), ".omniroute.bak");
if (!fs.existsSync(backupDir)) fs.mkdirSync(backupDir, { recursive: true });
const backupPath = path.join(backupDir, path.basename(configPath) + ".bak");
fs.copyFileSync(configPath, backupPath);
return backupPath;
}
async function runConfigListCommand(opts = {}) {
const { detectAllTools } = await import("../../../src/lib/cli-helper/tool-detector.js");
const tools = await detectAllTools();
if (opts.json) {
console.log(JSON.stringify(tools, null, 2));
} else {
printHeading("CLI Tool Configuration Status");
for (const t of tools) {
const status = t.configured
? "✓ Configured"
: t.installed
? "✗ Not configured"
: "✗ Not installed";
console.log(` ${t.name.padEnd(14)} ${status}`);
if (t.version) console.log(` version: ${t.version}`);
console.log(` config: ${t.configPath}`);
}
}
return 0;
}
async function runConfigGetCommand(toolId, opts = {}) {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config get <tool>");
return 1;
}
const { detectTool } = await import("../../../src/lib/cli-helper/tool-detector.js");
const tool = await detectTool(toolId);
if (!tool) {
printError(`Unknown tool: ${toolId}`);
return 1;
}
if (opts.json) {
console.log(JSON.stringify(tool, null, 2));
} else {
printHeading(`${tool.name} Configuration`);
console.log(` Installed: ${tool.installed ? "Yes" : "No"}`);
console.log(` Configured: ${tool.configured ? "Yes" : "No"}`);
console.log(` Config: ${tool.configPath}`);
if (tool.version) console.log(` Version: ${tool.version}`);
if (tool.configContents) {
console.log(`\n Contents:`);
console.log(tool.configContents);
}
}
return 0;
}
async function runConfigSetCommand(toolId, opts = {}) {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config set <tool> [options]");
return 1;
}
const baseUrl = opts.baseUrl || "http://localhost:20128/v1";
const apiKey = opts.apiKey;
const model = opts.model;
if (!apiKey) {
printError("API key required. Use --api-key or set OMNIROUTE_API_KEY.");
return 1;
}
const { generateConfig } = await import("../../../src/lib/cli-helper/config-generator/index.js");
const result = await generateConfig(toolId, { baseUrl, apiKey, model });
if (!result.success) {
printError(result.error || "Failed to generate config");
return 1;
}
const nonInteractive = opts.nonInteractive || opts.yes;
if (!nonInteractive) {
console.log(`\n About to write config to: ${result.configPath}`);
console.log(` Content preview:\n`);
console.log(result.content);
console.log("");
const readline = await import("node:readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const answer = await new Promise((resolve) => rl.question("Proceed? [y/N] ", resolve));
rl.close();
if (!/^y(es)?$/i.test(answer)) {
console.log("Aborted.");
return 0;
}
}
const dir = path.dirname(result.configPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const backupPath = ensureBackup(result.configPath);
if (backupPath) printInfo(`Backup saved to: ${backupPath}`);
fs.writeFileSync(result.configPath, result.content, "utf-8");
printSuccess(`Config written to ${result.configPath}`);
return 0;
}
async function runConfigValidateCommand(toolId, opts = {}) {
if (!toolId) {
printError("Tool ID required. Usage: omniroute config validate <tool>");
return 1;
}
const baseUrl = opts.baseUrl || "http://localhost:20128/v1";
const apiKey = opts.apiKey || "test-key";
const model = opts.model;
const { generateConfig } = await import("../../../src/lib/cli-helper/config-generator/index.js");
const result = await generateConfig(toolId, { baseUrl, apiKey, model });
if (!result.success) {
printError(`Validation failed: ${result.error}`);
return 1;
}
printSuccess(`Config for ${toolId} is valid`);
if (opts.json) {
console.log(JSON.stringify({ valid: true, content: result.content }, null, 2));
}
return 0;
}
function loadI18nLocales() {
const cfgPath = path.join(
path.dirname(path.dirname(path.dirname(path.dirname(fileURLToPath(import.meta.url))))),
"config",
"i18n.json"
);
try {
return JSON.parse(fs.readFileSync(cfgPath, "utf8")).locales || [];
} catch {
return [];
}
}
function getCliEnvPath() {
return path.join(resolveDataDir(), ".env");
}
function upsertEnvLine(envPath, key, value) {
let content = "";
if (fs.existsSync(envPath)) content = fs.readFileSync(envPath, "utf8");
const lines = content.split("\n");
const idx = lines.findIndex((l) => l.trimStart().startsWith(`${key}=`));
const newLine = `${key}=${value}`;
if (idx >= 0) {
lines[idx] = newLine;
} else {
if (content && !content.endsWith("\n")) lines.push("");
lines.push(newLine);
}
const dir = path.dirname(envPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const tmp = `${envPath}.tmp`;
fs.writeFileSync(tmp, lines.join("\n"), "utf8");
fs.renameSync(tmp, envPath);
}
export async function runConfigLangGetCommand(opts = {}) {
const { getLocale } = await import("../i18n.mjs");
const code = getLocale();
const locales = loadI18nLocales();
const entry = locales.find((l) => l.code === code);
const name = entry ? entry.english : code;
if (opts.output === "json" || opts.json) {
console.log(JSON.stringify({ code, name }, null, 2));
} else {
console.log(t("config.lang.current", { code, name }));
}
return 0;
}
export async function runConfigLangSetCommand(code, opts = {}) {
if (!code) {
console.error(t("config.lang.noCode"));
return 1;
}
const locales = loadI18nLocales();
const entry = locales.find((l) => l.code === code);
if (!entry) {
console.error(t("config.lang.unknown", { code }));
return 1;
}
const { getLocale, setLocale } = await import("../i18n.mjs");
const current = getLocale();
if (current === code && !opts.force) {
console.log(t("config.lang.alreadySet", { code }));
return 0;
}
const envPath = getCliEnvPath();
upsertEnvLine(envPath, "OMNIROUTE_LANG", code);
setLocale(code);
console.log(t("config.lang.saved", { code, name: entry.english }));
console.log(t("config.lang.envHint", { code }));
return 0;
}
export async function runConfigLangListCommand(opts = {}) {
const { getLocale } = await import("../i18n.mjs");
const current = getLocale();
const locales = loadI18nLocales();
if (opts.output === "json" || opts.json) {
console.log(
JSON.stringify(
locales.map((l) => ({ ...l, active: l.code === current })),
null,
2
)
);
return 0;
}
console.log(`\n\x1b[1m\x1b[36m${t("config.lang.listTitle")}\x1b[0m\n`);
for (const loc of locales) {
const active = loc.code === current ? " \x1b[32m◀ active\x1b[0m" : "";
console.log(
` ${loc.flag} ${loc.code.padEnd(8)} ${loc.english.padEnd(28)} ${loc.native}${active}`
);
}
console.log("");
return 0;
}
export function registerConfig(program) {
const config = program.command("config").description("Show or update CLI tool configuration");
config
.command("list")
.description("List all CLI tools and config status")
.option("--json", "Output as JSON")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigListCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
config
.command("get <tool>")
.description("Show current config for a tool")
.option("--json", "Output as JSON")
.action(async (tool, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigGetCommand(tool, { ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
config
.command("set <tool>")
.description("Write config for a tool")
.option("--model <model>", "Model identifier (where applicable)")
.option("--non-interactive", "Do not prompt for confirmation")
.option("--yes", "Skip confirmation prompt")
.action(async (tool, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigSetCommand(tool, {
...opts,
apiKey: opts.apiKey || globalOpts.apiKey || process.env.OMNIROUTE_API_KEY,
baseUrl: opts.baseUrl || globalOpts.baseUrl || process.env.OMNIROUTE_BASE_URL,
output: globalOpts.output,
});
if (exitCode !== 0) process.exit(exitCode);
});
config
.command("validate <tool>")
.description("Validate config format without writing")
.option("--model <model>", "Model identifier (where applicable)")
.option("--json", "Output as JSON")
.action(async (tool, opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigValidateCommand(tool, {
...opts,
apiKey: opts.apiKey || globalOpts.apiKey || process.env.OMNIROUTE_API_KEY,
baseUrl: opts.baseUrl || globalOpts.baseUrl || process.env.OMNIROUTE_BASE_URL,
output: globalOpts.output,
});
if (exitCode !== 0) process.exit(exitCode);
});
// Convenience alias: `config opencode` → `config set opencode`
// Matches the documented CLI usage in docs/frameworks/OPENCODE.md.
config
.command("opencode")
.description("Generate OpenCode config (alias for 'config set opencode')")
.option("--model <model>", "Model identifier")
.option("--non-interactive", "Do not prompt for confirmation")
.option("--yes", "Skip confirmation prompt")
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.optsWithGlobals();
const exitCode = await runConfigSetCommand("opencode", {
...opts,
apiKey: opts.apiKey || globalOpts.apiKey || process.env.OMNIROUTE_API_KEY,
baseUrl: opts.baseUrl || globalOpts.baseUrl || process.env.OMNIROUTE_BASE_URL,
output: globalOpts.output,
});
if (exitCode !== 0) process.exit(exitCode);
});
// lang subgroup
const lang = config.command("lang").description(t("config.lang.description"));
lang
.command("get")
.description(t("config.lang.getDescription"))
.option("--json", t("common.jsonOpt"))
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.parent.optsWithGlobals();
const exitCode = await runConfigLangGetCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
lang
.command("set <code>")
.description(t("config.lang.setDescription"))
.option("--force", "Set even if already active")
.action(async (code, opts, cmd) => {
const exitCode = await runConfigLangSetCommand(code, opts);
if (exitCode !== 0) process.exit(exitCode);
});
lang
.command("list")
.description(t("config.lang.listDescription"))
.option("--json", t("common.jsonOpt"))
.action(async (opts, cmd) => {
const globalOpts = cmd.parent.parent.optsWithGlobals();
const exitCode = await runConfigLangListCommand({ ...opts, output: globalOpts.output });
if (exitCode !== 0) process.exit(exitCode);
});
// Register contexts/profiles CRUD as a subgroup of config.
registerContexts(config);
}