@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.
package/dist/cache.js ADDED
@@ -0,0 +1,168 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir, tmpdir } from "node:os";
3
+ import { DISCOVERY_CACHE_VERSION, MODELS_DEV_CACHE_TTL, MODELS_DEV_URL } from "./constants.js";
4
+ import { safeFilename } from "./utils.js";
5
+ // ── Discovery Cache ─────────────────────────────────────────
6
+ /**
7
+ * Directory used for all 9router cache files.
8
+ */
9
+ function cacheDir() {
10
+ try {
11
+ if (process.env.XDG_CACHE_HOME) {
12
+ return `${process.env.XDG_CACHE_HOME}/opencode-9router`;
13
+ }
14
+ const home = homedir();
15
+ if (home) {
16
+ return `${home}/.cache/opencode-9router`;
17
+ }
18
+ }
19
+ catch {
20
+ // Fall through to tmpdir
21
+ }
22
+ return `${tmpdir()}/opencode-9router`;
23
+ }
24
+ /**
25
+ * Unique, filesystem-safe cache key for a given baseURL.
26
+ */
27
+ function discoveryCacheKey(baseURL) {
28
+ return Buffer.from(baseURL).toString("base64url");
29
+ }
30
+ /**
31
+ * Cache file path for a provider's discovery result, prefixed with the
32
+ * provider key so cache files are human-identifiable.
33
+ */
34
+ function discoveryCacheFile(baseURL, providerKey) {
35
+ return `${cacheDir()}/discovery-${safeFilename(providerKey)}-${discoveryCacheKey(baseURL)}.json`;
36
+ }
37
+ /**
38
+ * Read a valid (fresh) discovery cache entry.
39
+ * Returns `null` if missing, stale, or corrupted.
40
+ */
41
+ export function readDiscoveryCache(baseURL, ttl, providerKey) {
42
+ const cacheFile = discoveryCacheFile(baseURL, providerKey);
43
+ try {
44
+ if (existsSync(cacheFile)) {
45
+ const stat = statSync(cacheFile);
46
+ if (Date.now() - stat.mtimeMs < ttl) {
47
+ return parseDiscoveryCache(readFileSync(cacheFile, "utf-8"));
48
+ }
49
+ }
50
+ }
51
+ catch {
52
+ // Corrupted or unreadable — ignore
53
+ }
54
+ return null;
55
+ }
56
+ /**
57
+ * Parse a discovery cache file, accepting only entries written by the current
58
+ * DISCOVERY_CACHE_VERSION. Legacy (bare, unversioned) or future entries are
59
+ * treated as a miss so the model list is refetched with current logic.
60
+ */
61
+ function parseDiscoveryCache(raw) {
62
+ const parsed = JSON.parse(raw);
63
+ const envelope = parsed;
64
+ if (envelope &&
65
+ typeof envelope === "object" &&
66
+ envelope.v === DISCOVERY_CACHE_VERSION &&
67
+ envelope.models &&
68
+ typeof envelope.models === "object") {
69
+ return envelope.models;
70
+ }
71
+ return null;
72
+ }
73
+ /**
74
+ * Read a stale (expired) discovery cache entry as fallback.
75
+ */
76
+ export function readStaleDiscoveryCache(baseURL, providerKey) {
77
+ const cacheFile = discoveryCacheFile(baseURL, providerKey);
78
+ try {
79
+ if (existsSync(cacheFile)) {
80
+ return parseDiscoveryCache(readFileSync(cacheFile, "utf-8"));
81
+ }
82
+ }
83
+ catch {
84
+ // Corrupted or unreadable — ignore
85
+ }
86
+ return null;
87
+ }
88
+ /**
89
+ * Persist discovery results to cache (best-effort).
90
+ */
91
+ export function writeDiscoveryCache(baseURL, models, providerKey) {
92
+ const cacheFile = discoveryCacheFile(baseURL, providerKey);
93
+ try {
94
+ mkdirSync(cacheDir(), { recursive: true });
95
+ const envelope = { v: DISCOVERY_CACHE_VERSION, models };
96
+ writeFileSync(cacheFile, JSON.stringify(envelope), "utf-8");
97
+ }
98
+ catch {
99
+ // Cache write is best-effort
100
+ }
101
+ }
102
+ // ── Models.dev Catalog Cache ────────────────────────────────
103
+ /**
104
+ * Fetch the models.dev capability catalog, cached for MODELS_DEV_CACHE_TTL.
105
+ * Returns the flattened entry list, or `null` when the catalog is unreachable
106
+ * and no fresh cache exists.
107
+ */
108
+ export async function fetchModelsDevCatalog() {
109
+ const cacheDirPath = cacheDir();
110
+ const cacheFile = `${cacheDirPath}/models-dev.json`;
111
+ const url = process.env.OPENCODE_MODELS_URL || MODELS_DEV_URL;
112
+ // Try cache — raw API response cached as-is, flattened on read
113
+ try {
114
+ if (existsSync(cacheFile)) {
115
+ const stat = statSync(cacheFile);
116
+ if (Date.now() - stat.mtimeMs < MODELS_DEV_CACHE_TTL) {
117
+ const content = readFileSync(cacheFile, "utf-8");
118
+ const parsed = JSON.parse(content);
119
+ // Old (pre-v0.7.7) caches stored a flat array — treat as miss
120
+ if (!Array.isArray(parsed)) {
121
+ return flattenModelsDevCatalog(parsed);
122
+ }
123
+ // Fall through to re-fetch if array (old format)
124
+ }
125
+ }
126
+ }
127
+ catch {
128
+ // Cache miss or invalid — continue to fetch
129
+ }
130
+ try {
131
+ const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
132
+ if (!response.ok)
133
+ return null;
134
+ const raw = await response.json();
135
+ const flattened = flattenModelsDevCatalog(raw);
136
+ // Best-effort cache write: store raw dict, not flattened array
137
+ try {
138
+ mkdirSync(cacheDirPath, { recursive: true });
139
+ writeFileSync(cacheFile, JSON.stringify(raw), "utf-8");
140
+ }
141
+ catch {
142
+ // Cache write is optional
143
+ }
144
+ return flattened;
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ }
150
+ /**
151
+ * models.dev/api.json returns a dict of providers, each with a nested
152
+ * models dict. Flatten into a list of entries preserving catalogProvider
153
+ * for exact matching in reasoning control lookup.
154
+ */
155
+ export function flattenModelsDevCatalog(raw) {
156
+ const result = [];
157
+ for (const [catalogProvider, provider] of Object.entries(raw)) {
158
+ if (!provider?.models)
159
+ continue;
160
+ for (const entry of Object.values(provider.models)) {
161
+ if (entry?.id) {
162
+ // Preserve provider identity for exact matching; avoid mutating cached input
163
+ result.push({ ...entry, catalogProvider });
164
+ }
165
+ }
166
+ }
167
+ return result;
168
+ }
@@ -0,0 +1,50 @@
1
+ import type { ModelConfig, ModelsDevEntry, RouterModelInfo } from "./types.js";
2
+ /**
3
+ * Detect whether a model is a 9Router virtual combo. The authoritative signal
4
+ * is `owned_by === "combo"`; when `owned_by` is absent (legacy responses) fall
5
+ * back to the prefix heuristic where combo IDs carry no provider prefix.
6
+ */
7
+ export declare function isComboModel(modelId: string, ownedBy?: string): boolean;
8
+ /**
9
+ * Capability fragment forced onto combo models that resolved no information
10
+ * from the models.dev catalog or the per-model API. Assumes multimodal input
11
+ * (text/image/audio), tool calling, and reasoning, and exposes thinking-level
12
+ * variants explicitly so they survive OpenCode's id-based exclusions.
13
+ */
14
+ export declare function forceComboConfig(): Partial<ModelConfig>;
15
+ /**
16
+ * Map 9Router model info into an OpenCode model config fragment.
17
+ * Only present capabilities are copied; limit fields are validated as
18
+ * positive integers and emitted only as a complete context+output pair,
19
+ * which OpenCode's config schema requires.
20
+ */
21
+ export declare function mapRouterCapabilities(info: RouterModelInfo): Partial<ModelConfig>;
22
+ /**
23
+ * Find the best models.dev catalog entry for a model ID, matching by suffix
24
+ * (preferred) or substring after stripping known provider prefixes.
25
+ * Returns null when nothing matches.
26
+ */
27
+ export declare function findModelsDevMatch(modelId: string, catalog: ModelsDevEntry[]): RouterModelInfo | null;
28
+ /**
29
+ * Find a models.dev catalog entry whose final path segment exactly equals the
30
+ * normalized model ID. Stricter than {@link findModelsDevMatch}: a loose
31
+ * substring hit (e.g. `vision` → `gpt-4-turbo-vision`) is rejected, so combo
32
+ * models are only treated as enriched when the catalog truly knows them.
33
+ */
34
+ export declare function findModelsDevMatchExact(modelId: string, catalog: ModelsDevEntry[]): RouterModelInfo | null;
35
+ /**
36
+ * Whether a `/models/info` response carries a meaningful capability signal.
37
+ * A bare `tools: true` (the default stub returned by some 9Router backends) is
38
+ * NOT a signal; vision, reasoning, audio input, or a positive token limit are.
39
+ */
40
+ export declare function isRealRouterSignal(info: RouterModelInfo): boolean;
41
+ /**
42
+ * Resolve capabilities for a batch of model IDs using the models.dev catalog
43
+ * first, then falling back to per-model API queries within a time budget.
44
+ *
45
+ * Combo IDs (see {@link isComboModel}) are held to a stricter bar: they only
46
+ * count as resolved on an exact models.dev match or a meaningful API signal,
47
+ * so backends that return a capability stub for combos do not suppress the
48
+ * forced multimodal defaults.
49
+ */
50
+ export declare function resolveCapabilitiesBatch(modelIds: string[], apiURL: string, apiKey?: string, comboIds?: ReadonlySet<string>): Promise<Record<string, Partial<ModelConfig>>>;
@@ -0,0 +1,300 @@
1
+ import { COMBO_CONTEXT_WINDOW, COMBO_MAX_OUTPUT, COMBO_OWNER, COMBO_REASONING_EFFORTS, KNOWN_PROVIDER_PREFIXES, MAX_CONCURRENT_INFO, MODEL_INFO_TIMEOUT, } from "./constants.js";
2
+ import { fetchModelsDevCatalog } from "./cache.js";
3
+ import { findReasoningOptions } from "./reasoning.js";
4
+ import { toPositiveInt } from "./utils.js";
5
+ // ── Capability Resolution ──────────────────────────────────
6
+ /**
7
+ * Detect whether a model is a 9Router virtual combo. The authoritative signal
8
+ * is `owned_by === "combo"`; when `owned_by` is absent (legacy responses) fall
9
+ * back to the prefix heuristic where combo IDs carry no provider prefix.
10
+ */
11
+ export function isComboModel(modelId, ownedBy) {
12
+ if (ownedBy !== undefined) {
13
+ return ownedBy === COMBO_OWNER;
14
+ }
15
+ return !modelId.includes("/");
16
+ }
17
+ /**
18
+ * Capability fragment forced onto combo models that resolved no information
19
+ * from the models.dev catalog or the per-model API. Assumes multimodal input
20
+ * (text/image/audio), tool calling, and reasoning, and exposes thinking-level
21
+ * variants explicitly so they survive OpenCode's id-based exclusions.
22
+ */
23
+ export function forceComboConfig() {
24
+ return {
25
+ attachment: true,
26
+ tool_call: true,
27
+ reasoning: true,
28
+ modalities: { input: ["text", "image", "audio"], output: ["text"] },
29
+ limit: { context: COMBO_CONTEXT_WINDOW, output: COMBO_MAX_OUTPUT },
30
+ variants: Object.fromEntries(COMBO_REASONING_EFFORTS.map((effort) => [effort, { reasoningEffort: effort }])),
31
+ search: false,
32
+ context_length: COMBO_CONTEXT_WINDOW,
33
+ max_completion_tokens: COMBO_MAX_OUTPUT,
34
+ };
35
+ }
36
+ /**
37
+ * Query the per-model `/models/info` endpoint of a 9Router-compatible API.
38
+ * Retries once with exponential backoff on transient failures.
39
+ */
40
+ async function fetchModelInfo(apiURL, modelId, apiKey, retries = 1) {
41
+ for (let attempt = 0; attempt <= retries; attempt++) {
42
+ try {
43
+ const headers = {};
44
+ if (apiKey) {
45
+ headers["Authorization"] = `Bearer ${apiKey}`;
46
+ }
47
+ const response = await fetch(`${apiURL}/models/info?id=${encodeURIComponent(modelId)}`, {
48
+ signal: AbortSignal.timeout(MODEL_INFO_TIMEOUT),
49
+ headers,
50
+ });
51
+ if (!response.ok)
52
+ return null;
53
+ return (await response.json());
54
+ }
55
+ catch {
56
+ if (attempt === retries)
57
+ return null;
58
+ await new Promise((r) => setTimeout(r, 500 * Math.pow(2, attempt)));
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+ /**
64
+ * Map 9Router model info into an OpenCode model config fragment.
65
+ * Only present capabilities are copied; limit fields are validated as
66
+ * positive integers and emitted only as a complete context+output pair,
67
+ * which OpenCode's config schema requires.
68
+ */
69
+ export function mapRouterCapabilities(info) {
70
+ const config = {};
71
+ const inputModalities = new Set(["text"]);
72
+ if (info.capabilities) {
73
+ if (info.capabilities.vision) {
74
+ config.attachment = true;
75
+ inputModalities.add("image");
76
+ }
77
+ if (info.capabilities.tools) {
78
+ config.tool_call = true;
79
+ }
80
+ if (info.capabilities.reasoning) {
81
+ config.reasoning = true;
82
+ }
83
+ if (info.capabilities.audioInput) {
84
+ inputModalities.add("audio");
85
+ }
86
+ }
87
+ if (inputModalities.size > 1) {
88
+ config.modalities = { input: Array.from(inputModalities), output: ["text"] };
89
+ }
90
+ // 9Router /v1/models exposes per-model thinking levels, e.g.
91
+ // ["none","low","medium","high"]. Mirror them onto the config and emit a
92
+ // variant per level so OpenCode surfaces the reasoning-effort selector.
93
+ const thinkingLevels = Array.isArray(info.thinking_levels) && info.thinking_levels.length > 0
94
+ ? info.thinking_levels
95
+ : Array.isArray(info.capabilities?.thinking_levels) &&
96
+ info.capabilities.thinking_levels.length > 0
97
+ ? info.capabilities.thinking_levels
98
+ : undefined;
99
+ if (thinkingLevels) {
100
+ config.thinking_levels = thinkingLevels;
101
+ config.variants = Object.fromEntries(thinkingLevels.map((level) => [level, { reasoningEffort: level }]));
102
+ }
103
+ // reasoning_options from 9Router per-model endpoint (if provided)
104
+ // These are raw/validated controls that supplement or override bulk thinking_levels.
105
+ // May live nested under capabilities or at the top level depending on backend shape.
106
+ const rawReasoningOptions = Array.isArray(info.capabilities?.reasoning_options) && info.capabilities.reasoning_options.length > 0
107
+ ? info.capabilities.reasoning_options
108
+ : Array.isArray(info.reasoning_options) && info.reasoning_options.length > 0
109
+ ? info.reasoning_options
110
+ : undefined;
111
+ if (rawReasoningOptions) {
112
+ config.reasoning_options = rawReasoningOptions;
113
+ console.log("[capabilities] reasoning_options set for", info.id, "->", JSON.stringify(rawReasoningOptions));
114
+ }
115
+ else {
116
+ console.log("[capabilities] no reasoning_options for", info.id, "keys:", Object.keys(info));
117
+ }
118
+ // Context window / max output limits. OpenCode's context-usage percentage
119
+ // is computed from `limit.context`; without it, the UI always shows 0%
120
+ // used. 9Router exposes these both nested under `capabilities` and as
121
+ // top-level `context_length` / `max_completion_tokens` fields.
122
+ //
123
+ // OpenCode's config schema requires BOTH `limit.context` and `limit.output`
124
+ // whenever `limit` is present, so a context-only limit is rejected at config
125
+ // load. Image models (e.g. flux-kontext-max) report `output: 0`, which
126
+ // toPositiveInt rejects; emit a limit only when both bounds are valid.
127
+ const contextWindow = info.capabilities?.contextWindow ?? info.context_length;
128
+ const context = toPositiveInt(contextWindow);
129
+ const maxOutput = info.capabilities?.maxOutput ?? info.max_completion_tokens;
130
+ const output = toPositiveInt(maxOutput);
131
+ if (context !== undefined && output !== undefined) {
132
+ config.limit = { context, output };
133
+ }
134
+ return config;
135
+ }
136
+ /** Normalize a model ID for catalog comparison: strip a known provider
137
+ * prefix, lowercase, and canonicalize dots to dashes. */
138
+ function normalizeModelId(modelId) {
139
+ const stripPrefixes = [
140
+ ...Object.keys(KNOWN_PROVIDER_PREFIXES),
141
+ "nvidia/",
142
+ "cmc/",
143
+ "azure/",
144
+ "aws/",
145
+ "gcp/",
146
+ ];
147
+ let stripped = modelId;
148
+ for (const prefix of stripPrefixes) {
149
+ if (modelId.startsWith(prefix)) {
150
+ stripped = modelId.slice(prefix.length);
151
+ break;
152
+ }
153
+ }
154
+ return stripped.toLowerCase().replace(/\./g, "-");
155
+ }
156
+ /** Last path segment of a catalog ID, normalized for comparison. */
157
+ function catalogLastSegment(catalogId) {
158
+ const parts = catalogId.toLowerCase().replace(/\./g, "-").split("/");
159
+ return parts[parts.length - 1] ?? "";
160
+ }
161
+ /** Project a models.dev entry onto the RouterModelInfo shape. */
162
+ function toRouterModelInfo(entry) {
163
+ const inputModalities = entry.modalities?.input ?? [];
164
+ return {
165
+ id: entry.id,
166
+ capabilities: {
167
+ vision: entry.attachment ?? inputModalities.includes("image"),
168
+ tools: entry.tool_call ?? false,
169
+ reasoning: entry.reasoning ?? false,
170
+ audioInput: inputModalities.includes("audio"),
171
+ // models.dev exposes token limits at the entry's top level as
172
+ // limit.context / limit.output. Mirror them onto the capabilities
173
+ // fields mapRouterCapabilities reads so they reach config.limit
174
+ // through the single validated path (toPositiveInt).
175
+ contextWindow: entry.limit?.context,
176
+ maxOutput: entry.limit?.output,
177
+ },
178
+ };
179
+ }
180
+ /**
181
+ * Find the best models.dev catalog entry for a model ID, matching by suffix
182
+ * (preferred) or substring after stripping known provider prefixes.
183
+ * Returns null when nothing matches.
184
+ */
185
+ export function findModelsDevMatch(modelId, catalog) {
186
+ const normalized = normalizeModelId(modelId);
187
+ let bestMatch = null;
188
+ for (const entry of catalog) {
189
+ const catalogId = typeof entry.id === "string"
190
+ ? entry.id.toLowerCase().replace(/\./g, "-")
191
+ : "";
192
+ if (catalogId.endsWith(normalized)) {
193
+ bestMatch = entry;
194
+ break;
195
+ }
196
+ if (catalogId.includes(normalized) && !bestMatch) {
197
+ bestMatch = entry;
198
+ }
199
+ }
200
+ return bestMatch ? toRouterModelInfo(bestMatch) : null;
201
+ }
202
+ /**
203
+ * Find a models.dev catalog entry whose final path segment exactly equals the
204
+ * normalized model ID. Stricter than {@link findModelsDevMatch}: a loose
205
+ * substring hit (e.g. `vision` → `gpt-4-turbo-vision`) is rejected, so combo
206
+ * models are only treated as enriched when the catalog truly knows them.
207
+ */
208
+ export function findModelsDevMatchExact(modelId, catalog) {
209
+ const normalized = normalizeModelId(modelId);
210
+ for (const entry of catalog) {
211
+ if (typeof entry.id === "string" && catalogLastSegment(entry.id) === normalized) {
212
+ return toRouterModelInfo(entry);
213
+ }
214
+ }
215
+ return null;
216
+ }
217
+ /**
218
+ * Whether a `/models/info` response carries a meaningful capability signal.
219
+ * A bare `tools: true` (the default stub returned by some 9Router backends) is
220
+ * NOT a signal; vision, reasoning, audio input, or a positive token limit are.
221
+ */
222
+ export function isRealRouterSignal(info) {
223
+ const capabilities = info.capabilities;
224
+ if (capabilities?.vision || capabilities?.reasoning || capabilities?.audioInput) {
225
+ return true;
226
+ }
227
+ return toPositiveInt(capabilities?.contextWindow ?? info.context_length) !== undefined;
228
+ }
229
+ const CAPABILITY_BUDGET_MS = 10000;
230
+ /**
231
+ * Resolve capabilities for a batch of model IDs using the models.dev catalog
232
+ * first, then falling back to per-model API queries within a time budget.
233
+ *
234
+ * Combo IDs (see {@link isComboModel}) are held to a stricter bar: they only
235
+ * count as resolved on an exact models.dev match or a meaningful API signal,
236
+ * so backends that return a capability stub for combos do not suppress the
237
+ * forced multimodal defaults.
238
+ */
239
+ export async function resolveCapabilitiesBatch(modelIds, apiURL, apiKey, comboIds) {
240
+ const capabilities = {};
241
+ // 1. Fetch models.dev catalog first (cached 1h → near-instant most runs)
242
+ const catalog = await fetchModelsDevCatalog();
243
+ // 2. Resolve from catalog, queue remainder for API
244
+ const pendingIds = [];
245
+ for (const id of modelIds) {
246
+ const isCombo = comboIds?.has(id) ?? false;
247
+ let resolved = false;
248
+ if (catalog) {
249
+ const match = isCombo
250
+ ? findModelsDevMatchExact(id, catalog)
251
+ : findModelsDevMatch(id, catalog);
252
+ if (match?.capabilities) {
253
+ capabilities[id] = mapRouterCapabilities(match);
254
+ resolved = true;
255
+ }
256
+ // Even if capabilities not fully resolved, extract reasoning_options from catalog
257
+ // as fallback for models where 9Router bulk doesn't provide thinking_levels
258
+ if (catalog && !resolved) {
259
+ const reasoningOptions = findReasoningOptions(id, catalog);
260
+ if (reasoningOptions) {
261
+ capabilities[id] = {
262
+ ...capabilities[id],
263
+ reasoning: true,
264
+ reasoning_options: reasoningOptions,
265
+ };
266
+ resolved = true;
267
+ }
268
+ }
269
+ }
270
+ if (!resolved) {
271
+ pendingIds.push(id);
272
+ }
273
+ }
274
+ // 3. Only hit per-model API for models not in catalog, with time budget
275
+ if (pendingIds.length === 0)
276
+ return capabilities;
277
+ const startTime = Date.now();
278
+ for (let i = 0; i < pendingIds.length; i += MAX_CONCURRENT_INFO) {
279
+ if (Date.now() - startTime > CAPABILITY_BUDGET_MS) {
280
+ // Budget exhausted — give up on remaining models, fallback will serve them
281
+ break;
282
+ }
283
+ const batch = pendingIds.slice(i, i + MAX_CONCURRENT_INFO);
284
+ const results = await Promise.allSettled(batch.map((id) => fetchModelInfo(apiURL, id, apiKey)));
285
+ for (let j = 0; j < batch.length; j++) {
286
+ const result = results[j];
287
+ if (result.status === "fulfilled" && result.value) {
288
+ const id = batch[j];
289
+ if (comboIds?.has(id) && !isRealRouterSignal(result.value)) {
290
+ continue;
291
+ }
292
+ capabilities[id] = mapRouterCapabilities(result.value);
293
+ }
294
+ else if (result.status === "rejected") {
295
+ console.log(`[capabilities] per-model fetch rejected for ${batch[j]}: ${result.reason}`);
296
+ }
297
+ }
298
+ }
299
+ return capabilities;
300
+ }
@@ -0,0 +1,43 @@
1
+ export declare const PLUGIN_NAME = "9router";
2
+ export declare const PROVIDER_DISPLAY_NAME = "9Router";
3
+ export declare const DEFAULT_BASE_URL = "http://localhost:20128";
4
+ export declare const DEFAULT_API_PATH = "/v1";
5
+ /**
6
+ * Well-known 9Router models used as fallback when the API is unreachable.
7
+ * Covers the most common providers and tiers routed through 9Router.
8
+ */
9
+ export declare const FALLBACK_MODELS: Record<string, {
10
+ name: string;
11
+ }>;
12
+ /** URL for the models.dev capability catalog. */
13
+ export declare const MODELS_DEV_URL = "https://models.dev/api.json";
14
+ /** Cache TTL for the models.dev catalog (1 hour). */
15
+ export declare const MODELS_DEV_CACHE_TTL: number;
16
+ /** Default cache TTL for model discovery results (3 hours). */
17
+ export declare const DISCOVERY_CACHE_TTL: number;
18
+ /** Timeout for model list discovery request (30 seconds). */
19
+ export declare const DISCOVERY_TIMEOUT = 30000;
20
+ /** Timeout per-model info request (5 seconds). */
21
+ export declare const MODEL_INFO_TIMEOUT = 5000;
22
+ /** Max concurrent per-model info requests. */
23
+ export declare const MAX_CONCURRENT_INFO = 15;
24
+ /** `owned_by` value 9Router assigns to virtual combo models. */
25
+ export declare const COMBO_OWNER = "combo";
26
+ /** Default context window forced onto unenriched combo models (256K). */
27
+ export declare const COMBO_CONTEXT_WINDOW = 262144;
28
+ /** Default max output tokens forced onto unenriched combo models (128K). */
29
+ export declare const COMBO_MAX_OUTPUT = 131072;
30
+ /**
31
+ * Thinking-level variants exposed for forced combos. Every level is forwarded
32
+ * verbatim as `reasoningEffort` so OpenCode users can pick any of them.
33
+ */
34
+ export declare const COMBO_REASONING_EFFORTS: readonly ["low", "medium", "high", "xhigh", "max", "minimal", "thinking"];
35
+ /**
36
+ * Discovery cache format version. Bumped whenever the stored model config
37
+ * shape changes so stale entries are refetched instead of served as-is.
38
+ * v5: adds reasoning_options (effort + toggle) and catalogProvider to ModelConfig.
39
+ * Rejects v3 and v4 caches to ensure validated controls are present.
40
+ */
41
+ export declare const DISCOVERY_CACHE_VERSION = 5;
42
+ /** Known provider prefixes in 9Router model IDs for human-readable naming. */
43
+ export declare const KNOWN_PROVIDER_PREFIXES: Record<string, string>;
@@ -0,0 +1,106 @@
1
+ export const PLUGIN_NAME = "9router";
2
+ export const PROVIDER_DISPLAY_NAME = "9Router";
3
+ export const DEFAULT_BASE_URL = "http://localhost:20128";
4
+ export const DEFAULT_API_PATH = "/v1";
5
+ /**
6
+ * Well-known 9Router models used as fallback when the API is unreachable.
7
+ * Covers the most common providers and tiers routed through 9Router.
8
+ */
9
+ export const FALLBACK_MODELS = {
10
+ // --- Claude Code (Subscription) ---
11
+ "cc/claude-opus-4-7": { name: "Claude Opus 4.7 (Claude Code)" },
12
+ "cc/claude-opus-4-6": { name: "Claude Opus 4.6 (Claude Code)" },
13
+ "cc/claude-sonnet-4-6": { name: "Claude Sonnet 4.6 (Claude Code)" },
14
+ "cc/claude-haiku-4-5-20251001": { name: "Claude Haiku 4.5 (Claude Code)" },
15
+ // --- OpenCode / Codex (Subscription) ---
16
+ "cx/gpt-5.5": { name: "GPT-5.5 (Codex)" },
17
+ "cx/gpt-5.4": { name: "GPT-5.4 (Codex)" },
18
+ // --- GitHub Copilot (Subscription) ---
19
+ "gh/gpt-5.4": { name: "GPT-5.4 (Copilot)" },
20
+ "gh/claude-sonnet-4.6": { name: "Claude Sonnet 4.6 (Copilot)" },
21
+ // --- Kiro AI (FREE) ---
22
+ "kr/claude-sonnet-4.5": { name: "Claude Sonnet 4.5 (Kiro Free)" },
23
+ "kr/claude-haiku-4.5": { name: "Claude Haiku 4.5 (Kiro Free)" },
24
+ "kr/glm-5": { name: "GLM-5 (Kiro Free)" },
25
+ "kr/MiniMax-M2.5": { name: "MiniMax M2.5 (Kiro Free)" },
26
+ "kr/qwen3-coder-next": { name: "Qwen3 Coder Next (Kiro Free)" },
27
+ "kr/deepseek-3.2": { name: "DeepSeek 3.2 (Kiro Free)" },
28
+ // --- OpenCode Free (FREE) ---
29
+ "oc/auto": { name: "OpenCode Free (Auto)" },
30
+ // --- Vertex AI ($300 credits) ---
31
+ "vertex/gemini-3.1-pro-preview": { name: "Gemini 3.1 Pro (Vertex)" },
32
+ "vertex/gemini-3-flash-preview": { name: "Gemini 3 Flash (Vertex)" },
33
+ // --- GLM (Cheap, $0.6/1M) ---
34
+ "glm/glm-5.1": { name: "GLM-5.1" },
35
+ "glm/glm-5": { name: "GLM-5" },
36
+ "glm/glm-4.7": { name: "GLM-4.7" },
37
+ // --- MiniMax (Cheapest, $0.2/1M) ---
38
+ "minimax/MiniMax-M2.7": { name: "MiniMax M2.7" },
39
+ "minimax/MiniMax-M2.5": { name: "MiniMax M2.5" },
40
+ // --- Kimi ($9/mo flat) ---
41
+ "kimi/kimi-k2.5": { name: "Kimi K2.5" },
42
+ "kimi/kimi-k2.5-thinking": { name: "Kimi K2.5 (Thinking)" },
43
+ // --- Cursor (Subscription) ---
44
+ "cu/claude-4.6-opus-max": { name: "Claude 4.6 Opus Max (Cursor)" },
45
+ // --- Standard Key Providers ---
46
+ "deepseek/deepseek-chat": { name: "DeepSeek Chat" },
47
+ "groq/llama-4.5-70b": { name: "Llama 4.5 70B (Groq)" },
48
+ };
49
+ /** URL for the models.dev capability catalog. */
50
+ export const MODELS_DEV_URL = "https://models.dev/api.json";
51
+ /** Cache TTL for the models.dev catalog (1 hour). */
52
+ export const MODELS_DEV_CACHE_TTL = 60 * 60 * 1000;
53
+ /** Default cache TTL for model discovery results (3 hours). */
54
+ export const DISCOVERY_CACHE_TTL = 3 * 60 * 60 * 1000;
55
+ /** Timeout for model list discovery request (30 seconds). */
56
+ export const DISCOVERY_TIMEOUT = 30000;
57
+ /** Timeout per-model info request (5 seconds). */
58
+ export const MODEL_INFO_TIMEOUT = 5000;
59
+ /** Max concurrent per-model info requests. */
60
+ export const MAX_CONCURRENT_INFO = 15;
61
+ /** `owned_by` value 9Router assigns to virtual combo models. */
62
+ export const COMBO_OWNER = "combo";
63
+ /** Default context window forced onto unenriched combo models (256K). */
64
+ export const COMBO_CONTEXT_WINDOW = 262144;
65
+ /** Default max output tokens forced onto unenriched combo models (128K). */
66
+ export const COMBO_MAX_OUTPUT = 131072;
67
+ /**
68
+ * Thinking-level variants exposed for forced combos. Every level is forwarded
69
+ * verbatim as `reasoningEffort` so OpenCode users can pick any of them.
70
+ */
71
+ export const COMBO_REASONING_EFFORTS = [
72
+ "low",
73
+ "medium",
74
+ "high",
75
+ "xhigh",
76
+ "max",
77
+ "minimal",
78
+ "thinking",
79
+ ];
80
+ /**
81
+ * Discovery cache format version. Bumped whenever the stored model config
82
+ * shape changes so stale entries are refetched instead of served as-is.
83
+ * v5: adds reasoning_options (effort + toggle) and catalogProvider to ModelConfig.
84
+ * Rejects v3 and v4 caches to ensure validated controls are present.
85
+ */
86
+ export const DISCOVERY_CACHE_VERSION = 5;
87
+ /** Known provider prefixes in 9Router model IDs for human-readable naming. */
88
+ export const KNOWN_PROVIDER_PREFIXES = {
89
+ "cc/": "Claude Code",
90
+ "cx/": "Codex",
91
+ "gh/": "GitHub Copilot",
92
+ "kr/": "Kiro AI",
93
+ "oc/": "OpenCode Free",
94
+ "vertex/": "Vertex AI",
95
+ "vertex-partner/": "Vertex Partner",
96
+ "glm/": "GLM",
97
+ "minimax/": "MiniMax",
98
+ "kimi/": "Kimi",
99
+ "cu/": "Cursor",
100
+ "gc/": "Gemini CLI",
101
+ "if/": "iFlow",
102
+ "qw/": "Qwen",
103
+ "openrouter/": "OpenRouter",
104
+ "deepseek/": "DeepSeek",
105
+ "groq/": "Groq",
106
+ };
@@ -0,0 +1,9 @@
1
+ import type { ModelConfig } from "./types.js";
2
+ /** Log function type shared by the discovery pipeline. */
3
+ export type DiscoveryLogger = (level: "info" | "warn" | "error" | "debug", message: string) => Promise<void>;
4
+ /**
5
+ * Discover models from a 9Router-compatible API, enriching each model with
6
+ * capabilities from the models.dev catalog and the per-model API. Results are
7
+ * cached; an expired cache entry is used as fallback when the fetch fails.
8
+ */
9
+ export declare function discoverModels(baseURL: string, apiKey: string | undefined, cacheEnabled: boolean, cacheTTL: number, discoveryTimeout: number, providerKey: string, log: DiscoveryLogger): Promise<Record<string, ModelConfig> | null>;