opencode-model-router 2.1.0 → 2.2.0
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/CHANGELOG.md +21 -0
- package/README.md +9 -2
- package/package.json +1 -1
- package/src/compat/v2-hooks.ts +57 -17
- package/src/index.ts +71 -23
- package/src/router/config.ts +332 -54
- package/tiers.json +43 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.2.0] - 2026-10-05
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Config hot reload: the router re-reads `tiers.json`, the global and project
|
|
15
|
+
overrides files and the state file when their mtime/ctime/size fingerprint changes,
|
|
16
|
+
with no restart. A source that turns invalid or unreachable keeps the last valid
|
|
17
|
+
config (the reason is surfaced by `getConfigReloadError()`); only ENOENT/ENOTDIR
|
|
18
|
+
count as a removed file. `/router-reload` forces a reload, and on OpenCode 2 the
|
|
19
|
+
agent and command registry is refreshed on reload and after `/preset`.
|
|
20
|
+
- `hybrid-2` preset: `@fast` → `openai/gpt-6-luna-fast` (medium), `@medium` →
|
|
21
|
+
`anthropic/claude-sonnet-5-5` (xhigh), `@heavy` → `anthropic/claude-opus-5-5`
|
|
22
|
+
(xhigh).
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- Project overrides are found again on opencode v2 service mode (#70): the override
|
|
27
|
+
lookup and the config cache are now keyed by the host-provided project directory
|
|
28
|
+
instead of `process.cwd()` (which the v2 server moves to `$HOME`), so several
|
|
29
|
+
projects in one process each keep their own config, reload state and error.
|
|
30
|
+
|
|
10
31
|
## [2.1.0] - 2026-10-05
|
|
11
32
|
|
|
12
33
|
Observations by @MetalbolicX in opencode-smart-router (#17); implementation written from scratch.
|
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ Every tier carries its `costRatio` (fast=1x, medium=5x, heavy=20x) injected into
|
|
|
35
35
|
If the orchestrator is already running on Opus, the rule `self∈opus→never→@heavy` fires — it does the heavy work itself rather than delegating to another Opus instance.
|
|
36
36
|
|
|
37
37
|
**Multi-provider support with automatic fallback.**
|
|
38
|
-
|
|
38
|
+
Eight presets out of the box: Anthropic, OpenAI, GitHub Copilot, Google, hybrid, hybrid-2, fable-effort, and Zai (GLM). Switch with `/preset`. If a provider fails, the fallback chain tries the next one automatically.
|
|
39
39
|
|
|
40
40
|
**Plan annotation for long tasks.**
|
|
41
41
|
`/annotate-plan` reads a markdown plan and tags each step with `[tier:fast]`, `[tier:medium]`, or `[tier:heavy]` — removing all routing ambiguity from multi-step workflows.
|
|
@@ -415,7 +415,7 @@ For an npm install, `tiers.json` is **inside the cached package directory**, not
|
|
|
415
415
|
|
|
416
416
|
### Presets
|
|
417
417
|
|
|
418
|
-
The plugin ships with
|
|
418
|
+
The plugin ships with eight presets (switch with `/preset <name>`):
|
|
419
419
|
|
|
420
420
|
**anthropic** (default):
|
|
421
421
|
| Tier | Model | Cost ratio |
|
|
@@ -452,6 +452,13 @@ The plugin ships with seven presets (switch with `/preset <name>`):
|
|
|
452
452
|
| @medium | `openai/gpt-6-astra-fast` (high) | 5x |
|
|
453
453
|
| @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
|
|
454
454
|
|
|
455
|
+
**hybrid-2** — OpenAI for exploration, Anthropic for implementation and heavy analysis:
|
|
456
|
+
| Tier | Model | Cost ratio |
|
|
457
|
+
|------|-------|-----------|
|
|
458
|
+
| @fast | `openai/gpt-6-luna-fast` (medium) | 1x |
|
|
459
|
+
| @medium | `anthropic/claude-sonnet-5-5` (variant/effort: xhigh) | 5x |
|
|
460
|
+
| @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
|
|
461
|
+
|
|
455
462
|
**fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
|
|
456
463
|
| Tier | Model | Effort | Cost ratio |
|
|
457
464
|
|------|-------|--------|-----------|
|
package/package.json
CHANGED
package/src/compat/v2-hooks.ts
CHANGED
|
@@ -114,25 +114,55 @@ export async function registerV2Hooks(
|
|
|
114
114
|
};
|
|
115
115
|
|
|
116
116
|
try {
|
|
117
|
+
// Captured once: after our own transform, ctx.agent.list() returns
|
|
118
|
+
// router-modified agents, which would defeat the originals diff on refresh.
|
|
117
119
|
const agents = await ctx.agent.list();
|
|
118
|
-
const
|
|
119
|
-
for (const agent of agents.data)
|
|
120
|
+
const baseSeed: Record<string, LegacyAgent> = {};
|
|
121
|
+
for (const agent of agents.data) baseSeed[agent.id] = {
|
|
120
122
|
mode: agent.mode,
|
|
121
123
|
model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
|
|
122
124
|
variant: agent.model?.variant,
|
|
123
125
|
};
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
126
|
+
let config: LegacyConfig = { agent: {}, command: {} };
|
|
127
|
+
let originals = new Map<string, string>();
|
|
128
|
+
let agentOptions = new Map<string, Record<string, unknown>>();
|
|
129
|
+
let lastConfig: unknown;
|
|
130
|
+
// Returns the router config the registry state was built from; the caller
|
|
131
|
+
// advances `lastConfig` only once the host registries have reloaded from it.
|
|
132
|
+
const buildConfig = async (): Promise<unknown> => {
|
|
133
|
+
const next: LegacyConfig = { agent: JSON.parse(JSON.stringify(baseSeed)), command: {} };
|
|
134
|
+
const nextOriginals = new Map(Object.entries(next.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
|
|
135
|
+
await hooks.config?.(next);
|
|
136
|
+
const nextOptions = new Map<string, Record<string, unknown>>();
|
|
137
|
+
for (const [name, definition] of Object.entries(next.agent)) {
|
|
138
|
+
if (nextOriginals.get(name) === JSON.stringify(definition) || !definition.options) continue;
|
|
139
|
+
const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
|
|
140
|
+
const normalized = { ...options };
|
|
141
|
+
if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
|
|
142
|
+
if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
|
|
143
|
+
if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
|
|
144
|
+
nextOptions.set(name, normalized);
|
|
145
|
+
}
|
|
146
|
+
config = next;
|
|
147
|
+
originals = nextOriginals;
|
|
148
|
+
agentOptions = nextOptions;
|
|
149
|
+
return loadConfig(ctx.location.directory);
|
|
150
|
+
};
|
|
151
|
+
lastConfig = await buildConfig();
|
|
152
|
+
let refreshChain: Promise<void> = Promise.resolve();
|
|
153
|
+
const refresh = (): Promise<void> => {
|
|
154
|
+
const run = refreshChain.then(async () => {
|
|
155
|
+
if (disposed) return;
|
|
156
|
+
const built = await buildConfig();
|
|
157
|
+
await ctx.agent.reload();
|
|
158
|
+
await ctx.command.reload();
|
|
159
|
+
// Only after both registries reloaded: a rejected reload leaves
|
|
160
|
+
// `lastConfig` stale so the next prompt retries the refresh.
|
|
161
|
+
lastConfig = built;
|
|
162
|
+
});
|
|
163
|
+
refreshChain = run.catch(() => {});
|
|
164
|
+
return run;
|
|
165
|
+
};
|
|
136
166
|
registrations.push(await ctx.agent.transform((editor) => {
|
|
137
167
|
if (runtime) editor.update(V2_GRADER_AGENT, (agent) => {
|
|
138
168
|
agent.mode = "subagent";
|
|
@@ -163,6 +193,15 @@ export async function registerV2Hooks(
|
|
|
163
193
|
await legacy["command.execute.before"]?.({
|
|
164
194
|
command: name, arguments: invocation.prompt.text, sessionID: invocation.sessionID,
|
|
165
195
|
}, output);
|
|
196
|
+
if (name === "router-reload") {
|
|
197
|
+
const reloadText = output.parts.map((part) => v2Instructions(part.text)).join("\n\n");
|
|
198
|
+
await refresh();
|
|
199
|
+
await ctx.session.synthetic({
|
|
200
|
+
sessionID: invocation.sessionID, text: reloadText, description: "Model router config reload", resume: false,
|
|
201
|
+
});
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (name === "preset") await refresh();
|
|
166
205
|
await ctx.session.prompt({
|
|
167
206
|
...invocation.prompt,
|
|
168
207
|
sessionID: invocation.sessionID,
|
|
@@ -207,6 +246,7 @@ export async function registerV2Hooks(
|
|
|
207
246
|
const output = { message: { agent: session.agent }, parts: [{ type: "text", text: event.prompt.text }] };
|
|
208
247
|
await legacy["chat.message"]?.({ sessionID: event.sessionID, agent: session.agent }, output);
|
|
209
248
|
event.prompt.text = output.parts.map((part) => part.text).join("\n\n");
|
|
249
|
+
if (loadConfig(ctx.location.directory) !== lastConfig) await refresh();
|
|
210
250
|
}));
|
|
211
251
|
registrations.push(await ctx.session.hook("context", async (event) => {
|
|
212
252
|
const input = { sessionID: event.sessionID, agent: event.agent, model: { ...event.model, modelID: event.model.id } };
|
|
@@ -215,7 +255,7 @@ export async function registerV2Hooks(
|
|
|
215
255
|
if (!(key in event.options)) event.options[key] = value;
|
|
216
256
|
}
|
|
217
257
|
await legacy["chat.params"]?.(input, event.options);
|
|
218
|
-
const verify = loadConfig().enforcement?.verify;
|
|
258
|
+
const verify = loadConfig(ctx.location.directory).enforcement?.verify;
|
|
219
259
|
if (event.agent === V2_GRADER_AGENT
|
|
220
260
|
&& (verify?.graderTemperature === null
|
|
221
261
|
|| !(verify?.graderTemperatureModels ?? []).includes(`${event.model.providerID}/${event.model.id}`))) {
|
|
@@ -256,7 +296,7 @@ export async function registerV2Hooks(
|
|
|
256
296
|
const source = message.id ? attributed.get(message.id) : undefined;
|
|
257
297
|
if (!source || source.type !== "synthetic") continue;
|
|
258
298
|
const filtered = { system: [source.text] };
|
|
259
|
-
stripDelegateInstructions(filtered, loadConfig(), session.location?.directory ?? ctx.location.directory);
|
|
299
|
+
stripDelegateInstructions(filtered, loadConfig(ctx.location.directory), session.location?.directory ?? ctx.location.directory);
|
|
260
300
|
const retained = filtered.system.join("");
|
|
261
301
|
if (retained === source.text) continue;
|
|
262
302
|
const index = event.messages.indexOf(message);
|
|
@@ -274,7 +314,7 @@ export async function registerV2Hooks(
|
|
|
274
314
|
const original = args && typeof args === "object" ? { ...args } : args;
|
|
275
315
|
const output = { args };
|
|
276
316
|
if (event.tool === "subagent" && args && typeof args.agent === "string" && args.model === undefined) {
|
|
277
|
-
const cfg = loadConfig();
|
|
317
|
+
const cfg = loadConfig(ctx.location.directory);
|
|
278
318
|
if (cfg.subagentTiers?.[args.agent]) {
|
|
279
319
|
const actual = await ctx.agent.list();
|
|
280
320
|
const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
|
package/src/index.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
resolvePresetName,
|
|
9
9
|
writeState,
|
|
10
10
|
invalidateConfigCache,
|
|
11
|
+
getConfigReloadError,
|
|
11
12
|
overridePath,
|
|
12
13
|
localOverridePath,
|
|
13
14
|
findProjectOverride,
|
|
@@ -127,8 +128,8 @@ function describeError(error: unknown): string {
|
|
|
127
128
|
}
|
|
128
129
|
}
|
|
129
130
|
|
|
130
|
-
function saveActivePreset(presetName: string): void {
|
|
131
|
-
const cfg = loadConfig();
|
|
131
|
+
function saveActivePreset(presetName: string, projectDir?: string): void {
|
|
132
|
+
const cfg = loadConfig(projectDir);
|
|
132
133
|
const resolved = resolvePresetName(cfg, presetName);
|
|
133
134
|
if (!resolved) {
|
|
134
135
|
return;
|
|
@@ -143,8 +144,8 @@ function saveActivePreset(presetName: string): void {
|
|
|
143
144
|
invalidateConfigCache();
|
|
144
145
|
}
|
|
145
146
|
|
|
146
|
-
function saveActiveMode(modeName: string): void {
|
|
147
|
-
const cfg = loadConfig();
|
|
147
|
+
function saveActiveMode(modeName: string, projectDir?: string): void {
|
|
148
|
+
const cfg = loadConfig(projectDir);
|
|
148
149
|
if (!cfg.modes?.[modeName]) {
|
|
149
150
|
return;
|
|
150
151
|
}
|
|
@@ -163,7 +164,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
|
|
|
163
164
|
* `/router` dispatch. Decides and persists here; rendering lives in
|
|
164
165
|
* src/commands/output.ts.
|
|
165
166
|
*/
|
|
166
|
-
function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
167
|
+
function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
|
|
167
168
|
const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
168
169
|
const sub = (tokens[0] ?? "").toLowerCase();
|
|
169
170
|
|
|
@@ -180,8 +181,8 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
|
180
181
|
|
|
181
182
|
if (sub === "overrides") {
|
|
182
183
|
const globalPath = overridePath();
|
|
183
|
-
const foundLocal = findProjectOverride();
|
|
184
|
-
const localPath = foundLocal ?? localOverridePath();
|
|
184
|
+
const foundLocal = findProjectOverride(projectDir);
|
|
185
|
+
const localPath = foundLocal ?? localOverridePath(projectDir);
|
|
185
186
|
return buildOverridesOutput({
|
|
186
187
|
globalPath,
|
|
187
188
|
globalPresent: existsSync(globalPath),
|
|
@@ -198,7 +199,7 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
|
198
199
|
}
|
|
199
200
|
|
|
200
201
|
/** `/budget` dispatch. Persists the switch, then renders. */
|
|
201
|
-
function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
202
|
+
function buildBudgetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
|
|
202
203
|
const modes = cfg.modes;
|
|
203
204
|
if (!modes || Object.keys(modes).length === 0) return buildNoModes();
|
|
204
205
|
|
|
@@ -207,7 +208,7 @@ function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
|
207
208
|
|
|
208
209
|
const mode = modes[requested];
|
|
209
210
|
if (mode) {
|
|
210
|
-
saveActiveMode(requested);
|
|
211
|
+
saveActiveMode(requested, projectDir);
|
|
211
212
|
return buildBudgetSwitched(mode, requested);
|
|
212
213
|
}
|
|
213
214
|
|
|
@@ -215,13 +216,13 @@ function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
|
215
216
|
}
|
|
216
217
|
|
|
217
218
|
/** `/preset` dispatch. Persists the switch, then renders. */
|
|
218
|
-
function buildPresetOutput(cfg: RouterConfig, args: string): string {
|
|
219
|
+
function buildPresetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
|
|
219
220
|
const requestedPreset = args.trim();
|
|
220
221
|
if (!requestedPreset) return buildPresetList(cfg);
|
|
221
222
|
|
|
222
223
|
const resolvedPreset = resolvePresetName(cfg, requestedPreset);
|
|
223
224
|
if (resolvedPreset) {
|
|
224
|
-
saveActivePreset(resolvedPreset);
|
|
225
|
+
saveActivePreset(resolvedPreset, projectDir);
|
|
225
226
|
cfg.activePreset = resolvedPreset;
|
|
226
227
|
return buildPresetSwitched(cfg, resolvedPreset);
|
|
227
228
|
}
|
|
@@ -254,8 +255,12 @@ const SESSION_ROOT_MEMO_MAX = 500;
|
|
|
254
255
|
const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
|
|
255
256
|
|
|
256
257
|
const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
257
|
-
|
|
258
|
-
|
|
258
|
+
// Project directory this plugin instance serves. Hosts that run several
|
|
259
|
+
// projects in one process (OpenCode v2) may also move process.cwd() away from
|
|
260
|
+
// it, so config/override lookup must use this and never the working directory.
|
|
261
|
+
const projectDir: string | undefined = ctx.directory || ctx.worktree || undefined;
|
|
262
|
+
let cfg = loadConfig(projectDir);
|
|
263
|
+
let activeTiers = getActiveTiers(cfg);
|
|
259
264
|
|
|
260
265
|
// Per-plugin-instance session store: owns subagentSessionIDs and subagentCapState.
|
|
261
266
|
const sessionStore = createSessionStore();
|
|
@@ -638,7 +643,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
638
643
|
try {
|
|
639
644
|
let activeCfg = cfg;
|
|
640
645
|
try {
|
|
641
|
-
activeCfg = loadConfig();
|
|
646
|
+
activeCfg = loadConfig(projectDir);
|
|
642
647
|
warnDeprecatedVerifyKeys(activeCfg, logger);
|
|
643
648
|
} catch {
|
|
644
649
|
activeCfg = cfg;
|
|
@@ -1115,7 +1120,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1115
1120
|
if (bypassed) return;
|
|
1116
1121
|
// Re-read cfg so /preset switches take effect without restart
|
|
1117
1122
|
try {
|
|
1118
|
-
cfg = loadConfig();
|
|
1123
|
+
cfg = loadConfig(projectDir);
|
|
1119
1124
|
warnDeprecatedVerifyKeys(cfg, logger);
|
|
1120
1125
|
} catch {}
|
|
1121
1126
|
try {
|
|
@@ -1734,6 +1739,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1734
1739
|
config: async (opencodeConfig: any) => {
|
|
1735
1740
|
opencodeConfig.agent ??= {};
|
|
1736
1741
|
|
|
1742
|
+
// Re-read so re-running this hook (v2 refresh) yields the current preset.
|
|
1743
|
+
cfg = loadConfig(projectDir);
|
|
1744
|
+
activeTiers = getActiveTiers(cfg);
|
|
1745
|
+
|
|
1737
1746
|
for (const [name, tier] of Object.entries(activeTiers)) {
|
|
1738
1747
|
// Resolve prompt: per-tier override wins; otherwise fall back to the
|
|
1739
1748
|
// style-appropriate default (goal-oriented or global tierPrompts[name]).
|
|
@@ -1869,6 +1878,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1869
1878
|
description:
|
|
1870
1879
|
"Annotate a plan with [tier:fast/medium/heavy] delegation tags",
|
|
1871
1880
|
};
|
|
1881
|
+
opencodeConfig.command["router-reload"] = {
|
|
1882
|
+
template: "",
|
|
1883
|
+
description:
|
|
1884
|
+
ctx.routerHost === "v2"
|
|
1885
|
+
? "Reload model-router config (tiers.json, overrides, state) without restarting"
|
|
1886
|
+
: "Reload model-router config (tiers.json, overrides, state); subagent models apply after an opencode restart",
|
|
1887
|
+
};
|
|
1872
1888
|
opencodeConfig.command["router"] = {
|
|
1873
1889
|
template: "$ARGUMENTS",
|
|
1874
1890
|
description:
|
|
@@ -1885,7 +1901,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1885
1901
|
"experimental.chat.system.transform": async (_input: any, output: any) => {
|
|
1886
1902
|
if (bypassed) return;
|
|
1887
1903
|
try {
|
|
1888
|
-
cfg = loadConfig(); // Returns cache unless invalidated
|
|
1904
|
+
cfg = loadConfig(projectDir); // Returns cache unless invalidated
|
|
1889
1905
|
warnDeprecatedVerifyKeys(cfg, logger);
|
|
1890
1906
|
} catch {
|
|
1891
1907
|
// Use last known config if file read fails
|
|
@@ -1975,7 +1991,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1975
1991
|
"command.execute.before": async (input: any, output: any) => {
|
|
1976
1992
|
if (input.command === "tiers") {
|
|
1977
1993
|
try {
|
|
1978
|
-
cfg = loadConfig();
|
|
1994
|
+
cfg = loadConfig(projectDir);
|
|
1979
1995
|
warnDeprecatedVerifyKeys(cfg, logger);
|
|
1980
1996
|
} catch {}
|
|
1981
1997
|
output.parts.push({
|
|
@@ -1984,14 +2000,46 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1984
2000
|
});
|
|
1985
2001
|
}
|
|
1986
2002
|
|
|
2003
|
+
if (input.command === "router-reload") {
|
|
2004
|
+
invalidateConfigCache();
|
|
2005
|
+
cfg = loadConfig(projectDir);
|
|
2006
|
+
activeTiers = getActiveTiers(cfg);
|
|
2007
|
+
const mapping = Object.entries(activeTiers)
|
|
2008
|
+
.map(([name, tier]) => ` ${name} -> ${tier.model}`)
|
|
2009
|
+
.join("\n");
|
|
2010
|
+
const reloadError = getConfigReloadError(projectDir);
|
|
2011
|
+
output.parts.push({
|
|
2012
|
+
type: "text" as const,
|
|
2013
|
+
text: [
|
|
2014
|
+
...(reloadError
|
|
2015
|
+
? [
|
|
2016
|
+
`Config reload FAILED — keeping last valid config:\n${reloadError}`,
|
|
2017
|
+
"Model router is still using the last valid config.",
|
|
2018
|
+
]
|
|
2019
|
+
: ["Model router config reloaded."]),
|
|
2020
|
+
`Preset: ${cfg.activePreset}`,
|
|
2021
|
+
`Mode: ${cfg.activeMode ?? "normal"}`,
|
|
2022
|
+
"Tiers:",
|
|
2023
|
+
mapping,
|
|
2024
|
+
// opencode v1 builds its agent registry once at startup; only the v2
|
|
2025
|
+
// adapter re-runs the config hook + agent reload after /router-reload.
|
|
2026
|
+
...(ctx.routerHost === "v2"
|
|
2027
|
+
? []
|
|
2028
|
+
: [
|
|
2029
|
+
"Note: opencode v1 keeps subagent (task) models from startup; restart opencode to apply tier model changes to subagents. Routing and protocol already use the new config.",
|
|
2030
|
+
]),
|
|
2031
|
+
].join("\n"),
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
|
|
1987
2035
|
if (input.command === "preset") {
|
|
1988
2036
|
try {
|
|
1989
|
-
cfg = loadConfig();
|
|
2037
|
+
cfg = loadConfig(projectDir);
|
|
1990
2038
|
warnDeprecatedVerifyKeys(cfg, logger);
|
|
1991
2039
|
} catch {}
|
|
1992
2040
|
output.parts.push({
|
|
1993
2041
|
type: "text" as const,
|
|
1994
|
-
text: buildPresetOutput(cfg, input.arguments ?? ""),
|
|
2042
|
+
text: buildPresetOutput(cfg, input.arguments ?? "", projectDir),
|
|
1995
2043
|
});
|
|
1996
2044
|
}
|
|
1997
2045
|
|
|
@@ -2012,18 +2060,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2012
2060
|
|
|
2013
2061
|
if (input.command === "budget") {
|
|
2014
2062
|
try {
|
|
2015
|
-
cfg = loadConfig();
|
|
2063
|
+
cfg = loadConfig(projectDir);
|
|
2016
2064
|
warnDeprecatedVerifyKeys(cfg, logger);
|
|
2017
2065
|
} catch {}
|
|
2018
2066
|
output.parts.push({
|
|
2019
2067
|
type: "text" as const,
|
|
2020
|
-
text: buildBudgetOutput(cfg, input.arguments ?? ""),
|
|
2068
|
+
text: buildBudgetOutput(cfg, input.arguments ?? "", projectDir),
|
|
2021
2069
|
});
|
|
2022
2070
|
}
|
|
2023
2071
|
|
|
2024
2072
|
if (input.command === "router") {
|
|
2025
2073
|
try {
|
|
2026
|
-
cfg = loadConfig();
|
|
2074
|
+
cfg = loadConfig(projectDir);
|
|
2027
2075
|
warnDeprecatedVerifyKeys(cfg, logger);
|
|
2028
2076
|
} catch {}
|
|
2029
2077
|
const args = (input.arguments ?? "").trim();
|
|
@@ -2035,7 +2083,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2035
2083
|
const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
|
|
2036
2084
|
text = buildModelsOutput(catalog, parts.slice(1).join(" "), orphans);
|
|
2037
2085
|
} else {
|
|
2038
|
-
text = buildRouterOutput(cfg, args);
|
|
2086
|
+
text = buildRouterOutput(cfg, args, projectDir);
|
|
2039
2087
|
// On the bare status view, surface stale or missing models inline.
|
|
2040
2088
|
if (sub === "") {
|
|
2041
2089
|
const catalog = await fetchCatalog();
|
package/src/router/config.ts
CHANGED
|
@@ -4,10 +4,11 @@ import {
|
|
|
4
4
|
readFileSync,
|
|
5
5
|
realpathSync,
|
|
6
6
|
renameSync,
|
|
7
|
+
statSync,
|
|
7
8
|
writeFileSync,
|
|
8
9
|
} from "node:fs";
|
|
9
10
|
import { availableParallelism, homedir } from "node:os";
|
|
10
|
-
import { dirname, join } from "node:path";
|
|
11
|
+
import { dirname, join, resolve as resolvePath } from "node:path";
|
|
11
12
|
import { fileURLToPath } from "node:url";
|
|
12
13
|
import { parseJsonc } from "./jsonc";
|
|
13
14
|
import type { DelegateInstructionsPolicy } from "./instructions";
|
|
@@ -264,12 +265,82 @@ export interface RouterState {
|
|
|
264
265
|
// Config loader with caching
|
|
265
266
|
// ---------------------------------------------------------------------------
|
|
266
267
|
|
|
267
|
-
|
|
268
|
-
|
|
268
|
+
/**
|
|
269
|
+
* Cache state for one project directory. Hosts such as OpenCode v2 run one
|
|
270
|
+
* plugin instance per project directory inside a single process, so the cache
|
|
271
|
+
* cannot be a single module-level slot: each directory has its own project
|
|
272
|
+
* override file and therefore its own config, fingerprint and last-good state.
|
|
273
|
+
*/
|
|
274
|
+
interface ConfigCacheEntry {
|
|
275
|
+
config: RouterConfig | null;
|
|
276
|
+
dirty: boolean;
|
|
277
|
+
fingerprint: string;
|
|
278
|
+
/** Source locations (paths only, no mtimes) that produced `config`. */
|
|
279
|
+
sourceKey: string;
|
|
280
|
+
/** Sources that were already failing when `config` was built (tolerated). */
|
|
281
|
+
tolerated: Set<string>;
|
|
282
|
+
/** Last hot-reload failure (null when the most recent rebuild succeeded). */
|
|
283
|
+
reloadError: string | null;
|
|
284
|
+
/** Fingerprint a reload-failure warning was last emitted for (warn once each). */
|
|
285
|
+
warnedFingerprint: string | null;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Keyed by {@link normalizeProjectDir}. */
|
|
289
|
+
const _configCaches = new Map<string, ConfigCacheEntry>();
|
|
290
|
+
|
|
291
|
+
function getCacheEntry(key: string): ConfigCacheEntry {
|
|
292
|
+
let entry = _configCaches.get(key);
|
|
293
|
+
if (!entry) {
|
|
294
|
+
entry = {
|
|
295
|
+
config: null,
|
|
296
|
+
dirty: true,
|
|
297
|
+
fingerprint: "",
|
|
298
|
+
sourceKey: "",
|
|
299
|
+
tolerated: new Set<string>(),
|
|
300
|
+
reloadError: null,
|
|
301
|
+
warnedFingerprint: null,
|
|
302
|
+
};
|
|
303
|
+
_configCaches.set(key, entry);
|
|
304
|
+
}
|
|
305
|
+
return entry;
|
|
306
|
+
}
|
|
269
307
|
|
|
270
|
-
/**
|
|
308
|
+
/**
|
|
309
|
+
* `realpathSync` that fails soft: an unresolvable path is used as-is, which is
|
|
310
|
+
* no worse than not resolving at all.
|
|
311
|
+
*/
|
|
312
|
+
function realpathOrSelf(p: string): string {
|
|
313
|
+
try {
|
|
314
|
+
return realpathSync(p);
|
|
315
|
+
} catch {
|
|
316
|
+
return p;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Canonical form of a project directory: absolute and symlink-resolved, so the
|
|
322
|
+
* same directory reached through different spellings shares one cache entry
|
|
323
|
+
* and compares equal to the (resolved) home directory. A missing or empty `dir`
|
|
324
|
+
* means "the process working directory at call time".
|
|
325
|
+
*/
|
|
326
|
+
function normalizeProjectDir(dir?: string): string {
|
|
327
|
+
return realpathOrSelf(dir ? resolvePath(dir) : process.cwd());
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Why the last config rebuild failed for `dir` (default: the working
|
|
332
|
+
* directory), or null when it succeeded. When a source (tiers.json, an
|
|
333
|
+
* overrides file, or the state file) becomes invalid after a successful load,
|
|
334
|
+
* loadConfig() keeps serving the last valid config and records the reason here
|
|
335
|
+
* instead of throwing or silently dropping layers.
|
|
336
|
+
*/
|
|
337
|
+
export function getConfigReloadError(dir?: string): string | null {
|
|
338
|
+
return _configCaches.get(normalizeProjectDir(dir))?.reloadError ?? null;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Mark every directory's config cache as stale so it is re-read on next access. */
|
|
271
342
|
export function invalidateConfigCache(): void {
|
|
272
|
-
|
|
343
|
+
for (const entry of _configCaches.values()) entry.dirty = true;
|
|
273
344
|
}
|
|
274
345
|
|
|
275
346
|
function getPluginRoot(): string {
|
|
@@ -293,17 +364,17 @@ export function overridePath(): string {
|
|
|
293
364
|
|
|
294
365
|
/**
|
|
295
366
|
* Default location of the project-local overrides file
|
|
296
|
-
* (`.opencode/opencode-model-router.overrides.jsonc` in the
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
* file is found.
|
|
367
|
+
* (`.opencode/opencode-model-router.overrides.jsonc` in the project directory,
|
|
368
|
+
* or in the current working directory when `dir` is omitted). This is the path
|
|
369
|
+
* to *create* the file at; the actual lookup walks upward — see
|
|
370
|
+
* {@link findProjectOverride}. Used for display when no project file is found.
|
|
300
371
|
*
|
|
301
372
|
* The project file is deep-merged *after* (and therefore wins over) the global
|
|
302
373
|
* overrides file, so a team can commit a shared file that unifies routing for
|
|
303
374
|
* the project on top of each member's personal global file.
|
|
304
375
|
*/
|
|
305
|
-
export function localOverridePath(): string {
|
|
306
|
-
return join(process.cwd(), ".opencode", OVERRIDE_FILENAME);
|
|
376
|
+
export function localOverridePath(dir?: string): string {
|
|
377
|
+
return join(dir ? resolvePath(dir) : process.cwd(), ".opencode", OVERRIDE_FILENAME);
|
|
307
378
|
}
|
|
308
379
|
|
|
309
380
|
/**
|
|
@@ -323,10 +394,54 @@ const REPO_MARKERS = [".git", ".hg", ".svn"] as const;
|
|
|
323
394
|
*/
|
|
324
395
|
const MAX_WALK_DEPTH = 16;
|
|
325
396
|
|
|
397
|
+
/** errno code of a thrown fs error, or "UNKNOWN" when it carries none. */
|
|
398
|
+
function errnoCode(err: unknown): string {
|
|
399
|
+
const code = (err as NodeJS.ErrnoException | undefined)?.code;
|
|
400
|
+
return typeof code === "string" ? code : "UNKNOWN";
|
|
401
|
+
}
|
|
402
|
+
|
|
326
403
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
404
|
+
* ENOENT (nothing there) and ENOTDIR (a path component is a file) both mean the
|
|
405
|
+
* path is gone. Every other errno (EACCES, EIO, ELOOP, …) means "cannot tell",
|
|
406
|
+
* which is NOT the same as "removed".
|
|
407
|
+
*/
|
|
408
|
+
function isGoneError(err: unknown): boolean {
|
|
409
|
+
const code = errnoCode(err);
|
|
410
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** A stat that failed for a reason other than the path being gone. */
|
|
414
|
+
interface StatFailure {
|
|
415
|
+
code: string;
|
|
416
|
+
message: string;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Outcome of looking at a config source: it is there, it is definitely gone, or
|
|
421
|
+
* it could not be inspected. Unlike `existsSync` — which folds every error into
|
|
422
|
+
* `false` — this keeps "removed" and "unreachable" apart, so a transient I/O
|
|
423
|
+
* error or a directory that lost search permission is never mistaken for the
|
|
424
|
+
* user deleting the file.
|
|
425
|
+
*/
|
|
426
|
+
type StatKind = "present" | "missing" | StatFailure;
|
|
427
|
+
|
|
428
|
+
function statKind(p: string): StatKind {
|
|
429
|
+
try {
|
|
430
|
+
statSync(p);
|
|
431
|
+
return "present";
|
|
432
|
+
} catch (err) {
|
|
433
|
+
if (isGoneError(err)) return "missing";
|
|
434
|
+
return { code: errnoCode(err), message: (err as Error).message };
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Locate the project-local overrides file by walking upward from `dir` (the
|
|
440
|
+
* host-provided project directory), so the project config is found even when
|
|
441
|
+
* opencode is launched from a subdirectory. When `dir` is omitted the walk
|
|
442
|
+
* starts at the process working directory; hosts that change the working
|
|
443
|
+
* directory away from the project (OpenCode v2 server mode chdirs to $HOME)
|
|
444
|
+
* must pass the project directory explicitly.
|
|
330
445
|
*
|
|
331
446
|
* The walk stops at the first of these, whichever comes first:
|
|
332
447
|
* - an ancestor containing a repo marker (`.git`, `.hg`, `.svn`), after
|
|
@@ -340,28 +455,34 @@ const MAX_WALK_DEPTH = 16;
|
|
|
340
455
|
* tree with no repo marker anywhere would otherwise be walked all the way to the
|
|
341
456
|
* filesystem root, silently adopting an unrelated ancestor's override file.
|
|
342
457
|
* Returns the resolved path, or undefined when no file applies.
|
|
458
|
+
*
|
|
459
|
+
* Only ENOENT/ENOTDIR count as "no file here". A candidate that cannot be
|
|
460
|
+
* inspected for any other reason (EACCES on a parent directory, a transient
|
|
461
|
+
* I/O error) is still returned and ends the walk — the nearest override wins,
|
|
462
|
+
* so it must not be skipped in favour of an ancestor's file — and the later
|
|
463
|
+
* read reports it as a failure instead of the source silently vanishing. A
|
|
464
|
+
* repo marker that cannot be inspected is likewise treated as present, so the
|
|
465
|
+
* walk never climbs past a project root it merely failed to stat.
|
|
343
466
|
*/
|
|
344
|
-
export function findProjectOverride(): string | undefined {
|
|
467
|
+
export function findProjectOverride(dir?: string): string | undefined {
|
|
468
|
+
return walkForProjectOverride(normalizeProjectDir(dir));
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** `startDir` must already be normalized (see {@link normalizeProjectDir}). */
|
|
472
|
+
function walkForProjectOverride(startDir: string): string | undefined {
|
|
345
473
|
// Both sides of the $HOME comparison below have to be resolved the same way.
|
|
346
474
|
// process.cwd() returns a realpath, while homedir() returns $HOME verbatim, so
|
|
347
475
|
// on any system where $HOME contains a symlinked component (macOS temp dirs,
|
|
348
476
|
// containers, some NFS homes) a raw string compare never matches and the home
|
|
349
|
-
// boundary silently stops applying.
|
|
350
|
-
//
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
} catch {
|
|
355
|
-
return p;
|
|
356
|
-
}
|
|
357
|
-
};
|
|
358
|
-
|
|
359
|
-
let dir = resolve(process.cwd());
|
|
360
|
-
const home = resolve(homedir());
|
|
477
|
+
// boundary silently stops applying. A host-provided project directory gets
|
|
478
|
+
// the same treatment (normalizeProjectDir). Fail soft: an unresolvable path
|
|
479
|
+
// is used as-is, which is no worse than not comparing at all.
|
|
480
|
+
let dir = startDir;
|
|
481
|
+
const home = realpathOrSelf(homedir());
|
|
361
482
|
let depth = 0;
|
|
362
483
|
|
|
363
484
|
for (;;) {
|
|
364
|
-
const hasMarker = REPO_MARKERS.some((m) =>
|
|
485
|
+
const hasMarker = REPO_MARKERS.some((m) => statKind(join(dir, m)) !== "missing");
|
|
365
486
|
|
|
366
487
|
// $HOME is not a project directory. Only look inside it when it is itself a
|
|
367
488
|
// repo root (a dotfiles repo), otherwise `~/.opencode/…` would be picked up
|
|
@@ -369,7 +490,7 @@ export function findProjectOverride(): string | undefined {
|
|
|
369
490
|
if (dir === home && !hasMarker) return undefined;
|
|
370
491
|
|
|
371
492
|
const candidate = join(dir, ".opencode", OVERRIDE_FILENAME);
|
|
372
|
-
if (
|
|
493
|
+
if (statKind(candidate) !== "missing") return candidate;
|
|
373
494
|
|
|
374
495
|
if (hasMarker) return undefined; // reached the project root, no file
|
|
375
496
|
if (dir === home) return undefined; // home was a repo root; never go above it
|
|
@@ -1179,38 +1300,58 @@ export function deepMerge(base: unknown, override: unknown): unknown {
|
|
|
1179
1300
|
* overrides file can never brick opencode startup — but the user still gets a
|
|
1180
1301
|
* visible reason why their override was ignored.
|
|
1181
1302
|
*/
|
|
1182
|
-
function readOverridesAt(
|
|
1303
|
+
function readOverridesAt(
|
|
1304
|
+
op: string,
|
|
1305
|
+
failures?: SourceFailure[],
|
|
1306
|
+
): Record<string, unknown> | undefined {
|
|
1307
|
+
// Only ENOENT/ENOTDIR mean the file is absent. Any other stat error (EACCES on
|
|
1308
|
+
// a parent directory, a transient I/O error) is a failure, never a removal —
|
|
1309
|
+
// otherwise a reload would swap the last valid config for lower-priority
|
|
1310
|
+
// defaults.
|
|
1311
|
+
const kind = statKind(op);
|
|
1312
|
+
if (kind === "missing") return undefined;
|
|
1313
|
+
|
|
1183
1314
|
let text: string;
|
|
1184
1315
|
try {
|
|
1185
|
-
if (
|
|
1316
|
+
if (kind !== "present") throw new Error(kind.message);
|
|
1186
1317
|
text = readFileSync(op, "utf-8");
|
|
1187
1318
|
} catch (err) {
|
|
1188
1319
|
// The file is there but unreadable (permissions, a dangling symlink, a
|
|
1189
1320
|
// race with a delete). Every other failure below says so; staying silent
|
|
1190
1321
|
// here makes an unreadable override look exactly like an absent one.
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
);
|
|
1322
|
+
const reason = `cannot read it — ${(err as Error).message}`;
|
|
1323
|
+
console.warn(`[model-router] ignoring ${op}: ${reason}`);
|
|
1324
|
+
failures?.push({ source: op, message: `${op}: ${reason}` });
|
|
1194
1325
|
return undefined;
|
|
1195
1326
|
}
|
|
1196
1327
|
|
|
1197
1328
|
try {
|
|
1198
1329
|
const parsed = parseJsonc(text) as unknown;
|
|
1199
1330
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
);
|
|
1331
|
+
const reason = "expected a JSON object at root";
|
|
1332
|
+
console.warn(`[model-router] ignoring ${op}: ${reason}`);
|
|
1333
|
+
failures?.push({ source: op, message: `${op}: ${reason}` });
|
|
1203
1334
|
return undefined;
|
|
1204
1335
|
}
|
|
1205
1336
|
return parsed as Record<string, unknown>;
|
|
1206
1337
|
} catch (err) {
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
);
|
|
1338
|
+
const reason = `invalid JSONC — ${(err as Error).message}`;
|
|
1339
|
+
console.warn(`[model-router] ignoring ${op}: ${reason}`);
|
|
1340
|
+
failures?.push({ source: op, message: `${op}: ${reason}` });
|
|
1210
1341
|
return undefined;
|
|
1211
1342
|
}
|
|
1212
1343
|
}
|
|
1213
1344
|
|
|
1345
|
+
/**
|
|
1346
|
+
* A source that exists on disk but could not be used while building the
|
|
1347
|
+
* config. `source` is a stable key (a file path, or the joined layer paths for
|
|
1348
|
+
* a combined-merge failure); `message` is the user-facing reason.
|
|
1349
|
+
*/
|
|
1350
|
+
interface SourceFailure {
|
|
1351
|
+
source: string;
|
|
1352
|
+
message: string;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1214
1355
|
/**
|
|
1215
1356
|
* The ordered override layers (lowest priority first): global, then
|
|
1216
1357
|
* project-local. Each present, well-formed file becomes a layer that is
|
|
@@ -1221,13 +1362,14 @@ export interface OverrideLayer {
|
|
|
1221
1362
|
data: Record<string, unknown>;
|
|
1222
1363
|
}
|
|
1223
1364
|
|
|
1224
|
-
function collectOverrideLayers(): OverrideLayer[] {
|
|
1365
|
+
function collectOverrideLayers(dir: string, failures?: SourceFailure[]): OverrideLayer[] {
|
|
1225
1366
|
const layers: OverrideLayer[] = [];
|
|
1226
|
-
// Lowest priority first: global, then project-local (found by upward search
|
|
1227
|
-
|
|
1367
|
+
// Lowest priority first: global, then project-local (found by upward search
|
|
1368
|
+
// from the project directory).
|
|
1369
|
+
const paths = [overridePath(), walkForProjectOverride(dir)];
|
|
1228
1370
|
for (const p of paths) {
|
|
1229
1371
|
if (!p) continue;
|
|
1230
|
-
const data = readOverridesAt(p);
|
|
1372
|
+
const data = readOverridesAt(p, failures);
|
|
1231
1373
|
if (data) layers.push({ path: p, data });
|
|
1232
1374
|
}
|
|
1233
1375
|
return layers;
|
|
@@ -1261,13 +1403,132 @@ function applyTierDefaults(cfg: RouterConfig): void {
|
|
|
1261
1403
|
}
|
|
1262
1404
|
}
|
|
1263
1405
|
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1406
|
+
/**
|
|
1407
|
+
* Every file location that feeds loadConfig() for the (normalized) project
|
|
1408
|
+
* directory `dir` (undefined = none applicable).
|
|
1409
|
+
*/
|
|
1410
|
+
function sourcePaths(dir: string): Array<string | undefined> {
|
|
1411
|
+
return [configPath(), overridePath(), walkForProjectOverride(dir), statePath()];
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
/**
|
|
1415
|
+
* mtime/ctime/size fingerprint of every file that feeds loadConfig(). ctime is
|
|
1416
|
+
* included because restoring access to a previously unreadable file (chmod)
|
|
1417
|
+
* changes ctime but not mtime/size, and that must trigger a retry. Only
|
|
1418
|
+
* ENOENT/ENOTDIR map to `missing` (removal); any other stat error maps to
|
|
1419
|
+
* `error:<code>`, a distinct marker, so losing access to a file is never
|
|
1420
|
+
* fingerprinted — or reloaded — as if it had been deleted.
|
|
1421
|
+
*/
|
|
1422
|
+
function sourceFingerprint(paths: Array<string | undefined>): string {
|
|
1423
|
+
return paths
|
|
1424
|
+
.map((p) => {
|
|
1425
|
+
if (!p) return "none";
|
|
1426
|
+
try {
|
|
1427
|
+
const st = statSync(p);
|
|
1428
|
+
return `${p}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
|
|
1429
|
+
} catch (err) {
|
|
1430
|
+
return isGoneError(err) ? `${p}:missing` : `${p}:error:${errnoCode(err)}`;
|
|
1431
|
+
}
|
|
1432
|
+
})
|
|
1433
|
+
.join("|");
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
/**
|
|
1437
|
+
* Load the effective config for the project directory `dir` (the host-provided
|
|
1438
|
+
* project dir; defaults to the process working directory). Each directory has
|
|
1439
|
+
* its own cache entry, so several project instances sharing one process never
|
|
1440
|
+
* see or overwrite each other's config.
|
|
1441
|
+
*/
|
|
1442
|
+
export function loadConfig(dir?: string): RouterConfig {
|
|
1443
|
+
const projectDir = normalizeProjectDir(dir);
|
|
1444
|
+
const entry = getCacheEntry(projectDir);
|
|
1445
|
+
const paths = sourcePaths(projectDir);
|
|
1446
|
+
const fingerprint = sourceFingerprint(paths);
|
|
1447
|
+
if (entry.config && !entry.dirty && fingerprint === entry.fingerprint) {
|
|
1448
|
+
return entry.config;
|
|
1267
1449
|
}
|
|
1268
1450
|
|
|
1451
|
+
// A previous config is only a valid fallback when it was built for the same
|
|
1452
|
+
// project identity: HOME + the normalized project dir (the cache key) + the
|
|
1453
|
+
// state path. Deliberately NOT the resolved override file paths: a project
|
|
1454
|
+
// override created after startup must not turn a broken file into a
|
|
1455
|
+
// tolerated "first load".
|
|
1456
|
+
const sourceKey = [homedir(), projectDir, statePath()].join("|");
|
|
1457
|
+
const previous =
|
|
1458
|
+
entry.config !== null && sourceKey === entry.sourceKey ? entry.config : null;
|
|
1459
|
+
|
|
1460
|
+
const failures: SourceFailure[] = [];
|
|
1461
|
+
let cfg: RouterConfig;
|
|
1462
|
+
try {
|
|
1463
|
+
cfg = buildConfig(projectDir, failures);
|
|
1464
|
+
} catch (err) {
|
|
1465
|
+
// First load: unchanged behaviour — throw. Reload: keep the last good one.
|
|
1466
|
+
if (!previous) throw err;
|
|
1467
|
+
return keepLastValidConfig(
|
|
1468
|
+
entry,
|
|
1469
|
+
previous,
|
|
1470
|
+
fingerprint,
|
|
1471
|
+
`${configPath()}: ${(err as Error).message}`,
|
|
1472
|
+
);
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
if (previous) {
|
|
1476
|
+
// Sources that were already failing when `previous` was built are an
|
|
1477
|
+
// accepted state (e.g. a broken override at startup); only a source that
|
|
1478
|
+
// newly broke counts as a failed reload.
|
|
1479
|
+
const regressions = failures.filter((f) => !entry.tolerated.has(f.source));
|
|
1480
|
+
if (regressions.length > 0) {
|
|
1481
|
+
return keepLastValidConfig(
|
|
1482
|
+
entry,
|
|
1483
|
+
previous,
|
|
1484
|
+
fingerprint,
|
|
1485
|
+
regressions.map((f) => f.message).join("\n"),
|
|
1486
|
+
);
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
entry.config = cfg;
|
|
1491
|
+
entry.fingerprint = fingerprint;
|
|
1492
|
+
entry.sourceKey = sourceKey;
|
|
1493
|
+
entry.tolerated = new Set(failures.map((f) => f.source));
|
|
1494
|
+
entry.dirty = false;
|
|
1495
|
+
entry.reloadError = null;
|
|
1496
|
+
entry.warnedFingerprint = null;
|
|
1497
|
+
return cfg;
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/**
|
|
1501
|
+
* Reload failed: keep serving `previous` (same object reference), remember the
|
|
1502
|
+
* fingerprint so we do not retry on every message until a file changes (or
|
|
1503
|
+
* invalidateConfigCache() is called), record the reason, and warn once per
|
|
1504
|
+
* failed fingerprint. All state lives on the directory's own cache `entry`.
|
|
1505
|
+
*/
|
|
1506
|
+
function keepLastValidConfig(
|
|
1507
|
+
entry: ConfigCacheEntry,
|
|
1508
|
+
previous: RouterConfig,
|
|
1509
|
+
fingerprint: string,
|
|
1510
|
+
message: string,
|
|
1511
|
+
): RouterConfig {
|
|
1512
|
+
entry.fingerprint = fingerprint;
|
|
1513
|
+
entry.dirty = false;
|
|
1514
|
+
entry.reloadError = message;
|
|
1515
|
+
if (entry.warnedFingerprint !== fingerprint) {
|
|
1516
|
+
entry.warnedFingerprint = fingerprint;
|
|
1517
|
+
console.warn(
|
|
1518
|
+
`[model-router] config reload failed — keeping last valid config: ${message}`,
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
return previous;
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
/**
|
|
1525
|
+
* Build a fresh config from tiers.json + override layers + persisted state.
|
|
1526
|
+
* Throws only when tiers.json itself is unreadable/invalid. Override and state
|
|
1527
|
+
* problems are warned about, skipped, and appended to `failures`.
|
|
1528
|
+
*/
|
|
1529
|
+
function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
|
|
1269
1530
|
const base = JSON.parse(readFileSync(configPath(), "utf-8"));
|
|
1270
|
-
const layers = collectOverrideLayers();
|
|
1531
|
+
const layers = collectOverrideLayers(dir, failures);
|
|
1271
1532
|
|
|
1272
1533
|
// Bundled config must be valid on its own — throw otherwise (unchanged
|
|
1273
1534
|
// behaviour). Override layers are then applied on top.
|
|
@@ -1287,6 +1548,11 @@ export function loadConfig(): RouterConfig {
|
|
|
1287
1548
|
console.warn(
|
|
1288
1549
|
`[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
|
|
1289
1550
|
);
|
|
1551
|
+
const layerPaths = layers.map((l) => l.path).join(" + ");
|
|
1552
|
+
failures.push({
|
|
1553
|
+
source: layerPaths,
|
|
1554
|
+
message: `${layerPaths}: combined overrides are invalid — ${(err as Error).message}`,
|
|
1555
|
+
});
|
|
1290
1556
|
for (let i = layers.length - 1; i >= 0; i--) {
|
|
1291
1557
|
try {
|
|
1292
1558
|
cfg = validateConfig(merge([layers[i]!]));
|
|
@@ -1300,6 +1566,10 @@ export function loadConfig(): RouterConfig {
|
|
|
1300
1566
|
console.warn(
|
|
1301
1567
|
`[model-router] ignoring ${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
1302
1568
|
);
|
|
1569
|
+
failures.push({
|
|
1570
|
+
source: layers[i]!.path,
|
|
1571
|
+
message: `${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
1572
|
+
});
|
|
1303
1573
|
cfg = validateConfig(base);
|
|
1304
1574
|
}
|
|
1305
1575
|
}
|
|
@@ -1307,7 +1577,12 @@ export function loadConfig(): RouterConfig {
|
|
|
1307
1577
|
}
|
|
1308
1578
|
|
|
1309
1579
|
try {
|
|
1310
|
-
|
|
1580
|
+
const stateKind = statKind(statePath());
|
|
1581
|
+
if (stateKind !== "missing") {
|
|
1582
|
+
// Present-but-uninspectable (EACCES, EIO, …) is a failure, not an absent
|
|
1583
|
+
// state file: reverting the persisted preset on a transient error would
|
|
1584
|
+
// be silent data loss.
|
|
1585
|
+
if (stateKind !== "present") throw new Error(`cannot read it — ${stateKind.message}`);
|
|
1311
1586
|
const state = JSON.parse(
|
|
1312
1587
|
readFileSync(statePath(), "utf-8"),
|
|
1313
1588
|
) as RouterState;
|
|
@@ -1324,14 +1599,17 @@ export function loadConfig(): RouterConfig {
|
|
|
1324
1599
|
cfg.enforcement = { ...(cfg.enforcement ?? {}), mode: state.enforcementMode };
|
|
1325
1600
|
}
|
|
1326
1601
|
}
|
|
1327
|
-
} catch {
|
|
1328
|
-
//
|
|
1602
|
+
} catch (err) {
|
|
1603
|
+
// State read errors never block startup: keep tiers.json defaults. They are
|
|
1604
|
+
// recorded so a state file that breaks on a later reload is reported (and
|
|
1605
|
+
// the last valid config kept) rather than silently reverting the preset.
|
|
1606
|
+
failures.push({
|
|
1607
|
+
source: statePath(),
|
|
1608
|
+
message: `${statePath()}: ${(err as Error).message}`,
|
|
1609
|
+
});
|
|
1329
1610
|
}
|
|
1330
1611
|
|
|
1331
1612
|
applyTierDefaults(cfg);
|
|
1332
|
-
|
|
1333
|
-
_cachedConfig = cfg;
|
|
1334
|
-
_configDirty = false;
|
|
1335
1613
|
return cfg;
|
|
1336
1614
|
}
|
|
1337
1615
|
|
package/tiers.json
CHANGED
|
@@ -288,6 +288,49 @@
|
|
|
288
288
|
]
|
|
289
289
|
}
|
|
290
290
|
},
|
|
291
|
+
"hybrid-2": {
|
|
292
|
+
"fast": {
|
|
293
|
+
"model": "openai/gpt-6-luna-fast",
|
|
294
|
+
"variant": "medium",
|
|
295
|
+
"costRatio": 1,
|
|
296
|
+
"description": "GPT 6 Luna (medium) for exploration, search, and simple reads",
|
|
297
|
+
"steps": 30,
|
|
298
|
+
"whenToUse": [
|
|
299
|
+
"Codebase exploration and search",
|
|
300
|
+
"Simple file reads and listing",
|
|
301
|
+
"Grep/glob operations",
|
|
302
|
+
"Quick lookups and research"
|
|
303
|
+
]
|
|
304
|
+
},
|
|
305
|
+
"medium": {
|
|
306
|
+
"model": "anthropic/claude-sonnet-5-5",
|
|
307
|
+
"variant": "xhigh",
|
|
308
|
+
"effort": "xhigh",
|
|
309
|
+
"costRatio": 5,
|
|
310
|
+
"description": "Claude Sonnet (xhigh) for implementation and standard coding",
|
|
311
|
+
"steps": 50,
|
|
312
|
+
"whenToUse": [
|
|
313
|
+
"Feature implementation",
|
|
314
|
+
"Refactoring",
|
|
315
|
+
"Writing tests",
|
|
316
|
+
"Bug fixes"
|
|
317
|
+
]
|
|
318
|
+
},
|
|
319
|
+
"heavy": {
|
|
320
|
+
"model": "anthropic/claude-opus-5-5",
|
|
321
|
+
"variant": "xhigh",
|
|
322
|
+
"effort": "xhigh",
|
|
323
|
+
"costRatio": 20,
|
|
324
|
+
"description": "Claude Opus 5.5 xhigh for architecture, complex debugging, and security",
|
|
325
|
+
"steps": 120,
|
|
326
|
+
"whenToUse": [
|
|
327
|
+
"Architecture decisions",
|
|
328
|
+
"Complex debugging (after 2+ failures)",
|
|
329
|
+
"Security review",
|
|
330
|
+
"Performance optimization"
|
|
331
|
+
]
|
|
332
|
+
}
|
|
333
|
+
},
|
|
291
334
|
"fable-effort": {
|
|
292
335
|
"fast": {
|
|
293
336
|
"model": "anthropic/claude-fable-5-1",
|