@joaogsbarbosa/opencode-9router 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ import { readDiscoveryCache, readStaleDiscoveryCache, writeDiscoveryCache } from "./cache.js";
2
+ import { forceComboConfig, isComboModel, resolveCapabilitiesBatch } from "./capabilities.js";
3
+ import { ensureAPIPath, formatModelName } from "./utils.js";
4
+ /**
5
+ * Build reasoning variants from thinking_levels (9Router bulk) and/or
6
+ * reasoning_options (models.dev catalog / per-model info).
7
+ *
8
+ * Both sources can coexist:
9
+ * - thinking_levels provides effort variants (e.g. none/low/medium/high)
10
+ * - reasoning_options adds effort variants (dedup) and/or toggle variants
11
+ * (none/thinking with body.enable_thinking).
12
+ *
13
+ * Effort from thinking_levels wins a same-ID toggle collision.
14
+ * All values are passed through as-is; no vocabulary filtering is applied.
15
+ */
16
+ function buildReasoningVariants(config) {
17
+ const variants = {};
18
+ // Effort from thinking_levels (9Router bulk /models response)
19
+ if (Array.isArray(config.thinking_levels) && config.thinking_levels.length > 0) {
20
+ for (const level of config.thinking_levels) {
21
+ variants[String(level)] = { reasoningEffort: level };
22
+ }
23
+ }
24
+ // Effort + toggle from reasoning_options (models.dev catalog / per-model info)
25
+ if (Array.isArray(config.reasoning_options) && config.reasoning_options.length > 0) {
26
+ for (const option of config.reasoning_options) {
27
+ if (option.type === "effort") {
28
+ for (const effort of option.values) {
29
+ if (!variants[String(effort)]) {
30
+ variants[String(effort)] = { reasoningEffort: effort };
31
+ }
32
+ }
33
+ }
34
+ else if (option.type === "toggle") {
35
+ if (!variants.none) {
36
+ variants.none = { reasoningEffort: null, body: { enable_thinking: false } };
37
+ }
38
+ if (!variants.thinking) {
39
+ variants.thinking = { reasoningEffort: null, body: { enable_thinking: true } };
40
+ }
41
+ }
42
+ }
43
+ }
44
+ return Object.keys(variants).length > 0 ? variants : undefined;
45
+ }
46
+ /**
47
+ * Discover models from a 9Router-compatible API, enriching each model with
48
+ * capabilities from the models.dev catalog and the per-model API. Results are
49
+ * cached; an expired cache entry is used as fallback when the fetch fails.
50
+ */
51
+ export async function discoverModels(baseURL, apiKey, cacheEnabled, cacheTTL, discoveryTimeout, providerKey, log) {
52
+ // ── Cache hit: return fresh cached models ──
53
+ if (cacheEnabled) {
54
+ const cached = readDiscoveryCache(baseURL, cacheTTL, providerKey);
55
+ if (cached) {
56
+ log("info", `[discovery] Cache HIT for ${baseURL} (${Object.keys(cached).length} models)`);
57
+ return cached;
58
+ }
59
+ }
60
+ log("info", `[discovery] Cache MISS for ${baseURL}, fetching with ${discoveryTimeout}ms timeout`);
61
+ const apiURL = ensureAPIPath(baseURL);
62
+ try {
63
+ const headers = {};
64
+ if (apiKey) {
65
+ headers["Authorization"] = `Bearer ${apiKey}`;
66
+ }
67
+ log("info", `[discovery] Fetching ${apiURL}/models with ${discoveryTimeout}ms timeout`);
68
+ const response = await fetch(`${apiURL}/models`, {
69
+ signal: AbortSignal.timeout(discoveryTimeout),
70
+ headers,
71
+ });
72
+ if (!response.ok) {
73
+ throw new Error(`Fetch not OK: ${response.status} ${response.statusText}`);
74
+ }
75
+ log("info", `[discovery] Fetch OK (${response.status}) for ${baseURL}`);
76
+ const data = (await response.json());
77
+ if (!data.data || !Array.isArray(data.data) || data.data.length === 0) {
78
+ throw new Error(`Empty or invalid response data from ${apiURL}/models`);
79
+ }
80
+ const models = Object.create(null);
81
+ const modelIds = [];
82
+ const comboIds = new Set();
83
+ for (const model of data.data) {
84
+ models[model.id] = { name: formatModelName(model.id) };
85
+ // Preserve the per-model thinking levels advertised by the 9Router
86
+ // /v1/models response (e.g. ["none","low","medium","high"]) so the
87
+ // reasoning-effort variants survive catalog enrichment.
88
+ if (Array.isArray(model.thinking_levels) && model.thinking_levels.length > 0) {
89
+ models[model.id].thinking_levels = model.thinking_levels;
90
+ }
91
+ modelIds.push(model.id);
92
+ if (isComboModel(model.id, model.owned_by)) {
93
+ comboIds.add(model.id);
94
+ }
95
+ }
96
+ // Enrich with capabilities
97
+ const capabilities = await resolveCapabilitiesBatch(modelIds, apiURL, apiKey, comboIds);
98
+ for (const [id, caps] of Object.entries(capabilities)) {
99
+ if (models[id]) {
100
+ Object.assign(models[id], caps);
101
+ }
102
+ }
103
+ // Generate reasoning variants from thinking_levels (9Router bulk) and/or
104
+ // reasoning_options (models.dev catalog / per-model info). Both sources can
105
+ // coexist: thinking_levels provides effort variants, reasoning_options adds
106
+ // effort (dedup) and/or toggle (enable_thinking) variants.
107
+ for (const config of Object.values(models)) {
108
+ if (!config.variants) {
109
+ config.variants = buildReasoningVariants(config);
110
+ }
111
+ }
112
+ // Default: tool_call is true for API-discovered models
113
+ for (const config of Object.values(models)) {
114
+ config.tool_call = config.tool_call ?? true;
115
+ }
116
+ // Combos with no real capability info get forced multimodal defaults.
117
+ for (const id of comboIds) {
118
+ const config = models[id];
119
+ if (config && !capabilities[id]) {
120
+ Object.assign(config, forceComboConfig());
121
+ }
122
+ }
123
+ // ── Cache write on success ──
124
+ if (cacheEnabled) {
125
+ writeDiscoveryCache(baseURL, models, providerKey);
126
+ log("info", `[discovery] Cached ${Object.keys(models).length} models for ${baseURL}`);
127
+ }
128
+ return models;
129
+ }
130
+ catch (err) {
131
+ const msg = err instanceof Error ? err.message : String(err);
132
+ await log("warn", `[discovery] Fetch threw for ${apiURL}/models: ${msg}`);
133
+ // ── Stale cache fallback: return expired cache if fetch failed ──
134
+ log("info", `[discovery] Fetch failed for ${baseURL}, trying stale cache fallback`);
135
+ if (cacheEnabled) {
136
+ const stale = readStaleDiscoveryCache(baseURL, providerKey);
137
+ if (stale) {
138
+ log("info", `[discovery] Stale cache fallback for ${baseURL} (${Object.keys(stale).length} models)`);
139
+ return stale;
140
+ }
141
+ log("info", `[discovery] No stale cache for ${baseURL}, returning null`);
142
+ }
143
+ return null;
144
+ }
145
+ }
@@ -0,0 +1,9 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+ import { NineRouterPlugin } from "./plugin.js";
3
+ declare const _default: {
4
+ id: string;
5
+ setup: (context: Plugin.Context) => Promise<Plugin.Cleanup | void> | Plugin.Cleanup | void;
6
+ server: import("@opencode-ai/plugin").Plugin;
7
+ };
8
+ export default _default;
9
+ export { NineRouterPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+ import { NineRouterPlugin } from "./plugin.js";
3
+ import { nineRouterV2 } from "./v2.js";
4
+ // ── Dual V1 + V2 Package Entry ──────────────────────────────
5
+ /**
6
+ * Combined plugin export. OpenCode V2 reads the `setup`/`id` fields produced by
7
+ * `Plugin.define`; OpenCode V1 (1.18.29+) reads the `server` field. Both
8
+ * implementations share the same discovery core.
9
+ *
10
+ * `nineRouterV2` is passed through `Plugin.define` for validation, but the
11
+ * default export is written as an explicit object literal so the emitted
12
+ * declaration is stable and clearly includes `id`, `setup`, and `server`.
13
+ */
14
+ const v2 = Plugin.define(nineRouterV2);
15
+ export default {
16
+ id: v2.id,
17
+ setup: v2.setup,
18
+ server: NineRouterPlugin,
19
+ };
20
+ // Named export retained for V1 consumers that import it directly.
21
+ export { NineRouterPlugin };
@@ -0,0 +1,7 @@
1
+ import type { Plugin } from "@opencode-ai/plugin";
2
+ /**
3
+ * OpenCode plugin provider for 9Router. Registers a "9router" provider and,
4
+ * in the config hook, auto-discovers models (enriched with capabilities and
5
+ * token limits) for every configured 9router-family provider.
6
+ */
7
+ export declare const NineRouterPlugin: Plugin;
package/dist/plugin.js ADDED
@@ -0,0 +1,85 @@
1
+ import { DEFAULT_BASE_URL, DISCOVERY_CACHE_TTL, DISCOVERY_TIMEOUT, PLUGIN_NAME, PROVIDER_DISPLAY_NAME, } from "./constants.js";
2
+ import { discoverModels } from "./discovery.js";
3
+ import { ensureAPIPath, normalizeBaseURL } from "./utils.js";
4
+ // ── Plugin Entry ────────────────────────────────────────────
5
+ /**
6
+ * OpenCode plugin provider for 9Router. Registers a "9router" provider and,
7
+ * in the config hook, auto-discovers models (enriched with capabilities and
8
+ * token limits) for every configured 9router-family provider.
9
+ */
10
+ export const NineRouterPlugin = async ({ client }) => {
11
+ const log = async (level, message) => {
12
+ try {
13
+ await client.app.log({
14
+ body: {
15
+ service: "9router-provider",
16
+ level,
17
+ message,
18
+ },
19
+ });
20
+ }
21
+ catch {
22
+ // Logging is best-effort
23
+ }
24
+ };
25
+ return {
26
+ config: async (config) => {
27
+ config.provider ??= {};
28
+ const provider = config.provider;
29
+ // Collect all existing providers whose key starts with "9router"
30
+ const providerKeys = Object.keys(provider).filter((k) => k.startsWith("9router"));
31
+ // Backward compat: if no 9router-family providers exist, register the default one
32
+ if (providerKeys.length === 0) {
33
+ config.provider[PLUGIN_NAME] = {
34
+ npm: "@ai-sdk/openai-compatible",
35
+ name: PROVIDER_DISPLAY_NAME,
36
+ options: {
37
+ baseURL: DEFAULT_BASE_URL,
38
+ },
39
+ models: {},
40
+ };
41
+ providerKeys.push(PLUGIN_NAME);
42
+ }
43
+ // Process each 9router-family provider independently
44
+ const results = await Promise.allSettled(providerKeys.map(async (key) => {
45
+ const existing = provider[key];
46
+ const options = existing?.options;
47
+ const baseURL = options?.baseURL ?? DEFAULT_BASE_URL;
48
+ const apiKey = options?.apiKey;
49
+ const normalizedURL = normalizeBaseURL(baseURL);
50
+ const apiURL = ensureAPIPath(normalizedURL);
51
+ // Per-provider cache configuration
52
+ const cacheEnabled = options?.cache ?? true;
53
+ const cacheTTL = options?.cacheTTL ?? DISCOVERY_CACHE_TTL;
54
+ const discoveryTimeout = options?.discoveryTimeout ?? DISCOVERY_TIMEOUT;
55
+ const discovered = await discoverModels(normalizedURL, apiKey, cacheEnabled, cacheTTL, discoveryTimeout, key, log);
56
+ const entry = provider[key];
57
+ entry.npm ??= "@ai-sdk/openai-compatible";
58
+ entry.name ??= key;
59
+ entry.api = apiURL;
60
+ entry.options = { ...entry.options, baseURL: apiURL };
61
+ // Catalog controls are V2 overlays, not legacy model configuration keys.
62
+ entry.models = Object.fromEntries(Object.entries(discovered ?? {}).map(([id, model]) => {
63
+ const { reasoning_options, ...legacy } = model;
64
+ return [id, legacy];
65
+ }));
66
+ return { key, discovered, apiURL };
67
+ }));
68
+ // Log results
69
+ for (const result of results) {
70
+ if (result.status === "fulfilled") {
71
+ const { key, discovered, apiURL } = result.value;
72
+ if (discovered) {
73
+ await log("info", `[${key}] Discovered ${Object.keys(discovered).length} models from ${apiURL}`);
74
+ }
75
+ else {
76
+ await log("warn", `[${key}] Failed to discover models from ${apiURL}. Check if the service is running and accessible.`);
77
+ }
78
+ }
79
+ else {
80
+ await log("error", `Provider pipeline error: ${result.reason}`);
81
+ }
82
+ }
83
+ },
84
+ };
85
+ };
@@ -0,0 +1,15 @@
1
+ import type { ModelsDevEntry, ReasoningOption } from "./types.js";
2
+ /**
3
+ * 9Router provider ID prefixes → models.dev provider identities.
4
+ * Identity translation only; not capability presets.
5
+ * Subset of 9Router's PROVIDER_ALIASES at pinned commit 89ffac5a2c8108449c432afd1ad6531578fa81cd.
6
+ * Unlisted provider IDs are matched unchanged.
7
+ */
8
+ export declare const CATALOG_PROVIDERS: Record<string, string>;
9
+ /**
10
+ * Find reasoning options for a model ID from the models.dev catalog.
11
+ * Requires EXACT provider + full model ID match (after prefix translation).
12
+ * Returns undefined for ambiguous, unmatched, or non-reasoning entries.
13
+ * All values are passed through as-is; no vocabulary filtering is applied.
14
+ */
15
+ export declare function findReasoningOptions(modelId: string, catalog: ModelsDevEntry[]): ReasoningOption[] | undefined;
@@ -0,0 +1,58 @@
1
+ // ── Reasoning Controls from models.dev Catalog ───────────────
2
+ /**
3
+ * 9Router provider ID prefixes → models.dev provider identities.
4
+ * Identity translation only; not capability presets.
5
+ * Subset of 9Router's PROVIDER_ALIASES at pinned commit 89ffac5a2c8108449c432afd1ad6531578fa81cd.
6
+ * Unlisted provider IDs are matched unchanged.
7
+ */
8
+ export const CATALOG_PROVIDERS = {
9
+ glm: "zai",
10
+ "glm-cn": "zhipuai",
11
+ zhipu: "zhipuai",
12
+ gemini: "google",
13
+ kimi: "moonshotai",
14
+ "kimi-cn": "moonshotai-cn",
15
+ qwen: "alibaba",
16
+ "qwen-cn": "alibaba-cn",
17
+ github: "github-copilot",
18
+ gh: "github-copilot",
19
+ claude: "anthropic",
20
+ doubao: "volcengine",
21
+ "cloudflare-ai": "cloudflare-workers-ai",
22
+ };
23
+ /**
24
+ * Find reasoning options for a model ID from the models.dev catalog.
25
+ * Requires EXACT provider + full model ID match (after prefix translation).
26
+ * Returns undefined for ambiguous, unmatched, or non-reasoning entries.
27
+ * All values are passed through as-is; no vocabulary filtering is applied.
28
+ */
29
+ export function findReasoningOptions(modelId, catalog) {
30
+ const slash = modelId.indexOf("/");
31
+ if (slash < 1)
32
+ return undefined;
33
+ const route = modelId.slice(0, slash);
34
+ const provider = CATALOG_PROVIDERS[route] ?? route;
35
+ const id = modelId.slice(slash + 1);
36
+ // Exact match: single entry with matching catalogProvider and id, reasoning=true
37
+ const matches = catalog.filter((entry) => entry.catalogProvider === provider && entry.id === id && entry.reasoning === true);
38
+ if (matches.length !== 1)
39
+ return undefined;
40
+ const raw = matches[0].reasoning_options;
41
+ if (!Array.isArray(raw))
42
+ return undefined;
43
+ const options = [];
44
+ for (const option of raw) {
45
+ if (!option || typeof option !== "object")
46
+ continue;
47
+ if (option.type === "effort" && Array.isArray(option.values)) {
48
+ // Deduplicate values; all strings pass through
49
+ const values = [...new Set(option.values.filter((v) => typeof v === "string"))];
50
+ if (values.length)
51
+ options.push({ type: "effort", values });
52
+ }
53
+ else if (option.type === "toggle") {
54
+ options.push({ type: "toggle" });
55
+ }
56
+ }
57
+ return options.length ? options : undefined;
58
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Optional token limit values carried by 9Router responses and the models.dev
3
+ * catalog. Number and string forms are both possible (values arrive via JSON).
4
+ */
5
+ export type TokenLimitValue = number | string;
6
+ /**
7
+ * Validated reasoning controls from models.dev catalog.
8
+ * - effort: discrete reasoningEffort values (subset of OpenCode vocabulary)
9
+ * - toggle: boolean enable_thinking switch (9Router-specific body field)
10
+ */
11
+ export type ReasoningOption = {
12
+ type: "effort";
13
+ values: string[];
14
+ } | {
15
+ type: "toggle";
16
+ };
17
+ /**
18
+ * Token limits OpenCode receives per model. OpenCode computes the context-usage
19
+ * percentage shown in the UI from `context`; without it, usage always shows 0%.
20
+ * Both fields are optional because a provider may only report one of them.
21
+ */
22
+ export type ModelLimits = {
23
+ context?: number;
24
+ output?: number;
25
+ };
26
+ /** OpenCode model config fragment generated per discovered model. */
27
+ export type ModelConfig = {
28
+ name: string;
29
+ attachment?: boolean;
30
+ reasoning?: boolean;
31
+ temperature?: boolean;
32
+ tool_call?: boolean;
33
+ modalities?: {
34
+ input: Array<"text" | "audio" | "image" | "video" | "pdf">;
35
+ output: Array<"text" | "audio" | "image" | "video" | "pdf">;
36
+ };
37
+ interleaved?: true | {
38
+ field: "reasoning" | "reasoning_content" | "reasoning_details";
39
+ };
40
+ limit?: ModelLimits;
41
+ variants?: Record<string, Record<string, unknown>>;
42
+ /** Thinking levels advertised by 9Router, e.g. ["none","low","medium","high"]. */
43
+ thinking_levels?: string[];
44
+ /** Validated catalog controls; lowered to V2 overlays, never provider settings. */
45
+ reasoning_options?: ReasoningOption[];
46
+ search?: boolean;
47
+ context_length?: number;
48
+ max_completion_tokens?: number;
49
+ };
50
+ /**
51
+ * Model metadata returned by the 9Router `/models/info` endpoint. Capability
52
+ * flags live under `capabilities`; token limits appear both nested there and
53
+ * as top-level `context_length` / `max_completion_tokens` on bulk responses.
54
+ */
55
+ export interface RouterModelInfo {
56
+ id: string;
57
+ capabilities?: {
58
+ vision?: boolean;
59
+ audioInput?: boolean;
60
+ tools?: boolean;
61
+ reasoning?: boolean;
62
+ search?: boolean;
63
+ contextWindow?: TokenLimitValue;
64
+ maxOutput?: TokenLimitValue;
65
+ thinking_levels?: string[];
66
+ /** Raw reasoning options from 9Router per-model endpoint (if provided). */
67
+ reasoning_options?: unknown;
68
+ };
69
+ context_length?: TokenLimitValue;
70
+ max_completion_tokens?: TokenLimitValue;
71
+ /** Thinking levels advertised by 9Router for reasoning-capable models. */
72
+ thinking_levels?: string[];
73
+ /** Provider identity from models.dev catalog for exact matching. */
74
+ catalogProvider?: string;
75
+ /** Raw reasoning options from 9Router per-model endpoint (top-level fallback). */
76
+ reasoning_options?: unknown;
77
+ }
78
+ /**
79
+ * Single entry of the models.dev capability catalog. Shape mirrors a subset
80
+ * of RouterModelInfo plus catalog-specific fields (`attachment`, modalities).
81
+ */
82
+ export interface ModelsDevEntry {
83
+ id: string;
84
+ attachment?: boolean;
85
+ reasoning?: boolean;
86
+ tool_call?: boolean;
87
+ capabilities?: RouterModelInfo["capabilities"];
88
+ modalities?: {
89
+ input?: string[];
90
+ output?: string[];
91
+ };
92
+ limit?: ModelLimits;
93
+ /** Validated reasoning controls from catalog (effort values and/or toggle). */
94
+ reasoning_options?: ReasoningOption[];
95
+ /** Provider identity as stored in models.dev (e.g., "openrouter", "zai", "google"). */
96
+ catalogProvider?: string;
97
+ [key: string]: unknown;
98
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ // ── Shared Types ───────────────────────────────────────────
2
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { TokenLimitValue } from "./types.js";
2
+ /**
3
+ * Format a model ID for display, replacing a known provider prefix with its
4
+ * human-readable name (e.g. "cc/the model" → "the model ([CC])").
5
+ */
6
+ export declare function formatModelName(modelId: string): string;
7
+ /**
8
+ * Sanitize a string to contain only safe filename characters.
9
+ * Replaces any character that is NOT alphanumeric, dash, underscore, or dot with an underscore.
10
+ */
11
+ export declare function safeFilename(input: string): string;
12
+ /** Strip trailing slashes from a base URL. */
13
+ export declare function normalizeBaseURL(url: string): string;
14
+ /** Append the default API path to a base URL when it is not already present. */
15
+ export declare function ensureAPIPath(baseURL: string): string;
16
+ /**
17
+ * Coerce a token-limit value into a positive finite integer, or undefined when
18
+ * the value is absent or not a valid positive integer (0, negative, NaN,
19
+ * Infinity, float, or a non-numeric string are all rejected).
20
+ */
21
+ export declare function toPositiveInt(value: TokenLimitValue | undefined): number | undefined;
package/dist/utils.js ADDED
@@ -0,0 +1,38 @@
1
+ import { DEFAULT_API_PATH, KNOWN_PROVIDER_PREFIXES } from "./constants.js";
2
+ // ── Utility Functions ──────────────────────────────────────
3
+ /**
4
+ * Format a model ID for display, replacing a known provider prefix with its
5
+ * human-readable name (e.g. "cc/the model" → "the model ([CC])").
6
+ */
7
+ export function formatModelName(modelId) {
8
+ for (const [prefix, provider] of Object.entries(KNOWN_PROVIDER_PREFIXES)) {
9
+ if (modelId.startsWith(prefix)) {
10
+ return `${modelId.slice(prefix.length)} (${provider})`;
11
+ }
12
+ }
13
+ return modelId;
14
+ }
15
+ /**
16
+ * Sanitize a string to contain only safe filename characters.
17
+ * Replaces any character that is NOT alphanumeric, dash, underscore, or dot with an underscore.
18
+ */
19
+ export function safeFilename(input) {
20
+ return input.replace(/[^a-zA-Z0-9._-]/g, "_");
21
+ }
22
+ /** Strip trailing slashes from a base URL. */
23
+ export function normalizeBaseURL(url) {
24
+ return url.replace(/\/+$/, "");
25
+ }
26
+ /** Append the default API path to a base URL when it is not already present. */
27
+ export function ensureAPIPath(baseURL) {
28
+ return baseURL.endsWith(DEFAULT_API_PATH) ? baseURL : `${baseURL}${DEFAULT_API_PATH}`;
29
+ }
30
+ /**
31
+ * Coerce a token-limit value into a positive finite integer, or undefined when
32
+ * the value is absent or not a valid positive integer (0, negative, NaN,
33
+ * Infinity, float, or a non-numeric string are all rejected).
34
+ */
35
+ export function toPositiveInt(value) {
36
+ const num = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
37
+ return Number.isSafeInteger(num) && num > 0 ? num : undefined;
38
+ }
@@ -0,0 +1,19 @@
1
+ import { Model } from "@opencode/plugin";
2
+ import type { ModelConfig } from "./types.js";
3
+ /** Fallback context window when a discovered model reports no limit. */
4
+ export declare const DEFAULT_CONTEXT_LIMIT = 200000;
5
+ /** Fallback max output tokens when a discovered model reports no limit. */
6
+ export declare const DEFAULT_OUTPUT_LIMIT = 32000;
7
+ /**
8
+ * Map a single discovered V1 `ModelConfig` fragment onto a V2 `Model.Info`,
9
+ * based on `Model.Info.default(providerID, modelID)` and overriding the fields
10
+ * 9Router discovery enriches. V2 requires both `limit.context` and
11
+ * `limit.output` as numbers, so fallbacks are applied when discovery omitted
12
+ * them.
13
+ */
14
+ export declare function toModelInfo(providerID: string, modelID: string, config: ModelConfig): Model.Info;
15
+ /**
16
+ * Map a full discovery result (`Record<string, ModelConfig>`) onto a list of V2
17
+ * `Model.Info` values, preserving key order.
18
+ */
19
+ export declare function toModelInfos(providerID: string, models: Record<string, ModelConfig>): Model.Info[];
package/dist/v2-map.js ADDED
@@ -0,0 +1,104 @@
1
+ import { Model, Provider } from "@opencode/plugin";
2
+ // ── V1 ModelConfig → V2 Model.Info Mapping ──────────────────
3
+ /** Fallback context window when a discovered model reports no limit. */
4
+ export const DEFAULT_CONTEXT_LIMIT = 200000;
5
+ /** Fallback max output tokens when a discovered model reports no limit. */
6
+ export const DEFAULT_OUTPUT_LIMIT = 32000;
7
+ /**
8
+ * Build the V2 capability input modality list from a V1 config. `text` is
9
+ * always present (V2 requires it); `attachment` implies image input; any
10
+ * explicit modalities from discovery are carried through verbatim.
11
+ */
12
+ function mapInputModalities(config) {
13
+ const modalities = new Set(config.modalities?.input ?? []);
14
+ modalities.add("text");
15
+ if (config.attachment) {
16
+ modalities.add("image");
17
+ }
18
+ return Array.from(modalities);
19
+ }
20
+ /**
21
+ * Build the V2 capability output modality list from a V1 config. Defaults to
22
+ * `["text"]` and guarantees `text` is present.
23
+ */
24
+ function mapOutputModalities(config) {
25
+ const modalities = new Set(config.modalities?.output ?? []);
26
+ modalities.add("text");
27
+ return Array.from(modalities);
28
+ }
29
+ /**
30
+ * Map the V1 `variants` record (`{ low: { reasoningEffort: "low" } }`) into the
31
+ * V2 array shape (`[{ id, settings }]`). Explicit variants win over catalog controls.
32
+ */
33
+ function mapVariants(config) {
34
+ // 1. Explicit config.variants (from discovery or user config) — highest priority
35
+ if (config.variants !== undefined) {
36
+ return Object.entries(config.variants).map(([id, settings]) => ({
37
+ id: Model.VariantID.make(id),
38
+ settings: settings,
39
+ }));
40
+ }
41
+ // 2. reasoning_options from catalog (effort + toggle) — fallback
42
+ const variants = new Map();
43
+ for (const option of config.reasoning_options ?? []) {
44
+ if (option.type === "effort") {
45
+ for (const effort of option.values) {
46
+ variants.set(String(effort), {
47
+ id: Model.VariantID.make(String(effort)),
48
+ settings: { reasoningEffort: effort },
49
+ });
50
+ }
51
+ }
52
+ else if (option.type === "toggle") {
53
+ // Toggle variants: clear inherited effort so 9Router honors the toggle
54
+ for (const [id, enabled] of [
55
+ ["none", false],
56
+ ["thinking", true],
57
+ ]) {
58
+ if (!variants.has(id)) {
59
+ variants.set(id, {
60
+ id: Model.VariantID.make(id),
61
+ settings: { reasoningEffort: null },
62
+ body: { enable_thinking: enabled },
63
+ });
64
+ }
65
+ }
66
+ }
67
+ }
68
+ // Effort advertised wins a same-ID toggle collision (in either catalog order)
69
+ return [...variants.values()];
70
+ }
71
+ /**
72
+ * Map a single discovered V1 `ModelConfig` fragment onto a V2 `Model.Info`,
73
+ * based on `Model.Info.default(providerID, modelID)` and overriding the fields
74
+ * 9Router discovery enriches. V2 requires both `limit.context` and
75
+ * `limit.output` as numbers, so fallbacks are applied when discovery omitted
76
+ * them.
77
+ */
78
+ export function toModelInfo(providerID, modelID, config) {
79
+ const base = Model.Info.default(Provider.ID.make(providerID), Model.ID.make(modelID));
80
+ const info = {
81
+ ...base,
82
+ name: config.name,
83
+ capabilities: {
84
+ tools: config.tool_call ?? true,
85
+ input: mapInputModalities(config),
86
+ output: mapOutputModalities(config),
87
+ },
88
+ limit: {
89
+ context: config.limit?.context ?? DEFAULT_CONTEXT_LIMIT,
90
+ output: config.limit?.output ?? DEFAULT_OUTPUT_LIMIT,
91
+ },
92
+ variants: mapVariants(config),
93
+ enabled: true,
94
+ status: "active",
95
+ };
96
+ return info;
97
+ }
98
+ /**
99
+ * Map a full discovery result (`Record<string, ModelConfig>`) onto a list of V2
100
+ * `Model.Info` values, preserving key order.
101
+ */
102
+ export function toModelInfos(providerID, models) {
103
+ return Object.entries(models).map(([id, config]) => toModelInfo(providerID, id, config));
104
+ }
package/dist/v2.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+ /** Runtime package used for OpenAI-compatible providers in OpenCode V2. */
3
+ export declare const OPENAI_COMPATIBLE_PACKAGE = "@opencode/ai/providers/openai-compatible";
4
+ /** How often captured discovery data is refreshed and replayed. */
5
+ export declare const REFRESH_INTERVAL: number;
6
+ /** Bounded retries for config providers registered after external plugin setup. */
7
+ export declare const CONFIG_PROVIDER_RETRY_DELAYS: readonly [0, 100, 500, 1500, 5000];
8
+ /** Delay before retrying a refresh whose provider publication failed. */
9
+ export declare const REFRESH_RETRY_DELAY = 1000;
10
+ /** Consecutive publication retries allowed before waiting for an external trigger. */
11
+ export declare const MAX_REFRESH_RETRIES = 1;
12
+ /**
13
+ * OpenCode V2 plugin for 9Router. Discovers models for every 9router-family
14
+ * provider, injects them through provider and model transforms, and refreshes
15
+ * captured inventories as config providers and model lists change.
16
+ */
17
+ export declare const nineRouterV2: Plugin.Plugin;