From e50126e63956fb0c5e45a22317d625edfb695e52 Mon Sep 17 00:00:00 2001 From: Mourad Maatoug Date: Mon, 18 May 2026 16:25:31 +0200 Subject: [PATCH 1/3] feat(@omniroute/opencode-provider): expand config helpers, MCP entry, live model fetch, combo builder - T1: model/small_model top-level keys in buildOmniRouteOpenCodeConfig - T2: mergeIntoExistingConfig() non-destructive provider merge - T3: createOmniRouteMCPEntry() + OMNIROUTE_MCP_DEFAULT_SCOPES (7 read scopes) - T4: fetchLiveModels() async helper, plain fetch, camelCase+snake_case normalisation (field-variant logic adapted from Alph4d0g/opencode-omniroute-auth, MIT) - T5: listCombos() hits GET /api/combos, normalises compressionOverride - T6: createOmniRouteComboConfig() typed POST/PATCH payload builder - T7: OMNIROUTE_DEFAULT_OPENCODE_MODELS expanded to 7 (added cc/ prefix models) - T8: CI workflow path-filtered on @omniroute/opencode-provider/**, Node 20/22/24 - 32 tests (was 12), 0 failures --- .github/workflows/opencode-provider-ci.yml | 61 +++ @omniroute/opencode-provider/src/index.ts | 444 +++++++++++++++++- .../opencode-provider/tests/index.test.ts | 270 +++++++++++ 3 files changed, 771 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/opencode-provider-ci.yml 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"); +}); From 0c44185d0dd88c6decae4547b5956690a018417f Mon Sep 17 00:00:00 2001 From: Mourad Maatoug Date: Mon, 18 May 2026 16:43:09 +0200 Subject: [PATCH 2/3] fix(@omniroute/opencode-provider): address gemini-code-assist review - fetchJSON: consolidate all ops inside try, handle non-Error throws, catch JSON parse errors - fetchLiveModels: null-safe data-envelope check - listCombos: null-safe combos-envelope check - createOmniRouteComboConfig: omit providers key when filtered list empty --- @omniroute/opencode-provider/src/index.ts | 31 ++++++++++++----------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/@omniroute/opencode-provider/src/index.ts b/@omniroute/opencode-provider/src/index.ts index 38d060f688..d13b50afd9 100644 --- a/@omniroute/opencode-provider/src/index.ts +++ b/@omniroute/opencode-provider/src/index.ts @@ -330,25 +330,23 @@ async function fetchJSON(url: string, apiKey: string, timeoutMs: number): Pro const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); - let response: Response; try { - response = await fetch(url, { + const response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` }, signal: controller.signal, }); + + if (!response.ok) { + throw new Error(`received HTTP ${response.status}`); + } + + return (await response.json()) as T; } catch (err) { - throw new Error( - `@omniroute/opencode-provider: request to ${url} failed: ${(err as Error).message}` - ); + const message = err instanceof Error ? err.message : String(err); + throw new Error(`@omniroute/opencode-provider: request to ${url} failed: ${message}`); } finally { clearTimeout(timer); } - - if (!response.ok) { - throw new Error(`@omniroute/opencode-provider: received HTTP ${response.status} from ${url}`); - } - - return response.json() as Promise; } /** @@ -403,7 +401,7 @@ export async function fetchLiveModels( const rawList: unknown[] = Array.isArray(body) ? body - : Array.isArray((body as { data?: unknown[] }).data) + : body && typeof body === "object" && Array.isArray((body as { data?: unknown[] }).data) ? ((body as { data: unknown[] }).data as unknown[]) : []; @@ -498,7 +496,7 @@ export async function listCombos( const body = await fetchJSON(url, key, timeoutMs); const rawList: unknown[] = Array.isArray(body) ? body - : Array.isArray((body as { combos?: unknown[] }).combos) + : body && typeof body === "object" && Array.isArray((body as { combos?: unknown[] }).combos) ? ((body as { combos: unknown[] }).combos as unknown[]) : []; @@ -586,8 +584,11 @@ export function createOmniRouteComboConfig( payload.compressionOverride = options.compressionOverride; } - if (options.providers !== undefined && options.providers.length > 0) { - payload.providers = options.providers.filter((p) => typeof p === "string" && p.trim()); + if (options.providers !== undefined) { + const providers = options.providers.filter((p) => typeof p === "string" && p.trim()); + if (providers.length > 0) { + payload.providers = providers; + } } return payload; From 57354ac6d765abd2f50ae6bc103e1ec03c2e190b Mon Sep 17 00:00:00 2001 From: Mourad Maatoug Date: Mon, 18 May 2026 17:06:13 +0200 Subject: [PATCH 3/3] feat(@omniroute/opencode-provider): model capabilities, agent block, mode block (UI helpers) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds three UI-surface helpers on top of T1–T8 in PR #2375: A) Model capability flags - ModelCapabilities interface (label, attachment, reasoning, temperature, tool_call) - OMNIROUTE_DEFAULT_MODEL_CAPABILITIES seeds capabilities for all 7 default model ids - OmniRouteProviderOptions.modelCapabilities merges over defaults per id - createOmniRouteProvider emits capability flags inline in models[id], per OpenCode's ProviderConfig.models schema (snake_case JSON keys, optional) - Label precedence: modelCapabilities[id].label > modelLabels[id] > id B) createOmniRouteAgentBlock - OmniRouteAgentRole + OmniRouteAgentBlockOptions + OpenCodeAgentEntry - Emits Record', temperature?, top_p?, tools?: Record, prompt? }> - Only fields present in OpenCode's AgentConfig schema are emitted - Tools normalized to Record per schema (not string[]) - Roles with empty modelId are skipped C) createOmniRouteModesBlock (deprecated alias) - Same shape as createOmniRouteAgentBlock since OpenCode treats top-level 'mode' block identically to 'agent' (both reference AgentConfig) - Helper kept for back-compat; @deprecated tags steer callers to agent Shared helper buildAgentEntry eliminates duplication between A/B helpers. Schema validation - All emitted keys verified against https://opencode.ai/config.json - Removed initially-considered reasoningEffort + max_tokens fields (not in AgentConfig schema) - tools shape changed from string[] to Record per schema Build hygiene - tsconfig.json narrowed to lib: ['ES2022'] + types: ['node'] (no DOM lib leakage); @types/node added as devDep - Tests: 32 → 45 green (+13 net) - Build: ESM 10.39 KB / CJS 11.01 KB / DTS 18.87 KB --- .../opencode-provider/package-lock.json | 57 ++-- @omniroute/opencode-provider/package.json | 1 + @omniroute/opencode-provider/src/index.ts | 246 +++++++++++++++++- .../opencode-provider/tests/index.test.ts | 176 +++++++++++++ @omniroute/opencode-provider/tsconfig.json | 1 + 5 files changed, 437 insertions(+), 44 deletions(-) diff --git a/@omniroute/opencode-provider/package-lock.json b/@omniroute/opencode-provider/package-lock.json index c7b0102595..ad01c86c67 100644 --- a/@omniroute/opencode-provider/package-lock.json +++ b/@omniroute/opencode-provider/package-lock.json @@ -9,6 +9,7 @@ "version": "0.1.0", "license": "MIT", "devDependencies": { + "@types/node": "^20.19.41", "tsup": "^8.5.0", "tsx": "^4.20.0", "typescript": "^5.9.0" @@ -590,9 +591,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -607,9 +605,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -624,9 +619,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -641,9 +633,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -658,9 +647,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -675,9 +661,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -692,9 +675,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -709,9 +689,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -726,9 +703,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -743,9 +717,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -760,9 +731,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -777,9 +745,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -794,9 +759,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -894,6 +856,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "20.19.41", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", + "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, "node_modules/acorn": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", @@ -2014,6 +1986,13 @@ "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", "dev": true, "license": "MIT" + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" } } } diff --git a/@omniroute/opencode-provider/package.json b/@omniroute/opencode-provider/package.json index 3259f24da7..6df9e352aa 100644 --- a/@omniroute/opencode-provider/package.json +++ b/@omniroute/opencode-provider/package.json @@ -52,6 +52,7 @@ "access": "public" }, "devDependencies": { + "@types/node": "^20.19.41", "tsup": "^8.5.0", "tsx": "^4.20.0", "typescript": "^5.9.0" diff --git a/@omniroute/opencode-provider/src/index.ts b/@omniroute/opencode-provider/src/index.ts index d13b50afd9..2b9981b56f 100644 --- a/@omniroute/opencode-provider/src/index.ts +++ b/@omniroute/opencode-provider/src/index.ts @@ -55,6 +55,56 @@ export const OMNIROUTE_DEFAULT_OPENCODE_MODELS = [ "gemini-3-flash", ] as const; +/** + * Optional capability flags surfaced to OpenCode's model picker. + * + * OpenCode reads these per-model keys (snake_case in JSON) to render badges + * and to gate features such as image attachments, reasoning mode, temperature + * controls and tool-calling. Omitted flags default to OpenCode's heuristics. + * + * Mirrors the capability shape used by Alph4d0g/opencode-omniroute-auth + * (https://github.com/Alph4d0g/opencode-omniroute-auth, MIT). + */ +export interface ModelCapabilities { + /** Display label shown in the model picker. Falls back to the model id. */ + label?: string; + /** Model accepts image / file attachments. */ + attachment?: boolean; + /** Model exposes a "reasoning" / extended-thinking surface. */ + reasoning?: boolean; + /** Model honours the `temperature` parameter. */ + temperature?: boolean; + /** Model supports tool / function calling. */ + tool_call?: boolean; +} + +/** + * Default per-model capability hints for the curated default catalog. + * + * Conservative defaults: every default model accepts attachments, tool calls + * and temperature; `reasoning` is opt-in per model id. Callers override per + * model via `OmniRouteProviderOptions.modelCapabilities`. + */ +export const OMNIROUTE_DEFAULT_MODEL_CAPABILITIES: Record = { + "cc/claude-opus-4-7": { attachment: true, reasoning: true, temperature: true, tool_call: true }, + "cc/claude-sonnet-4-6": { attachment: true, reasoning: true, temperature: true, tool_call: true }, + "cc/claude-haiku-4-5-20251001": { attachment: true, temperature: true, tool_call: true }, + "claude-opus-4-5-thinking": { + attachment: true, + reasoning: true, + temperature: true, + tool_call: true, + }, + "claude-sonnet-4-5-thinking": { + attachment: true, + reasoning: true, + temperature: true, + tool_call: true, + }, + "gemini-3.1-pro-high": { attachment: true, reasoning: true, temperature: true, tool_call: true }, + "gemini-3-flash": { attachment: true, temperature: true, tool_call: true }, +}; + export interface OmniRouteProviderOptions { /** OmniRoute base URL, with or without trailing `/v1`. Required. */ baseURL: string; @@ -64,8 +114,14 @@ export interface OmniRouteProviderOptions { displayName?: string; /** Override the model catalog. Defaults to `OMNIROUTE_DEFAULT_OPENCODE_MODELS`. */ models?: readonly string[]; - /** Optional human-readable labels keyed by model id. */ + /** Optional human-readable labels keyed by model id. Overridden by `modelCapabilities[id].label`. */ modelLabels?: Record; + /** + * Optional capability overrides keyed by model id. Merged on top of + * `OMNIROUTE_DEFAULT_MODEL_CAPABILITIES` for ids in the default catalog; + * for custom ids the override is used verbatim. + */ + modelCapabilities?: Record; /** * Primary model for OpenCode (top-level `model` key). * Emitted as `"omniroute/"`. When omitted the key is not written. @@ -78,6 +134,15 @@ export interface OmniRouteProviderOptions { smallModel?: string; } +/** Per-model entry written under `provider.omniroute.models[id]`. */ +export interface OpenCodeModelEntry { + name: string; + attachment?: boolean; + reasoning?: boolean; + temperature?: boolean; + tool_call?: boolean; +} + export interface OpenCodeProviderEntry { /** Identifier of the OpenCode runtime package that will speak to OmniRoute. */ npm: typeof OMNIROUTE_PROVIDER_NPM; @@ -89,7 +154,7 @@ export interface OpenCodeProviderEntry { apiKey: string; }; /** Model catalog surfaced to OpenCode. */ - models: Record; + models: Record; } export interface OpenCodeConfigDocument { @@ -144,14 +209,28 @@ export function createOmniRouteProvider(options: OmniRouteProviderOptions): Open : [...OMNIROUTE_DEFAULT_OPENCODE_MODELS]; const labels = options.modelLabels ?? {}; - const models: Record = {}; + const overrides = options.modelCapabilities ?? {}; + const models: Record = {}; const seen = new Set(); for (const raw of modelList) { const id = typeof raw === "string" ? raw.trim() : ""; if (!id || seen.has(id)) continue; seen.add(id); - const label = typeof labels[id] === "string" && labels[id].trim() ? labels[id].trim() : id; - models[id] = { name: label }; + const defaults = OMNIROUTE_DEFAULT_MODEL_CAPABILITIES[id] ?? {}; + const override = overrides[id] ?? {}; + const merged: ModelCapabilities = { ...defaults, ...override }; + const explicitLabel = + typeof merged.label === "string" && merged.label.trim() + ? merged.label.trim() + : typeof labels[id] === "string" && labels[id].trim() + ? labels[id].trim() + : id; + const entry: OpenCodeModelEntry = { name: explicitLabel }; + if (typeof merged.attachment === "boolean") entry.attachment = merged.attachment; + if (typeof merged.reasoning === "boolean") entry.reasoning = merged.reasoning; + if (typeof merged.temperature === "boolean") entry.temperature = merged.temperature; + if (typeof merged.tool_call === "boolean") entry.tool_call = merged.tool_call; + models[id] = entry; } return { @@ -594,4 +673,161 @@ export function createOmniRouteComboConfig( return payload; } +/** + * Override fields supported per agent / mode entry. Mirrors the subset of + * OpenCode's `AgentConfig` schema that is safe to set declaratively from a + * config generator. Only fields present in + * https://opencode.ai/config.json#AgentConfig are exposed. + */ +export interface OmniRouteRoleOverrides { + /** Forward to OpenCode's `temperature` field. */ + temperature?: number; + /** Forward to OpenCode's `top_p` field. */ + top_p?: number; +} + +/** Per-role binding used by `createOmniRouteAgentBlock`. */ +export interface OmniRouteAgentRole extends OmniRouteRoleOverrides { + /** OmniRoute model id, e.g. `"claude-sonnet-4-5-thinking"`. */ + modelId: string; + /** Optional tools allow-list; per OpenCode schema, map of tool name → enabled. */ + tools?: Record; + /** Optional system prompt for this agent role. */ + prompt?: string; +} + +/** Options for `createOmniRouteAgentBlock`. */ +export interface OmniRouteAgentBlockOptions { + /** Per-role bindings. Keys become entries under OpenCode's `agent` block. */ + roles: Record; +} + +/** Single entry inside the emitted OpenCode `agent` block. */ +export interface OpenCodeAgentEntry extends OmniRouteRoleOverrides { + /** Always emitted as `"omniroute/"`. */ + model: string; + /** Per OpenCode schema, `Record`. */ + tools?: Record; + /** Optional system prompt. */ + prompt?: string; +} + +function buildAgentEntry(role: OmniRouteAgentRole): OpenCodeAgentEntry | undefined { + if (!role || typeof role.modelId !== "string") return undefined; + const modelId = role.modelId.trim(); + if (!modelId) return undefined; + const entry: OpenCodeAgentEntry = { model: `${OMNIROUTE_PROVIDER_KEY}/${modelId}` }; + if (typeof role.temperature === "number") entry.temperature = role.temperature; + if (typeof role.top_p === "number") entry.top_p = role.top_p; + if (role.tools && typeof role.tools === "object" && !Array.isArray(role.tools)) { + const tools: Record = {}; + for (const [name, enabled] of Object.entries(role.tools)) { + if (typeof name !== "string" || !name.trim()) continue; + if (typeof enabled !== "boolean") continue; + tools[name] = enabled; + } + if (Object.keys(tools).length > 0) entry.tools = tools; + } + if (typeof role.prompt === "string" && role.prompt.trim()) { + entry.prompt = role.prompt; + } + return entry; +} + +/** + * Build the OpenCode `agent` block, pre-wired so each agent role routes to a + * specific OmniRoute model. Useful for `.opencode/agent/*.md` defaults and + * scaffolded `opencode.json` files. + * + * Emitted fields are limited to those declared in OpenCode's `AgentConfig` + * schema (`model`, `temperature`, `top_p`, `tools`, `prompt`). The `tools` + * field is a `Record` per the schema, not a string array. + * + * Roles with empty / missing `modelId` are skipped. + * + * @example + * ```ts + * const agentBlock = createOmniRouteAgentBlock({ + * roles: { + * build: { modelId: "claude-sonnet-4-5-thinking", temperature: 0.2 }, + * plan: { modelId: "claude-opus-4-5-thinking", top_p: 0.95 }, + * review: { modelId: "gemini-3-flash", tools: { edit: false, bash: false } }, + * }, + * }); + * // -> { build: { model: "omniroute/claude-sonnet-4-5-thinking", temperature: 0.2 }, ... } + * ``` + */ +export function createOmniRouteAgentBlock( + options: OmniRouteAgentBlockOptions +): Record { + const out: Record = {}; + const roles = options.roles ?? {}; + for (const [roleName, role] of Object.entries(roles)) { + const entry = buildAgentEntry(role); + if (entry) out[roleName] = entry; + } + return out; +} + +/** + * Per-mode binding used by `createOmniRouteModesBlock`. + * + * @deprecated OpenCode's top-level `mode` block is deprecated in favour of + * `agent`. Prefer `OmniRouteAgentRole` + `createOmniRouteAgentBlock`. This + * type and the corresponding helper are kept for back-compat with configs + * still using `mode:`. + */ +export interface OmniRouteMode extends OmniRouteAgentRole {} + +/** + * Options for `createOmniRouteModesBlock`. + * + * @deprecated See `OmniRouteMode`. + */ +export interface OmniRouteModesBlockOptions { + /** Per-mode bindings. Keys become entries under OpenCode's deprecated top-level `mode` block. */ + modes: Record; +} + +/** + * Single entry inside the emitted OpenCode `mode` block. + * + * @deprecated See `OmniRouteMode`. + */ +export interface OpenCodeModeEntry extends OpenCodeAgentEntry {} + +/** + * Build the OpenCode top-level `mode` block, pre-wired so each mode routes to + * a specific OmniRoute model. Emits the same shape as the `agent` block since + * OpenCode's schema treats them identically (both reference `AgentConfig`). + * + * Modes with empty / missing `modelId` are skipped. + * + * @deprecated OpenCode's top-level `mode` block is deprecated in favour of + * `agent`. Prefer `createOmniRouteAgentBlock`. This helper is kept for + * back-compat with configs still using `mode:`. + * + * @example + * ```ts + * const modesBlock = createOmniRouteModesBlock({ + * modes: { + * build: { modelId: "claude-sonnet-4-5-thinking", tools: { edit: true, bash: true } }, + * plan: { modelId: "claude-opus-4-5-thinking", prompt: "Plan first, code later." }, + * review: { modelId: "gemini-3-flash" }, + * }, + * }); + * ``` + */ +export function createOmniRouteModesBlock( + options: OmniRouteModesBlockOptions +): Record { + const out: Record = {}; + const modes = options.modes ?? {}; + for (const [modeName, mode] of Object.entries(modes)) { + const entry = buildAgentEntry(mode); + if (entry) out[modeName] = entry; + } + return out; +} + export default createOmniRouteProvider; diff --git a/@omniroute/opencode-provider/tests/index.test.ts b/@omniroute/opencode-provider/tests/index.test.ts index af94f7faf9..324ae68bfa 100644 --- a/@omniroute/opencode-provider/tests/index.test.ts +++ b/@omniroute/opencode-provider/tests/index.test.ts @@ -5,13 +5,16 @@ import type { Server } from "node:http"; import { buildOmniRouteOpenCodeConfig, + createOmniRouteAgentBlock, createOmniRouteComboConfig, createOmniRouteMCPEntry, + createOmniRouteModesBlock, createOmniRouteProvider, fetchLiveModels, listCombos, mergeIntoExistingConfig, normalizeBaseURL, + OMNIROUTE_DEFAULT_MODEL_CAPABILITIES, OMNIROUTE_DEFAULT_OPENCODE_MODELS, OMNIROUTE_MCP_DEFAULT_SCOPES, OMNIROUTE_PROVIDER_NPM, @@ -74,6 +77,7 @@ test("createOmniRouteProvider seeds the default model catalog", () => { assert.deepEqual(modelIds, defaultIds); for (const id of defaultIds) { assert.equal(provider.models[id]?.name, id); + assert.equal(provider.models[id]?.attachment, true); } }); @@ -389,3 +393,175 @@ test("OMNIROUTE_DEFAULT_OPENCODE_MODELS includes cc/ prefixed models", () => { ); assert.ok(defaults.length >= 7, "should have at least 7 models"); }); + +test("OMNIROUTE_DEFAULT_MODEL_CAPABILITIES covers every default model id", () => { + for (const id of OMNIROUTE_DEFAULT_OPENCODE_MODELS) { + const caps = OMNIROUTE_DEFAULT_MODEL_CAPABILITIES[id]; + assert.ok(caps, `default capabilities for ${id} missing`); + assert.equal(caps.attachment, true, `${id} should default to attachment=true`); + assert.equal(caps.tool_call, true, `${id} should default to tool_call=true`); + } +}); + +test("createOmniRouteProvider emits default capability flags inline with the model entry", () => { + const provider = createOmniRouteProvider({ + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + }); + const entry = provider.models["cc/claude-opus-4-7"]; + assert.equal(entry.name, "cc/claude-opus-4-7"); + assert.equal(entry.attachment, true); + assert.equal(entry.reasoning, true); + assert.equal(entry.temperature, true); + assert.equal(entry.tool_call, true); +}); + +test("createOmniRouteProvider modelCapabilities overrides defaults and merges per id", () => { + const provider = createOmniRouteProvider({ + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + modelCapabilities: { + "cc/claude-opus-4-7": { reasoning: false, label: "Opus (no thinking)" }, + }, + }); + const entry = provider.models["cc/claude-opus-4-7"]; + assert.equal(entry.name, "Opus (no thinking)"); + assert.equal(entry.reasoning, false); + assert.equal(entry.attachment, true); + assert.equal(entry.tool_call, true); +}); + +test("createOmniRouteProvider applies capability overrides to non-default model ids", () => { + const provider = createOmniRouteProvider({ + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + models: ["custom-model"], + modelCapabilities: { + "custom-model": { attachment: false, tool_call: true, label: "Custom" }, + }, + }); + const entry = provider.models["custom-model"]; + assert.equal(entry.name, "Custom"); + assert.equal(entry.attachment, false); + assert.equal(entry.tool_call, true); + assert.equal(entry.reasoning, undefined); + assert.equal(entry.temperature, undefined); +}); + +test("createOmniRouteProvider modelLabels still works when modelCapabilities omits label", () => { + const provider = createOmniRouteProvider({ + baseURL: "http://localhost:20128", + apiKey: "sk_omniroute", + models: ["claude-opus-4-5-thinking"], + modelLabels: { "claude-opus-4-5-thinking": "Opus 4.5 (legacy label)" }, + }); + assert.equal(provider.models["claude-opus-4-5-thinking"].name, "Opus 4.5 (legacy label)"); +}); + +test("createOmniRouteAgentBlock builds provider-prefixed entries per role", () => { + const block = createOmniRouteAgentBlock({ + roles: { + build: { modelId: "claude-sonnet-4-5-thinking", temperature: 0.2 }, + plan: { modelId: "claude-opus-4-5-thinking", top_p: 0.95 }, + review: { modelId: "gemini-3-flash", temperature: 0.0 }, + }, + }); + assert.equal(block.build.model, "omniroute/claude-sonnet-4-5-thinking"); + assert.equal(block.build.temperature, 0.2); + assert.equal(block.plan.model, "omniroute/claude-opus-4-5-thinking"); + assert.equal(block.plan.top_p, 0.95); + assert.equal(block.review.model, "omniroute/gemini-3-flash"); + assert.equal(block.review.temperature, 0.0); +}); + +test("createOmniRouteAgentBlock omits optional fields when not supplied", () => { + const block = createOmniRouteAgentBlock({ + roles: { build: { modelId: "claude-sonnet-4-5-thinking" } }, + }); + assert.equal(block.build.model, "omniroute/claude-sonnet-4-5-thinking"); + assert.ok(!("temperature" in block.build)); + assert.ok(!("top_p" in block.build)); + assert.ok(!("tools" in block.build)); + assert.ok(!("prompt" in block.build)); +}); + +test("createOmniRouteAgentBlock skips roles with empty modelId", () => { + const block = createOmniRouteAgentBlock({ + roles: { + build: { modelId: "claude-sonnet-4-5-thinking" }, + plan: { modelId: " " }, + review: { modelId: "" }, + }, + }); + assert.deepEqual(Object.keys(block), ["build"]); +}); + +test("createOmniRouteAgentBlock emits tools as Record per OC schema", () => { + const block = createOmniRouteAgentBlock({ + roles: { + build: { + modelId: "claude-sonnet-4-5-thinking", + tools: { edit: true, bash: true, web: false }, + prompt: "Edit files carefully.", + }, + }, + }); + assert.deepEqual(block.build.tools, { edit: true, bash: true, web: false }); + assert.equal(block.build.prompt, "Edit files carefully."); +}); + +test("createOmniRouteAgentBlock filters invalid tool entries and omits empty maps", () => { + const block = createOmniRouteAgentBlock({ + roles: { + build: { + modelId: "claude-sonnet-4-5-thinking", + // @ts-expect-error — exercising runtime guard against bad input + tools: { edit: true, bash: "yes", "": true, web: null }, + }, + plan: { + modelId: "claude-opus-4-5-thinking", + tools: {}, + }, + }, + }); + assert.deepEqual(block.build.tools, { edit: true }); + assert.ok(!("tools" in block.plan)); +}); + +test("createOmniRouteModesBlock builds provider-prefixed mode entries", () => { + const block = createOmniRouteModesBlock({ + modes: { + build: { modelId: "claude-sonnet-4-5-thinking", tools: { edit: true, bash: true } }, + plan: { modelId: "claude-opus-4-5-thinking", prompt: "Plan first, code later." }, + review: { modelId: "gemini-3-flash" }, + }, + }); + assert.equal(block.build.model, "omniroute/claude-sonnet-4-5-thinking"); + assert.deepEqual(block.build.tools, { edit: true, bash: true }); + assert.equal(block.plan.prompt, "Plan first, code later."); + assert.equal(block.review.model, "omniroute/gemini-3-flash"); +}); + +test("createOmniRouteModesBlock skips modes with empty modelId", () => { + const block = createOmniRouteModesBlock({ + modes: { + build: { modelId: "claude-sonnet-4-5-thinking" }, + plan: { modelId: "" }, + }, + }); + assert.deepEqual(Object.keys(block), ["build"]); +}); + +test("createOmniRouteModesBlock honours numeric overrides limited to OC schema", () => { + const block = createOmniRouteModesBlock({ + modes: { + build: { + modelId: "claude-sonnet-4-5-thinking", + temperature: 0.7, + top_p: 0.9, + }, + }, + }); + assert.equal(block.build.temperature, 0.7); + assert.equal(block.build.top_p, 0.9); +}); diff --git a/@omniroute/opencode-provider/tsconfig.json b/@omniroute/opencode-provider/tsconfig.json index ac1430ae95..05ee599fbc 100644 --- a/@omniroute/opencode-provider/tsconfig.json +++ b/@omniroute/opencode-provider/tsconfig.json @@ -4,6 +4,7 @@ "module": "ESNext", "moduleResolution": "Bundler", "lib": ["ES2022"], + "types": ["node"], "strict": true, "esModuleInterop": true, "skipLibCheck": true,