mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-01 04:42:10 +03:00
* chore(release): open v3.8.13 development cycle Bump 3.8.12 → 3.8.13 across package.json, lockfile, electron/, open-sse/, and docs/reference/openapi.yaml; add the [3.8.13] cycle placeholder to the root CHANGELOG and the 41 i18n mirrors. Integration branch for the v3.8.13 cycle — fixes/features land here via per-issue PRs and it merges to main at release time. * fix(ci): skip auto-deploy when VPS host is unreachable from the runner (#3299) Integrated into release/v3.8.13 * fix(dev): auto-rebuild better-sqlite3 on Node ABI mismatch at dev startup (#3301) Integrated into release/v3.8.13 * feat(api): accept path-scoped API keys on client API routes (#3300) Integrated into release/v3.8.13 * fix(sse): harden against empty responses causing Copilot Chat failures (#3297) Integrated into release/v3.8.13 * fix(api): remove Completions.me rickroll provider (discussion #3293) (#3302) Integrated into release/v3.8.13 * fix(opencode-provider): extract contextLength from live model catalog (#3298) Integrated into release/v3.8.13 * feat(web-cookie): self-service login infrastructure + auto-refresh daemon (#3292) Integrated into release/v3.8.13 * docs(changelog): record the v3.8.13 PRs merged this round (#3292/#3300/#3297/#3298/#3301/#3302/#3299) * fix(auth): harden URL token extraction — drop query-string fallback, gate to client routes (security follow-up to #3300) (#3309) Security follow-up to #3300 — integrated into release/v3.8.13 * docs: rename resolve-issues → review-issues skill references * fix(dashboard): keep no-auth providers visible under 'Show configured only' (#3290) (#3312) no-auth providers (opencode, duckduckgo-web, theoldllm, veoaifree-web) never create a DB connection row so stats.total stays 0, which the configured-only filter treated as 'unconfigured' and hid them — even though they are always usable and appear unconditionally in /v1/models. filterConfiguredProviderEntries now treats displayAuthType === 'no-auth' as configured. Co-authored-by: uniQta <uniQta@users.noreply.github.com> * fix(cli): resolve update paths relative to script + recursive backup (#3295) (#3313) omniroute update always failed on a global install: - getCurrentVersion() read package.json from process.cwd(), which on a global npm/brew install is the user's working dir, not the package root → null → 'Could not determine current version'. - createBackup() resolved bin/ from cwd too, and passed the 'cli' directory to copyFileSync → EISDIR, swallowed by the catch → 'Failed to create backup'. Both now resolve package.json/bin relative to the script via import.meta.url, and the backup uses cpSync({recursive:true}) so the cli/ directory is copied. Co-authored-by: uniQta <uniQta@users.noreply.github.com> * fix(theoldllm): read upstream body once to avoid [502] body-already-read (#3296) (#3314) On the cached-token path the executor never enters the refresh branch, so the same upstream Response was read with .text() twice (token-rejection check + final body). A Response body is single-use, so the second read threw 'Body is unusable: Body has already been read', caught and surfaced as [502]. Read the body once into finalBody and only re-read after a token-rejection refetch. Co-authored-by: onizukashonan14-png <onizukashonan14-png@users.noreply.github.com> * fix(sse): strip leaked internal tool envelopes from streaming output (#3311) Integrated into release/v3.8.13 * fix(sse): expose Claude + Gemini budget tiers in the antigravity catalog (#3184) (#3303) Integrated into release/v3.8.13 (#3184) * fix(catalog): compute combo context_length from known targets only (#3304) Integrated into release/v3.8.13 — live contextLength + known-targets combo context (#3298 follow-up) * chore(i18n): add message keys for proxy UI + vscode/ollama endpoint (#3307) Integrated into release/v3.8.13 — i18n message keys for proxy UI + vscode/ollama * feat(dashboard): i18n the proxy settings UI (#3310) Integrated into release/v3.8.13 — i18n the proxy settings UI * feat(api): model catalog enrichment + MCP model-catalog tools (#3306) Integrated into release/v3.8.13 — model catalog enrichment + MCP model-catalog tools, reconciled with #3309 URL-token hardening * test(catalog): align Antigravity preview-alias test with #3303 budget tiers #3303 added the Gemini `-high`/`-low` budget tiers to ANTIGRAVITY_PUBLIC_MODELS (user-callable on the Antigravity OAuth backend, verified via #3184), but did not update the catalog-route test that asserted `antigravity/gemini-3.1-pro-high` must NOT be exposed. The assertion now reflects the intended behavior — the client-visible budget alias IS surfaced — while keeping the legacy `gemini-claude-*` alias keys unexposed. Caught running the full catalog suite on the merged release HEAD (the #3303 round only ran the antigravity-aliases and usage-hardening files). * docs(changelog): record the 6 PRs merged this review round into v3.8.13 #3306/#3307/#3310 (New Features — VS Code split: catalog+MCP, i18n keys, proxy UI i18n), #3311/#3303/#3304 (Bug Fixes — SSE envelope sanitizer, antigravity budget tiers, combo known-targets context_length). * chore(release): finalize v3.8.13 changelog and cleanup Finalize the v3.8.13 changelog with release date, maintenance notes, and contributor credits. Update MCP docs to reference the correct tool inventory diagram, exclude nested .claude worktrees from ESLint scans, and tighten a response sanitizer type guard. * fix(dashboard): refresh connections after provider auth import (#3320) Integrated into release/v3.8.13 — refresh connections after provider auth import * fix(codex): strip client-only params on native /responses passthrough (#3317) (#3325) A /v1/responses request against the built-in codex/ provider does an openai-responses -> openai-responses passthrough (CodexExecutor.transformRequest returns the body early for _nativeCodexPassthrough). It forwarded client-only fields verbatim and the Codex upstream rejected them with 400 Unsupported parameter: prompt_cache_retention / safety_identifier / user — breaking Factory Droid (which injects all three). The chat-completions path already strips these (base.ts #1884, openai-responses translator #2770) but the passthrough skips translation. Strip the three fields in the shared block before the passthrough return; user is removed unconditionally since Codex /responses always rejects it. Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com> * fix(dashboard): normalize agent-bridge /state response to stop page crash (#3318) (#3326) The Agent Bridge page seeded a well-shaped initialData default then replaced it wholesale with the raw /api/tools/agent-bridge/state response. The route returns { server, agents } but the UI reads { serverState, agentStates, bypassPatterns, mappings }, so serverState became undefined and AgentBridgeServerCard crashed on serverState.running — surfaced as the full-page 'Internal Server Error' boundary (client render error, not a real 5xx). Add a shared normalizeAgentBridgeState() that maps the route shape into the page contract (server.running/certExists -> serverState) and always returns safe defaults (never undefined serverState). Wired into both the SSR loader (page.tsx) and the polling hook. The legacy 'agents' entry shape differs from AgentStateEntry so it is not coerced; full route<->page contract reconciliation (port, upstreamCa, bypassPatterns, mappings, agentStates) is a follow-up. Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com> * docs: VS Code/Ollama endpoints + env & i18n tooling (#3319) Integrated into release/v3.8.13 — VS Code/Ollama docs + env & i18n tooling * feat(provider): test-all endpoint, rate-limit overrides, visibility f… (#3267) Integrated into release/v3.8.13 — provider test-all endpoint, rate-limit overrides, model visibility * feat: auto-combo optimization, playground model dropdown, only-configured toggle (#3322) Integrated into release/v3.8.13 — auto-combo candidate expansion + playground dropdown + only-configured toggle * feat(api): VS Code Copilot Ollama-compatible BYOK endpoint (#3316) Integrated into release/v3.8.13 — VS Code Copilot Ollama-compatible BYOK endpoint (reconciled with #3306/#3309 auth hardening) * chore(release): document #3320 in the v3.8.13 changelog + contributor credits --------- Co-authored-by: Felipe Almeman <4226997+zhiru@users.noreply.github.com> Co-authored-by: Wilson <pedbookmed@gmail.com> Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: uniQta <uniQta@users.noreply.github.com> Co-authored-by: onizukashonan14-png <onizukashonan14-png@users.noreply.github.com> Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com> Co-authored-by: Vinayrnani <vinayrnani@gmail.com>
336 lines
9.8 KiB
TypeScript
336 lines
9.8 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { POST as postChatCompletion } from "@/app/api/v1/chat/completions/route";
|
|
import { handleValidatedEmbeddingRequestBody } from "@/app/api/v1/embeddings/route";
|
|
import { POST as postRerank } from "@/app/api/v1/rerank/route";
|
|
import { buildComboTestRequestBody, extractComboTestResponseText } from "@/lib/combos/testHealth";
|
|
import { getCustomModels } from "@/lib/localDb";
|
|
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
|
|
import { withRateLimit } from "@omniroute/open-sse/services/rateLimitManager";
|
|
|
|
const INTERNAL_ORIGIN = "http://omniroute.internal";
|
|
const DEFAULT_TEST_TIMEOUT_MS = 10_000;
|
|
|
|
function asRecord(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: {};
|
|
}
|
|
|
|
function getErrorMessage(error: unknown): string {
|
|
return sanitizeErrorMessage(error) || "Unknown error";
|
|
}
|
|
|
|
function getErrorName(error: unknown): string {
|
|
return error instanceof Error ? error.name : "";
|
|
}
|
|
|
|
function extractProviderErrorMessage(body: unknown, fallback: string) {
|
|
const record = asRecord(body);
|
|
const error = record.error;
|
|
if (typeof error === "string" && error.trim()) return error;
|
|
|
|
const errorRecord = asRecord(error);
|
|
const message = errorRecord.message;
|
|
return typeof message === "string" && message.trim() ? message : fallback;
|
|
}
|
|
|
|
function stripFirstSegment(modelId: string): string | null {
|
|
const slashIdx = modelId.indexOf("/");
|
|
return slashIdx > 0 ? modelId.slice(slashIdx + 1) : null;
|
|
}
|
|
|
|
async function findCustomModelMetadata(providerId: string, modelId: string) {
|
|
try {
|
|
const customModels = await getCustomModels(providerId);
|
|
if (!Array.isArray(customModels)) return null;
|
|
|
|
const candidates = new Set([modelId]);
|
|
const stripped = stripFirstSegment(modelId);
|
|
if (stripped) candidates.add(stripped);
|
|
if (modelId.startsWith(`${providerId}/`)) candidates.add(modelId.slice(providerId.length + 1));
|
|
|
|
return (
|
|
customModels.find(
|
|
(model: any) => typeof model?.id === "string" && candidates.has(model.id)
|
|
) || null
|
|
);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function buildInternalChatRequest(testBody: Record<string, unknown>, signal: AbortSignal) {
|
|
return new Request(`${INTERNAL_ORIGIN}/v1/chat/completions`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
// Reuse the existing strict-mode internal bypass for live health checks.
|
|
"X-Internal-Test": "combo-health-check",
|
|
"X-OmniRoute-No-Cache": "true",
|
|
"X-Request-Id": `model-test-${randomUUID()}`,
|
|
},
|
|
body: JSON.stringify(testBody),
|
|
signal,
|
|
});
|
|
}
|
|
|
|
function buildInternalRerankRequest(testBody: Record<string, unknown>, signal: AbortSignal) {
|
|
return new Request(`${INTERNAL_ORIGIN}/v1/rerank`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"X-Internal-Test": "combo-health-check",
|
|
"X-OmniRoute-No-Cache": "true",
|
|
"X-Request-Id": `model-test-${randomUUID()}`,
|
|
},
|
|
body: JSON.stringify(testBody),
|
|
signal,
|
|
});
|
|
}
|
|
|
|
export function detectTestKind(modelStr: string, customModel: any) {
|
|
const supportedEndpoints = Array.isArray(customModel?.supportedEndpoints)
|
|
? customModel.supportedEndpoints
|
|
: [];
|
|
const apiFormat = typeof customModel?.apiFormat === "string" ? customModel.apiFormat : "";
|
|
const lowerModel = modelStr.toLowerCase();
|
|
const isRerank =
|
|
apiFormat === "rerank" ||
|
|
supportedEndpoints.includes("rerank") ||
|
|
lowerModel.includes("rerank");
|
|
const isEmbedding =
|
|
!isRerank &&
|
|
(apiFormat === "embeddings" ||
|
|
supportedEndpoints.includes("embeddings") ||
|
|
lowerModel.includes("embedding") ||
|
|
lowerModel.includes("bge-") ||
|
|
lowerModel.includes("text-embed") ||
|
|
lowerModel.includes("jina-clip") ||
|
|
lowerModel.includes("colbert"));
|
|
return { isRerank, isEmbedding };
|
|
}
|
|
|
|
/**
|
|
* Parse a Retry-After header value (seconds-as-number or HTTP-date) into seconds.
|
|
* Returns undefined if the value is missing or unparseable.
|
|
*/
|
|
export function parseRetryAfterHeader(value: string | null | undefined): number | undefined {
|
|
if (typeof value !== "string") return undefined;
|
|
const trimmed = value.trim();
|
|
if (!trimmed) return undefined;
|
|
|
|
const num = Number(trimmed);
|
|
if (Number.isFinite(num) && num >= 0) {
|
|
return Math.ceil(num);
|
|
}
|
|
|
|
const ms = Date.parse(trimmed);
|
|
if (Number.isFinite(ms)) {
|
|
return Math.max(0, Math.ceil((ms - Date.now()) / 1000));
|
|
}
|
|
|
|
return undefined;
|
|
}
|
|
|
|
export interface RunSingleModelTestOptions {
|
|
providerId: string;
|
|
modelId: string;
|
|
connectionId?: string;
|
|
timeoutMs?: number;
|
|
}
|
|
|
|
export interface SingleModelTestResult {
|
|
modelId: string;
|
|
status: "ok" | "error" | "rate_limited";
|
|
latencyMs: number;
|
|
responseText?: string;
|
|
statusCode?: number;
|
|
httpStatus: number;
|
|
error?: string;
|
|
rateLimited?: boolean;
|
|
isTimeout?: boolean;
|
|
retryAfter?: number;
|
|
}
|
|
|
|
/**
|
|
* Run a single model test. When `connectionId` is provided, wraps the
|
|
* upstream call with `withRateLimit` (Bottleneck). Returns a plain
|
|
* `SingleModelTestResult` (not an HTTP Response) so the single-test and
|
|
* batch-test endpoints can format it differently.
|
|
*/
|
|
export async function runSingleModelTest(
|
|
options: RunSingleModelTestOptions
|
|
): Promise<SingleModelTestResult> {
|
|
const { providerId, modelId, connectionId, timeoutMs = DEFAULT_TEST_TIMEOUT_MS } = options;
|
|
|
|
let fullModelStr = modelId;
|
|
if (!fullModelStr.includes("/")) {
|
|
fullModelStr = `${providerId}/${modelId}`;
|
|
}
|
|
|
|
const startTime = Date.now();
|
|
const customModel = await findCustomModelMetadata(providerId, fullModelStr);
|
|
const { isRerank, isEmbedding } = detectTestKind(fullModelStr, customModel);
|
|
|
|
const testBody = isRerank
|
|
? {
|
|
model: fullModelStr,
|
|
query: "What is OmniRoute?",
|
|
documents: [
|
|
"OmniRoute routes AI requests across configured providers.",
|
|
"This document is unrelated to the test query.",
|
|
],
|
|
top_n: 1,
|
|
return_documents: false,
|
|
}
|
|
: buildComboTestRequestBody(fullModelStr, isEmbedding);
|
|
|
|
// Per-model AbortController. We track whether the timeout fired so we can
|
|
// distinguish "rate-limit queue aborted" (withRateLimit threw AbortError
|
|
// with no timeout) from "timeout fired and aborted withRateLimit".
|
|
const controller = new AbortController();
|
|
let timedOut = false;
|
|
const timeoutHandle = setTimeout(() => {
|
|
timedOut = true;
|
|
controller.abort();
|
|
}, timeoutMs);
|
|
|
|
const runInner = async (signal: AbortSignal): Promise<Response> => {
|
|
if (isEmbedding) {
|
|
return handleValidatedEmbeddingRequestBody(
|
|
testBody as Record<string, unknown> & { model: string }
|
|
);
|
|
}
|
|
if (isRerank) {
|
|
return postRerank(buildInternalRerankRequest(testBody, signal));
|
|
}
|
|
return postChatCompletion(buildInternalChatRequest(testBody, signal));
|
|
};
|
|
|
|
let res: Response;
|
|
try {
|
|
if (connectionId) {
|
|
res = await withRateLimit(
|
|
providerId,
|
|
connectionId,
|
|
fullModelStr,
|
|
(signal) => runInner(signal),
|
|
controller.signal
|
|
);
|
|
} else {
|
|
res = await runInner(controller.signal);
|
|
}
|
|
} catch (error: unknown) {
|
|
clearTimeout(timeoutHandle);
|
|
const latencyMs = Date.now() - startTime;
|
|
const errorName = getErrorName(error);
|
|
if (errorName === "AbortError") {
|
|
if (timedOut) {
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "error",
|
|
latencyMs,
|
|
httpStatus: 500,
|
|
error: `Timeout (${Math.round(timeoutMs / 1000)}s)`,
|
|
isTimeout: true,
|
|
};
|
|
}
|
|
// AbortError without timeout = withRateLimit queue rejection / abort.
|
|
// Surface as rate_limited so the batch endpoint can stop the loop.
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "rate_limited",
|
|
latencyMs,
|
|
httpStatus: 429,
|
|
error: "Rate limited (queue aborted)",
|
|
rateLimited: true,
|
|
};
|
|
}
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "error",
|
|
latencyMs,
|
|
httpStatus: 500,
|
|
error: getErrorMessage(error),
|
|
};
|
|
}
|
|
clearTimeout(timeoutHandle);
|
|
|
|
const latencyMs = Date.now() - startTime;
|
|
|
|
if (res.status === 429) {
|
|
const retryAfter = parseRetryAfterHeader(res.headers.get("retry-after"));
|
|
|
|
let errorMsg = "Rate limited";
|
|
try {
|
|
const errBody = await res.json();
|
|
errorMsg = extractProviderErrorMessage(errBody, res.statusText || errorMsg);
|
|
} catch {
|
|
errorMsg = res.statusText || errorMsg;
|
|
}
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "rate_limited",
|
|
latencyMs,
|
|
statusCode: res.status,
|
|
httpStatus: res.status,
|
|
error: errorMsg,
|
|
rateLimited: true,
|
|
...(retryAfter !== undefined ? { retryAfter } : {}),
|
|
};
|
|
}
|
|
|
|
if (res.ok) {
|
|
let responseBody = null;
|
|
try {
|
|
responseBody = await res.json();
|
|
} catch {
|
|
responseBody = null;
|
|
}
|
|
|
|
const responseText = extractComboTestResponseText(responseBody);
|
|
if (isRerank) {
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "ok",
|
|
latencyMs,
|
|
httpStatus: 200,
|
|
responseText: "[Rerank completed successfully]",
|
|
};
|
|
}
|
|
if (!responseText && !isEmbedding) {
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "error",
|
|
latencyMs,
|
|
statusCode: res.status,
|
|
httpStatus: 400,
|
|
error: "Provider returned HTTP 200 but no text content.",
|
|
};
|
|
}
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "ok",
|
|
latencyMs,
|
|
httpStatus: 200,
|
|
responseText,
|
|
};
|
|
}
|
|
|
|
let errorMsg = "";
|
|
try {
|
|
const errBody = await res.json();
|
|
errorMsg = extractProviderErrorMessage(errBody, res.statusText);
|
|
} catch {
|
|
errorMsg = res.statusText;
|
|
}
|
|
return {
|
|
modelId: fullModelStr,
|
|
status: "error",
|
|
latencyMs,
|
|
statusCode: res.status,
|
|
httpStatus: res.status,
|
|
error: errorMsg,
|
|
};
|
|
}
|