diff --git a/.github/workflows/opencode-provider-ci.yml b/.github/workflows/opencode-provider-ci.yml new file mode 100644 index 0000000000..1b09274ddd --- /dev/null +++ b/.github/workflows/opencode-provider-ci.yml @@ -0,0 +1,61 @@ +name: opencode-provider CI + +on: + push: + branches: [main, release/v3.8.0] + paths: + - "@omniroute/opencode-provider/**" + pull_request: + branches: [main, release/v3.8.0] + paths: + - "@omniroute/opencode-provider/**" + types: [opened, synchronize, reopened, ready_for_review] + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +defaults: + run: + working-directory: "@omniroute/opencode-provider" + +jobs: + test: + name: Test (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: ["20", "22", "24"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + cache-dependency-path: "@omniroute/opencode-provider/package-lock.json" + - run: npm ci + - run: npm test + + build: + name: Build + runs-on: ubuntu-latest + needs: test + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + cache-dependency-path: "@omniroute/opencode-provider/package-lock.json" + - run: npm ci + - run: npm run build + - uses: actions/upload-artifact@v4 + with: + name: opencode-provider-dist + path: "@omniroute/opencode-provider/dist" + retention-days: 7 diff --git a/@omniroute/opencode-provider/src/index.ts b/@omniroute/opencode-provider/src/index.ts index 92fac28390..38d060f688 100644 --- a/@omniroute/opencode-provider/src/index.ts +++ b/@omniroute/opencode-provider/src/index.ts @@ -38,10 +38,17 @@ export const OPENCODE_CONFIG_SCHEMA = "https://opencode.ai/config.json" as const /** * Default catalog of models surfaced to OpenCode when the caller does not - * supply an explicit `models` list. Mirrors the curated set used by the - * OmniRoute dashboard's "OpenCode" config generator. + * supply an explicit `models` list. + * + * Curated set covering the most commonly deployed OmniRoute models. Synced + * with the Alph4d0g/opencode-omniroute-auth OMNIROUTE_DEFAULT_MODELS constant + * (https://github.com/Alph4d0g/opencode-omniroute-auth, MIT) and extended + * with Claude Code passthrough models (`cc/` prefix). */ export const OMNIROUTE_DEFAULT_OPENCODE_MODELS = [ + "cc/claude-opus-4-7", + "cc/claude-sonnet-4-6", + "cc/claude-haiku-4-5-20251001", "claude-opus-4-5-thinking", "claude-sonnet-4-5-thinking", "gemini-3.1-pro-high", @@ -59,6 +66,16 @@ export interface OmniRouteProviderOptions { models?: readonly string[]; /** Optional human-readable labels keyed by model id. */ modelLabels?: Record; + /** + * Primary model for OpenCode (top-level `model` key). + * Emitted as `"omniroute/"`. When omitted the key is not written. + */ + model?: string; + /** + * Secondary / cheap model for OpenCode (top-level `small_model` key). + * Emitted as `"omniroute/"`. When omitted the key is not written. + */ + smallModel?: string; } export interface OpenCodeProviderEntry { @@ -77,6 +94,10 @@ export interface OpenCodeProviderEntry { export interface OpenCodeConfigDocument { $schema: typeof OPENCODE_CONFIG_SCHEMA; + /** Primary model for OpenCode, e.g. `"omniroute/claude-sonnet-4-5-thinking"`. */ + model?: string; + /** Secondary / cheap model for OpenCode, e.g. `"omniroute/gemini-3-flash"`. */ + small_model?: string; provider: { [OMNIROUTE_PROVIDER_KEY]: OpenCodeProviderEntry; }; @@ -100,7 +121,6 @@ function requireNonEmpty(value: unknown, field: string): string { export function normalizeBaseURL(rawBaseURL: string): string { const trimmed = requireNonEmpty(rawBaseURL, "baseURL"); try { - // Reject malformed URLs early. new URL(trimmed); } catch { throw new Error( @@ -145,16 +165,432 @@ export function createOmniRouteProvider(options: OmniRouteProviderOptions): Open /** * Build a full OpenCode config document (with `$schema` + `provider.omniroute`). * Useful when scaffolding a fresh `opencode.json`. + * + * When `options.model` / `options.smallModel` are supplied they are emitted as + * top-level `model` / `small_model` keys prefixed with `"omniroute/"` so + * OpenCode resolves them through the configured provider. */ export function buildOmniRouteOpenCodeConfig( options: OmniRouteProviderOptions ): OpenCodeConfigDocument { - return { + const doc: OpenCodeConfigDocument = { $schema: OPENCODE_CONFIG_SCHEMA, provider: { [OMNIROUTE_PROVIDER_KEY]: createOmniRouteProvider(options), }, }; + + if (options.model !== undefined) { + const id = options.model.trim(); + if (id) doc.model = `${OMNIROUTE_PROVIDER_KEY}/${id}`; + } + + if (options.smallModel !== undefined) { + const id = options.smallModel.trim(); + if (id) doc.small_model = `${OMNIROUTE_PROVIDER_KEY}/${id}`; + } + + return doc; +} + +/** + * Merge the OmniRoute provider entry (and optional `model` / `small_model` + * keys) into an already-existing OpenCode config object. + * + * Performs a non-destructive merge: all top-level keys in `existing` are + * preserved. The `provider` map is shallow-merged so other providers already + * present are not removed. If `existing.provider.omniroute` already exists it + * is overwritten by the newly built entry. + * + * `model` and `small_model` are only written when supplied in `options`. + * + * @example + * ```ts + * const existing = JSON.parse(readFileSync("opencode.json", "utf8")); + * const updated = mergeIntoExistingConfig(existing, { + * baseURL: "http://localhost:20128", + * apiKey: "sk_omniroute", + * model: "claude-sonnet-4-5-thinking", + * }); + * writeFileSync("opencode.json", JSON.stringify(updated, null, 2)); + * ``` + */ +export function mergeIntoExistingConfig( + existing: Record, + options: OmniRouteProviderOptions +): Record { + const partial = buildOmniRouteOpenCodeConfig(options); + + const merged: Record = { ...existing }; + + if (partial.model !== undefined) merged.model = partial.model; + if (partial.small_model !== undefined) merged.small_model = partial.small_model; + + const existingProvider = + typeof existing.provider === "object" && existing.provider !== null + ? (existing.provider as Record) + : {}; + + merged.provider = { + ...existingProvider, + [OMNIROUTE_PROVIDER_KEY]: partial.provider[OMNIROUTE_PROVIDER_KEY], + }; + + return merged; +} + +/** + * The 7 read-only MCP scopes that allow inspection without any write access. + * Suitable for shared / public environments. + */ +export const OMNIROUTE_MCP_DEFAULT_SCOPES = [ + "read:health", + "read:combos", + "read:quota", + "read:usage", + "read:models", + "read:cache", + "read:compression", +] as const; + +export type OmniRouteMCPScope = (typeof OMNIROUTE_MCP_DEFAULT_SCOPES)[number] | string; + +export interface OmniRouteMCPOptions { + /** Absolute path to the MCP server entry point (TypeScript or compiled JS). */ + serverPath: string; + /** OmniRoute API key forwarded to the MCP server as `OMNIROUTE_API_KEY`. */ + apiKey: string; + /** + * Management API key used for management-scoped operations. + * When supplied it is forwarded as `OMNIROUTE_MANAGEMENT_API_KEY`. + */ + managementApiKey?: string; + /** + * Comma-separated scope list passed as `OMNIROUTE_MCP_SCOPES`. + * When omitted `OMNIROUTE_MCP_ENFORCE_SCOPES` is not set and all scopes are + * available (development default). Pass an explicit list to restrict access. + */ + scopes?: OmniRouteMCPScope[]; + /** + * Runtime used to execute the MCP server. + * + * - `"tsx"` (default) — runs via `npx tsx` for TypeScript source files. + * - `"node"` — runs via `node` for compiled JS outputs. + */ + runtime?: "tsx" | "node"; +} + +export interface OpenCodeMCPServerEntry { + command: string; + args: string[]; + env: Record; +} + +/** + * Build the `mcp.servers.omniroute` entry for an OpenCode config document. + * + * @example + * ```ts + * const mcpEntry = createOmniRouteMCPEntry({ + * serverPath: "/home/user/.local/share/omniroute/open-sse/mcp-server/server.ts", + * apiKey: "sk_omniroute", + * managementApiKey: "sk_manage_...", + * scopes: ["read:health", "read:combos", "execute:completions"], + * }); + * // Place at config.mcp.servers.omniroute + * ``` + */ +export function createOmniRouteMCPEntry(options: OmniRouteMCPOptions): OpenCodeMCPServerEntry { + const serverPath = requireNonEmpty(options.serverPath, "serverPath"); + const apiKey = requireNonEmpty(options.apiKey, "apiKey"); + + const runtime = options.runtime ?? "tsx"; + + const command = runtime === "tsx" ? "npx" : "node"; + const args = runtime === "tsx" ? ["tsx", serverPath] : [serverPath]; + + const env: Record = { + OMNIROUTE_API_KEY: apiKey, + }; + + if (options.managementApiKey !== undefined) { + const mgmtKey = options.managementApiKey.trim(); + if (mgmtKey) env.OMNIROUTE_MANAGEMENT_API_KEY = mgmtKey; + } + + if (options.scopes !== undefined && options.scopes.length > 0) { + env.OMNIROUTE_MCP_ENFORCE_SCOPES = "true"; + env.OMNIROUTE_MCP_SCOPES = options.scopes.join(","); + } + + return { command, args, env }; +} + +async function fetchJSON(url: string, apiKey: string, timeoutMs: number): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + + let response: Response; + try { + response = await fetch(url, { + headers: { Authorization: `Bearer ${apiKey}` }, + signal: controller.signal, + }); + } catch (err) { + throw new Error( + `@omniroute/opencode-provider: request to ${url} failed: ${(err as Error).message}` + ); + } finally { + clearTimeout(timer); + } + + if (!response.ok) { + throw new Error(`@omniroute/opencode-provider: received HTTP ${response.status} from ${url}`); + } + + return response.json() as Promise; +} + +/** + * Lightweight model descriptor returned by `fetchLiveModels`. + * The shape mirrors the subset of fields that OmniRoute's `/v1/models` + * endpoint reliably provides across versions, normalised from both + * camelCase and snake_case variants used by different OmniRoute releases. + * + * Attribution: field-variant normalisation logic adapted from + * https://github.com/Alph4d0g/opencode-omniroute-auth (MIT). + */ +export interface OmniRouteLiveModel { + id: string; + name: string; +} + +/** + * Fetch the live model catalog from a running OmniRoute instance. + * + * Returns an array of `{ id, name }` objects from `GET /v1/models`. Handles + * both the camelCase (`modelId`, `displayName`) and snake_case (`model_id`, + * `display_name`) field variants across OmniRoute versions. + * + * Useful for dynamically populating the `models` option of + * `createOmniRouteProvider` / `buildOmniRouteOpenCodeConfig` instead of + * relying on `OMNIROUTE_DEFAULT_OPENCODE_MODELS`. + * + * @param baseURL - OmniRoute base URL (with or without `/v1`). + * @param apiKey - OmniRoute API key. + * @param timeoutMs - Request timeout in milliseconds (default 5000). + * + * @example + * ```ts + * const models = await fetchLiveModels("http://localhost:20128", "sk_omniroute"); + * const config = buildOmniRouteOpenCodeConfig({ + * baseURL: "http://localhost:20128", + * apiKey: "sk_omniroute", + * models: models.map((m) => m.id), + * modelLabels: Object.fromEntries(models.map((m) => [m.id, m.name])), + * }); + * ``` + */ +export async function fetchLiveModels( + baseURL: string, + apiKey: string, + timeoutMs = 5_000 +): Promise { + const key = requireNonEmpty(apiKey, "apiKey"); + const url = `${normalizeBaseURL(baseURL)}/models`; + + const body = await fetchJSON(url, key, timeoutMs); + + const rawList: unknown[] = Array.isArray(body) + ? body + : Array.isArray((body as { data?: unknown[] }).data) + ? ((body as { data: unknown[] }).data as unknown[]) + : []; + + const models: OmniRouteLiveModel[] = []; + for (const raw of rawList) { + if (typeof raw !== "object" || raw === null) continue; + const r = raw as Record; + + const id = + typeof r.id === "string" + ? r.id.trim() + : typeof r.modelId === "string" + ? r.modelId.trim() + : typeof r.model_id === "string" + ? r.model_id.trim() + : ""; + + if (!id) continue; + + const name = + typeof r.name === "string" + ? r.name.trim() + : typeof r.displayName === "string" + ? r.displayName.trim() + : typeof r.display_name === "string" + ? r.display_name.trim() + : id; + + models.push({ id, name: name || id }); + } + + return models; +} + +/** + * Valid per-combo compression override values. + * An empty string clears any existing override (inherits global setting). + */ +export type OmniRouteCompressionOverride = + | "" + | "off" + | "lite" + | "standard" + | "aggressive" + | "ultra" + | "rtk" + | "stacked"; + +const VALID_COMPRESSION_OVERRIDES = new Set([ + "", + "off", + "lite", + "standard", + "aggressive", + "ultra", + "rtk", + "stacked", +]); + +/** Slim combo descriptor returned by `listCombos`. */ +export interface OmniRouteCombo { + id: string; + name: string; + strategy: string; + active: boolean; + compressionOverride: OmniRouteCompressionOverride; +} + +/** + * Fetch the active routing combo list from a running OmniRoute instance. + * + * Returns an array of combo descriptors from `GET /api/combos`. The + * `compressionOverride` field reflects the per-combo compression strategy + * (one of the 8 recognised values; empty string means "inherit global"). + * + * Requires a management-scoped API key (Bearer `manage` scope) when the + * instance has `REQUIRE_API_KEY` enabled. + * + * @param baseURL - OmniRoute base URL (with or without `/v1`). + * @param managementApiKey - API key with `manage` scope. + * @param timeoutMs - Request timeout in milliseconds (default 5000). + */ +export async function listCombos( + baseURL: string, + managementApiKey: string, + timeoutMs = 5_000 +): Promise { + const key = requireNonEmpty(managementApiKey, "managementApiKey"); + const base = normalizeBaseURL(baseURL).replace(/\/v1$/, ""); + const url = `${base}/api/combos`; + + const body = await fetchJSON(url, key, timeoutMs); + const rawList: unknown[] = Array.isArray(body) + ? body + : Array.isArray((body as { combos?: unknown[] }).combos) + ? ((body as { combos: unknown[] }).combos as unknown[]) + : []; + + const combos: OmniRouteCombo[] = []; + for (const raw of rawList) { + if (typeof raw !== "object" || raw === null) continue; + const r = raw as Record; + + const id = typeof r.id === "string" ? r.id.trim() : ""; + if (!id) continue; + + const name = typeof r.name === "string" ? r.name.trim() : id; + const strategy = typeof r.strategy === "string" ? r.strategy : ""; + const active = typeof r.active === "boolean" ? r.active : false; + + const rawOverride = typeof r.compressionOverride === "string" ? r.compressionOverride : ""; + const compressionOverride = VALID_COMPRESSION_OVERRIDES.has(rawOverride) + ? (rawOverride as OmniRouteCompressionOverride) + : ""; + + combos.push({ id, name, strategy, active, compressionOverride }); + } + + return combos; +} + +/** + * Options for `createOmniRouteComboConfig`. + * Mirrors the subset of combo fields exposed by the OmniRoute `/api/combos` + * PATCH / POST payload that are safe to set programmatically. + */ +export interface OmniRouteComboConfigOptions { + /** Human-readable combo name. */ + name: string; + /** Routing strategy (e.g. `"priority"`, `"weighted"`, `"round-robin"`). */ + strategy: string; + /** + * Per-combo compression override. + * Empty string removes any override (inherits global setting). + */ + compressionOverride?: OmniRouteCompressionOverride; + /** Whether this combo is active for routing. Default: `true`. */ + active?: boolean; + /** + * Ordered list of provider IDs in this combo. + * Required for create operations; optional for updates. + */ + providers?: string[]; +} + +/** + * Build a typed combo payload suitable for OmniRoute's management API. + * + * The returned object is JSON-serialisable and safe to pass as the body of a + * `POST /api/combos` (create) or `PATCH /api/combos/:id` (update) request. + * + * @example + * ```ts + * const payload = createOmniRouteComboConfig({ + * name: "claude-primary", + * strategy: "priority", + * compressionOverride: "standard", + * providers: ["anthropic-claude-opus", "anthropic-claude-sonnet"], + * }); + * await fetch(`${baseURL}/api/combos`, { + * method: "POST", + * headers: { Authorization: `Bearer ${mgmtKey}`, "Content-Type": "application/json" }, + * body: JSON.stringify(payload), + * }); + * ``` + */ +export function createOmniRouteComboConfig( + options: OmniRouteComboConfigOptions +): Record { + const name = requireNonEmpty(options.name, "name"); + const strategy = requireNonEmpty(options.strategy, "strategy"); + + const payload: Record = { + name, + strategy, + active: options.active ?? true, + }; + + if (options.compressionOverride !== undefined) { + payload.compressionOverride = options.compressionOverride; + } + + if (options.providers !== undefined && options.providers.length > 0) { + payload.providers = options.providers.filter((p) => typeof p === "string" && p.trim()); + } + + return payload; } export default createOmniRouteProvider; diff --git a/@omniroute/opencode-provider/tests/index.test.ts b/@omniroute/opencode-provider/tests/index.test.ts index d346ff57bb..af94f7faf9 100644 --- a/@omniroute/opencode-provider/tests/index.test.ts +++ b/@omniroute/opencode-provider/tests/index.test.ts @@ -1,11 +1,19 @@ import test from "node:test"; import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import type { Server } from "node:http"; import { buildOmniRouteOpenCodeConfig, + createOmniRouteComboConfig, + createOmniRouteMCPEntry, createOmniRouteProvider, + fetchLiveModels, + listCombos, + mergeIntoExistingConfig, normalizeBaseURL, OMNIROUTE_DEFAULT_OPENCODE_MODELS, + OMNIROUTE_MCP_DEFAULT_SCOPES, OMNIROUTE_PROVIDER_NPM, OPENCODE_CONFIG_SCHEMA, } from "../src/index.ts"; @@ -119,3 +127,265 @@ test("config document is JSON-serialisable", () => { const round = JSON.parse(JSON.stringify(doc)); assert.deepEqual(round, doc); }); + +test("buildOmniRouteOpenCodeConfig emits model and small_model prefixed with provider key", () => { + const doc = buildOmniRouteOpenCodeConfig({ + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + model: "claude-sonnet-4-5-thinking", + smallModel: "gemini-3-flash", + }); + assert.equal(doc.model, "omniroute/claude-sonnet-4-5-thinking"); + assert.equal(doc.small_model, "omniroute/gemini-3-flash"); +}); + +test("buildOmniRouteOpenCodeConfig omits model and small_model when not supplied", () => { + const doc = buildOmniRouteOpenCodeConfig({ + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + }); + assert.equal(doc.model, undefined); + assert.equal(doc.small_model, undefined); + assert.ok(!("model" in doc)); + assert.ok(!("small_model" in doc)); +}); + +test("buildOmniRouteOpenCodeConfig ignores blank model strings", () => { + const doc = buildOmniRouteOpenCodeConfig({ + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + model: " ", + smallModel: "", + }); + assert.ok(!("model" in doc)); + assert.ok(!("small_model" in doc)); +}); + +test("mergeIntoExistingConfig preserves existing provider entries", () => { + const existing = { + $schema: OPENCODE_CONFIG_SCHEMA, + provider: { + anthropic: { npm: "@ai-sdk/anthropic", name: "Anthropic", options: {}, models: {} }, + }, + keybinds: { submit: "enter" }, + }; + const result = mergeIntoExistingConfig(existing, { + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + }); + assert.ok("anthropic" in (result.provider as Record)); + assert.ok("omniroute" in (result.provider as Record)); + assert.deepEqual((result as Record).keybinds, { submit: "enter" }); +}); + +test("mergeIntoExistingConfig overwrites existing omniroute entry", () => { + const existing = { + provider: { + omniroute: { + npm: "@ai-sdk/openai-compatible", + name: "OLD", + options: { baseURL: "http://old/v1", apiKey: "old" }, + models: {}, + }, + }, + }; + const result = mergeIntoExistingConfig(existing, { + baseURL: "http://new", + apiKey: "new-key", + displayName: "NEW", + }); + const omniroute = (result.provider as Record).omniroute as { name: string }; + assert.equal(omniroute.name, "NEW"); +}); + +test("mergeIntoExistingConfig writes model and small_model when supplied", () => { + const result = mergeIntoExistingConfig( + {}, + { + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + model: "claude-sonnet-4-5-thinking", + smallModel: "gemini-3-flash", + } + ); + assert.equal(result.model, "omniroute/claude-sonnet-4-5-thinking"); + assert.equal(result.small_model, "omniroute/gemini-3-flash"); +}); + +test("mergeIntoExistingConfig does not add model keys when not supplied", () => { + const result = mergeIntoExistingConfig( + {}, + { baseURL: "http://localhost:20128", apiKey: "sk_omniroute" } + ); + assert.ok(!("model" in result)); + assert.ok(!("small_model" in result)); +}); + +test("OMNIROUTE_MCP_DEFAULT_SCOPES contains 7 read-only scopes", () => { + assert.equal(OMNIROUTE_MCP_DEFAULT_SCOPES.length, 7); + assert.ok(OMNIROUTE_MCP_DEFAULT_SCOPES.every((s) => s.startsWith("read:"))); +}); + +test("createOmniRouteMCPEntry defaults to tsx runtime", () => { + const entry = createOmniRouteMCPEntry({ + serverPath: "/path/to/server.ts", + apiKey: "sk_omniroute", + }); + assert.equal(entry.command, "npx"); + assert.deepEqual(entry.args, ["tsx", "/path/to/server.ts"]); + assert.equal(entry.env.OMNIROUTE_API_KEY, "sk_omniroute"); + assert.ok(!("OMNIROUTE_MCP_ENFORCE_SCOPES" in entry.env)); + assert.ok(!("OMNIROUTE_MANAGEMENT_API_KEY" in entry.env)); +}); + +test("createOmniRouteMCPEntry uses node runtime when specified", () => { + const entry = createOmniRouteMCPEntry({ + serverPath: "/path/to/server.js", + apiKey: "sk_omniroute", + runtime: "node", + }); + assert.equal(entry.command, "node"); + assert.deepEqual(entry.args, ["/path/to/server.js"]); +}); + +test("createOmniRouteMCPEntry sets management key and scopes when supplied", () => { + const entry = createOmniRouteMCPEntry({ + serverPath: "/path/to/server.ts", + apiKey: "sk_omniroute", + managementApiKey: "sk_manage", + scopes: ["read:health", "read:combos", "execute:completions"], + }); + assert.equal(entry.env.OMNIROUTE_MANAGEMENT_API_KEY, "sk_manage"); + assert.equal(entry.env.OMNIROUTE_MCP_ENFORCE_SCOPES, "true"); + assert.equal(entry.env.OMNIROUTE_MCP_SCOPES, "read:health,read:combos,execute:completions"); +}); + +test("createOmniRouteMCPEntry rejects missing required fields", () => { + assert.throws( + () => createOmniRouteMCPEntry({ serverPath: "", apiKey: "x" }), + /serverPath is required/ + ); + assert.throws( + () => createOmniRouteMCPEntry({ serverPath: "/p", apiKey: "" }), + /apiKey is required/ + ); +}); + +function startMockServer( + handler: (path: string) => unknown +): Promise<{ url: string; close: () => void }> { + return new Promise((resolve) => { + const server: Server = createServer((req, res) => { + const body = JSON.stringify(handler(req.url ?? "")); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(body); + }); + server.listen(0, "127.0.0.1", () => { + const addr = server.address() as { port: number }; + resolve({ url: `http://127.0.0.1:${addr.port}`, close: () => server.close() }); + }); + }); +} + +test("fetchLiveModels handles array envelope", async () => { + const { url, close } = await startMockServer(() => [ + { id: "claude-sonnet", name: "Claude Sonnet" }, + { id: "gemini-flash", displayName: "Gemini Flash" }, + ]); + try { + const models = await fetchLiveModels(url, "sk_test"); + assert.equal(models.length, 2); + assert.equal(models[0].id, "claude-sonnet"); + assert.equal(models[0].name, "Claude Sonnet"); + assert.equal(models[1].id, "gemini-flash"); + assert.equal(models[1].name, "Gemini Flash"); + } finally { + close(); + } +}); + +test("fetchLiveModels handles data-envelope and snake_case fields", async () => { + const { url, close } = await startMockServer(() => ({ + data: [{ model_id: "gpt-4o", display_name: "GPT-4o" }], + })); + try { + const models = await fetchLiveModels(url, "sk_test"); + assert.equal(models.length, 1); + assert.equal(models[0].id, "gpt-4o"); + assert.equal(models[0].name, "GPT-4o"); + } finally { + close(); + } +}); + +test("fetchLiveModels falls back to id as name when no name field", async () => { + const { url, close } = await startMockServer(() => [{ id: "auto" }]); + try { + const models = await fetchLiveModels(url, "sk_test"); + assert.equal(models[0].name, "auto"); + } finally { + close(); + } +}); + +test("listCombos normalises compressionOverride", async () => { + const { url, close } = await startMockServer(() => ({ + combos: [ + { + id: "c1", + name: "Primary", + strategy: "priority", + active: true, + compressionOverride: "standard", + }, + { + id: "c2", + name: "Cheap", + strategy: "weighted", + active: false, + compressionOverride: "unknown-value", + }, + { id: "c3", name: "Off", strategy: "round-robin", active: true, compressionOverride: "" }, + ], + })); + try { + const combos = await listCombos(url, "sk_manage"); + assert.equal(combos.length, 3); + assert.equal(combos[0].compressionOverride, "standard"); + assert.equal(combos[1].compressionOverride, ""); + assert.equal(combos[2].compressionOverride, ""); + } finally { + close(); + } +}); + +test("createOmniRouteComboConfig builds minimal payload", () => { + const payload = createOmniRouteComboConfig({ name: "my-combo", strategy: "priority" }); + assert.equal(payload.name, "my-combo"); + assert.equal(payload.strategy, "priority"); + assert.equal(payload.active, true); + assert.ok(!("compressionOverride" in payload)); + assert.ok(!("providers" in payload)); +}); + +test("createOmniRouteComboConfig includes optional fields when supplied", () => { + const payload = createOmniRouteComboConfig({ + name: "full", + strategy: "weighted", + compressionOverride: "aggressive", + active: false, + providers: ["provider-a", "provider-b"], + }); + assert.equal(payload.compressionOverride, "aggressive"); + assert.equal(payload.active, false); + assert.deepEqual(payload.providers, ["provider-a", "provider-b"]); +}); + +test("OMNIROUTE_DEFAULT_OPENCODE_MODELS includes cc/ prefixed models", () => { + const defaults = [...OMNIROUTE_DEFAULT_OPENCODE_MODELS]; + assert.ok( + defaults.some((m) => m.startsWith("cc/")), + "should have cc/ prefixed models" + ); + assert.ok(defaults.length >= 7, "should have at least 7 models"); +});