mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-23 15:42:12 +03:00
Reconciliado com a release (conflito mecânico em stryker.conf.json — registro de teste que já existia na tip, apenas resolvido mantendo a entrada) e revalidado: 12/12 testes do arquivo log-level.test.ts passando (incluindo os 4 novos deste PR). CI vermelho é o base-red já rastreado em #9985. Obrigado!
This commit is contained in:
@@ -76,6 +76,17 @@ import {
|
||||
type FreeModelFreeType,
|
||||
} from "./naming.js";
|
||||
|
||||
/**
|
||||
* Minimal leveled logger sink accepted by the default fetchers and the static
|
||||
* catalog builder. A full `Logger` satisfies it structurally; the config hook
|
||||
* injects the same partial shape (see `createOmniRouteConfigHook` deps).
|
||||
*/
|
||||
type OmniRouteLoggerSink = {
|
||||
error?: (message: string, ...args: unknown[]) => void;
|
||||
warn: (message: string, ...args: unknown[]) => void;
|
||||
debug?: (message: string, ...args: unknown[]) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Zod schema for plugin options accepted as the second element of the
|
||||
* `plugin: [name, opts]` tuple in opencode.json. Strict by design — unknown
|
||||
@@ -791,13 +802,18 @@ export async function forceSyncOmniRouteModels(args: {
|
||||
try {
|
||||
rawCombos = await combosFetcher(auth.baseURL, auth.managementReadToken, 10_000);
|
||||
} catch (err) {
|
||||
console.warn("[omniroute-plugin] force sync: combos fetch failed", err);
|
||||
logger.warn("force sync: combos fetch failed", err);
|
||||
}
|
||||
}
|
||||
let rawAutoCombos: OmniRouteRawAutoCombo[] = [];
|
||||
if (wantAutoCombos) {
|
||||
try {
|
||||
rawAutoCombos = await autoCombosFetcher(auth.baseURL, auth.managementReadToken, 5_000);
|
||||
rawAutoCombos = await autoCombosFetcher(
|
||||
auth.baseURL,
|
||||
auth.managementReadToken,
|
||||
5_000,
|
||||
logger
|
||||
);
|
||||
} catch {
|
||||
/* soft-fail */
|
||||
}
|
||||
@@ -1089,7 +1105,7 @@ export const OmniRoutePlugin: Plugin = async (_input, options) => {
|
||||
|
||||
return {
|
||||
auth: createOmniRouteAuthHook(resolved),
|
||||
provider: createOmniRouteProviderHook(resolved, { cache: sharedCache }),
|
||||
provider: createOmniRouteProviderHook(resolved, { cache: sharedCache, logger }),
|
||||
config: configWithSyncCommand,
|
||||
tool: {
|
||||
omniroute_sync_models: syncTool,
|
||||
@@ -1676,7 +1692,8 @@ export interface OmniRouteRawAutoCombo {
|
||||
export type OmniRouteAutoCombosFetcher = (
|
||||
baseURL: string,
|
||||
apiKey: string,
|
||||
timeoutMs?: number
|
||||
timeoutMs?: number,
|
||||
logger?: OmniRouteLoggerSink
|
||||
) => Promise<OmniRouteRawAutoCombo[]>;
|
||||
|
||||
/**
|
||||
@@ -1688,9 +1705,11 @@ export type OmniRouteAutoCombosFetcher = (
|
||||
export const defaultOmniRouteAutoCombosFetcher: OmniRouteAutoCombosFetcher = async (
|
||||
baseURL,
|
||||
apiKey,
|
||||
timeoutMs = 5_000
|
||||
timeoutMs = 5_000,
|
||||
logger?: OmniRouteLoggerSink
|
||||
) => {
|
||||
if (!apiKey || !baseURL) return [];
|
||||
const log = logger ?? _logger;
|
||||
|
||||
const trimmed = trimTrailingSlashes(baseURL);
|
||||
const root = trimmed.replace(/\/v\d+$/, "");
|
||||
@@ -1709,15 +1728,11 @@ export const defaultOmniRouteAutoCombosFetcher: OmniRouteAutoCombosFetcher = asy
|
||||
});
|
||||
// 404 = endpoint not deployed yet — expected during rollout
|
||||
if (res.status === 404) {
|
||||
console.warn(
|
||||
`[omniroute-plugin] /api/combos/auto not available (404) — auto combos disabled`
|
||||
);
|
||||
log.warn(`/api/combos/auto not available (404) — auto combos disabled`);
|
||||
return [];
|
||||
}
|
||||
if (!res.ok) {
|
||||
console.warn(
|
||||
`[omniroute-plugin] /api/combos/auto failed: ${res.status} ${res.statusText} — auto combos disabled`
|
||||
);
|
||||
log.warn(`/api/combos/auto failed: ${res.status} ${res.statusText} — auto combos disabled`);
|
||||
return [];
|
||||
}
|
||||
const body = (await res.json()) as unknown;
|
||||
@@ -1735,8 +1750,8 @@ export const defaultOmniRouteAutoCombosFetcher: OmniRouteAutoCombosFetcher = asy
|
||||
return out;
|
||||
} catch (err) {
|
||||
// Network error, timeout, abort — all non-fatal
|
||||
console.warn(
|
||||
`[omniroute-plugin] /api/combos/auto fetch failed: ${err instanceof Error ? err.message : String(err)} — auto combos disabled`
|
||||
log.warn(
|
||||
`/api/combos/auto fetch failed: ${err instanceof Error ? err.message : String(err)} — auto combos disabled`
|
||||
);
|
||||
return [];
|
||||
} finally {
|
||||
@@ -2935,10 +2950,7 @@ export function passesModelAllowlist(
|
||||
* filter is set, all combos pass. Combos with zero resolvable members pass
|
||||
* (mirrors `isUsableCombo` semantics).
|
||||
*/
|
||||
export function passesComboAllowlist(
|
||||
combo: OmniRouteRawCombo,
|
||||
visible?: ModelListFilter
|
||||
): boolean {
|
||||
export function passesComboAllowlist(combo: OmniRouteRawCombo, visible?: ModelListFilter): boolean {
|
||||
if (!visible) return true;
|
||||
const steps = Array.isArray(combo.models) ? combo.models : [];
|
||||
if (steps.length === 0) return true;
|
||||
@@ -3130,9 +3142,15 @@ export function createOmniRouteProviderHook(
|
||||
providersFetcher?: OmniRouteProvidersFetcher;
|
||||
now?: () => number;
|
||||
cache?: OmniRouteFetchCache;
|
||||
logger?: _Logger;
|
||||
} = {}
|
||||
): ProviderHook {
|
||||
const resolved = resolveOmniRoutePluginOptions(opts);
|
||||
const logger =
|
||||
deps.logger ??
|
||||
createLogger(
|
||||
resolved.features?.startupDebug ? "debug" : (resolved.features?.logLevel ?? "warn")
|
||||
);
|
||||
const fetcher = deps.fetcher ?? defaultOmniRouteModelsFetcher;
|
||||
// T-05: combo discovery merges `/api/combos` entries into the same map as
|
||||
// `/v1/models`. Default fetcher is declared further down the file; the
|
||||
@@ -3206,8 +3224,8 @@ export function createOmniRouteProviderHook(
|
||||
: undefined) ??
|
||||
"";
|
||||
if (!baseURL) {
|
||||
console.warn(
|
||||
`[omniroute-plugin] provider.models(${resolved.providerId}): ` +
|
||||
logger.error(
|
||||
`provider.models(${resolved.providerId}): ` +
|
||||
`no baseURL resolvable — checked plugin opts, auth.json, and provider config. ` +
|
||||
`Set baseURL in opencode.json plugin options or run \`opencode connect ${resolved.providerId}\` with a baseURL.`
|
||||
);
|
||||
@@ -3238,8 +3256,8 @@ export function createOmniRouteProviderHook(
|
||||
rawModels = await fetcher(baseURL, apiKey, 10_000);
|
||||
|
||||
// T-05: combos fetch is best-effort, gated by features.combos.
|
||||
// Soft-fail on any error: emit a console.warn and fall back to a
|
||||
// models-only catalog. Rationale: /api/combos requires a
|
||||
// Soft-fail on any error: emit a warn-level diagnostic and fall back
|
||||
// to a models-only catalog. Rationale: /api/combos requires a
|
||||
// management-scoped key and OmniRoute may not have any combos
|
||||
// provisioned. Hard-failing when combos are optional would
|
||||
// silently hide the whole provider from OC's picker.
|
||||
@@ -3248,10 +3266,7 @@ export function createOmniRouteProviderHook(
|
||||
try {
|
||||
rawCombos = await combosFetcher(baseURL, managementReadToken, 10_000);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[omniroute-plugin] combos fetch failed, falling back to models-only catalog",
|
||||
err
|
||||
);
|
||||
logger.warn("combos fetch failed, falling back to models-only catalog", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3261,7 +3276,7 @@ export function createOmniRouteProviderHook(
|
||||
rawAutoCombos = [];
|
||||
if (wantAutoCombos) {
|
||||
try {
|
||||
rawAutoCombos = await autoCombosFetcher(baseURL, managementReadToken, 5_000);
|
||||
rawAutoCombos = await autoCombosFetcher(baseURL, managementReadToken, 5_000, logger);
|
||||
} catch {
|
||||
// Already handled inside the default fetcher — this catch
|
||||
// is belt-and-suspenders for injected stubs.
|
||||
@@ -3275,10 +3290,7 @@ export function createOmniRouteProviderHook(
|
||||
try {
|
||||
rawEnrichment = await enrichmentFetcher(baseURL, managementReadToken, 10_000);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[omniroute-plugin] enrichment fetch failed, falling back to raw ids",
|
||||
err
|
||||
);
|
||||
logger.warn("enrichment fetch failed, falling back to raw ids", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3293,7 +3305,7 @@ export function createOmniRouteProviderHook(
|
||||
10_000
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn("[omniroute-plugin] compression-metadata fetch failed", err);
|
||||
logger.warn("compression-metadata fetch failed", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3307,8 +3319,8 @@ export function createOmniRouteProviderHook(
|
||||
try {
|
||||
rawConnections = await providersFetcher(baseURL, managementReadToken, 10_000);
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
"[omniroute-plugin] /api/providers fetch failed; usableOnly filter disabled for this refresh",
|
||||
logger.warn(
|
||||
"/api/providers fetch failed; usableOnly filter disabled for this refresh",
|
||||
err
|
||||
);
|
||||
}
|
||||
@@ -3327,8 +3339,9 @@ export function createOmniRouteProviderHook(
|
||||
// Debug breadcrumb: surface fetch result so operators can confirm
|
||||
// the dynamic pipeline fired and how much catalog OmniRoute returned.
|
||||
// Emitted once per cache miss (TTL refresh) — quiet on cache hits.
|
||||
console.warn(
|
||||
`[omniroute-plugin] catalog refreshed for providerId=${resolved.providerId} baseURL=${baseURL}: ` +
|
||||
// Info-level: hidden at the default `warn` level (see #8982).
|
||||
logger.info(
|
||||
`catalog refreshed for providerId=${resolved.providerId} baseURL=${baseURL}: ` +
|
||||
`${rawModels.length} models + ${rawCombos.length} combos + ` +
|
||||
`${rawEnrichment.size} enrichment entries + ` +
|
||||
`${rawCompressionCombos.length} compression combos + ` +
|
||||
@@ -3608,9 +3621,7 @@ export function createOmniRouteProviderHook(
|
||||
const dedupeKey = `${cacheKey}::${comboKey}`;
|
||||
if (!collisionWarned.has(dedupeKey)) {
|
||||
collisionWarned.add(dedupeKey);
|
||||
console.warn(
|
||||
`[omniroute-plugin] combo key "${comboKey}" collides with a model id; combo wins.`
|
||||
);
|
||||
logger.warn(`combo key "${comboKey}" collides with a model id; combo wins.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3628,8 +3639,8 @@ export function createOmniRouteProviderHook(
|
||||
}
|
||||
|
||||
if (pending.length > 0) {
|
||||
console.warn(
|
||||
`[omniroute-plugin] ${pending.length} combo(s) could not resolve all nested combo-refs after ${MAX_COMBO_PASSES} passes; they will advertise context=0 to avoid over-claiming.`
|
||||
logger.warn(
|
||||
`${pending.length} combo(s) could not resolve all nested combo-refs after ${MAX_COMBO_PASSES} passes; they will advertise context=0 to avoid over-claiming.`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4273,8 +4284,10 @@ export function buildStaticProviderEntry(
|
||||
enrichment?: OmniRouteEnrichmentMap,
|
||||
compressionCombos?: OmniRouteCompressionCombo[],
|
||||
connections?: OmniRouteProviderConnection[],
|
||||
rawAutoCombos?: OmniRouteRawAutoCombo[]
|
||||
rawAutoCombos?: OmniRouteRawAutoCombo[],
|
||||
logger?: OmniRouteLoggerSink
|
||||
): OmniRouteStaticProviderEntry {
|
||||
const log = logger ?? _logger;
|
||||
const models: Record<string, OmniRouteStaticModelEntry> = {};
|
||||
const rawModelKeys = new Set<string>();
|
||||
|
||||
@@ -4652,8 +4665,8 @@ export function buildStaticProviderEntry(
|
||||
}
|
||||
|
||||
if (pendingStatic.length > 0) {
|
||||
console.warn(
|
||||
`[omniroute-plugin] ${pendingStatic.length} combo(s) in the static catalog could not resolve all nested combo-refs after ${MAX_STATIC_COMBO_PASSES} passes; they will be omitted.`
|
||||
log.warn(
|
||||
`${pendingStatic.length} combo(s) in the static catalog could not resolve all nested combo-refs after ${MAX_STATIC_COMBO_PASSES} passes; they will be omitted.`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4674,9 +4687,7 @@ export function buildStaticProviderEntry(
|
||||
const isExpectedRawTwin = autoCombo.id === key && rawModelKeys.has(key);
|
||||
if (!isExpectedRawTwin && !reportedCollisions.has(key)) {
|
||||
reportedCollisions.add(key);
|
||||
console.warn(
|
||||
`[omniroute-plugin] auto combo key "${key}" collides with an existing model; auto combo wins.`
|
||||
);
|
||||
log.warn(`auto combo key "${key}" collides with an existing model; auto combo wins.`);
|
||||
}
|
||||
}
|
||||
models[key] = entry;
|
||||
@@ -5347,7 +5358,8 @@ export function createOmniRouteConfigHook(
|
||||
warmSnapshot = snapshotResult;
|
||||
// Log snapshot age (accept any age — instant beats empty).
|
||||
const age = (snapshotResult as { writtenAt?: number }).writtenAt;
|
||||
const ageLabel = typeof age === "number" ? `${Math.round((Date.now() - age) / 3_600_000)}h` : "unknown";
|
||||
const ageLabel =
|
||||
typeof age === "number" ? `${Math.round((Date.now() - age) / 3_600_000)}h` : "unknown";
|
||||
logAt(
|
||||
"warn",
|
||||
`config shim: warm startup from disk snapshot (${snapshotResult.rawModels.length} models, age ${ageLabel})`
|
||||
@@ -5399,7 +5411,12 @@ export function createOmniRouteConfigHook(
|
||||
const doAutoCombos = async (): Promise<void> => {
|
||||
if (!wantAutoCombos) return;
|
||||
try {
|
||||
localRawAutoCombos = await autoCombosFetcher(baseURL, managementReadToken, 5_000);
|
||||
localRawAutoCombos = await autoCombosFetcher(
|
||||
baseURL,
|
||||
managementReadToken,
|
||||
5_000,
|
||||
logger
|
||||
);
|
||||
} catch {
|
||||
// Already handled inside the default fetcher
|
||||
}
|
||||
@@ -5420,7 +5437,11 @@ export function createOmniRouteConfigHook(
|
||||
const doCompression = async (): Promise<void> => {
|
||||
if (!wantCompressionMeta) return;
|
||||
try {
|
||||
localRawCompressionCombos = await compressionMetaFetcher(baseURL, managementReadToken, 10_000);
|
||||
localRawCompressionCombos = await compressionMetaFetcher(
|
||||
baseURL,
|
||||
managementReadToken,
|
||||
10_000
|
||||
);
|
||||
} catch (err) {
|
||||
logAt(
|
||||
"error",
|
||||
@@ -5533,7 +5554,8 @@ export function createOmniRouteConfigHook(
|
||||
localRawEnrichment,
|
||||
localRawCompressionCombos,
|
||||
localRawConnections,
|
||||
localRawAutoCombos
|
||||
localRawAutoCombos,
|
||||
logger
|
||||
);
|
||||
const inputWithProvider2 = input as { provider?: Record<string, unknown> };
|
||||
if (inputWithProvider2.provider) {
|
||||
@@ -5623,7 +5645,8 @@ export function createOmniRouteConfigHook(
|
||||
rawEnrichment,
|
||||
rawCompressionCombos,
|
||||
rawConnections,
|
||||
rawAutoCombos
|
||||
rawAutoCombos,
|
||||
logger
|
||||
);
|
||||
|
||||
// Mutate the input.provider map. The Config type declares
|
||||
|
||||
@@ -5,8 +5,14 @@ import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
import type { Config } from "@opencode-ai/plugin";
|
||||
|
||||
import { createOmniRouteConfigHook, OmniRoutePlugin } from "../src/index.js";
|
||||
import { getLogLevel, logger, setLogLevel, type LogLevel } from "../src/logger.js";
|
||||
import {
|
||||
createOmniRouteConfigHook,
|
||||
createOmniRouteProviderHook,
|
||||
defaultOmniRouteAutoCombosFetcher,
|
||||
OmniRoutePlugin,
|
||||
type OmniRouteRawModelEntry,
|
||||
} from "../src/index.js";
|
||||
import { createLogger, getLogLevel, logger, setLogLevel, type LogLevel } from "../src/logger.js";
|
||||
|
||||
type ConsoleMethod = "error" | "info" | "log" | "warn";
|
||||
type ConsoleEntries = Record<ConsoleMethod, unknown[][]>;
|
||||
@@ -216,3 +222,105 @@ test("logger error output remains visible at error level", async () => {
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
const MINIMAL_MODELS: OmniRouteRawModelEntry[] = [
|
||||
{
|
||||
id: "claude-primary",
|
||||
object: "model",
|
||||
owned_by: "combo",
|
||||
capabilities: { tool_calling: true, reasoning: true, vision: true, thinking: true },
|
||||
context_length: 200000,
|
||||
max_output_tokens: 64000,
|
||||
input_modalities: ["text", "image"],
|
||||
output_modalities: ["text"],
|
||||
},
|
||||
];
|
||||
|
||||
function providerHookWithLevel(level: LogLevel, baseURL?: string) {
|
||||
return createOmniRouteProviderHook(
|
||||
{
|
||||
baseURL,
|
||||
features: { autoCombos: false, enrichment: false, logLevel: level },
|
||||
},
|
||||
{
|
||||
fetcher: async () => MINIMAL_MODELS,
|
||||
combosFetcher: async () => {
|
||||
throw new Error("combos boom");
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
test("logLevel error suppresses provider.models() fallback warnings and the catalog-refresh breadcrumb", async () => {
|
||||
const hook = providerHookWithLevel("error", "https://or.example.com/v1");
|
||||
const lines = rendered(
|
||||
await captureConsole(async () => {
|
||||
await hook.models!({} as never, { auth: { type: "api", key: "sk-x" } as never });
|
||||
})
|
||||
);
|
||||
|
||||
assert.equal(lines.filter((line) => line.includes("combos fetch failed")).length, 0);
|
||||
assert.equal(lines.filter((line) => line.includes("catalog refreshed")).length, 0);
|
||||
});
|
||||
|
||||
test("logLevel debug preserves the provider.models() catalog-refresh breadcrumb", async () => {
|
||||
const hook = providerHookWithLevel("debug", "https://or.example.com/v1");
|
||||
const lines = rendered(
|
||||
await captureConsole(async () => {
|
||||
await hook.models!({} as never, { auth: { type: "api", key: "sk-x" } as never });
|
||||
})
|
||||
);
|
||||
|
||||
assert.ok(
|
||||
lines.some((line) => line.includes("catalog refreshed")),
|
||||
"catalog-refresh breadcrumb emitted at debug level"
|
||||
);
|
||||
});
|
||||
|
||||
test("no baseURL resolvable stays visible at error level", async () => {
|
||||
const hook = providerHookWithLevel("error");
|
||||
const lines = rendered(
|
||||
await captureConsole(async () => {
|
||||
await hook.models!({} as never, { auth: { type: "api", key: "sk-x" } as never });
|
||||
})
|
||||
);
|
||||
|
||||
assert.ok(
|
||||
lines.some((line) => line.includes("no baseURL resolvable")),
|
||||
"genuine misconfiguration error remains visible at error level"
|
||||
);
|
||||
});
|
||||
|
||||
test("default auto-combos fetcher 404 warning respects the threaded logger level", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
(globalThis as { fetch: unknown }).fetch = (async () => ({
|
||||
status: 404,
|
||||
ok: false,
|
||||
})) as typeof fetch;
|
||||
try {
|
||||
const silent = await captureConsole(async () => {
|
||||
await defaultOmniRouteAutoCombosFetcher(
|
||||
"https://or.example.com/v1",
|
||||
"sk-x",
|
||||
5_000,
|
||||
createLogger("error")
|
||||
);
|
||||
});
|
||||
assert.equal(rendered(silent).length, 0, "404 warning suppressed at error level");
|
||||
|
||||
const loud = await captureConsole(async () => {
|
||||
await defaultOmniRouteAutoCombosFetcher(
|
||||
"https://or.example.com/v1",
|
||||
"sk-x",
|
||||
5_000,
|
||||
createLogger("warn")
|
||||
);
|
||||
});
|
||||
assert.ok(
|
||||
rendered(loud).some((line) => line.includes("/api/combos/auto not available")),
|
||||
"404 warning emitted at warn level"
|
||||
);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user