opencode-model-router 1.15.0 → 2.0.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/src/v2.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { Plugin } from "@opencode/plugin";
2
+ import type { PluginInput } from "@opencode-ai/plugin";
3
+ import ModelRouterPlugin from "./index";
4
+ import { createV2Runtime } from "./compat/v2-client";
5
+ import { registerV2Hooks } from "./compat/v2-hooks";
6
+
7
+ /** Keep the routing engine shared; translate only the host API at this boundary. */
8
+ export default {
9
+ id: "opencode-model-router",
10
+ server: ModelRouterPlugin,
11
+ async setup(ctx: Plugin.Context) {
12
+ const runtime = createV2Runtime(ctx);
13
+ // The engine consumes directory/client only. V2 has no legacy HTTP server
14
+ // URL or Bun shell context; do not invent either for the adapter.
15
+ const input = {
16
+ directory: ctx.location.directory,
17
+ worktree: ctx.location.project.directory,
18
+ client: runtime.client,
19
+ routerChildRunner: runtime.childRunner,
20
+ };
21
+ const hooks = await ModelRouterPlugin(input as unknown as PluginInput);
22
+ return registerV2Hooks(ctx, hooks, runtime);
23
+ },
24
+ } satisfies Plugin.Plugin & { server: typeof ModelRouterPlugin };
@@ -82,7 +82,7 @@ export function atLeastProducerTier(
82
82
  // Prompt builder
83
83
  // ---------------------------------------------------------------------------
84
84
 
85
- const GRADER_SYSTEM =
85
+ export const GRADER_SYSTEM =
86
86
  'You are an independent, skeptical verification grader. You did NOT produce this work and have no stake in it. Evaluate ONLY whether the artefact satisfies EACH acceptance criterion below. For every criterion, cite concrete evidence from the artefact. If the evidence is missing, ambiguous, partial, or you are uncertain for ANY reason, you MUST fail that criterion. Default to FAIL. Do not give the benefit of the doubt. Output ONLY a single JSON object on one line: {"pass": boolean, "reasons": string[]}. Set pass=true ONLY if every criterion is satisfied with cited evidence; otherwise pass=false with a reason per failed criterion.';
87
87
 
88
88
  /** Upper bound on the working-directory string interpolated into the prompt. */
@@ -67,7 +67,7 @@ function none(reason: string): ReferenceState {
67
67
  * appended (a deleted file keeps its directory's canonical spelling); lexical `resolve` when no
68
68
  * ancestor resolves.
69
69
  */
70
- function canonicalPath(path: string): string {
70
+ export function canonicalPath(path: string): string {
71
71
  const absolute = resolve(path);
72
72
  let head = absolute;
73
73
  const tail: string[] = [];
package/src/verify/dod.ts CHANGED
@@ -25,6 +25,7 @@ export interface DoD {
25
25
  criteria: string[]; // [] when none
26
26
  deliverable: string | null;
27
27
  source: DoDSource;
28
+ cwd?: string;
28
29
  }
29
30
 
30
31
  export interface InferHints {
@@ -79,7 +80,8 @@ export function normalizeDoD(d: DoD): DoD {
79
80
  const rawDeliverable = typeof d.deliverable === "string" ? d.deliverable.trim() : "";
80
81
  const deliverable: string | null = rawDeliverable.length > 0 ? rawDeliverable : null;
81
82
 
82
- return { kind, checks, criteria, deliverable, source: d.source };
83
+ const cwd = typeof d.cwd === "string" ? d.cwd.trim() : "";
84
+ return { kind, checks, criteria, deliverable, source: d.source, ...(cwd ? { cwd } : {}) };
83
85
  }
84
86
 
85
87
  // ---------------------------------------------------------------------------
@@ -131,6 +133,7 @@ export function parseAcceptanceBlock(text: string, source: DoDSource = "explicit
131
133
  const criteria: string[] = [];
132
134
  let deliverable: string | null = null;
133
135
  let kindHint: DoDKind | null = null;
136
+ let cwd: string | undefined;
134
137
 
135
138
  for (const rawLine of innerLines) {
136
139
  const line = rawLine.trim();
@@ -153,6 +156,9 @@ export function parseAcceptanceBlock(text: string, source: DoDSource = "explicit
153
156
  if (kvPairs["path"] !== undefined) check.path = kvPairs["path"];
154
157
  if (kvPairs["schema"] !== undefined) check.schema = kvPairs["schema"];
155
158
  checks.push(check);
159
+ } else if (lline.startsWith("cwd:")) {
160
+ const rest = line.slice("cwd:".length).trim().replace(/^(["'])(.*)\1$/, "$2").trim();
161
+ if (rest) cwd = rest;
156
162
  } else if (lline.startsWith("criteria:")) {
157
163
  const rest = line.slice("criteria:".length).trim();
158
164
  if (rest) criteria.push(rest);
@@ -173,6 +179,7 @@ export function parseAcceptanceBlock(text: string, source: DoDSource = "explicit
173
179
  criteria,
174
180
  deliverable,
175
181
  source,
182
+ ...(cwd ? { cwd } : {}),
176
183
  });
177
184
  }
178
185
 
@@ -24,7 +24,8 @@ import { isCheckable } from "./dod";
24
24
  import { runDeterministic } from "./deterministic";
25
25
  import { runChecker } from "./checker";
26
26
  import type { ArtefactView, CheckerDeps } from "./checker";
27
- import { resolveBaseDir } from "./paths";
27
+ import { isAbsolute } from "node:path";
28
+ import { isWithinDir, resolveBaseDir } from "./paths";
28
29
 
29
30
  /** The concrete, inspectable result of a delegation (artefact contract §3.3). */
30
31
  export interface Artefact {
@@ -62,6 +63,12 @@ export interface GateDeps {
62
63
  */
63
64
  require?: "never" | "whenDoDPresent" | "always";
64
65
  strictUnverifiable?: boolean;
66
+ /**
67
+ * Canonicalizes a path for the outside-the-base check: one directory can be spelled several
68
+ * ways (a Windows 8.3 short name, a symlink such as macOS /var -> /private/var), and a lexical
69
+ * comparison would call the producer's own files "outside". Absent means lexical comparison.
70
+ */
71
+ canonicalPath?: (path: string) => string;
65
72
  }
66
73
 
67
74
  export interface GateResult {
@@ -187,6 +194,14 @@ export async function accept(
187
194
 
188
195
  let verdict: Verdict;
189
196
  if (dod.kind === "deterministic") {
197
+ const canonical = deps.canonicalPath ?? ((path: string) => path);
198
+ const canonicalBase = canonical(effectiveBaseDir);
199
+ if (artefact.changedFiles.length > 0 && artefact.changedFiles.every(
200
+ ({ path }) => isAbsolute(path) && !isWithinDir(canonical(path), canonicalBase),
201
+ )) {
202
+ const reason = `the producer changed files only outside ${effectiveBaseDir} (e.g. ${artefact.changedFiles[0].path}); checks run there cannot see them. Add "cwd: <dir>" to the [acceptance] block to verify where the work landed.`;
203
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
204
+ }
190
205
  verdict = await runDeterministic(dod, {
191
206
  ...deps.deterministic,
192
207
  cwd: effectiveBaseDir,
@@ -5,7 +5,15 @@
5
5
  // resolve relative paths against an effective base dir instead of the router's
6
6
  // own cwd.
7
7
 
8
- import { isAbsolute, join } from "node:path";
8
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
9
+
10
+ /** Lexical containment only: no filesystem or symlink resolution. */
11
+ export function isWithinDir(path: string, dir: string): boolean {
12
+ const key = (p: string) => process.platform === "win32" ? resolve(p).toLowerCase() : resolve(p);
13
+ const delta = relative(key(dir), key(path));
14
+ // Only a leading `..` SEGMENT leaves the dir: a child named `..cache` stays inside.
15
+ return delta !== ".." && !delta.startsWith(`..${sep}`) && !isAbsolute(delta);
16
+ }
9
17
 
10
18
  /**
11
19
  * Resolve the effective base directory for a delegation's verification.
@@ -14,6 +14,7 @@
14
14
  * silently stop applying to graded work.
15
15
  */
16
16
  import { createHash } from "node:crypto";
17
+ import type { ChildSessionRunner } from "../compat/child-session";
17
18
  import { access, readdir, readFile as fsReadFile, realpath, stat, unlink } from "node:fs/promises";
18
19
  import { isAbsolute, join, relative, resolve } from "node:path";
19
20
  import { createBatchCoordinator, type BatchCoordinatorOptions, type BatchPlanner } from "./batch";
@@ -64,6 +65,7 @@ import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
64
65
  import {
65
66
  buildAcceptedSuffix,
66
67
  buildForcingNote,
68
+ canonicalPath,
67
69
  tierModel,
68
70
  toolLabel,
69
71
  type ChangedFile,
@@ -123,6 +125,32 @@ export function extractAssistantText(res: any): string {
123
125
  .join("\n");
124
126
  }
125
127
 
128
+ function isValidHttpStatus(status: unknown): status is number {
129
+ return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599;
130
+ }
131
+
132
+ function graderPromptResponseError(res: unknown): Error | undefined {
133
+ if (typeof res !== "object" || res === null) return undefined;
134
+ const envelope = res as {
135
+ error?: unknown;
136
+ data?: { info?: { error?: unknown } };
137
+ response?: { status?: unknown };
138
+ };
139
+ const error = envelope.data?.info?.error ?? envelope.error;
140
+ const responseStatus = envelope.response?.status;
141
+ const validStatus = isValidHttpStatus(responseStatus);
142
+ const malformedStatus = responseStatus !== undefined && !validStatus;
143
+ const httpStatus = validStatus && responseStatus >= 400
144
+ ? responseStatus : undefined;
145
+ if (error == null && httpStatus === undefined && !malformedStatus) return undefined;
146
+ const detail = typeof error === "object" && error !== null ? error as {
147
+ data?: { statusCode?: unknown };
148
+ } : undefined;
149
+ const nestedStatus = detail?.data?.statusCode;
150
+ const status = httpStatus ?? (isValidHttpStatus(nestedStatus) ? nestedStatus : undefined);
151
+ return new Error(`grader prompt failed${status === undefined ? "" : ` (${status})`}: SDK error`);
152
+ }
153
+
126
154
  /** P0 (deterministic.ts header, T2): what a gate needs from its dispatch. */
127
155
  export interface PreparedVerification {
128
156
  /**
@@ -865,7 +893,7 @@ export interface VerificationWiring {
865
893
  ): Promise<PreparedVerification>;
866
894
  /** Session ids currently running a grader prompt, so hooks can skip them. */
867
895
  graderSessions: Set<string>;
868
- /** Abort then delete a plugin-created child session. Never throws. */
896
+ /** Stop a plugin-created child; v1 deletes it, a host runner owns v2 cleanup. Never throws. */
869
897
  disposeChildSession(sid: string): Promise<void>;
870
898
  /** Run one grader turn, parented to the caller's session when given. */
871
899
  dispatchGrader(
@@ -935,6 +963,7 @@ function errorText(err: unknown): string {
935
963
 
936
964
  export function createVerificationWiring(deps: {
937
965
  client: any;
966
+ childRunner?: ChildSessionRunner;
938
967
  /** Project root; relative paths in checks resolve against it. */
939
968
  directory: string;
940
969
  getConfig: () => RouterConfig;
@@ -1006,6 +1035,8 @@ export function createVerificationWiring(deps: {
1006
1035
  /** QA-3.1-3: dispatches starting together share their snapshot and capture (createSharedFlight). */
1007
1036
  const sharedSnapshots = createSharedFlight<TreeSnapshot>();
1008
1037
  const sharedCaptures = createSharedFlight<DispatchReference>();
1038
+ /** The gate-time snapshot of observeChange, shared the same way (keyed by priority, cwd and digest paths). */
1039
+ const sharedGateSnapshots = createSharedFlight<TreeSnapshot>();
1009
1040
 
1010
1041
  const abs = (p: string): string => (isAbsolute(p) ? p : join(directory, p));
1011
1042
 
@@ -1150,6 +1181,10 @@ export function createVerificationWiring(deps: {
1150
1181
  }
1151
1182
  }
1152
1183
  disposed.add(sid);
1184
+ if (deps.childRunner) {
1185
+ try { await deps.childRunner.dispose(sid); } catch { /* best-effort cleanup */ }
1186
+ return;
1187
+ }
1153
1188
  try {
1154
1189
  await client.session.abort({ path: { id: sid } });
1155
1190
  } catch {
@@ -1167,6 +1202,33 @@ export function createVerificationWiring(deps: {
1167
1202
  parentSessionID?: string,
1168
1203
  inFlight?: Set<string>,
1169
1204
  ): Promise<{ sessionID: string; text: string }> => {
1205
+ if (deps.childRunner) {
1206
+ const cfg = getConfig();
1207
+ const controller = new AbortController();
1208
+ let sid: string | undefined;
1209
+ try {
1210
+ return await withTimeout(deps.childRunner.run({
1211
+ parentSessionID,
1212
+ cwd: req.cwd,
1213
+ model: tierModel(cfg, req.tier) ?? undefined,
1214
+ system: req.system,
1215
+ prompt: req.prompt,
1216
+ signal: controller.signal,
1217
+ async onCreated(sessionID) {
1218
+ sid = sessionID;
1219
+ graderSessions.add(sessionID);
1220
+ inFlight?.add(sessionID);
1221
+ },
1222
+ }), graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs), "grader prompt");
1223
+ } finally {
1224
+ controller.abort();
1225
+ if (sid) {
1226
+ graderSessions.delete(sid);
1227
+ inFlight?.delete(sid);
1228
+ await disposeChildSession(sid);
1229
+ }
1230
+ }
1231
+ }
1170
1232
  // Scope the grader session to the producer's working directory when one was
1171
1233
  // declared. Naming the directory in the prompt is not enough: the grader
1172
1234
  // has real tools, and an unscoped session resolves every read and command
@@ -1208,6 +1270,8 @@ export function createVerificationWiring(deps: {
1208
1270
  graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs),
1209
1271
  "grader prompt",
1210
1272
  );
1273
+ const responseError = graderPromptResponseError(res);
1274
+ if (responseError) throw responseError;
1211
1275
  return { sessionID: sid, text: extractAssistantText(res) };
1212
1276
  } finally {
1213
1277
  graderSessions.delete(sid);
@@ -1335,6 +1399,7 @@ export function createVerificationWiring(deps: {
1335
1399
  },
1336
1400
  require: cfg.enforcement?.verify?.require,
1337
1401
  strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
1402
+ canonicalPath,
1338
1403
  };
1339
1404
  };
1340
1405
 
@@ -1385,8 +1450,20 @@ export function createVerificationWiring(deps: {
1385
1450
  const options = digests === undefined
1386
1451
  ? { lowPriority }
1387
1452
  : { lowPriority, digestPaths: digests === "unavailable" ? [] : [...digests.keys()] };
1453
+ // QA-3.1-3 at the finish: parallel finishes share one gate-time snapshot per key, and a run
1454
+ // only serves finishes that asked before it started (createSharedFlight), so each still sees
1455
+ // the tree as it was after its own producer returned. Unshared, 20 parallel deferred finishes
1456
+ // spawned 140 git processes and hit DEFERRED_FINISH_MS on a 4-core Windows runner.
1457
+ const digestKey = options.digestPaths === undefined
1458
+ ? "all"
1459
+ : createHash("sha256").update([...options.digestPaths].sort().join("\0")).digest("hex");
1460
+ const key = `${lowPriority ? "low" : "normal"}\0${base}\0${digestKey}`;
1388
1461
  snapshot = bound > 0 && !controller.signal.aborted
1389
- ? await withTimeout(snapshotTree(base, controller.signal, options), bound, "grade fingerprint")
1462
+ ? await withTimeout(
1463
+ sharedGateSnapshots(key, shared => snapshotTree(base, shared, options), controller.signal),
1464
+ bound,
1465
+ "grade fingerprint",
1466
+ )
1390
1467
  : undefined;
1391
1468
  } catch {
1392
1469
  snapshot = undefined; // Explicit unavailable disclaimer, never a raw tree.
package/tiers.json CHANGED
@@ -45,9 +45,11 @@
45
45
  "presets": {
46
46
  "anthropic": {
47
47
  "fast": {
48
- "model": "anthropic/claude-sonnet-5",
48
+ "model": "anthropic/claude-sonnet-5-5",
49
+ "variant": "low",
50
+ "effort": "low",
49
51
  "costRatio": 1,
50
- "description": "Sonnet 5 for exploration, search, and simple reads",
52
+ "description": "Sonnet 5.5 low for exploration, search, and simple reads",
51
53
  "steps": 30,
52
54
  "whenToUse": [
53
55
  "Codebase exploration and search",
@@ -57,11 +59,11 @@
57
59
  ]
58
60
  },
59
61
  "medium": {
60
- "model": "anthropic/claude-opus-5-5",
61
- "variant": "low",
62
- "effort": "low",
62
+ "model": "anthropic/claude-sonnet-5-5",
63
+ "variant": "medium",
64
+ "effort": "medium",
63
65
  "costRatio": 5,
64
- "description": "Opus 5.5 low for implementation, refactoring, and tests",
66
+ "description": "Sonnet 5.5 medium for implementation, refactoring, and tests",
65
67
  "steps": 50,
66
68
  "whenToUse": [
67
69
  "Feature implementation",
@@ -99,10 +101,10 @@
99
101
  ]
100
102
  },
101
103
  "medium": {
102
- "model": "openai/gpt-6-astra-fast",
103
- "variant": "high",
104
+ "model": "openai/gpt-6.1-sol-fast",
105
+ "variant": "xhigh",
104
106
  "costRatio": 5,
105
- "description": "GPT-5.6 Sol Fast (high) for implementation and standard coding",
107
+ "description": "GPT-6.1 Sol Fast (xhigh) for implementation and standard coding",
106
108
  "steps": 50,
107
109
  "whenToUse": [
108
110
  "Feature implementation",
@@ -154,7 +156,7 @@
154
156
  "heavy": {
155
157
  "model": "github-copilot/claude-fable-5-1",
156
158
  "costRatio": 20,
157
- "description": "Claude Fable 5 via GitHub Copilot for architecture, complex debugging, and security",
159
+ "description": "Claude Fable 5.1 via GitHub Copilot for architecture, complex debugging, and security",
158
160
  "steps": 120,
159
161
  "whenToUse": [
160
162
  "Architecture decisions",
@@ -247,9 +249,9 @@
247
249
  "hybrid": {
248
250
  "fast": {
249
251
  "model": "openai/gpt-6-luna-fast",
250
- "variant": "low",
252
+ "variant": "medium",
251
253
  "costRatio": 1,
252
- "description": "GPT 6 Luna (low) for exploration, search, and simple reads",
254
+ "description": "GPT 6 Luna (medium) for exploration, search, and simple reads",
253
255
  "steps": 30,
254
256
  "whenToUse": [
255
257
  "Codebase exploration and search",
@@ -260,9 +262,9 @@
260
262
  },
261
263
  "medium": {
262
264
  "model": "openai/gpt-6-astra-fast",
263
- "variant": "low",
265
+ "variant": "high",
264
266
  "costRatio": 5,
265
- "description": "GPT-6 Astra Fast (low) for implementation and standard coding",
267
+ "description": "GPT-6 Astra Fast (high) for implementation and standard coding",
266
268
  "steps": 50,
267
269
  "whenToUse": [
268
270
  "Feature implementation",
@@ -272,10 +274,11 @@
272
274
  ]
273
275
  },
274
276
  "heavy": {
275
- "model": "anthropic/claude-fable-5-1",
276
- "variant": "max",
277
+ "model": "anthropic/claude-opus-5-5",
278
+ "variant": "xhigh",
279
+ "effort": "xhigh",
277
280
  "costRatio": 20,
278
- "description": "Claude Fable 5.1 max for architecture, complex debugging, and security",
281
+ "description": "Claude Opus 5.5 xhigh for architecture, complex debugging, and security",
279
282
  "steps": 120,
280
283
  "whenToUse": [
281
284
  "Architecture decisions",