chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
*.log
|
||||
.DS_Store
|
||||
@@ -0,0 +1,7 @@
|
||||
src
|
||||
tests
|
||||
tsconfig.json
|
||||
tsup.config.ts
|
||||
node_modules
|
||||
.DS_Store
|
||||
*.log
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 OmniRoute contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,156 @@
|
||||
# @omniroute/opencode-provider
|
||||
|
||||
> ## ⚠️ Deprecated — use [`@omniroute/opencode-plugin`](https://www.npmjs.com/package/@omniroute/opencode-plugin) instead
|
||||
>
|
||||
> This package writes a **static** `provider.omniroute` block to `opencode.json` from a hardcoded default model list, so it **drifts behind your live OmniRoute catalog** — adding a model in OmniRoute won't show up in OpenCode until you re-run the generator, and OpenCode Desktop/Web only surfaces a subset of the static models.
|
||||
>
|
||||
> **`@omniroute/opencode-plugin`** solves this by fetching `GET /v1/models` from your OmniRoute instance at OpenCode startup, so the model list is always live (see [#3419](https://github.com/diegosouzapw/OmniRoute/issues/3419)). It is now the recommended path.
|
||||
>
|
||||
> **One-line migration** — replace the static `provider.omniroute` block in `opencode.json` with a single plugin entry:
|
||||
>
|
||||
> ```jsonc
|
||||
> // opencode.json
|
||||
> {
|
||||
> "$schema": "https://opencode.ai/config.json",
|
||||
> "plugin": ["@omniroute/opencode-plugin"]
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> This package is **not removed** and still works for static/offline config generation, but it is no longer actively recommended and won't track new models automatically.
|
||||
|
||||
Helper for connecting [OpenCode](https://opencode.ai) to a running [OmniRoute](https://github.com/diegosouzapw/OmniRoute) AI gateway.
|
||||
|
||||
The package emits a **schema-valid entry** for `opencode.json` (`https://opencode.ai/config.json`) that delegates the actual runtime to [`@ai-sdk/openai-compatible`](https://www.npmjs.com/package/@ai-sdk/openai-compatible). It does not ship any new HTTP client — OmniRoute already exposes an OpenAI-compatible surface, and OpenCode already speaks it through the AI SDK.
|
||||
|
||||
> Pre-1.0. The API may still change. See `CHANGELOG` in the OmniRoute repo for breaking notes.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install --save-dev @omniroute/opencode-provider
|
||||
# or
|
||||
pnpm add -D @omniroute/opencode-provider
|
||||
```
|
||||
|
||||
You also need OpenCode's own runtime dep, but that's a transitive concern — OpenCode itself ships with `@ai-sdk/openai-compatible`. This package only **generates configuration**.
|
||||
|
||||
## Quick start
|
||||
|
||||
### 1. Scaffold a fresh `opencode.json`
|
||||
|
||||
```ts
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { buildOmniRouteOpenCodeConfig } from "@omniroute/opencode-provider";
|
||||
|
||||
const config = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128", // or your OmniRoute deployment URL
|
||||
apiKey: process.env.OMNIROUTE_API_KEY ?? "sk_omniroute",
|
||||
});
|
||||
|
||||
writeFileSync("opencode.json", JSON.stringify(config, null, 2));
|
||||
```
|
||||
|
||||
The resulting `opencode.json`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"provider": {
|
||||
"omniroute": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "OmniRoute",
|
||||
"options": {
|
||||
"baseURL": "http://localhost:20128/v1",
|
||||
"apiKey": "sk_omniroute",
|
||||
},
|
||||
"models": {
|
||||
"claude-opus-4-5-thinking": { "name": "claude-opus-4-5-thinking" },
|
||||
"claude-sonnet-4-5-thinking": { "name": "claude-sonnet-4-5-thinking" },
|
||||
"gemini-3.1-pro-high": { "name": "gemini-3.1-pro-high" },
|
||||
"gemini-3-flash": { "name": "gemini-3-flash" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Merge into an existing `opencode.json`
|
||||
|
||||
```ts
|
||||
import { createOmniRouteProvider } from "@omniroute/opencode-provider";
|
||||
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: process.env.OMNIROUTE_API_KEY!,
|
||||
});
|
||||
|
||||
// Place `provider` under provider.omniroute in your opencode.json
|
||||
```
|
||||
|
||||
If you already have an `opencode.json` on disk and want a non-destructive merge from the OmniRoute side, use `omniroute config opencode` from the CLI (ships with the main OmniRoute install) — it preserves comments and unrelated keys.
|
||||
|
||||
## API
|
||||
|
||||
### `createOmniRouteProvider(options): OpenCodeProviderEntry`
|
||||
|
||||
Returns the value to place under `provider.omniroute` inside `opencode.json`.
|
||||
|
||||
| Option | Type | Required | Description |
|
||||
| ------------- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `baseURL` | `string` | Yes | OmniRoute base URL. Accepts `http://host:port` **or** `http://host:port/v1`. Trailing slashes are tolerated. |
|
||||
| `apiKey` | `string` | Yes | OmniRoute API key. Use `sk_omniroute` for local installs that have `REQUIRE_API_KEY=false`. |
|
||||
| `displayName` | `string` | No | Custom name shown in the OpenCode UI. Default: `"OmniRoute"`. |
|
||||
| `models` | `string[]` | No | Override the surfaced model catalog. Default: 4 curated models — see `OMNIROUTE_DEFAULT_OPENCODE_MODELS`. |
|
||||
| `modelLabels` | `Record<string,string>` | No | Human-readable labels keyed by model id. |
|
||||
|
||||
Throws on empty/invalid input — `baseURL` must be a real URL, `apiKey` must be a non-empty string.
|
||||
|
||||
### `buildOmniRouteOpenCodeConfig(options): OpenCodeConfigDocument`
|
||||
|
||||
Same options as above, but returns a full document with `$schema` and the `provider.omniroute` wrapper, ready to write to `opencode.json`.
|
||||
|
||||
### `normalizeBaseURL(input): string`
|
||||
|
||||
Exported for completeness. Strips trailing `/`, deduplicates a trailing `/v1`, and re-appends exactly one `/v1`. Throws on empty / non-URL input.
|
||||
|
||||
### Constants
|
||||
|
||||
- `OMNIROUTE_PROVIDER_KEY` — `"omniroute"` (the key used under `provider.*`).
|
||||
- `OMNIROUTE_PROVIDER_NPM` — `"@ai-sdk/openai-compatible"` (the runtime delegate).
|
||||
- `OPENCODE_CONFIG_SCHEMA` — `"https://opencode.ai/config.json"`.
|
||||
- `OMNIROUTE_DEFAULT_OPENCODE_MODELS` — readonly list of default model ids.
|
||||
|
||||
## Custom model catalog
|
||||
|
||||
```ts
|
||||
import { createOmniRouteProvider } from "@omniroute/opencode-provider";
|
||||
|
||||
createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["auto", "claude-opus-4-8", "gpt-5.5"],
|
||||
modelLabels: {
|
||||
auto: "Auto-Combo (recommended)",
|
||||
"claude-opus-4-8": "Claude Opus 4.8",
|
||||
"gpt-5.5": "GPT-5.5",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Duplicates and empty strings are dropped automatically, and order is preserved.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **Requests 404 with `/v1/v1/...`** — you're on an old version (≤1.0.0). Update to `≥0.1.0` of this re-released package. The new build normalises `baseURL` automatically.
|
||||
- **`401 Invalid API key`** — your OmniRoute instance has `REQUIRE_API_KEY=true` but the key you supplied doesn't exist there. Create one via the dashboard or set `REQUIRE_API_KEY=false` and use `sk_omniroute`.
|
||||
- **OpenCode complains the provider has no models** — supply an explicit `models` list; the default 4 may be hidden by your provider visibility settings.
|
||||
|
||||
## Related
|
||||
|
||||
- [OmniRoute](https://github.com/diegosouzapw/OmniRoute) — the AI gateway this plugin targets.
|
||||
- [OpenCode](https://opencode.ai) — the agentic CLI consumer.
|
||||
- [`@ai-sdk/openai-compatible`](https://www.npmjs.com/package/@ai-sdk/openai-compatible) — the runtime delegate that actually speaks HTTP.
|
||||
|
||||
## License
|
||||
|
||||
MIT — see [`LICENSE`](./LICENSE).
|
||||
+1514
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"name": "@omniroute/opencode-provider",
|
||||
"version": "0.1.0",
|
||||
"description": "DEPRECATED — use @omniroute/opencode-plugin instead (it fetches the live OmniRoute /v1/models catalog at startup, so models never drift). This static-config generator still works but is no longer the recommended path. OpenCode provider helper for the OmniRoute AI Gateway.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js",
|
||||
"require": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"clean": "rm -rf dist",
|
||||
"test": "node --import tsx/esm --test tests/index.test.ts",
|
||||
"prepublishOnly": "npm run clean && npm run build && npm test"
|
||||
},
|
||||
"keywords": [
|
||||
"omniroute",
|
||||
"opencode",
|
||||
"opencode-ai",
|
||||
"ai-sdk",
|
||||
"openai-compatible",
|
||||
"provider",
|
||||
"ai-gateway",
|
||||
"llm-router"
|
||||
],
|
||||
"author": "OmniRoute contributors",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/diegosouzapw/OmniRoute.git",
|
||||
"directory": "@omniroute/opencode-provider"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/diegosouzapw/OmniRoute/issues"
|
||||
},
|
||||
"homepage": "https://github.com/diegosouzapw/OmniRoute/tree/main/%40omniroute/opencode-provider#readme",
|
||||
"engines": {
|
||||
"node": ">=22.22.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.19.19",
|
||||
"tsup": "^8.5.1",
|
||||
"tsx": "^4.22.3",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"overrides": {
|
||||
"esbuild": "^0.28.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,908 @@
|
||||
/**
|
||||
* OpenCode provider plugin for OmniRoute AI Gateway.
|
||||
*
|
||||
* Generates an OpenCode-compatible provider object that points to a running
|
||||
* OmniRoute instance. The output follows the OpenCode config schema
|
||||
* (https://opencode.ai/config.json) and delegates the runtime to
|
||||
* `@ai-sdk/openai-compatible` so OpenCode can drive any OmniRoute-exposed
|
||||
* model through its standard OpenAI-compatible client.
|
||||
*
|
||||
* Two ways to consume the helper:
|
||||
*
|
||||
* 1. As code, when you build your own opencode.json programmatically:
|
||||
*
|
||||
* ```ts
|
||||
* import { buildOmniRouteOpenCodeConfig } from "@omniroute/opencode-provider";
|
||||
* const config = buildOmniRouteOpenCodeConfig({
|
||||
* baseURL: "http://localhost:20128",
|
||||
* apiKey: "sk_omniroute",
|
||||
* });
|
||||
* // config -> { $schema, provider: { omniroute: { npm, name, options, models } } }
|
||||
* ```
|
||||
*
|
||||
* 2. As a single-provider entry to merge into an existing opencode.json:
|
||||
*
|
||||
* ```ts
|
||||
* import { createOmniRouteProvider } from "@omniroute/opencode-provider";
|
||||
* const provider = createOmniRouteProvider({ baseURL, apiKey });
|
||||
* // provider -> the value to place under provider.omniroute in opencode.json
|
||||
* ```
|
||||
*
|
||||
* Note: `baseURL` accepts both `http://host:port` and `http://host:port/v1`.
|
||||
* The helper normalises trailing slashes / `/v1` so you never get `/v1/v1`.
|
||||
*/
|
||||
|
||||
export const OMNIROUTE_PROVIDER_KEY = "omniroute" as const;
|
||||
export const OMNIROUTE_PROVIDER_NPM = "@ai-sdk/openai-compatible" as const;
|
||||
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.
|
||||
*
|
||||
* 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-8",
|
||||
"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",
|
||||
"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 context window sizes (tokens) for the curated default catalog.
|
||||
* Matches the context lengths used by OmniRoute's provider registry.
|
||||
*/
|
||||
export const OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS: Record<string, number> = {
|
||||
"cc/claude-opus-4-8": 1_000_000,
|
||||
"cc/claude-opus-4-7": 1_000_000,
|
||||
"cc/claude-sonnet-4-6": 200_000,
|
||||
"cc/claude-haiku-4-5-20251001": 200_000,
|
||||
"claude-opus-4-5-thinking": 200_000,
|
||||
"claude-sonnet-4-5-thinking": 200_000,
|
||||
"gemini-3.1-pro-high": 1_000_000,
|
||||
"gemini-3-flash": 1_000_000,
|
||||
};
|
||||
|
||||
/**
|
||||
* 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<string, ModelCapabilities> = {
|
||||
"cc/claude-opus-4-8": { attachment: true, reasoning: true, temperature: true, tool_call: true },
|
||||
"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;
|
||||
/** OmniRoute API key. Required. Use `sk_omniroute` for local instances without REQUIRE_API_KEY. */
|
||||
apiKey: string;
|
||||
/** Override the display name shown in OpenCode. Default: `"OmniRoute"`. */
|
||||
displayName?: string;
|
||||
/** Override the model catalog. Accepts model ids (strings) or live model entries from `fetchLiveModels`. When entries carry a `contextLength`, it is used directly — no hardcoded map needed. */
|
||||
models?: readonly (string | { id: string; contextLength?: number })[];
|
||||
/** Optional human-readable labels keyed by model id. Overridden by `modelCapabilities[id].label`. */
|
||||
modelLabels?: Record<string, string>;
|
||||
/**
|
||||
* 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<string, ModelCapabilities>;
|
||||
/**
|
||||
* Optional per-model context-length overrides (tokens). Takes precedence
|
||||
* over the static `OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS` map but is
|
||||
* superseded by `contextLength` on live model entries passed via `models`.
|
||||
*/
|
||||
modelContextLengths?: Record<string, string | number>;
|
||||
/**
|
||||
* Primary model for OpenCode (top-level `model` key).
|
||||
* Emitted as `"omniroute/<id>"`. When omitted the key is not written.
|
||||
*/
|
||||
model?: string;
|
||||
/**
|
||||
* Secondary / cheap model for OpenCode (top-level `small_model` key).
|
||||
* Emitted as `"omniroute/<id>"`. When omitted the key is not written.
|
||||
*/
|
||||
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;
|
||||
/**
|
||||
* Context window limit. OpenCode reads this to determine usable context
|
||||
* length for compaction, overflow detection, and router decisions.
|
||||
* Maps to `limit.context` in OpenCode's provider config schema.
|
||||
*/
|
||||
limit?: {
|
||||
/** Maximum context length in tokens (e.g. 200000 for Claude, 1000000 for Gemini). */
|
||||
context: number;
|
||||
/** Optional per-request max input tokens. */
|
||||
input?: number;
|
||||
/** Optional max output tokens. */
|
||||
output?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OpenCodeProviderEntry {
|
||||
/** Identifier of the OpenCode runtime package that will speak to OmniRoute. */
|
||||
npm: typeof OMNIROUTE_PROVIDER_NPM;
|
||||
/** Display name in the OpenCode UI. */
|
||||
name: string;
|
||||
/** Options forwarded to `@ai-sdk/openai-compatible`. */
|
||||
options: {
|
||||
baseURL: string;
|
||||
apiKey: string;
|
||||
};
|
||||
/** Model catalog surfaced to OpenCode. */
|
||||
models: Record<string, OpenCodeModelEntry>;
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
function requireNonEmpty(value: unknown, field: string): string {
|
||||
if (typeof value !== "string") {
|
||||
throw new TypeError(`@omniroute/opencode-provider: ${field} must be a string`);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error(`@omniroute/opencode-provider: ${field} is required and cannot be empty`);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise the user-supplied baseURL so the final `options.baseURL` always
|
||||
* ends in exactly one `/v1`. Accepts both `http://host` and `http://host/v1`.
|
||||
*/
|
||||
export function normalizeBaseURL(rawBaseURL: string): string {
|
||||
const trimmed = requireNonEmpty(rawBaseURL, "baseURL");
|
||||
try {
|
||||
new URL(trimmed);
|
||||
} catch {
|
||||
throw new Error(
|
||||
`@omniroute/opencode-provider: baseURL is not a valid URL: ${JSON.stringify(rawBaseURL)}`
|
||||
);
|
||||
}
|
||||
let base = trimmed;
|
||||
let end = base.length;
|
||||
while (end > 0 && base[end - 1] === "/") end--;
|
||||
base = end < base.length ? base.slice(0, end) : base;
|
||||
if (base.endsWith("/v1")) base = base.slice(0, -3);
|
||||
return base + "/v1";
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `provider.omniroute` entry for an OpenCode config document.
|
||||
* The returned object is JSON-serialisable and safe to embed verbatim.
|
||||
*/
|
||||
export function createOmniRouteProvider(options: OmniRouteProviderOptions): OpenCodeProviderEntry {
|
||||
const baseURL = normalizeBaseURL(options.baseURL);
|
||||
const apiKey = requireNonEmpty(options.apiKey, "apiKey");
|
||||
|
||||
const modelList =
|
||||
options.models && options.models.length > 0
|
||||
? [...options.models]
|
||||
: [...OMNIROUTE_DEFAULT_OPENCODE_MODELS];
|
||||
|
||||
const labels = options.modelLabels ?? {};
|
||||
const overrides = options.modelCapabilities ?? {};
|
||||
const models: Record<string, OpenCodeModelEntry> = {};
|
||||
const seen = new Set<string>();
|
||||
for (const raw of modelList) {
|
||||
const id =
|
||||
typeof raw === "object" && raw !== null && "id" in raw && typeof (raw as any).id === "string"
|
||||
? (raw as { id: string }).id.trim()
|
||||
: typeof raw === "string"
|
||||
? raw.trim()
|
||||
: "";
|
||||
if (!id || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
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;
|
||||
|
||||
// Context window: live model entry (from API catalog) > modelContextLengths > static defaults
|
||||
const liveContext =
|
||||
typeof raw === "object" && raw !== null
|
||||
? (raw as { contextLength?: number }).contextLength
|
||||
: undefined;
|
||||
const rawContextLength =
|
||||
liveContext ??
|
||||
options.modelContextLengths?.[id] ??
|
||||
OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];
|
||||
const contextLength =
|
||||
typeof rawContextLength === "string" ? parseInt(rawContextLength, 10) : rawContextLength;
|
||||
if (typeof contextLength === "number" && !isNaN(contextLength) && contextLength > 0) {
|
||||
entry.limit = { context: contextLength };
|
||||
}
|
||||
|
||||
models[id] = entry;
|
||||
}
|
||||
|
||||
return {
|
||||
npm: OMNIROUTE_PROVIDER_NPM,
|
||||
name: options.displayName?.trim() || "OmniRoute",
|
||||
options: { baseURL, apiKey },
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
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<string, unknown>,
|
||||
options: OmniRouteProviderOptions
|
||||
): Record<string, unknown> {
|
||||
const partial = buildOmniRouteOpenCodeConfig(options);
|
||||
|
||||
const merged: Record<string, unknown> = { ...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<string, unknown>)
|
||||
: {};
|
||||
|
||||
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<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, string> = {
|
||||
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<T>(url: string, apiKey: string, timeoutMs: number): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
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) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`@omniroute/opencode-provider: request to ${url} failed: ${message}`);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
/** Context window length in tokens (e.g. 200000 for Claude, 1000000 for Gemini). */
|
||||
contextLength?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, // OmniRouteLiveModel[] — contextLength auto-extracted
|
||||
* modelLabels: Object.fromEntries(models.map((m) => [m.id, m.name])),
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export async function fetchLiveModels(
|
||||
baseURL: string,
|
||||
apiKey: string,
|
||||
timeoutMs = 5_000
|
||||
): Promise<OmniRouteLiveModel[]> {
|
||||
const key = requireNonEmpty(apiKey, "apiKey");
|
||||
const url = `${normalizeBaseURL(baseURL)}/models`;
|
||||
|
||||
const body = await fetchJSON<unknown>(url, key, timeoutMs);
|
||||
|
||||
const rawList: unknown[] = Array.isArray(body)
|
||||
? body
|
||||
: body && typeof body === "object" && 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<string, unknown>;
|
||||
|
||||
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;
|
||||
|
||||
// Extract context_length from OmniRoute's /v1/models response.
|
||||
// OmniRoute returns context_length in snake_case for both synced
|
||||
// models (with inputTokenLimit) and custom models; the catalog's
|
||||
// getDefaultContextFallback also injects it from registry defaults.
|
||||
const contextLength =
|
||||
typeof r.context_length === "number" && r.context_length > 0
|
||||
? r.context_length
|
||||
: typeof r.max_context_window_tokens === "number" && r.max_context_window_tokens > 0
|
||||
? r.max_context_window_tokens
|
||||
: undefined;
|
||||
|
||||
models.push({ id, name: name || id, ...(contextLength ? { contextLength } : {}) });
|
||||
}
|
||||
|
||||
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<string>([
|
||||
"",
|
||||
"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<OmniRouteCombo[]> {
|
||||
const key = requireNonEmpty(managementApiKey, "managementApiKey");
|
||||
const base = normalizeBaseURL(baseURL).replace(/\/v1$/, "");
|
||||
const url = `${base}/api/combos`;
|
||||
|
||||
const body = await fetchJSON<unknown>(url, key, timeoutMs);
|
||||
const rawList: unknown[] = Array.isArray(body)
|
||||
? body
|
||||
: body && typeof body === "object" && 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<string, unknown>;
|
||||
|
||||
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<string, unknown> {
|
||||
const name = requireNonEmpty(options.name, "name");
|
||||
const strategy = requireNonEmpty(options.strategy, "strategy");
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
name,
|
||||
strategy,
|
||||
active: options.active ?? true,
|
||||
};
|
||||
|
||||
if (options.compressionOverride !== undefined) {
|
||||
payload.compressionOverride = options.compressionOverride;
|
||||
}
|
||||
|
||||
if (options.providers !== undefined) {
|
||||
const providers = options.providers.filter((p) => typeof p === "string" && p.trim());
|
||||
if (providers.length > 0) {
|
||||
payload.providers = providers;
|
||||
}
|
||||
}
|
||||
|
||||
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<string, boolean>;
|
||||
/** 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<string, OmniRouteAgentRole>;
|
||||
}
|
||||
|
||||
/** Single entry inside the emitted OpenCode `agent` block. */
|
||||
export interface OpenCodeAgentEntry extends OmniRouteRoleOverrides {
|
||||
/** Always emitted as `"omniroute/<modelId>"`. */
|
||||
model: string;
|
||||
/** Per OpenCode schema, `Record<string, boolean>`. */
|
||||
tools?: Record<string, boolean>;
|
||||
/** 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<string, boolean> = {};
|
||||
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<string, boolean>` 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<string, OpenCodeAgentEntry> {
|
||||
const out: Record<string, OpenCodeAgentEntry> = {};
|
||||
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<string, OmniRouteMode>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, OpenCodeModeEntry> {
|
||||
const out: Record<string, OpenCodeModeEntry> = {};
|
||||
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;
|
||||
@@ -0,0 +1,686 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import type { Server } from "node:http";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import {
|
||||
buildOmniRouteOpenCodeConfig,
|
||||
createOmniRouteAgentBlock,
|
||||
createOmniRouteComboConfig,
|
||||
createOmniRouteMCPEntry,
|
||||
createOmniRouteModesBlock,
|
||||
createOmniRouteProvider,
|
||||
fetchLiveModels,
|
||||
listCombos,
|
||||
mergeIntoExistingConfig,
|
||||
normalizeBaseURL,
|
||||
OMNIROUTE_DEFAULT_MODEL_CAPABILITIES,
|
||||
OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS,
|
||||
OMNIROUTE_DEFAULT_OPENCODE_MODELS,
|
||||
OMNIROUTE_MCP_DEFAULT_SCOPES,
|
||||
OMNIROUTE_PROVIDER_NPM,
|
||||
OPENCODE_CONFIG_SCHEMA,
|
||||
} from "../src/index.ts";
|
||||
|
||||
test("normalizeBaseURL preserves a bare host:port", () => {
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128"), "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("normalizeBaseURL strips trailing slashes", () => {
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128////"), "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("normalizeBaseURL deduplicates an existing /v1 suffix", () => {
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128/v1"), "http://localhost:20128/v1");
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128/v1/"), "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("normalizeBaseURL rejects empty input", () => {
|
||||
assert.throws(() => normalizeBaseURL(" "), /baseURL is required/);
|
||||
});
|
||||
|
||||
test("normalizeBaseURL rejects malformed URLs", () => {
|
||||
assert.throws(() => normalizeBaseURL("not a url"), /not a valid URL/);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider validates required fields", () => {
|
||||
assert.throws(
|
||||
() => createOmniRouteProvider({ baseURL: "", apiKey: "x" } as never),
|
||||
/baseURL is required/
|
||||
);
|
||||
assert.throws(
|
||||
() => createOmniRouteProvider({ baseURL: "http://x", apiKey: "" } as never),
|
||||
/apiKey is required/
|
||||
);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider produces the OpenCode-compatible shape", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
|
||||
assert.equal(provider.npm, OMNIROUTE_PROVIDER_NPM);
|
||||
assert.equal(provider.name, "OmniRoute");
|
||||
assert.equal(provider.options.baseURL, "http://localhost:20128/v1");
|
||||
assert.equal(provider.options.apiKey, "sk_omniroute");
|
||||
assert.equal(typeof provider.models, "object");
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider seeds the default model catalog", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
|
||||
const modelIds = Object.keys(provider.models).sort();
|
||||
const defaultIds = [...OMNIROUTE_DEFAULT_OPENCODE_MODELS].sort();
|
||||
assert.deepEqual(modelIds, defaultIds);
|
||||
for (const id of defaultIds) {
|
||||
assert.equal(provider.models[id]?.name, id);
|
||||
assert.equal(provider.models[id]?.attachment, true);
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider honours a custom models list and labels", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["auto", "claude-opus-4-7"],
|
||||
modelLabels: { auto: "Auto-Combo", "claude-opus-4-7": "Opus 4.7" },
|
||||
});
|
||||
|
||||
assert.deepEqual(Object.keys(provider.models), ["auto", "claude-opus-4-7"]);
|
||||
assert.equal(provider.models.auto.name, "Auto-Combo");
|
||||
assert.equal(provider.models["claude-opus-4-7"].name, "Opus 4.7");
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider deduplicates and trims model ids", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: [" auto ", "auto", "", "claude-opus-4-7"],
|
||||
});
|
||||
assert.deepEqual(Object.keys(provider.models), ["auto", "claude-opus-4-7"]);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider honours displayName override", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
displayName: "Local OmniRoute",
|
||||
});
|
||||
assert.equal(provider.name, "Local OmniRoute");
|
||||
});
|
||||
|
||||
test("buildOmniRouteOpenCodeConfig wraps the provider with the OpenCode schema", () => {
|
||||
const doc = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128/v1",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
|
||||
assert.equal(doc.$schema, OPENCODE_CONFIG_SCHEMA);
|
||||
assert.equal(typeof doc.provider.omniroute, "object");
|
||||
assert.equal(doc.provider.omniroute.options.baseURL, "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("config document is JSON-serialisable", () => {
|
||||
const doc = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
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<string, unknown>));
|
||||
assert.ok("omniroute" in (result.provider as Record<string, unknown>));
|
||||
assert.deepEqual((result as Record<string, unknown>).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<string, unknown>).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.includes("cc/claude-opus-4-8"));
|
||||
assert.ok(
|
||||
defaults.some((m) => m.startsWith("cc/")),
|
||||
"should have cc/ prefixed models"
|
||||
);
|
||||
assert.ok(defaults.length >= 7, "should have at least 7 models");
|
||||
});
|
||||
|
||||
test("OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS covers every default model id", () => {
|
||||
for (const id of OMNIROUTE_DEFAULT_OPENCODE_MODELS) {
|
||||
const ctx = OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];
|
||||
assert.ok(
|
||||
typeof ctx === "number" && ctx > 0,
|
||||
`default context_length for ${id} missing — should be a positive number`
|
||||
);
|
||||
// Sanity: context should be at least 8K, at most 2M tokens
|
||||
assert.ok(ctx >= 8_000, `${id} context_length ${ctx} seems too low`);
|
||||
assert.ok(ctx <= 2_000_000, `${id} context_length ${ctx} seems too high`);
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider emits limit.context on default model entries", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
const entry = provider.models["cc/claude-opus-4-8"];
|
||||
assert.ok(entry.limit, "model entry should have a limit field");
|
||||
assert.equal(entry.limit!.context, 1_000_000);
|
||||
assert.equal(provider.models["cc/claude-opus-4-7"].limit!.context, 1_000_000);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider omits limit.context for unknown model ids", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["completely-unknown-model"],
|
||||
});
|
||||
const entry = provider.models["completely-unknown-model"];
|
||||
assert.equal(entry.limit, undefined);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider reads contextLength from a live model entry for ids absent from the static map", () => {
|
||||
// #3298 regression guard: the static OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS
|
||||
// map only covers the legacy 8 Claude/Gemini ids. Before this change, any
|
||||
// other model got `undefined` context (see the test above, string form) and
|
||||
// OpenCode silently fell back to its 128K internal default. A live model
|
||||
// entry carrying `contextLength` must now surface as `limit.context`.
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: [{ id: "completely-unknown-model", contextLength: 262_144 }],
|
||||
});
|
||||
const entry = provider.models["completely-unknown-model"];
|
||||
assert.ok(entry.limit, "a live contextLength should produce a limit field even for ids absent from the static map");
|
||||
assert.equal(entry.limit!.context, 262_144);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider: a live model contextLength wins over the static default map", () => {
|
||||
// `cc/claude-opus-4-8` has a static default (1_000_000). A live entry carrying
|
||||
// a different contextLength must take precedence (live > modelContextLengths >
|
||||
// static defaults).
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: [{ id: "cc/claude-opus-4-8", contextLength: 524_288 }],
|
||||
});
|
||||
assert.equal(provider.models["cc/claude-opus-4-8"].limit!.context, 524_288);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider serialises limit.context to JSON", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
const round = JSON.parse(JSON.stringify(provider));
|
||||
for (const id of OMNIROUTE_DEFAULT_OPENCODE_MODELS) {
|
||||
const expectedContext = OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];
|
||||
assert.equal(
|
||||
round.models[id].limit?.context,
|
||||
expectedContext,
|
||||
`${id} should serialise limit.context=${expectedContext}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("fetchLiveModels extracts context_length from snake_case field", async () => {
|
||||
const { url, close } = await startMockServer(() => ({
|
||||
data: [
|
||||
{ id: "cc/claude-opus-4-7", name: "Claude Opus 4.7", context_length: 200_000 },
|
||||
{ id: "gemini-3.1-pro-high", name: "Gemini 3.1 Pro", context_length: 1_000_000 },
|
||||
{ id: "no-context", name: "No Context" },
|
||||
],
|
||||
}));
|
||||
try {
|
||||
const models = await fetchLiveModels(url, "sk_test");
|
||||
const claude = models.find((m) => m.id === "cc/claude-opus-4-7");
|
||||
assert.ok(claude, "claude model should be present");
|
||||
assert.equal(claude!.contextLength, 200_000);
|
||||
const gemini = models.find((m) => m.id === "gemini-3.1-pro-high");
|
||||
assert.equal(gemini!.contextLength, 1_000_000);
|
||||
const noCtx = models.find((m) => m.id === "no-context");
|
||||
assert.equal(noCtx!.contextLength, undefined);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
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-8"];
|
||||
assert.equal(entry.name, "cc/claude-opus-4-8");
|
||||
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<string, boolean> 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);
|
||||
});
|
||||
|
||||
// #3419 — soft-deprecation in favour of @omniroute/opencode-plugin. Guard the
|
||||
// deprecation notice so it can't be silently dropped while the package is kept
|
||||
// publishing (it still works; it is just no longer the recommended path).
|
||||
test("package is marked deprecated in favour of @omniroute/opencode-plugin (#3419)", () => {
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
|
||||
assert.match(pkg.description, /DEPRECATED/);
|
||||
assert.match(pkg.description, /@omniroute\/opencode-plugin/);
|
||||
|
||||
const readme = readFileSync(join(here, "..", "README.md"), "utf8");
|
||||
assert.match(readme, /Deprecated/i);
|
||||
assert.match(readme, /@omniroute\/opencode-plugin/);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022"],
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"isolatedModules": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["dist", "node_modules", "tests"]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
dts: true,
|
||||
clean: true,
|
||||
sourcemap: false,
|
||||
splitting: false,
|
||||
treeshake: true,
|
||||
target: "node22",
|
||||
outDir: "dist",
|
||||
minify: false,
|
||||
});
|
||||
|
||||
// CJS consumers should prefer named imports (`require(pkg).createOmniRouteProvider`).
|
||||
// The `default` export is also exposed for ESM ergonomics, which makes tsup warn
|
||||
// about mixed exports — that's expected and harmless for this package.
|
||||
Reference in New Issue
Block a user