mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-26 09:52:11 +03:00
* fix(cli-tools): guard modelId type before calling indexOf E2E shakedown v3.8.0: cli-tools quebrava com TypeError quando dynamicModels continha entradas sem .id (objeto retornado diretamente em vez de string). * fix(offline): avoid SSR/CSR hydration mismatch on navigator.onLine Replace useState+lazy-initializer with useSyncExternalStore so the server snapshot (() => false) and client snapshot (() => navigator.onLine) are declared separately. React hydrates with the server value and switches to the real online status client-side without a mismatch. * chore(i18n): add missing en.json keys for translator, cli-tools, memory, onboarding Adds 58 missing keys identified by the new dashboard audit script: - cliTools: 18 custom CLI builder keys (CustomCliCard) - translator: 24 keys covering stream transformer, live monitor, test bench - memory: 12 health/pagination/dialog keys - onboarding.tier: 8 keys for the tier tour walkthrough Also adds scripts/i18n/audit-dashboard-pages.mjs which scans all dashboard pages, reports t() calls referencing missing en.json keys, and flags candidate hardcoded JSX/attribute strings. * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 1) Subagents refactored 8 high-impact dashboard pages, replacing 81 of the 407 hardcoded English/PT strings flagged by the audit with proper useTranslations() lookups. Added 73 corresponding keys to en.json across the home, apiManager, providers, settings, and usage namespaces. Pages affected: - BudgetTab (27 → 0) - HomePageClient (2 → 0) - RoutingTab (25 → 7) - ResilienceTab (38 → 18) - SystemStorageTab (42 → 21) - providers/[id] (17 → 15) - ApiManagerPageClient (14 → 13) - OneproxyTab (13 → 10) Also adds two helper scripts: - scripts/i18n/extract-keys-from-diff.mjs — extracts new keys from git diff - scripts/i18n/merge-keys.mjs — merges a pending-keys JSON into en.json Remaining hardcoded strings will be addressed in follow-up rounds. * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 2) Continues round 1 (commit8d34f4c65). Round-2 subagents refactored additional dashboard pages, replacing 77 more hardcoded strings with useTranslations() lookups. Added 79 corresponding keys to en.json across the a2aDashboard, agents, analytics, apiManager, cliTools, common, and settings namespaces. Pages affected: - a2a/page (new useTranslations + 6 keys) - agent-skills/page (new useTranslations + 9 keys) - AutoRoutingAnalyticsTab (new useTranslations + 6 keys) - AppearanceTab (8 → 6 remaining) - OneproxyTab (10 → 0) - ResilienceTab (18 → 0 missing key) - RoutingTab (7 → 0 missing key) - VisionBridgeSettingsTab (new useTranslations + 6 keys) - CopilotToolCard (7 → 0 missing key) - ApiManagerPageClient (13 → 0 missing key) - gamification/admin (new useTranslations + 7 keys) Hardcoded total: 326 → 249. Real missing keys: 0 (the 6 still flagged are false positives in exampleTemplates.tsx where t is passed as a parameter — keys exist at translator.templatePayloads.*). * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 3) Round-3 subagents and manual edits refactored 9 more dashboard pages (plus 2 small extras), replacing ~80 hardcoded strings with useTranslations() lookups. Added 79 corresponding keys to en.json across analytics, cloudAgents, combos, common, health, settings, and usage namespaces. Pages affected: - analytics/ComboHealthTab (new useTranslations + 15 keys) - analytics/CompressionAnalyticsTab (new useTranslations + 11 keys) - settings/SystemStorageTab (21 → 0 missing key) - tokens/page (new useTranslations + 13 keys) - usage/BudgetTab (9 missing fixed) - health/page (manual: 6 keys) - cloud-agents/page (manual: 3 keys) - combos/page (manual: 1 key) Hardcoded total: 249 → 164. Real missing keys: 0 (6 remaining are exampleTemplates.tsx false positives). Also adds scripts/i18n/build-pending-from-missing.mjs which reads _audit.json and locates English values from HEAD to rebuild _pending-keys.json after race-condition resets between subagent edits. * chore(i18n): localize remaining dashboard settings labels Replace hardcoded labels in compression and resilience settings with translation lookups to continue the dashboard i18n cleanup. Add the v3.8.0 dashboard shakedown runbook to document the manual smoke-test process and known dev environment pitfalls. * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 4) Round-4 subagent + manual key-resolution refactored remaining strings in 3 high-traffic settings/API tabs, plus extracted English values for keys that were already added as t() calls but lost during the previous en.json race-condition resets. Pages affected: - api-manager/ApiManagerPageClient (7 → 0 missing key) - settings/CompressionSettingsTab (8 → 0 missing key) - settings/MemorySkillsTab (8 → 0 missing key) - settings/ResilienceTab (4 more keys recovered) Hardcoded total: 164 → 140. Real missing keys: 0 (6 remaining are the exampleTemplates.tsx false positives — t passed as parameter). * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 5) Round-5 agent began processing the remaining smaller dashboard files. Added 5 more keys to en.json for providers/[id]/page.tsx OAuth flow labels and the cross-OS auto-detection hint. Pages affected: - providers/[id]/page.tsx (5 keys) Hardcoded total: 140 → 136. Real missing keys: 0. * chore(i18n): resolve last 2 missing providers/[id] keys Adds providerDetailMyClaudeAccountPlaceholder and providerDetailPathAutoDetected — the final user-visible labels in the providers/[id] page that the round-5 subagent rewrote to t() calls without yet adding to en.json. Real missing keys: 0 (6 remaining are exampleTemplates.tsx false positives — t is passed as a parameter so the audit cannot resolve the namespace; keys do exist at translator.templatePayloads.*). * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 6 — 10 parallel agents) Round-6 dispatched 10 parallel subagents covering all 57 remaining dashboard files. Each agent worked on a disjoint file set to avoid en.json race conditions. Added ~60 new i18n keys across 9 namespaces covering small UI labels, table headers, search placeholders, and empty-state messages. Major changes: - analytics: SearchAnalyticsTab, ProviderUtilizationTab, DiversityScoreCard, CompressionAnalyticsTab (new useTranslations + keys) - batch: BatchDetailModal, BatchListTab, FileDetailModal, FilesListTab (new useTranslations + keys) - settings: CliproxyapiSettingsTab, PayloadRulesTab, ModelCooldownsCard, AppearanceTab, PricingTab (mostly new useTranslations) - endpoint: TokenSaverCard, ApiEndpointsTab, EndpointPageClient - cache: CachePerformance, IdempotencyLayer, ReasoningCacheTab, MediaPageClient, page - combos: IntelligentComboPanel, page - playground: ChatPlayground, SearchPlayground - providers: ProviderCard - onboarding: TierFlowDiagram - changelog: ChangelogViewer - home: ProviderTopology, TierCoverageWidget, BootstrapBanner, BadgeToast - usage: BudgetTab, BudgetTelemetryCards, QuotaTable - quotaShare: QuotaSharePageClient - profile: page - leaderboard: page - skills: page Hardcoded total: 131 → 60. Real missing keys: 0 plus 1 false-positive for combos.modePack (lookup via prop-passed t). * chore(i18n): finalize round-6 keys for batch/cache/endpoint/usage Adds the remaining keys produced by parallel agents A4, A6, A8, A9: - common: batch-related labels (BatchDetailModal, BatchListTab, FileDetailModal, FilesListTab, page) + profile/leaderboard - cache: hit rate, latency, retry, avg chars - endpoint: token saver, API endpoints, copy URL, cloud/local labels - usage: noSpend, activeSessions, quotaAlerts, budget timing - skills: install/marketplace/filter - proxyRegistry/quotaShare/mcpDashboard: misc labels Hardcoded total: 60 → 48. Real missing keys: 0 (modePack remaining is a false positive — combos.modePack exists but the audit can't resolve it since IntelligentComboPanel receives t as a prop). * fix(playground): dedupe filteredModels to avoid duplicate React key warning The /v1/models endpoint can return the same model id twice (e.g., when a model is listed by both an alias and its canonical provider), which made the <Select> emit two <option> elements with the same key — triggering "Encountered two children with the same key, codex/gpt-5.5". Replace the chained filter + map with a single pass that skips ids already added. * fix(playground): guard against non-string model ids before .split/.startsWith The /v1/models endpoint can include synthetic entries (combos, locals, in-progress imports) with a null/undefined id. The playground used to call m.id.split("/") in the provider-discovery loop, which threw on the first non-string entry; the surrounding .catch(() => {}) silently swallowed the error, so the provider/model/account dropdowns ended up empty even though /v1/models returned thousands of valid entries. - Skip entries without a string id before split/startsWith. - Log the rejection in the .catch handler so future regressions are visible in DevTools instead of silently emptying the UI. * fix(playground): guard ChatPlayground filteredModels for non-string ids Same root cause as commit49fe356b9: ChatPlayground filtered models with m.id.startsWith(...) which crashed on null/undefined ids returned by /v1/models (synthetic combo entries). Apply the same defensive guard and dedupe used in the parent page. * fix(claude): drop orphan tool_result after fixToolAdjacency strip (discussion #2410) Discussion #2410 reports Claude returning 400 for sequences like: assistant: tool_use(id=X) user: <plain text> ← breaks adjacency user: tool_result(id=X) The previous round added `fixToolAdjacency` (commit44d9abac9) which correctly strips the orphan tool_use from the assistant message. But that left the now-unmatched tool_result intact, so the upstream rejected the request with: messages.N.content.M: unexpected `tool_use_id` found in `tool_result` blocks: X. Each tool_result block must have a corresponding tool_use block in the previous message. Fix: after running `fixToolAdjacency`, re-run `fixToolPairs` to drop the orphaned tool_result blocks. All three call sites updated: - contextManager.purifyHistory (both inside the binary-search loop and the final pass) - BaseExecutor message-prep (Claude path) - claudeCodeCompatible request signer Also tightens an unrelated dynamic-key access in readNestedString (claudeCodeCompatible) to satisfy the prototype- pollution scanner triggered by the post-tool semgrep hook. * fix(mitm): point runtime manager re-export to js entrypoint Use the emitted `.js` path for the runtime manager re-export so dynamic runtime loading resolves correctly outside the Turbopack alias handling. * docs: add AgentRouter setup guide (#2422) Integrated into release/v3.8.0 — AgentRouter setup guide docs. * feat: add new feature on combos - falloverBeforeRetry (#2417) Integrated into release/v3.8.0 — falloverBeforeRetry for per-model quota skipping in combos. * feat(batch): implement 10 feature requests harvested (#2414) Integrated into release/v3.8.0 — batch of 10 feature requests: llama.cpp local provider, upstream error exposure, Termux detection, providers rotate CLI, t3.chat web skeleton, Zed Docker integration, Kiro multi-account OAuth isolation, auto-combo cost blending, auto-combo context filter, combo provider-level exhaustion tracking (#1731). Conflicts with #2417 (falloverBeforeRetry) resolved. * fix(gamification): resolve SQL bug, auth gap, pagination, and anomaly scoring (#2421) Integrated into release/v3.8.0 — 6 critical gamification bug fixes: SQL SELECT in checkActionCountBadges, federation auth enforcement, leaderboard pagination offset, real z-score computation, addXp level calculation, and barrel index.ts * docs(changelog): add post-release entries for #2414 #2417 #2421 #2422 - feat(batch): T3-Chat-Web executor, exhaustedProviders set (#1731), Zed Docker - feat(combos): falloverBeforeRetry + setTry loop (#2417 — @hartmark) - fix(gamification): SQL SELECT bug, federation auth, pagination, z-score (#2421 — @oyi77) - docs: AgentRouter setup guide (#2422 — @leninejunior) * fix(security): resolve CodeQL random/password-hash alerts and sync docs & tests --------- Co-authored-by: diegosouzapw <diego.souza.pw@gmail.com> Co-authored-by: Lenine Júnior <lenine@engrene.com.br> Co-authored-by: Markus Hartung <mail@hartmark.se> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
707 lines
22 KiB
JavaScript
707 lines
22 KiB
JavaScript
import { apiFetch, isServerUp } from "../api.mjs";
|
|
import { emit } from "../output.mjs";
|
|
import { printHeading } from "../io.mjs";
|
|
import { getAvailableProviderCategories, loadAvailableProviders } from "../provider-catalog.mjs";
|
|
import { testProviderApiKey } from "../provider-test.mjs";
|
|
import {
|
|
findProviderConnection,
|
|
getProviderApiKey,
|
|
listProviderConnections,
|
|
updateProviderApiKey,
|
|
updateProviderTestResult,
|
|
} from "../provider-store.mjs";
|
|
import { encryptCredential } from "../encryption.mjs";
|
|
import { openOmniRouteDb } from "../sqlite.mjs";
|
|
import { t } from "../i18n.mjs";
|
|
|
|
function publicConnection(connection) {
|
|
return {
|
|
id: connection.id,
|
|
provider: connection.provider,
|
|
name: connection.name,
|
|
authType: connection.authType,
|
|
isActive: connection.isActive,
|
|
testStatus: connection.testStatus,
|
|
lastTested: connection.lastTested,
|
|
lastError: connection.lastError,
|
|
defaultModel: connection.defaultModel,
|
|
};
|
|
}
|
|
|
|
function statusColor(status) {
|
|
if (status === "active" || status === "success") return "\x1b[32m";
|
|
if (status === "error" || status === "expired" || status === "unavailable") return "\x1b[31m";
|
|
return "\x1b[33m";
|
|
}
|
|
|
|
function printProviderTable(connections) {
|
|
if (connections.length === 0) {
|
|
console.log("No providers configured.");
|
|
return;
|
|
}
|
|
|
|
for (const connection of connections) {
|
|
const shortId = connection.id.slice(0, 8);
|
|
const status = connection.testStatus || "unknown";
|
|
const color = statusColor(status);
|
|
console.log(
|
|
`${shortId.padEnd(10)} ${connection.provider.padEnd(14)} ${String(connection.name).padEnd(
|
|
24
|
|
)} ${color}${status}\x1b[0m`
|
|
);
|
|
}
|
|
}
|
|
|
|
function normalizeCategoryFilter(category) {
|
|
const normalized = String(category || "")
|
|
.trim()
|
|
.toLowerCase()
|
|
.replaceAll("_", "-");
|
|
if (normalized === "apikey") return "api-key";
|
|
return normalized;
|
|
}
|
|
|
|
function availableProviderNotes(provider) {
|
|
const notes = [];
|
|
if (provider.alias) notes.push(`alias:${provider.alias}`);
|
|
if (provider.hasFree) notes.push("free");
|
|
if (provider.passthroughModels) notes.push("passthrough");
|
|
if (provider.deprecated) notes.push("deprecated");
|
|
return notes.join(", ");
|
|
}
|
|
|
|
function publicAvailableProvider(provider) {
|
|
return {
|
|
id: provider.id,
|
|
name: provider.name,
|
|
category: provider.category,
|
|
alias: provider.alias,
|
|
website: provider.website,
|
|
deprecated: provider.deprecated,
|
|
hasFree: provider.hasFree,
|
|
passthroughModels: provider.passthroughModels,
|
|
};
|
|
}
|
|
|
|
function filterAvailableProviders(providers, opts) {
|
|
const search = String(opts.search || opts.q || "")
|
|
.trim()
|
|
.toLowerCase();
|
|
const category = normalizeCategoryFilter(opts.category);
|
|
|
|
return providers.filter((provider) => {
|
|
if (category && provider.category !== category) return false;
|
|
if (!search) return true;
|
|
|
|
return [provider.id, provider.name, provider.category, provider.alias]
|
|
.filter(Boolean)
|
|
.some((value) => String(value).toLowerCase().includes(search));
|
|
});
|
|
}
|
|
|
|
function printAvailableProviderTable(providers, categories) {
|
|
if (providers.length === 0) {
|
|
console.log("No available providers matched the filters.");
|
|
return;
|
|
}
|
|
|
|
console.log(`${providers.length} providers available.`);
|
|
console.log(`Categories: ${categories.join(", ")}`);
|
|
console.log("Use --search <text> or --category <category> to filter.\n");
|
|
console.log(`${"ID".padEnd(24)} ${"Category".padEnd(14)} ${"Name".padEnd(28)} Notes`);
|
|
|
|
for (const provider of providers) {
|
|
console.log(
|
|
`${provider.id.padEnd(24)} ${provider.category.padEnd(14)} ${String(provider.name).padEnd(
|
|
28
|
|
)} ${availableProviderNotes(provider)}`
|
|
);
|
|
}
|
|
}
|
|
|
|
function buildTestInput(connection, apiKey) {
|
|
return {
|
|
provider: connection.provider,
|
|
apiKey,
|
|
defaultModel: connection.defaultModel,
|
|
baseUrl: connection.providerSpecificData?.baseUrl || null,
|
|
};
|
|
}
|
|
|
|
async function runProviderTest(db, connection) {
|
|
try {
|
|
const apiKey = getProviderApiKey(connection);
|
|
const result = await testProviderApiKey(buildTestInput(connection, apiKey));
|
|
updateProviderTestResult(db, connection.id, result);
|
|
return {
|
|
connection: publicConnection(connection),
|
|
...result,
|
|
};
|
|
} catch (error) {
|
|
const result = {
|
|
valid: false,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
statusCode: null,
|
|
};
|
|
updateProviderTestResult(db, connection.id, result);
|
|
return {
|
|
connection: publicConnection(connection),
|
|
...result,
|
|
};
|
|
}
|
|
}
|
|
|
|
function validateConnection(connection) {
|
|
const issues = [];
|
|
const warnings = [];
|
|
|
|
if (!connection.id) issues.push("Missing id");
|
|
if (!connection.provider) issues.push("Missing provider");
|
|
if (!connection.authType) warnings.push("Missing auth type");
|
|
|
|
if (connection.authType === "apikey") {
|
|
try {
|
|
getProviderApiKey(connection);
|
|
} catch (error) {
|
|
issues.push(error instanceof Error ? error.message : String(error));
|
|
}
|
|
} else if (!connection.accessToken && !connection.refreshToken) {
|
|
warnings.push("OAuth connection has no access or refresh token visible locally");
|
|
}
|
|
|
|
if (connection.providerSpecificData === null && connection.providerSpecificData !== undefined) {
|
|
warnings.push("provider_specific_data is absent or not an object");
|
|
}
|
|
|
|
return {
|
|
connection: publicConnection(connection),
|
|
valid: issues.length === 0,
|
|
issues,
|
|
warnings,
|
|
};
|
|
}
|
|
|
|
export async function runAvailableCommand(opts = {}) {
|
|
const allProviders = loadAvailableProviders();
|
|
const providers = filterAvailableProviders(allProviders, opts).map(publicAvailableProvider);
|
|
const categories = getAvailableProviderCategories(allProviders);
|
|
|
|
if (opts.json) {
|
|
console.log(JSON.stringify({ count: providers.length, categories, providers }, null, 2));
|
|
} else {
|
|
printHeading("OmniRoute Available Providers");
|
|
printAvailableProviderTable(providers, categories);
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
export async function runListCommand(opts = {}) {
|
|
const { db } = await openOmniRouteDb();
|
|
try {
|
|
const connections = listProviderConnections(db).map(publicConnection);
|
|
if (opts.json) {
|
|
console.log(JSON.stringify({ providers: connections }, null, 2));
|
|
} else {
|
|
printHeading("OmniRoute Providers");
|
|
printProviderTable(connections);
|
|
}
|
|
return 0;
|
|
} finally {
|
|
db.close();
|
|
}
|
|
}
|
|
|
|
export async function runTestCommand(selector, opts = {}) {
|
|
if (!selector) {
|
|
console.error("Provider id or name is required.");
|
|
return 1;
|
|
}
|
|
|
|
const { db } = await openOmniRouteDb();
|
|
try {
|
|
const connection = findProviderConnection(db, selector);
|
|
if (!connection) {
|
|
console.error(`Provider connection not found: ${selector}`);
|
|
return 1;
|
|
}
|
|
|
|
const result = await runProviderTest(db, connection);
|
|
if (opts.json) {
|
|
console.log(JSON.stringify(result, null, 2));
|
|
} else if (result.valid) {
|
|
console.log(`\x1b[32mOK\x1b[0m ${connection.name}: provider test passed`);
|
|
} else {
|
|
console.log(`\x1b[31mFAIL\x1b[0m ${connection.name}: ${result.error}`);
|
|
}
|
|
return result.valid ? 0 : 1;
|
|
} finally {
|
|
db.close();
|
|
}
|
|
}
|
|
|
|
export async function runTestAllCommand(opts = {}) {
|
|
const { db } = await openOmniRouteDb();
|
|
try {
|
|
const connections = listProviderConnections(db);
|
|
const results = [];
|
|
for (const connection of connections) {
|
|
if (!connection.isActive) {
|
|
results.push({
|
|
connection: publicConnection(connection),
|
|
valid: false,
|
|
skipped: true,
|
|
error: "Connection is inactive",
|
|
});
|
|
continue;
|
|
}
|
|
results.push(await runProviderTest(db, connection));
|
|
}
|
|
|
|
if (opts.json) {
|
|
console.log(JSON.stringify({ results }, null, 2));
|
|
} else {
|
|
printHeading("OmniRoute Provider Tests");
|
|
for (const result of results) {
|
|
const label = result.valid
|
|
? "\x1b[32mOK\x1b[0m"
|
|
: result.skipped
|
|
? "\x1b[33mSKIP\x1b[0m"
|
|
: "\x1b[31mFAIL\x1b[0m";
|
|
console.log(
|
|
`${label} ${result.connection.name}: ${result.valid ? "provider test passed" : result.error}`
|
|
);
|
|
}
|
|
}
|
|
|
|
return results.some((result) => !result.valid && !result.skipped) ? 1 : 0;
|
|
} finally {
|
|
db.close();
|
|
}
|
|
}
|
|
|
|
export async function runValidateCommand(opts = {}) {
|
|
const { db } = await openOmniRouteDb();
|
|
try {
|
|
const results = listProviderConnections(db).map(validateConnection);
|
|
if (opts.json) {
|
|
console.log(JSON.stringify({ results }, null, 2));
|
|
} else {
|
|
printHeading("OmniRoute Provider Validation");
|
|
if (results.length === 0) {
|
|
console.log("No providers configured.");
|
|
}
|
|
for (const result of results) {
|
|
const label = result.valid ? "\x1b[32mOK\x1b[0m" : "\x1b[31mFAIL\x1b[0m";
|
|
const messages = [...result.issues, ...result.warnings].join("; ");
|
|
console.log(`${label} ${result.connection.name}${messages ? `: ${messages}` : ""}`);
|
|
}
|
|
}
|
|
return results.some((result) => !result.valid) ? 1 : 0;
|
|
} finally {
|
|
db.close();
|
|
}
|
|
}
|
|
|
|
export async function runProvidersRotateCommand(selector, opts = {}) {
|
|
if (!selector) {
|
|
console.error("Provider connection id or name is required.");
|
|
return 2;
|
|
}
|
|
|
|
// --- Resolve connection ---
|
|
const { db } = await openOmniRouteDb();
|
|
let connection;
|
|
try {
|
|
connection = findProviderConnection(db, selector);
|
|
} finally {
|
|
db.close();
|
|
}
|
|
|
|
if (!connection) {
|
|
console.error(`Provider connection not found: ${selector}`);
|
|
return 2;
|
|
}
|
|
|
|
// --- OAuth short-circuit ---
|
|
if (opts.oauth || connection.authType !== "apikey") {
|
|
console.log(t("providers.rotate.oauthHint", { provider: connection.provider }));
|
|
return 0;
|
|
}
|
|
|
|
// --- Source new key ---
|
|
let newKey;
|
|
if (opts.fromEnv) {
|
|
newKey = process.env[opts.fromEnv];
|
|
if (!newKey) {
|
|
console.error(t("providers.rotate.envVarEmpty", { var: opts.fromEnv }));
|
|
return 2;
|
|
}
|
|
} else if (opts.newKey) {
|
|
newKey = opts.newKey;
|
|
} else {
|
|
// Interactive prompt (echo-off not strictly needed for a key value, but best practice)
|
|
const readline = await import("node:readline");
|
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
newKey = await new Promise((resolve) =>
|
|
rl.question(`New API key for ${connection.name}: `, (a) => {
|
|
rl.close();
|
|
resolve(a.trim());
|
|
})
|
|
);
|
|
if (!newKey) {
|
|
console.error("No key provided.");
|
|
return 2;
|
|
}
|
|
}
|
|
|
|
// --- Dry-run ---
|
|
if (opts.dryRun) {
|
|
console.log(
|
|
t("providers.rotate.dryRunResult", { name: connection.name, id: connection.id.slice(0, 8) })
|
|
);
|
|
return 0;
|
|
}
|
|
|
|
// --- Confirm ---
|
|
if (!opts.yes) {
|
|
const readline = await import("node:readline");
|
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
const answer = await new Promise((resolve) =>
|
|
rl.question(
|
|
t("providers.rotate.confirmPrompt", {
|
|
name: connection.name,
|
|
id: connection.id.slice(0, 8),
|
|
}),
|
|
resolve
|
|
)
|
|
);
|
|
rl.close();
|
|
if (!/^y(es|s)?$/i.test(answer)) {
|
|
console.log(t("common.cancelled"));
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
// --- Write ---
|
|
const serverUp = await isServerUp();
|
|
if (serverUp) {
|
|
try {
|
|
const res = await apiFetch(`/api/providers/${encodeURIComponent(connection.id)}`, {
|
|
method: "PATCH",
|
|
body: {
|
|
apiKey: newKey,
|
|
testStatus: "unknown",
|
|
lastError: null,
|
|
rateLimitedUntil: null,
|
|
backoffLevel: 0,
|
|
},
|
|
retry: false,
|
|
acceptNotOk: true,
|
|
});
|
|
if (!res.ok) {
|
|
console.error(t("common.error", { message: `HTTP ${res.status}` }));
|
|
return 1;
|
|
}
|
|
} catch {
|
|
// Fall through to direct DB write
|
|
const { db: db2 } = await openOmniRouteDb();
|
|
try {
|
|
updateProviderApiKey(db2, connection.id, encryptCredential(newKey));
|
|
} finally {
|
|
db2.close();
|
|
}
|
|
}
|
|
} else {
|
|
const { db: db2 } = await openOmniRouteDb();
|
|
try {
|
|
updateProviderApiKey(db2, connection.id, encryptCredential(newKey));
|
|
} finally {
|
|
db2.close();
|
|
}
|
|
}
|
|
|
|
console.log(
|
|
t("providers.rotate.success", { name: connection.name, id: connection.id.slice(0, 8) })
|
|
);
|
|
|
|
// --- Post-rotation test ---
|
|
if (!opts.skipTest) {
|
|
const { db: db3 } = await openOmniRouteDb();
|
|
try {
|
|
const fresh = findProviderConnection(db3, connection.id);
|
|
if (fresh) {
|
|
const result = await runProviderTest(db3, fresh);
|
|
if (result.valid) {
|
|
console.log(t("providers.rotate.testPassed"));
|
|
} else {
|
|
console.error(t("providers.rotate.testFailed", { error: result.error }));
|
|
}
|
|
}
|
|
} finally {
|
|
db3.close();
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
export async function runProvidersStatusCommand(opts = {}) {
|
|
const serverUp = await isServerUp();
|
|
if (!serverUp) {
|
|
console.error(t("providers.status.requiresServer"));
|
|
return 3;
|
|
}
|
|
|
|
const res = await apiFetch("/api/providers/expiration", { acceptNotOk: true, retry: false });
|
|
if (!res.ok) {
|
|
console.error(t("common.error", { message: `HTTP ${res.status}` }));
|
|
return 1;
|
|
}
|
|
|
|
const data = await res.json();
|
|
const list = data.list || [];
|
|
|
|
// Optional provider filter
|
|
const filter = opts.provider ? String(opts.provider).toLowerCase() : null;
|
|
const rows = filter ? list.filter((item) => item.provider?.toLowerCase().includes(filter)) : list;
|
|
|
|
if (opts.json || opts.output === "json") {
|
|
console.log(JSON.stringify({ count: rows.length, connections: rows }, null, 2));
|
|
return 0;
|
|
}
|
|
|
|
if (rows.length === 0) {
|
|
console.log(t("providers.status.noData"));
|
|
return 0;
|
|
}
|
|
|
|
console.log(t("providers.status.header"));
|
|
for (const item of rows) {
|
|
const shortId = (item.connectionId || item.id || "").slice(0, 8);
|
|
const expiry = item.expiresAt ? new Date(item.expiresAt).toLocaleDateString() : "-";
|
|
const expiryStatus = item.status || "unknown";
|
|
const testStatus = item.testStatus || "unknown";
|
|
const cooldown = item.rateLimitedUntil ? new Date(item.rateLimitedUntil).toLocaleString() : "-";
|
|
const expiryColor = statusColor(expiryStatus);
|
|
const testColor = statusColor(testStatus);
|
|
console.log(
|
|
`${shortId.padEnd(10)} ${String(item.provider || "").padEnd(14)} ${String(item.name || "").padEnd(24)} ` +
|
|
`${expiry.padEnd(12)} ${expiryColor}${expiryStatus.padEnd(8)}\x1b[0m ` +
|
|
`${testColor}${testStatus.padEnd(12)}\x1b[0m ${cooldown}`
|
|
);
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
export function registerProviders(program) {
|
|
const providers = program.command("providers").description(t("providers.title"));
|
|
|
|
providers
|
|
.command("available")
|
|
.description("Show available providers in the OmniRoute catalog")
|
|
.option("--json", "Print machine-readable JSON")
|
|
.option("--search <query>", "Filter by id, name, alias, or category")
|
|
.option("-q, --q <query>", "Alias for --search")
|
|
.option("--category <category>", "Filter by category (api-key, oauth, free)")
|
|
.action(async (opts, cmd) => {
|
|
const globalOpts = cmd.parent.optsWithGlobals();
|
|
const exitCode = await runAvailableCommand({ ...opts, output: globalOpts.output });
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
|
|
providers
|
|
.command("list")
|
|
.description("List configured provider connections")
|
|
.option("--json", "Print machine-readable JSON")
|
|
.action(async (opts, cmd) => {
|
|
const globalOpts = cmd.parent.optsWithGlobals();
|
|
const exitCode = await runListCommand({ ...opts, output: globalOpts.output });
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
|
|
providers
|
|
.command("test <idOrName>")
|
|
.description("Test a configured provider connection")
|
|
.option("--json", "Print machine-readable JSON")
|
|
.action(async (idOrName, opts, cmd) => {
|
|
const globalOpts = cmd.parent.optsWithGlobals();
|
|
const exitCode = await runTestCommand(idOrName, { ...opts, output: globalOpts.output });
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
|
|
providers
|
|
.command("test-all")
|
|
.description("Test all active provider connections")
|
|
.option("--json", "Print machine-readable JSON")
|
|
.action(async (opts, cmd) => {
|
|
const globalOpts = cmd.parent.optsWithGlobals();
|
|
const exitCode = await runTestAllCommand({ ...opts, output: globalOpts.output });
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
|
|
providers
|
|
.command("validate")
|
|
.description("Validate local provider configuration without calling upstream")
|
|
.option("--json", "Print machine-readable JSON")
|
|
.action(async (opts, cmd) => {
|
|
const globalOpts = cmd.parent.optsWithGlobals();
|
|
const exitCode = await runValidateCommand({ ...opts, output: globalOpts.output });
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
|
|
providers
|
|
.command("rotate <idOrName>")
|
|
.description(t("providers.rotate.description"))
|
|
.option("--new-key <key>", t("providers.rotate.newKeyOpt"))
|
|
.option("--from-env <VAR>", t("providers.rotate.fromEnvOpt"))
|
|
.option("--oauth", t("providers.rotate.oauthOpt"))
|
|
.option("--yes", t("common.yesOpt"))
|
|
.option("--skip-test", t("providers.rotate.skipTestOpt"))
|
|
.option("--dry-run", t("providers.rotate.dryRunOpt"))
|
|
.action(async (idOrName, opts, cmd) => {
|
|
const globalOpts = cmd.parent.optsWithGlobals();
|
|
const exitCode = await runProvidersRotateCommand(idOrName, {
|
|
...opts,
|
|
output: globalOpts.output,
|
|
});
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
|
|
providers
|
|
.command("status")
|
|
.description(t("providers.status.description"))
|
|
.option("--provider <name>", t("providers.status.providerOpt"))
|
|
.option("--json", "Print machine-readable JSON")
|
|
.action(async (opts, cmd) => {
|
|
const globalOpts = cmd.parent.optsWithGlobals();
|
|
const exitCode = await runProvidersStatusCommand({ ...opts, output: globalOpts.output });
|
|
if (exitCode !== 0) process.exit(exitCode);
|
|
});
|
|
|
|
extendProvidersMetrics(providers);
|
|
}
|
|
|
|
const providerMetricsSchema = [
|
|
{ key: "provider", header: "Provider", width: 20 },
|
|
{ key: "requests", header: "Reqs", formatter: (v) => (v != null ? v.toLocaleString() : "0") },
|
|
{
|
|
key: "successRate",
|
|
header: "Success %",
|
|
formatter: (v) => (v != null ? `${(v * 100).toFixed(1)}%` : "-"),
|
|
},
|
|
{
|
|
key: "avgLatencyMs",
|
|
header: "Avg Latency",
|
|
formatter: (v) => (v ? `${Math.round(v)}ms` : "-"),
|
|
},
|
|
{ key: "latencyP95Ms", header: "P95", formatter: (v) => (v ? `${v}ms` : "-") },
|
|
{
|
|
key: "costUsd",
|
|
header: "Cost (USD)",
|
|
formatter: (v) => (v != null ? `$${Number(v).toFixed(4)}` : "-"),
|
|
},
|
|
{ key: "errors", header: "Errors", formatter: (v) => (v != null ? String(v) : "0") },
|
|
{ key: "breakerState", header: "Breaker" },
|
|
];
|
|
|
|
function sortRows(rows, sortBy) {
|
|
if (!sortBy) return rows;
|
|
return [...rows].sort((a, b) => {
|
|
const av = a[sortBy] ?? 0;
|
|
const bv = b[sortBy] ?? 0;
|
|
return bv > av ? 1 : bv < av ? -1 : 0;
|
|
});
|
|
}
|
|
|
|
export async function runProvidersMetrics(opts, cmd) {
|
|
const globalOpts = cmd.optsWithGlobals();
|
|
|
|
const fetchMetrics = async () => {
|
|
const params = new URLSearchParams({ period: opts.period ?? "24h" });
|
|
if (opts.provider) params.set("provider", opts.provider);
|
|
if (opts.connectionId) params.set("connectionId", opts.connectionId);
|
|
if (opts.compare) params.set("providers", opts.compare);
|
|
const res = await apiFetch(`/api/provider-metrics?${params}`, {
|
|
timeout: globalOpts.timeout,
|
|
acceptNotOk: true,
|
|
});
|
|
if (!res.ok) return [];
|
|
const data = await res.json();
|
|
const raw = data.metrics ?? data.items ?? data.providers ?? data;
|
|
if (Array.isArray(raw)) return raw;
|
|
return Object.entries(raw).map(([provider, m]) => ({
|
|
provider,
|
|
...(typeof m === "object" && m !== null ? m : {}),
|
|
}));
|
|
};
|
|
|
|
const renderOnce = async () => {
|
|
const rows = await fetchMetrics();
|
|
const sorted = sortRows(rows, opts.sortBy);
|
|
emit(sorted.slice(0, opts.limit ?? 50), globalOpts, providerMetricsSchema);
|
|
};
|
|
|
|
if (opts.watch) {
|
|
process.stderr.write("[watching — Ctrl+C to exit]\n");
|
|
await renderOnce();
|
|
const interval = setInterval(async () => {
|
|
process.stdout.write("\x1b[2J\x1b[H");
|
|
await renderOnce();
|
|
}, 5000);
|
|
process.on("SIGINT", () => {
|
|
clearInterval(interval);
|
|
process.exit(0);
|
|
});
|
|
return;
|
|
}
|
|
|
|
await renderOnce();
|
|
}
|
|
|
|
export async function runProviderMetricSingle(id, metric, opts, cmd) {
|
|
const globalOpts = cmd.optsWithGlobals();
|
|
const params = new URLSearchParams({ connectionId: id, period: opts.period ?? "24h" });
|
|
const res = await apiFetch(`/api/provider-metrics?${params}`, {
|
|
timeout: globalOpts.timeout,
|
|
acceptNotOk: true,
|
|
});
|
|
if (!res.ok) {
|
|
process.stderr.write(t("common.serverOffline") + "\n");
|
|
process.exit(res.exitCode ?? 1);
|
|
}
|
|
const data = await res.json();
|
|
const raw = data.metrics ?? data;
|
|
const connData =
|
|
raw[id] ??
|
|
(Array.isArray(raw) ? raw.find((r) => r.connectionId === id || r.provider === id) : null);
|
|
const value = connData?.[metric] ?? connData;
|
|
if (globalOpts.output === "json") {
|
|
process.stdout.write(JSON.stringify(value, null, 2) + "\n");
|
|
} else {
|
|
process.stdout.write(`${metric}: ${JSON.stringify(value)}\n`);
|
|
}
|
|
}
|
|
|
|
export function extendProvidersMetrics(providers) {
|
|
providers
|
|
.command("metrics")
|
|
.description(t("providers.metrics.description"))
|
|
.option("--provider <id>", t("providers.metrics.provider"))
|
|
.option("--connection-id <id>", t("providers.metrics.connection_id"))
|
|
.option("--period <p>", t("providers.metrics.period"), "24h")
|
|
.option("--metric <m>", t("providers.metrics.metric"))
|
|
.option("--sort-by <field>", t("providers.metrics.sort"))
|
|
.option("--limit <n>", t("providers.metrics.limit"), parseInt, 50)
|
|
.option("--watch", t("providers.metrics.watch"))
|
|
.option("--compare <list>", t("providers.metrics.compare"))
|
|
.action(runProvidersMetrics);
|
|
|
|
providers
|
|
.command("metric <connectionId> <metric>")
|
|
.description(t("providers.metric_single.description"))
|
|
.option("--period <p>", t("providers.metrics.period"), "24h")
|
|
.action(runProviderMetricSingle);
|
|
}
|