mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-09-09 16:32:12 +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>
212 lines
7.4 KiB
TypeScript
212 lines
7.4 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { homedir } from "node:os";
|
|
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
import { dirname, join } from "node:path";
|
|
import type {
|
|
OmniRouteEnrichmentEntry,
|
|
OmniRouteEnrichmentMap,
|
|
OmniRouteProviderConnection,
|
|
OmniRouteRawAutoCombo,
|
|
OmniRouteRawCombo,
|
|
OmniRouteRawModelEntry,
|
|
} from "./shared/index.js";
|
|
|
|
export const DEFAULT_MODEL_CACHE_TTL_MS = 300_000 as const;
|
|
|
|
/**
|
|
* Breather after a refresh whose models fetch came back empty (gateway down
|
|
* or refusing). Transforms inside the window serve last-known-good without
|
|
* re-firing the fetch suite. Short on purpose: it only guards the
|
|
* pathological case, normal TTL expiry still refetches every window.
|
|
*/
|
|
export const UNREACHABLE_COOLDOWN_MS = 15_000 as const;
|
|
|
|
export interface CatalogSnapshot {
|
|
models: OmniRouteRawModelEntry[];
|
|
combos: OmniRouteRawCombo[];
|
|
autoCombos: OmniRouteRawAutoCombo[];
|
|
providers?: OmniRouteProviderConnection[];
|
|
enrichment?: OmniRouteEnrichmentMap;
|
|
fetchedAt: number;
|
|
}
|
|
|
|
export const SNAPSHOT_FORMAT_VERSION = 2 as const;
|
|
|
|
/**
|
|
* A raw snapshot entry is stale when it cannot be mapped to a publishable
|
|
* model: no string `id` (unroutable) or a pre-mapped `api` block without a
|
|
* valid `npm` package (the runner would reject it as `Unsupported package`).
|
|
* Plain `/v1/models` entries carry no `api` block -- it is synthesized at
|
|
* publish time -- so only a present-but-invalid block drops the entry.
|
|
*/
|
|
export function isStaleSnapshotModel(entry: unknown): boolean {
|
|
if (!entry || typeof entry !== "object") return true;
|
|
const id = (entry as { id?: unknown }).id;
|
|
if (typeof id !== "string" || id.length === 0) return true;
|
|
const api = (entry as { api?: unknown }).api;
|
|
if (api === undefined) return false;
|
|
if (!api || typeof api !== "object") return true;
|
|
const npm = (api as { npm?: unknown }).npm;
|
|
return typeof npm !== "string" || npm.length === 0;
|
|
}
|
|
|
|
interface DiskSnapshotV2 {
|
|
v: 2;
|
|
identityFingerprint: string;
|
|
models: OmniRouteRawModelEntry[];
|
|
combos: OmniRouteRawCombo[];
|
|
autoCombos?: OmniRouteRawAutoCombo[];
|
|
providers?: OmniRouteProviderConnection[];
|
|
/**
|
|
* Display names, provider labels, pricing and free-tier budgets, as
|
|
* `[key, entry]` pairs (a Map does not survive JSON). Persisted because a
|
|
* cold start otherwise publishes raw model ids until the first refresh
|
|
* completes — which is the moment the snapshot exists to cover.
|
|
*/
|
|
enrichment?: [string, OmniRouteEnrichmentEntry][];
|
|
writtenAt: number;
|
|
}
|
|
|
|
/**
|
|
* Ceiling on what one snapshot may occupy on disk. A gateway with thousands of
|
|
* models makes this file grow without bound otherwise; past the cap the
|
|
* enrichment overlay is dropped first (it is rebuilt on the next refresh)
|
|
* rather than losing the catalog itself.
|
|
*/
|
|
const MAX_SNAPSHOT_BYTES = 32 * 1024 * 1024;
|
|
|
|
function trimTrailingSlashes(value: string): string {
|
|
let i = value.length;
|
|
while (i > 0 && value.charCodeAt(i - 1) === 0x2f) i -= 1;
|
|
return i === value.length ? value : value.slice(0, i);
|
|
}
|
|
|
|
function normalizeBaseURL(baseURL: string): string {
|
|
try {
|
|
const parsed = new URL(baseURL);
|
|
parsed.hash = "";
|
|
parsed.pathname = trimTrailingSlashes(parsed.pathname) || "/";
|
|
return parsed.toString();
|
|
} catch {
|
|
return trimTrailingSlashes(baseURL);
|
|
}
|
|
}
|
|
|
|
export function memoryCacheKey(baseURL: string, credentialId: string): string {
|
|
return `${baseURL}::${createHash("sha256").update(credentialId).digest("hex")}`;
|
|
}
|
|
|
|
export function snapshotIdentityFingerprint(
|
|
baseURL: string,
|
|
apiKey: string,
|
|
managementReadToken: string
|
|
): string {
|
|
return createHash("sha256")
|
|
.update(JSON.stringify([normalizeBaseURL(baseURL), apiKey, managementReadToken]))
|
|
.digest("hex");
|
|
}
|
|
|
|
export function diskSnapshotPath(providerId: string): string {
|
|
// OPENCODE_DATA_DIR is honoured verbatim when set: whoever controls the
|
|
// process environment already chooses where the process writes, so
|
|
// resolving it further would only surprise. The providerId segment stays
|
|
// bounded by the options schema (letters, digits, '.', '_' and '-'; never
|
|
// "." or ".."), keeping the file inside <dir>/plugins/.
|
|
const dir = process.env.OPENCODE_DATA_DIR ?? join(homedir(), ".local", "share", "opencode");
|
|
return join(dir, "plugins", `omniroute-${providerId}.json`);
|
|
}
|
|
|
|
export async function readDiskSnapshot(
|
|
providerId: string,
|
|
identityFingerprint: string,
|
|
logger?: { warn: (message: string) => void }
|
|
): Promise<CatalogSnapshot | undefined> {
|
|
try {
|
|
const body = await readFile(diskSnapshotPath(providerId), "utf8");
|
|
const parsed = JSON.parse(body) as Partial<DiskSnapshotV2>;
|
|
if (
|
|
!parsed ||
|
|
typeof parsed.v !== "number" ||
|
|
parsed.v < SNAPSHOT_FORMAT_VERSION ||
|
|
typeof parsed.identityFingerprint !== "string" ||
|
|
parsed.identityFingerprint !== identityFingerprint
|
|
) {
|
|
return undefined;
|
|
}
|
|
if (
|
|
!Array.isArray(parsed.models) ||
|
|
parsed.models.length === 0 ||
|
|
!Array.isArray(parsed.combos)
|
|
) {
|
|
return undefined;
|
|
}
|
|
const stale = (parsed.models as unknown[]).filter(isStaleSnapshotModel).length;
|
|
const models = (parsed.models as OmniRouteRawModelEntry[]).filter(
|
|
(entry) => !isStaleSnapshotModel(entry)
|
|
);
|
|
if (stale > 0) {
|
|
logger?.warn(`[omniroute-v2] dropping ${stale} stale snapshot entries without api block`);
|
|
}
|
|
if (models.length === 0) return undefined;
|
|
return {
|
|
models,
|
|
combos: parsed.combos as OmniRouteRawCombo[],
|
|
autoCombos: Array.isArray(parsed.autoCombos)
|
|
? (parsed.autoCombos as OmniRouteRawAutoCombo[])
|
|
: [],
|
|
providers: Array.isArray(parsed.providers)
|
|
? (parsed.providers as OmniRouteProviderConnection[])
|
|
: [],
|
|
// A snapshot written before this field existed, or one whose overlay was
|
|
// dropped for size, simply starts unenriched and recovers on the first
|
|
// refresh — the same state as before it was persisted at all.
|
|
enrichment: Array.isArray(parsed.enrichment)
|
|
? new Map(parsed.enrichment as [string, OmniRouteEnrichmentEntry][])
|
|
: undefined,
|
|
fetchedAt: typeof parsed.writtenAt === "number" ? parsed.writtenAt : Date.now(),
|
|
};
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
export async function writeDiskSnapshot(
|
|
providerId: string,
|
|
snapshot: CatalogSnapshot,
|
|
identityFingerprint: string
|
|
): Promise<void> {
|
|
try {
|
|
if (snapshot.models.length === 0) return;
|
|
const file = diskSnapshotPath(providerId);
|
|
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
const envelope: DiskSnapshotV2 = {
|
|
v: 2,
|
|
identityFingerprint,
|
|
models: snapshot.models,
|
|
combos: snapshot.combos,
|
|
autoCombos: snapshot.autoCombos,
|
|
providers: snapshot.providers ?? [],
|
|
enrichment: snapshot.enrichment ? [...snapshot.enrichment.entries()] : undefined,
|
|
writtenAt: Date.now(),
|
|
};
|
|
let payload = JSON.stringify(envelope);
|
|
if (payload.length > MAX_SNAPSHOT_BYTES && envelope.enrichment !== undefined) {
|
|
delete envelope.enrichment;
|
|
payload = JSON.stringify(envelope);
|
|
}
|
|
if (payload.length > MAX_SNAPSHOT_BYTES) return;
|
|
await writeFile(file, payload, { encoding: "utf8", mode: 0o600 });
|
|
} catch {
|
|
// Best-effort: callers already hold the in-memory entry.
|
|
}
|
|
}
|
|
|
|
export async function clearDiskSnapshot(providerId: string): Promise<boolean> {
|
|
try {
|
|
await unlink(diskSnapshotPath(providerId));
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|