mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-09-10 00:42:21 +03:00
opencode v2 loads plugins through a contract the existing
@omniroute/opencode-plugin cannot satisfy: v1 exports plugin factories with an
auth/provider/config/tool hook object, v2 expects a default define({id, setup})
carrying catalog and integration domains. One package would have to satisfy
both loaders from a single entrypoint. An opencode v2 install therefore has no
route to an OmniRoute gateway at all: no model discovery, no combos, no
enrichment.
This adds @omniroute/opencode-plugin-v2, a self-contained package. The v1
plugin is untouched, so v1 users see no move, no migration and no breaking
version. The two packages deliberately share no code and no release: the
mapping logic here began as a port of v1's and now lives in this package, which
keeps either one free to change without a coordinated publish.
The plugin publishes models, combos and auto-combos into the host catalog,
refreshes them lazily behind a 300s TTL, and keeps serving the last known
catalog from an on-disk snapshot when the gateway is unreachable. Publishing is
staged: models and combos are what a catalog is, so they go out as soon as they
are known, while auto-combos, the provider list and the enrichment overlay fold
into the snapshot when they land. Gating the publish on all of them made the
catalog hostage to the slowest source — a gateway that accepts the connection
and never answers /api/combos/auto left everything unpublished until that fetch
timed out, which is longer than a short-lived host stays alive.
Display names carry what the gateway knows about a model: the upstream provider
it routes to, whether it is free, and the budget that comes with it. Those parts
were already fetched and then dropped, so two connections selling the same model
looked identical in the picker. The provider prefix can be turned off with
`providerTag: false`.
The on-disk snapshot carries that overlay too, under a size cap, so a cold start
opens on named models rather than raw ids. The host is asked to reload only when
the catalog or the overlay actually moved, never once per refresh window.
The gateway key comes from the host credential store when one is connected, so
connecting the integration from opencode is enough and no secret needs to sit
in opencode.json; a plugin option and an environment variable remain as
fallbacks, and a host too old to expose a credential store still loads. Nothing
is silent when a key is missing or refused: an absent key is named once at
startup with the three ways to supply one, and an enrichment source the gateway
rejects is reported per endpoint with what the catalog loses. Those three
failures used to be empty catch blocks, which turned a management token the
gateway refuses into a catalog of raw model ids with no explanation.
Tool calling to Gemini keeps working. Gemini answers 400 INVALID_ARGUMENT for
an entire request whose tool declarations carry $schema, $ref or
additionalProperties. The v1 plugin handled it by wrapping fetch and rewriting
the JSON body; v2 does it on the language model, where the tools are still
structured data, and only for Gemini models of this provider. It can be turned
off with geminiSanitization: false, and a host exposing no aisdk domain loads
without it.
The catalog contract itself is a moving target, so the plugin adapts to the
host instead of assuming one shape. The released CLI keeps the aisdk package,
the endpoint (as settings.baseURL), the request headers and the variant options
directly on the model and provider; the current SDK types keep the same
information inside an api block. Writing only the api block yields a catalog
the released CLI lists but cannot route. Rather than key off a version list
that goes stale on the next release, the plugin reads the shape the host seeds
into the catalog draft and publishes accordingly: a seed with a top-level
package and no api block gets both field sets, a seed with an api block gets
that block alone, and an undisclosed seed gets both. None of the legacy keys
collide with a key of the current types, so the two shapes coexist on one
object, variants included.
Four v1 behaviours are deliberately not carried over, because v2 either owns
them or no longer needs them: the plugin-side debug log (the host has its own
logging), the compression-metadata suffix on combo names, the MCP auto-emit
(the v2 host owns MCP), and the omni-sync command plus its background timer
(the TTL and a content fingerprint drive catalog.reload instead).
A refresh never downgrades what is already published: the previous overlay is
carried forward until the new one lands, so names, pricing and the usable
filter no longer drop out for the length of every TTL window. The disk snapshot
is read after the credential is resolved, because it is keyed by that
credential — reading it earlier looked up the identity the options carry rather
than the one in use, and rejected a perfectly good catalog exactly when the
gateway was down.
The tool-schema cleaner now knows where a schema ends and a property name
begins. Stripping keywords by name anywhere in the tree deleted a tool
parameter called `ref` while leaving it in `required`, handing the model a
schema it could not satisfy; a `$ref` it cannot resolve now forwards the tool
untouched instead of widening it to accept anything. Gemini detection is
anchored on the model family, so `gemini-compatible-proxy` is no longer treated
as a Gemini model.
A source the gateway refuses is reported on the library entry point as well,
not only through the plugin, so the usable-provider filter can no longer disable
itself in silence. `providerId` is bounded to a safe character set because it
reaches a filesystem path, `hiddenModels` covers combos as it already covered
models, the Anthropic block gets the gateway root rather than a doubled `/v1`, an unparseable tool schema forwards the tool instead
of failing the request, and the package typechecks under the same settings as
the v1 plugin.
CI mirrors the existing plugin workflow: install, build and test on Node 22 and
24, for both packages. The plugin SDK stays pinned, and the host-shape assertions carry the risk of
a contract move rather than a check against a rolling upstream tag.
Co-authored-by: Max <maxmad64@gmail.com>
296 lines
11 KiB
TypeScript
296 lines
11 KiB
TypeScript
/**
|
|
* Universal model naming template for the OmniRoute plugin.
|
|
*
|
|
* Naming pipeline:
|
|
* [tag] <provider-label><separator><display-name><suffix>
|
|
*
|
|
* [Free] <provider> - <name> · <budget> ← free model
|
|
* Auto: <variant> (<N>p) ← auto combo
|
|
* Combo: <name> ← DB combo
|
|
* <provider> - <name> ← regular model
|
|
*/
|
|
|
|
// ── Constants ────────────────────────────────────────────────────────────
|
|
|
|
/** Separator between provider label and model display name. */
|
|
export const PROVIDER_TAG_SEPARATOR = " - ";
|
|
|
|
/** Threshold beyond which providerDisplayName is abbreviated. */
|
|
const PROVIDER_LABEL_MAX_CHARS = 12;
|
|
|
|
/** Aliases longer than this get title-case instead of UPPER. */
|
|
const ALIAS_UPPER_MAX_CHARS = 5;
|
|
|
|
// ── Auto Combo Types ─────────────────────────────────────────────────────
|
|
|
|
export type AutoVariant = "coding" | "fast" | "cheap" | "offline" | "smart" | "lkgp";
|
|
|
|
export const AUTO_VARIANTS: AutoVariant[] = ["coding", "fast", "cheap", "offline", "smart", "lkgp"];
|
|
|
|
export const AUTO_VARIANT_DESCRIPTIONS: Record<AutoVariant | "default", string> = {
|
|
default: "Best provider via scoring",
|
|
coding: "Quality-first for code tasks",
|
|
fast: "Latency-optimized routing",
|
|
cheap: "Cost-optimized routing",
|
|
offline: "Offline-friendly providers",
|
|
smart: "Quality-first with exploration",
|
|
lkgp: "Last-Known-Good-Provider routing",
|
|
};
|
|
|
|
// ── Free Model Types ─────────────────────────────────────────────────────
|
|
|
|
export type FreeModelFreeType =
|
|
| "recurring-daily"
|
|
| "recurring-monthly"
|
|
| "recurring-credit"
|
|
| "one-time-initial"
|
|
| "keyless"
|
|
| "discontinued";
|
|
|
|
// ── Provider Label ────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Title-case a long, lowercase-looking alias.
|
|
* `antigravity` → `Antigravity`
|
|
*/
|
|
function titleCaseAlias(alias: string): string {
|
|
if (alias.length === 0) return alias;
|
|
return alias.charAt(0).toUpperCase() + alias.slice(1).toLowerCase();
|
|
}
|
|
|
|
/**
|
|
* Pick the short label for an upstream provider.
|
|
*
|
|
* Rules:
|
|
* 1. Trim `providerDisplayName`. If ≤12 chars → use verbatim.
|
|
* 2. Alias ≤5 chars → UPPER(alias). Alias >5 → titleCase.
|
|
* 3. Neither → undefined.
|
|
*/
|
|
export function shortProviderLabel(
|
|
enrichment: { providerDisplayName?: string; providerAlias?: string } | undefined
|
|
): string | undefined {
|
|
if (!enrichment) return undefined;
|
|
const raw =
|
|
typeof enrichment.providerDisplayName === "string" ? enrichment.providerDisplayName.trim() : "";
|
|
if (raw.length > 0 && raw.length <= PROVIDER_LABEL_MAX_CHARS) return raw;
|
|
const alias = typeof enrichment.providerAlias === "string" ? enrichment.providerAlias.trim() : "";
|
|
if (alias.length > 0) {
|
|
return alias.length <= ALIAS_UPPER_MAX_CHARS ? alias.toUpperCase() : titleCaseAlias(alias);
|
|
}
|
|
// Long displayName with no alias to fall back on: keep the long label
|
|
// rather than dropping the provider prefix entirely.
|
|
return raw.length > 0 ? raw : undefined;
|
|
}
|
|
|
|
// ── Free Label ────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Normalise display name so free-tier models get a consistent `[Free] ` prefix.
|
|
*
|
|
* "GPT-4.1 (Free)" → "[Free] GPT-4.1"
|
|
* "DeepSeek V4 Flash Free" → "[Free] DeepSeek V4 Flash"
|
|
* "Claude Opus 4.7" → "Claude Opus 4.7" (unchanged)
|
|
*/
|
|
export function normaliseFreeLabel(name: string): string {
|
|
// Bounded whitespace quantifiers ({0,8}/{1,8}) avoid the polynomial-ReDoS
|
|
// backtracking that unbounded \s* before an anchored \s*$ would allow on
|
|
// attacker-influenced display names. 8 covers any realistic label spacing.
|
|
const cleaned = name
|
|
.replace(/\s{0,8}\(free\)\s{0,8}$/i, "")
|
|
.replace(/[\s-]{1,8}free\s{0,8}$/i, "")
|
|
.trim();
|
|
const wasFree = cleaned.length < name.trim().length;
|
|
if (!wasFree) return name;
|
|
return `[Free] ${cleaned}`;
|
|
}
|
|
|
|
// ── Free Budget Formatting ────────────────────────────────────────────────
|
|
|
|
/** Scales, largest first, so the unit is chosen by descending magnitude. */
|
|
const TOKEN_UNITS = [
|
|
[1e9, "B"],
|
|
[1e6, "M"],
|
|
[1e3, "K"],
|
|
] as const;
|
|
|
|
/**
|
|
* Format a token count as a short magnitude string: `25M`, `1.5K`, `999`.
|
|
*
|
|
* The unit has to be picked from the value that will actually be *printed*,
|
|
* not from the raw input. `toFixed(1)` rounds to the nearest tenth, so at the
|
|
* K scale 999_950 and above render as `1000.0` — and by then the M branch has
|
|
* already been skipped, producing `1000K` for a number that is `1M`. The same
|
|
* carry turns just under a billion into `1000M`. When the rounded value reaches
|
|
* the next scale, re-render at that scale instead.
|
|
*/
|
|
function fmtTokens(n: number): string {
|
|
for (let i = 0; i < TOKEN_UNITS.length; i++) {
|
|
const [scale, suffix] = TOKEN_UNITS[i]!;
|
|
if (n < scale) continue;
|
|
const value = Number((n / scale).toFixed(1));
|
|
// `Number()` also drops a trailing `.0`, which the previous regex did.
|
|
if (value < 1000 || i === 0) return `${value}${suffix}`;
|
|
const [nextScale, nextSuffix] = TOKEN_UNITS[i - 1]!;
|
|
return `${Number((n / nextScale).toFixed(1))}${nextSuffix}`;
|
|
}
|
|
return String(n);
|
|
}
|
|
|
|
/**
|
|
* Format a free model budget into a short human-readable suffix.
|
|
*
|
|
* recurring-daily → "25M tokens/day"
|
|
* recurring-monthly → "25M tokens/month"
|
|
* recurring-credit → "10M credits"
|
|
* one-time-initial → "1M credits (one-time)"
|
|
* keyless → "(keyless)"
|
|
* discontinued → "(discontinued)"
|
|
*/
|
|
export function formatFreeBudget(params: {
|
|
freeType: FreeModelFreeType;
|
|
monthlyTokens?: number;
|
|
creditTokens?: number;
|
|
}): string {
|
|
const { freeType, monthlyTokens = 0, creditTokens = 0 } = params;
|
|
|
|
switch (freeType) {
|
|
case "recurring-daily":
|
|
return `${fmtTokens(monthlyTokens)} tokens/day`;
|
|
case "recurring-monthly":
|
|
return `${fmtTokens(monthlyTokens)} tokens/month`;
|
|
case "recurring-credit":
|
|
return `${fmtTokens(creditTokens)} credits`;
|
|
case "one-time-initial":
|
|
return `${fmtTokens(creditTokens)} credits (one-time)`;
|
|
case "keyless":
|
|
return "(keyless)";
|
|
case "discontinued":
|
|
return "(discontinued)";
|
|
default:
|
|
return "";
|
|
}
|
|
}
|
|
|
|
// ── Auto Combo Naming ─────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Format auto combo display name.
|
|
*
|
|
* "Auto: Coding (4p)"
|
|
* "Auto: Default (6p)"
|
|
* "Auto" (no candidate count when unknown)
|
|
*/
|
|
export function formatAutoComboName(
|
|
variant: AutoVariant | undefined,
|
|
candidateCount?: number
|
|
): string {
|
|
const label = variant ? variant.charAt(0).toUpperCase() + variant.slice(1) : "Default";
|
|
const count =
|
|
typeof candidateCount === "number" && candidateCount > 0 ? ` (${candidateCount}p)` : "";
|
|
return `Auto: ${label}${count}`;
|
|
}
|
|
|
|
/**
|
|
* Build the model ID for an auto combo entry.
|
|
* "auto/coding", "auto/fast", "auto" (default).
|
|
*/
|
|
export function autoComboModelId(variant: AutoVariant | undefined): string {
|
|
return variant ? `auto/${variant}` : "auto";
|
|
}
|
|
|
|
// ── Universal Display Name Builder ────────────────────────────────────────
|
|
|
|
export interface ModelDisplayNameParams {
|
|
/** Raw model ID (e.g. "cc/claude-sonnet-4-6"). */
|
|
rawId: string;
|
|
/** Enrichment display name (e.g. "Claude Sonnet 4.6"). */
|
|
enrichmentName?: string;
|
|
/** Provider tag enrichment. */
|
|
providerAlias?: string;
|
|
/** Human-readable upstream provider label. */
|
|
providerDisplayName?: string;
|
|
/** Whether model is free tier. */
|
|
isFree?: boolean;
|
|
/** Free model budget info. */
|
|
freeType?: FreeModelFreeType;
|
|
/** Monthly token budget (for recurring free models). */
|
|
monthlyTokens?: number;
|
|
/** Credit token budget (for credit-based free models). */
|
|
creditTokens?: number;
|
|
/** Whether this is a combo entry (skip provider tag). */
|
|
isCombo?: boolean;
|
|
/** Whether this is an auto combo entry. */
|
|
isAutoCombo?: boolean;
|
|
/** Auto combo variant. */
|
|
autoVariant?: AutoVariant;
|
|
/** Auto combo candidate count. */
|
|
autoCandidateCount?: number;
|
|
}
|
|
|
|
/**
|
|
* Build the final display name following the universal template.
|
|
*
|
|
* Priority:
|
|
* 1. Auto combo → "Auto: <variant> (<N>p)"
|
|
* 2. DB combo → "Combo: <name>"
|
|
* 3. Free + enrichment + provider tag → "[Free] <label> - <name> · <budget>"
|
|
* 4. Free + enrichment → "[Free] <name> · <budget>"
|
|
* 5. Free + raw → "[Free] <rawId> · <budget>"
|
|
* 6. Enrichment + provider tag → "<label> - <name>"
|
|
* 7. Enrichment only → "<name>"
|
|
* 8. Raw fallback → normaliseFreeLabel(rawId)
|
|
*/
|
|
export function buildModelDisplayName(params: ModelDisplayNameParams): string {
|
|
// Auto combos
|
|
if (params.isAutoCombo) {
|
|
return formatAutoComboName(params.autoVariant, params.autoCandidateCount);
|
|
}
|
|
|
|
// Determine base name — strip any existing free suffix first
|
|
const rawBase =
|
|
params.enrichmentName && params.enrichmentName.trim().length > 0
|
|
? params.enrichmentName
|
|
: params.rawId;
|
|
const cleanedBase = rawBase
|
|
.replace(/\s*\(free\)\s*$/i, "")
|
|
.replace(/[\s-]+free\s*$/i, "")
|
|
.trim();
|
|
const wasFree = cleanedBase.length < rawBase.trim().length;
|
|
const isFree = !!params.isFree || wasFree;
|
|
|
|
let baseName = cleanedBase;
|
|
|
|
// Provider tag (skip for combos)
|
|
if (!params.isCombo) {
|
|
const label = shortProviderLabel({
|
|
providerDisplayName: params.providerDisplayName,
|
|
providerAlias: params.providerAlias,
|
|
});
|
|
if (label) {
|
|
const prefix = `${label}${PROVIDER_TAG_SEPARATOR}`;
|
|
if (!baseName.startsWith(prefix)) {
|
|
baseName = `${prefix}${baseName}`;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Prepend [Free] if applicable (AFTER provider tag for correct ordering)
|
|
if (isFree) {
|
|
baseName = `[Free] ${baseName}`;
|
|
}
|
|
|
|
// Free budget suffix
|
|
if (isFree && params.freeType) {
|
|
const budget = formatFreeBudget({
|
|
freeType: params.freeType,
|
|
monthlyTokens: params.monthlyTokens,
|
|
creditTokens: params.creditTokens,
|
|
});
|
|
if (budget) {
|
|
baseName = `${baseName} · ${budget}`;
|
|
}
|
|
}
|
|
|
|
return baseName;
|
|
}
|