mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-09-10 08:52: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>
225 lines
9.2 KiB
TypeScript
225 lines
9.2 KiB
TypeScript
import { describe, it } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { createReadStream } from "node:fs";
|
|
import type { CatalogDraft } from "@opencode-ai/plugin/v2/promise";
|
|
import type { ModelV2Info, ProviderV2Info } from "@opencode-ai/sdk/v2/types";
|
|
import { publishCatalog } from "../src/catalog.js";
|
|
import {
|
|
mapComboToModelV2 as sharedMapCombo,
|
|
mapRawModelToModelV2 as sharedMapModel,
|
|
type OmniRouteCombosFetcher,
|
|
type OmniRouteModelsFetcher,
|
|
type OmniRouteRawCombo,
|
|
type OmniRouteRawModelEntry,
|
|
} from "../src/shared/index.js";
|
|
|
|
interface Fixture {
|
|
models: OmniRouteRawModelEntry[];
|
|
combos: OmniRouteRawCombo[];
|
|
}
|
|
|
|
/**
|
|
* What the v1 plugin produces for the same fixture, recorded in
|
|
* `fixtures/v1-parity.json`. Running v1 here instead would mean importing its
|
|
* build output from a sibling package: it only exists on a machine that has
|
|
* built v1, so the check silently passed locally and could not run in CI at
|
|
* all. Recording it makes the claim reviewable in the diff and reproducible
|
|
* anywhere.
|
|
*/
|
|
interface V1Parity {
|
|
v1PluginVersion: string;
|
|
hookId: string;
|
|
publishedKeys: string[];
|
|
comboSlugs: string[];
|
|
mappedModels: Record<string, unknown>;
|
|
mappedCombos: Record<string, unknown>;
|
|
}
|
|
|
|
async function loadFixture(): Promise<Fixture> {
|
|
const chunks: Buffer[] = [];
|
|
for await (const chunk of createReadStream(new URL("./fixtures/catalog.json", import.meta.url))) {
|
|
chunks.push(chunk as Buffer);
|
|
}
|
|
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as Fixture;
|
|
}
|
|
|
|
async function loadV1Parity(): Promise<V1Parity> {
|
|
const chunks: Buffer[] = [];
|
|
for await (const chunk of createReadStream(
|
|
new URL("./fixtures/v1-parity.json", import.meta.url)
|
|
)) {
|
|
chunks.push(chunk as Buffer);
|
|
}
|
|
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as V1Parity;
|
|
}
|
|
|
|
type ApiAuth = { type: "api"; key: string };
|
|
|
|
function fakeDraft() {
|
|
const providers = new Map<string, ProviderV2Info>();
|
|
const models = new Map<string, ModelV2Info>();
|
|
return {
|
|
providers,
|
|
models,
|
|
provider: {
|
|
list: () => [],
|
|
get: (id: string) => providers.get(id) as never,
|
|
update: (id: string, fn: (p: ProviderV2Info) => void) => {
|
|
const p = (providers.get(id) ?? { id }) as ProviderV2Info;
|
|
fn(p);
|
|
providers.set(id, p);
|
|
},
|
|
remove: () => {},
|
|
},
|
|
model: {
|
|
get: () => undefined,
|
|
update: (pid: string, mid: string, fn: (m: ModelV2Info) => void) => {
|
|
const k = pid + "/" + mid;
|
|
const m = (models.get(k) ?? { id: mid, providerID: pid }) as ModelV2Info;
|
|
fn(m);
|
|
models.set(k, m);
|
|
},
|
|
remove: () => {},
|
|
default: { get: () => undefined, set: () => {} },
|
|
},
|
|
};
|
|
}
|
|
|
|
const TEST_OPTS = {
|
|
baseURL: "https://gw.example.com",
|
|
providerId: "omniroute",
|
|
apiKey: "parity-key",
|
|
timeoutMs: 1000,
|
|
modelCacheTtlMs: 300000,
|
|
usableOnly: false as const,
|
|
};
|
|
|
|
describe("v1-vs-v2 catalog parity", () => {
|
|
it("same fixture models publish the same key set modulo documented exclusions", async () => {
|
|
const fixture = await loadFixture();
|
|
assert.equal(fixture.models.length, 5);
|
|
assert.equal(fixture.combos.length, 2);
|
|
|
|
const fetcher: OmniRouteModelsFetcher = async () => fixture.models;
|
|
const combosFetcher: OmniRouteCombosFetcher = async () => fixture.combos;
|
|
|
|
const recorded = await loadV1Parity();
|
|
assert.equal(recorded.hookId, "opencode-omniroute", "v1 published under its own provider id");
|
|
|
|
const stripX = (k: string): string =>
|
|
k.startsWith("omniroute/") ? k.slice("omniroute/".length) : k;
|
|
const v1Keys = recorded.publishedKeys;
|
|
|
|
const draft = fakeDraft();
|
|
const counts = await publishCatalog(draft, TEST_OPTS, { fetcher, combosFetcher });
|
|
assert.equal(counts.models, 5);
|
|
assert.equal(counts.combos, 2);
|
|
assert.equal(counts.autoCombos, 0);
|
|
|
|
// Final converted ModelV2Info shape (legacy→info boundary in
|
|
// src/catalog.ts assignModelFields): api resolves to the
|
|
// openai-compatible AISDK block, capabilities fold tool_calling into
|
|
// tools, cost is zeroed (pricing lives server-side).
|
|
const mAlpha = draft.models.get("omniroute/m-alpha");
|
|
assert.ok(mAlpha, "m-alpha published in v2 draft");
|
|
assert.equal(mAlpha.api.type, "aisdk");
|
|
if (mAlpha.api.type !== "aisdk") throw new Error("m-alpha api must be aisdk");
|
|
assert.equal(mAlpha.api.package, "@ai-sdk/openai-compatible");
|
|
assert.equal(mAlpha.capabilities.tools, true);
|
|
assert.equal(mAlpha.cost[0].input, 0);
|
|
|
|
// Measured key shapes: v1 namespaces the friendly name
|
|
// (`Combo Fast` -> `omniroute/combo-fast`) and keys the colliding combo
|
|
// by its raw id (`good-combo` -> `omniroute/good-combo`, combo wins);
|
|
// v2 publishes combo ids verbatim (`omniroute/combo-fast`,
|
|
// `omniroute/good-combo` overwriting the raw model). v1 and v2 therefore
|
|
// publish the SAME model keys (modulo the slashed-id exclusion above)
|
|
// and the SAME non-colliding combo key; the colliding `good-combo` combo
|
|
// overwrites the same-named raw model on BOTH sides (warn asserted below).
|
|
const v1Combo = v1Keys.filter((k) => k.startsWith("combo-") || k === "good-combo").sort();
|
|
const v2Combo = [...draft.models.keys()]
|
|
.map(stripX)
|
|
.filter((k) => k.startsWith("combo-") || k === "good-combo")
|
|
.sort();
|
|
// slug("Combo Fast") = "combo-fast", slug("Good Combo") = "good-combo".
|
|
assert.deepEqual(v2Combo, ["combo-fast", "good-combo"]);
|
|
assert.deepEqual(v1Combo, ["combo-fast", "good-combo"]);
|
|
assert.deepEqual(v2Combo, v1Combo);
|
|
assert.deepEqual(recorded.comboSlugs, ["combo-fast", "good-combo"]);
|
|
const v1Models = v1Keys.filter((k) => !k.startsWith("combo-") && k !== "good-combo").sort();
|
|
// Anchor v1 model keys as literals (modulo the slashed-id exclusion
|
|
// documented above: the bare `cc/m-gamma` key fails the
|
|
// `startsWith("omniroute/")` filter and is dropped here).
|
|
assert.deepEqual(v1Models, ["local-delta", "m-alpha", "m-beta"]);
|
|
const v2Models = [...draft.models.keys()]
|
|
.map(stripX)
|
|
.filter((k) => !k.includes("/") && !k.startsWith("combo-") && k !== "good-combo")
|
|
.sort();
|
|
assert.deepEqual(v2Models, v1Models);
|
|
|
|
// Collision: the combo whose friendly name collides with a raw model id
|
|
// wins on both sides (v1 warns via injected logger, v2 via console.warn).
|
|
const warns: string[] = [];
|
|
const origWarn = console.warn;
|
|
console.warn = (...args: unknown[]) => {
|
|
warns.push(String(args[0]));
|
|
};
|
|
try {
|
|
const draft2 = fakeDraft();
|
|
await publishCatalog(draft2, TEST_OPTS, { fetcher, combosFetcher });
|
|
assert.ok(draft2.models.has("omniroute/good-combo"), "colliding combo key wins in v2");
|
|
} finally {
|
|
console.warn = origWarn;
|
|
}
|
|
assert.ok(warns.some((w) => w.includes("collides with a model id; combo wins")));
|
|
|
|
// Mapper-level parity for the slashed-id exclusion: v1 and shared mappers
|
|
// must produce identical ModelV2 payloads for every fixture entry.
|
|
// (No apiFormat on either side — the parity scope is key publication,
|
|
// not the v1-prefix vs v2-allowlist routing rule covered by A2 tests.
|
|
// The `cc/m-gamma` fixture entry is therefore EXCLUDED from the mapper
|
|
// comparison: v1 routes it to anthropic via its default
|
|
// anthropicPrefixes while shared/v2 leave it openai-compatible without
|
|
// an explicit anthropicModels allowlist.)
|
|
// Mapper parity for the slashed-id exclusion: shared must still produce
|
|
// the payloads v1 produced. (`cc/m-gamma` is excluded: v1 routes it to
|
|
// anthropic through its default prefix list, while v2 leaves it
|
|
// openai-compatible without an explicit allowlist — covered by the
|
|
// apiFormat tests.)
|
|
for (const entry of fixture.models.filter((m) => m.id !== "cc/m-gamma")) {
|
|
const expected = recorded.mappedModels[entry.id];
|
|
assert.ok(expected, `v1 output recorded for ${entry.id}`);
|
|
const viaShared = sharedMapModel(entry, {
|
|
providerId: "omniroute",
|
|
baseURL: TEST_OPTS.baseURL,
|
|
});
|
|
assert.deepEqual(
|
|
JSON.parse(JSON.stringify({ ...viaShared, providerID: undefined })),
|
|
JSON.parse(JSON.stringify({ ...(expected as object), providerID: undefined })),
|
|
`model mapper parity for ${entry.id}`
|
|
);
|
|
}
|
|
const byId = new Map(fixture.models.map((m) => [m.id, m]));
|
|
for (const combo of fixture.combos) {
|
|
const members = (combo.models ?? [])
|
|
.filter((s) => s?.kind !== "combo-ref" && typeof s?.model === "string")
|
|
.map((s) => byId.get(s.model as string))
|
|
.filter((m): m is OmniRouteRawModelEntry => m !== undefined);
|
|
assert.deepEqual(
|
|
JSON.parse(JSON.stringify(sharedMapCombo(combo, members, "omniroute", TEST_OPTS.baseURL))),
|
|
recorded.mappedCombos[combo.id],
|
|
`combo mapper parity for ${combo.id}`
|
|
);
|
|
}
|
|
});
|
|
|
|
it("fixture is rejected when it drifts from the 5+2 shape (guard against silent shrink)", async () => {
|
|
const fixture = await loadFixture();
|
|
assert.ok(fixture.models.length >= 5, "fixture must keep at least 5 models");
|
|
assert.ok(fixture.combos.length >= 2, "fixture must keep at least 2 combos");
|
|
});
|
|
});
|
|
|
|
void (0 as unknown as ApiAuth);
|
|
void (0 as unknown as CatalogDraft);
|