opencode-model-router 1.9.0 → 1.10.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 CHANGED
@@ -5,6 +5,66 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.10.0] - 2026-08-20
9
+
10
+ Minor release. Config errors are caught at load instead of drifting to a later turn,
11
+ the logging path 1.9.0 introduced is finished — it was losing messages entirely in
12
+ short-lived processes, and one warning had never been routed through it at all — and
13
+ there is now a smoke lane that needs no credential and therefore actually runs.
14
+
15
+ ### Added
16
+
17
+ - **A credential-free smoke lane, running on every push.** `opencode debug agent`
18
+ loads the plugin, runs the `config` hook, resolves overrides and registers agents
19
+ with no API key and no model call, so an end-to-end check of registration costs
20
+ ~20s. The existing smoke lane is gated on secrets, which made it a green no-op on
21
+ forks — and meant the only test covering the `config` hook had been asserting the
22
+ pre-1.8.0 anthropic preset for a whole release without anyone finding out. Those
23
+ pins are repaired, and the new lane asserts that **stderr is empty**, which is
24
+ coverage unit tests structurally cannot provide: they hand the plugin a stub client,
25
+ so they have neither a real SDK receiver nor a real process's stderr to check.
26
+
27
+ - **A malformed tier `model` is rejected when the config loads, not on some later
28
+ turn.** `"model": "claude-sonnet-5"` — a ref missing its provider — used to validate
29
+ clean and only surface as a catalog issue on a turn that happened to have the catalog
30
+ in hand, or never, if the fetch failed. The `provider/model` shape needs no network,
31
+ so it is now decided at load, alongside the existing `effort` and `promptStyle`
32
+ checks. `parseModelRef` moved to `config.ts` (re-exported from `catalog.ts`) so load
33
+ validation and catalog lookup share one definition of well-formed: passing the first
34
+ now guarantees parsing in the second. Observed by @MetalbolicX in
35
+ [#17](https://github.com/marco-jardim/opencode-model-router/issues/17); implementation
36
+ is independent of the fork's.
37
+
38
+ Behaviour change for an existing malformed config: an overrides file carrying a bad
39
+ ref is now dropped with a warning naming the offending value, and the bundled
40
+ defaults stand. Startup is never blocked — the layer-drop path already guaranteed
41
+ that, and there is now a test pinning it for this case specifically.
42
+
43
+ ### Fixed
44
+
45
+ - **The orphaned-pattern warning no longer suggests a fix that cannot apply.** It still
46
+ told the user a provider rename was the likely cause and to update
47
+ `modelGenerations.strong` to match. Since 1.9.0 normalizes separators, a rename is
48
+ matched rather than orphaned, so the only way to reach the warning is a user-authored
49
+ pattern naming something genuinely absent. The copy now says that and forecloses the
50
+ separator fix explicitly.
51
+
52
+ - **Passive warnings are no longer lost in short-lived processes.** 1.9.0 sent them to
53
+ opencode's log fire-and-forget, which is right for a hook — a warning must never
54
+ block one — but in `opencode run` or `opencode debug` the post never settled before
55
+ the process exited, and the console fallback never fired because nothing had failed.
56
+ The warning reached neither the log nor the terminal. The plugin API has
57
+ `dispose?: () => Promise<void>`, and opencode calls *and awaits* it even on a
58
+ two-second run, so the logger now tracks in-flight posts and `dispose` drains them.
59
+ The tracked promise is the already-`catch`-wrapped one, so a failing post can never
60
+ reject out of teardown. ([#36](https://github.com/marco-jardim/opencode-model-router/issues/36))
61
+
62
+ - **The `opencode-anthropic-fix` dependency notice reaches the log instead of the
63
+ terminal.** 1.9.0 routed five of the six `warnAgentOptionsEffortOnce` call sites
64
+ through the logger and missed the one in `index.ts`, so that warning kept writing to
65
+ stderr — the exact symptom the change existed to remove. Found by running a real
66
+ process, not by a test; there is now a test.
67
+
8
68
  ## [1.9.0] - 2026-08-20
9
69
 
10
70
  Minor release. One real bug — prompt-style resolution broke when a provider renamed a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -9,6 +9,7 @@
9
9
  "test:watch": "vitest",
10
10
  "test:coverage": "vitest run --coverage",
11
11
  "smoke": "cross-env RUN_OC_SMOKE=1 vitest run --config vitest.smoke.config.ts test/smoke",
12
+ "smoke:keyless": "cross-env RUN_OC_SMOKE_KEYLESS=1 vitest run --config vitest.smoke.config.ts test/smoke/registration.smoke.test.ts test/smoke/subagent-tiers.smoke.test.ts",
12
13
  "typecheck": "tsc --noEmit"
13
14
  },
14
15
  "license": "GPL-3.0-only",
@@ -284,8 +284,9 @@ export function buildModelsOutput(
284
284
  }
285
285
 
286
286
  /**
287
- * Render strong-model patterns that match no model in the active preset (see
288
- * `findOrphanedStrongPatterns`). Report-only — the router never edits the
287
+ * Render strong-model patterns that match no model the configured providers
288
+ * serve (see `findOrphanedStrongPatterns`). Only ever user-authored patterns:
289
+ * shipped defaults are not reported. Report-only — the router never edits the
289
290
  * user's pattern list.
290
291
  */
291
292
  export function formatOrphanedStrongPatterns(patterns: string[]): string {
@@ -293,7 +294,7 @@ export function formatOrphanedStrongPatterns(patterns: string[]): string {
293
294
  "⚠ **Strong-model patterns matching no model your providers serve:**",
294
295
  ...patterns.map((p) => `- \`${p}\``),
295
296
  "",
296
- "This may silently change prompt-style resolution for tiers on `promptStyle: auto`. If a provider renamed a model, update `modelGenerations.strong` in your overrides file (`/router overrides`).",
297
+ "You set these in `modelGenerations.strong`, so they decide nothing here and tiers on `promptStyle: auto` resolve without them. Matching already ignores case and separator style, so `opus-4-8` finds `opus-4.8` — a pattern listed above is absent, not merely spelled differently. Fix or drop it in your overrides file (`/router overrides`).",
297
298
  ].join("\n");
298
299
  }
299
300
 
package/src/index.ts CHANGED
@@ -326,6 +326,13 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
326
326
  process.env.MODEL_ROUTER_VERIFIED_DELEGATE === "1";
327
327
 
328
328
  return {
329
+ // Warnings post to /log fire-and-forget, which loses the message when the
330
+ // process is about to exit — `opencode run` and `opencode debug` are short
331
+ // enough for that to be the normal case. Verified against opencode 1.18.16
332
+ // that dispose is both called and awaited, so flushing here is enough.
333
+ dispose: async () => {
334
+ await logger.flush();
335
+ },
329
336
  tool: {
330
337
  ...(enableDelegateTool ? { delegate: tool({
331
338
  description:
@@ -727,13 +734,15 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
727
734
  catalogWarned = true;
728
735
  const catalog = deferredCatalog;
729
736
  if (catalog) {
730
- // Strong-model patterns matching nothing any configured provider
731
- // serves, which can silently flip prompt-style resolution for
732
- // tiers on auto. Catalog-dependent, so it rides the same deferred
733
- // path — it is NOT emitted on turn 1.
737
+ // User-authored strong-model patterns matching nothing any
738
+ // configured provider serves. Shipped defaults are never reported
739
+ // (see findOrphanedStrongPatterns), so reaching here means the
740
+ // user wrote a claim about this environment that is false.
741
+ // Catalog-dependent, so it rides the same deferred path — it is
742
+ // NOT emitted on turn 1.
734
743
  for (const p of findOrphanedStrongPatterns(cfg, catalog)) {
735
744
  logger.warn(
736
- `strong-model pattern '${p}' matches no model your providers serve — may silently change prompt-style resolution for tiers on auto`,
745
+ `strong-model pattern '${p}' from your modelGenerations.strong matches no model your providers serve, so it decides nothing — separator style is already ignored when matching`,
737
746
  { pattern: p },
738
747
  );
739
748
  }
@@ -1036,6 +1045,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1036
1045
  warnAgentOptionsEffortOnce(
1037
1046
  "anthropic-effort-dependency",
1038
1047
  "effort on Anthropic models requires the opencode-anthropic-fix plugin (commit 307aea9+ for fable/mythos); non-adaptive Claude models (e.g. haiku) silently strip effort at the API layer, and without the plugin a top-level effort can break Claude-Code billing fingerprinting",
1048
+ logger,
1039
1049
  );
1040
1050
  }
1041
1051
 
@@ -5,7 +5,11 @@
5
5
  // raw payload is handed here for normalization and analysis.
6
6
  // ---------------------------------------------------------------------------
7
7
 
8
- import { DEFAULT_STRONG_MODEL_PATTERNS, type RouterConfig } from "./config";
8
+ import {
9
+ DEFAULT_STRONG_MODEL_PATTERNS,
10
+ parseModelRef,
11
+ type RouterConfig,
12
+ } from "./config";
9
13
  import { flattenModelID } from "./prompts";
10
14
  import { getActiveTiers } from "./protocol";
11
15
 
@@ -80,17 +84,12 @@ export function isCatalogEmpty(catalog: Catalog): boolean {
80
84
  }
81
85
 
82
86
  /**
83
- * Split a tier model reference (`"provider/model"`) into its parts. Splits on
84
- * the FIRST slash only, so multi-segment model ids (e.g.
85
- * `openrouter/deepseek/deepseek-v3.2`) keep their full model id.
87
+ * Re-exported from config.ts, where it lives because the `provider/model` shape
88
+ * is a property of the config format rather than of the catalog. Config load
89
+ * rejects a ref this cannot parse, so by the time a ref reaches the lookups
90
+ * below it has already been through the same function.
86
91
  */
87
- export function parseModelRef(
88
- ref: string,
89
- ): { providerId: string; modelId: string } | undefined {
90
- const i = ref.indexOf("/");
91
- if (i <= 0 || i === ref.length - 1) return undefined;
92
- return { providerId: ref.slice(0, i), modelId: ref.slice(i + 1) };
93
- }
92
+ export { parseModelRef };
94
93
 
95
94
  function findProvider(
96
95
  catalog: Catalog,
@@ -338,6 +338,25 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
338
338
  return typeof v === "object" && v !== null && !Array.isArray(v);
339
339
  }
340
340
 
341
+ /**
342
+ * Split a tier model reference (`"provider/model"`) into its parts. Splits on
343
+ * the FIRST slash only, so multi-segment model ids (e.g.
344
+ * `openrouter/deepseek/deepseek-v3.2`) keep their full model id.
345
+ *
346
+ * Lives here rather than in catalog.ts because the `provider/model` shape is a
347
+ * property of the config format, not of the catalog. Config load and catalog
348
+ * lookup have to agree on what a well-formed ref is; sharing one function is
349
+ * what makes "it validated at load" mean "it will parse later". catalog.ts
350
+ * re-exports it so the reference is still reachable from where it is used.
351
+ */
352
+ export function parseModelRef(
353
+ ref: string,
354
+ ): { providerId: string; modelId: string } | undefined {
355
+ const i = ref.indexOf("/");
356
+ if (i <= 0 || i === ref.length - 1) return undefined;
357
+ return { providerId: ref.slice(0, i), modelId: ref.slice(i + 1) };
358
+ }
359
+
341
360
  /**
342
361
  * Shape of every preset and every tier within it. Returns the presets map so
343
362
  * the caller can hand it to validateActivePreset without re-narrowing.
@@ -372,6 +391,18 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
372
391
  `tiers.json: '${presetName}.${tierName}.model' must be a non-empty string`,
373
392
  );
374
393
  }
394
+ // Same reasoning as effort and promptStyle below, one step earlier: a ref
395
+ // missing its provider (`claude-sonnet-5`) or missing its model
396
+ // (`anthropic/`) used to load clean and only surface much later, as a
397
+ // catalog issue on a turn that happened to fetch the catalog — or never,
398
+ // if the fetch failed. The shape is knowable without the network, so it
399
+ // is decided here. parseModelRef is the same function the catalog lookup
400
+ // uses, so passing this guarantees the ref parses there too.
401
+ if (!parseModelRef(t.model)) {
402
+ throw new Error(
403
+ `tiers.json: '${presetName}.${tierName}.model' must be 'provider/model' (got '${t.model}')`,
404
+ );
405
+ }
375
406
  if (t.description !== undefined && typeof t.description !== "string") {
376
407
  throw new Error(
377
408
  `tiers.json: '${presetName}.${tierName}.description' must be a string`,
@@ -26,10 +26,29 @@
26
26
  * 2. `App.log` defaults to `ThrowOnError = false`, so an HTTP failure RESOLVES
27
27
  * as `{ data: undefined, error }` instead of rejecting. A bare `.catch()`
28
28
  * sees nothing on a 400, so the settled value is inspected as well.
29
+ * 3. Fire-and-forget loses the message outright when the process is about to
30
+ * exit: the post never settles, and the fallback never runs because nothing
31
+ * failed. A long-lived server never notices; `opencode run` and `opencode
32
+ * debug` are short-lived and would go silent, which is strictly worse than
33
+ * the stderr write this file exists to avoid. Hence `flush()`, awaited from
34
+ * the plugin's `dispose` hook. Verified against a live opencode 1.18.16:
35
+ * `dispose` is both called and awaited on `opencode debug agent`.
36
+ *
37
+ * One thing to know before debugging this: the `service` tag is a namespace,
38
+ * not a rendered field. Entries land as
39
+ * `timestamp=... level=WARN run=... message="..." <extra keys>` with no
40
+ * `service=` anywhere, so grepping opencode's log for `service=model-router`
41
+ * finds nothing even when the entry is there. Match on the message text.
29
42
  */
30
43
 
31
44
  export interface PluginLogger {
32
45
  warn(message: string, extra?: Record<string, unknown>): void;
46
+ /**
47
+ * Await every post still in flight, so a shutting-down process does not drop
48
+ * warnings it already decided to emit. Never rejects: a failing flush must
49
+ * not be the thing that breaks teardown.
50
+ */
51
+ flush(): Promise<void>;
33
52
  }
34
53
 
35
54
  /** The service tag on every entry, so entries are greppable by origin. */
@@ -86,9 +105,15 @@ export function createPluginLogger(client?: unknown): PluginLogger {
86
105
  warn(message) {
87
106
  console.warn(`${CONSOLE_PREFIX} ${message}`);
88
107
  },
108
+ // console.warn is synchronous, so there is never anything to wait for.
109
+ flush: () => Promise.resolve(),
89
110
  };
90
111
  }
91
112
 
113
+ // Posts still in flight. Entries remove themselves once settled, so this
114
+ // stays bounded on a long-lived server rather than growing for its lifetime.
115
+ const inFlight = new Set<Promise<void>>();
116
+
92
117
  return {
93
118
  warn(message, extra) {
94
119
  const toConsole = () => console.warn(`${CONSOLE_PREFIX} ${message}`);
@@ -112,11 +137,20 @@ export function createPluginLogger(client?: unknown): PluginLogger {
112
137
  // Fire-and-forget: never await, but never leave a rejection unhandled
113
138
  // either, and do not lose the diagnostic when the post fails — whether it
114
139
  // fails by rejecting or by resolving with an error. See (2) above.
115
- void Promise.resolve(result)
116
- .then((settled) => {
117
- if (isErrorResult(settled)) toConsole();
140
+ const settled: Promise<void> = Promise.resolve(result)
141
+ .then((value) => {
142
+ if (isErrorResult(value)) toConsole();
118
143
  })
119
144
  .catch(toConsole);
145
+ // Tracked so `flush` can wait for it. `settled` already absorbs its own
146
+ // failures, so nothing here can reject. See (3) above.
147
+ inFlight.add(settled);
148
+ void settled.finally(() => {
149
+ inFlight.delete(settled);
150
+ });
151
+ },
152
+ async flush() {
153
+ await Promise.allSettled([...inFlight]);
120
154
  },
121
155
  };
122
156
  }