opencode-model-router 2.1.0 → 2.3.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +44 -5
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +174 -47
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +557 -61
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1691 -67
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
  55. package/tiers.json +43 -0
@@ -0,0 +1,298 @@
1
+ /**
2
+ * `[route …]` line (D13) — parse, strip and apply. Design L1–L3 of
3
+ * `docs/qa/cost-aware-routing/phase-1.2.md`.
4
+ *
5
+ * Pure. The route line is a typed override written by the orchestrator or by
6
+ * `/annotate-plan`; it is read from its own line only (a `[route …]` mention
7
+ * inside a sentence is text) and every route line is stripped from the prompt.
8
+ */
9
+
10
+ import { fenceMask } from "./fences";
11
+ import {
12
+ CLASS_IMPLIED_NEEDS,
13
+ CONFIDENCE,
14
+ DETECTIONS,
15
+ NEEDS,
16
+ RISKS,
17
+ ROUTE_LINE_MAX_CHARS,
18
+ ROUTE_LINE_RE,
19
+ SCOPES,
20
+ TASK_CLASSES,
21
+ type Detection,
22
+ type Need,
23
+ type Risk,
24
+ type RouteLine,
25
+ type RouteLineParse,
26
+ type Scope,
27
+ type TaskClass,
28
+ type TaskFacts,
29
+ } from "./types";
30
+
31
+ const ROUTE_MENTION_RE = /\[route/i;
32
+ /**
33
+ * `needs=shell, edit , network`: whitespace around the commas of a needs list is
34
+ * not a separator (QA-1.2-14). A word followed by `=` starts the next field, so
35
+ * `needs=shell, class=debug` keeps its two fields.
36
+ */
37
+ const NEEDS_LIST_RE = /(\bneeds=[a-z_]*)((?:\s*,\s*[a-z_]+(?![a-z_]|\s*=))+)/gi;
38
+ const LINE_SPLIT_RE = /(\r\n|\n|\r)/;
39
+
40
+ function isMember<T extends string>(values: readonly T[], value: string): value is T {
41
+ return (values as readonly string[]).includes(value);
42
+ }
43
+
44
+ function stripTail(value: string): string {
45
+ return value.replace(/[,;]+$/, "");
46
+ }
47
+
48
+ /** `pin` values: bare / true / yes / 1 → true; false / no / 0 → false; anything else → undefined. */
49
+ function parsePin(value: string | null): boolean | undefined {
50
+ if (value === null) return true;
51
+ if (value === "true" || value === "yes" || value === "1") return true;
52
+ if (value === "false" || value === "no" || value === "0") return false;
53
+ return undefined;
54
+ }
55
+
56
+ function parseNeeds(value: string): readonly Need[] | undefined {
57
+ const found = new Set<Need>();
58
+ for (const token of value.split(",")) {
59
+ const t = token.trim();
60
+ if (isMember(NEEDS, t)) found.add(t);
61
+ }
62
+ if (found.size === 0) return undefined;
63
+ return NEEDS.filter((need) => found.has(need));
64
+ }
65
+
66
+ /** L2: the fields of one route line body. */
67
+ function parseFields(body: string): RouteLine {
68
+ let taskClass: TaskClass | undefined;
69
+ let risk: Risk | undefined;
70
+ let scope: Scope | undefined;
71
+ let needs: readonly Need[] | undefined;
72
+ let detection: Detection | undefined;
73
+ let pin = false;
74
+ const ignored: string[] = [];
75
+ const seen = new Set<string>();
76
+
77
+ const tokens = body
78
+ .replace(/\s*=\s*/g, "=")
79
+ .replace(NEEDS_LIST_RE, (_whole, head: string, tail: string) => head + tail.replace(/\s+/g, ""))
80
+ .split(/\s+/)
81
+ .filter((token) => token !== "");
82
+ for (const token of tokens) {
83
+ const eq = token.indexOf("=");
84
+ const key = stripTail((eq === -1 ? token : token.slice(0, eq)).toLowerCase());
85
+ const value = eq === -1 ? null : stripTail(token.slice(eq + 1).toLowerCase());
86
+ if (key === "") {
87
+ ignored.push(token);
88
+ continue;
89
+ }
90
+ if (seen.has(key)) {
91
+ ignored.push(`dup:${key}`);
92
+ continue;
93
+ }
94
+ seen.add(key);
95
+ switch (key) {
96
+ case "class":
97
+ if (value !== null && isMember(TASK_CLASSES, value)) taskClass = value;
98
+ else ignored.push(key);
99
+ break;
100
+ case "risk":
101
+ if (value !== null && isMember(RISKS, value)) risk = value;
102
+ else ignored.push(key);
103
+ break;
104
+ case "scope":
105
+ if (value !== null && isMember(SCOPES, value)) scope = value;
106
+ else ignored.push(key);
107
+ break;
108
+ case "needs": {
109
+ const parsed = value === null ? undefined : parseNeeds(value);
110
+ if (parsed) needs = parsed;
111
+ else ignored.push(key);
112
+ break;
113
+ }
114
+ case "d":
115
+ if (value !== null && isMember(DETECTIONS, value)) detection = value;
116
+ else ignored.push(key);
117
+ break;
118
+ case "pin": {
119
+ const parsed = parsePin(value);
120
+ if (parsed === undefined) ignored.push(key);
121
+ else pin = parsed;
122
+ break;
123
+ }
124
+ default:
125
+ ignored.push(key);
126
+ }
127
+ }
128
+
129
+ return {
130
+ ...(taskClass ? { class: taskClass } : {}),
131
+ ...(risk ? { risk } : {}),
132
+ ...(scope ? { scope } : {}),
133
+ ...(needs ? { needs } : {}),
134
+ ...(detection ? { detection } : {}),
135
+ pin,
136
+ ignored,
137
+ };
138
+ }
139
+
140
+ /** Leading whitespace of 4+ columns (tabs count 4): an indented code block, not a directive. */
141
+ const INDENTED_CODE_RE = /^(?: {0,3}\t| {4})/;
142
+ const QUOTED_RE = /^\s*>/;
143
+
144
+ /**
145
+ * Only a plain, unquoted, unindented, outside-any-fence, short line can be a
146
+ * route line: anything else is text quoted or pasted into the prompt (a file,
147
+ * a log, an issue) and must neither steer routing nor be stripped.
148
+ */
149
+ function isRecognisable(line: string, inFence: boolean): boolean {
150
+ return (
151
+ !inFence &&
152
+ line.length <= ROUTE_LINE_MAX_CHARS &&
153
+ !INDENTED_CODE_RE.test(line) &&
154
+ !QUOTED_RE.test(line) &&
155
+ ROUTE_LINE_RE.test(line)
156
+ );
157
+ }
158
+
159
+ function canonical(line: RouteLine): string {
160
+ return JSON.stringify([line.class, line.risk, line.scope, line.needs, line.detection, line.pin]);
161
+ }
162
+
163
+ /**
164
+ * Several route lines: when they differ in any field the parse is a conflict.
165
+ * The effective line keeps the FIRST line's class/risk/scope/needs only where no
166
+ * other line carries a different value for the same field, keeps the first
167
+ * line's own `pin` (a later line can neither add one nor take it away, A22) and
168
+ * never keeps `d` (a conflict must not be able to switch verification off).
169
+ */
170
+ function resolveConflict(lines: readonly RouteLine[]): RouteLine {
171
+ const first = lines[0]!;
172
+ const ignored = [...first.ignored, "conflict"];
173
+ const contradicted = (pick: (l: RouteLine) => unknown): boolean => {
174
+ const mine = JSON.stringify(pick(first));
175
+ return lines.some((other) => {
176
+ const theirs = pick(other);
177
+ return theirs !== undefined && JSON.stringify(theirs) !== mine;
178
+ });
179
+ };
180
+ const keep = <T>(field: string, value: T | undefined, pick: (l: RouteLine) => unknown): T | undefined => {
181
+ if (value === undefined) return undefined;
182
+ if (contradicted(pick)) {
183
+ ignored.push(`conflict:${field}`);
184
+ return undefined;
185
+ }
186
+ return value;
187
+ };
188
+ const taskClass = keep("class", first.class, (l) => l.class);
189
+ const risk = keep("risk", first.risk, (l) => l.risk);
190
+ const scope = keep("scope", first.scope, (l) => l.scope);
191
+ const needs = keep("needs", first.needs, (l) => l.needs);
192
+ if (lines.some((l) => l.detection !== undefined)) ignored.push("conflict:d");
193
+ return {
194
+ ...(taskClass ? { class: taskClass } : {}),
195
+ ...(risk ? { risk } : {}),
196
+ ...(scope ? { scope } : {}),
197
+ ...(needs ? { needs } : {}),
198
+ // The first line is the directive; a later line cannot take its pin away or add one (A22).
199
+ pin: first.pin,
200
+ ignored,
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Where a route line is recognised (A22): `first` = only the first non-empty line
206
+ * of the text (the protocol: the orchestrator's directive is the first line),
207
+ * `edges` = the first or the last non-empty line, `any` = anywhere outside
208
+ * fences, quotes and indented code. Elsewhere a `[route …]` line is plain text
209
+ * and stays in the prompt.
210
+ */
211
+ export type RouteLinePositions = "first" | "edges" | "any";
212
+
213
+ export interface RouteLineOptions {
214
+ /** Default `any` for the parser itself; `classify` defaults to `first`. */
215
+ readonly positions?: RouteLinePositions;
216
+ }
217
+
218
+ /**
219
+ * L1 + L2: find every recognisable route line, parse them, strip them. Route
220
+ * lines are whole lines; the terminator that follows a dropped line goes with
221
+ * it, everything else is kept byte for byte (including route-looking lines in
222
+ * fences, indented code and quotes).
223
+ */
224
+ export function parseRouteLine(text: string, options: RouteLineOptions = {}): RouteLineParse {
225
+ if (typeof text !== "string") {
226
+ return { line: null, count: 0, stripped: "", conflict: false, edgeOnly: true };
227
+ }
228
+ if (!ROUTE_MENTION_RE.test(text)) {
229
+ return { line: null, count: 0, stripped: text, conflict: false, edgeOnly: true };
230
+ }
231
+ const positions = options.positions ?? "any";
232
+ const parts = text.split(LINE_SPLIT_RE);
233
+ const lines: string[] = [];
234
+ for (let i = 0; i < parts.length; i += 2) lines.push(parts[i]!);
235
+ const fenced = fenceMask(lines);
236
+
237
+ let firstNonEmpty = -1;
238
+ let lastNonEmpty = -1;
239
+ lines.forEach((line, i) => {
240
+ if (line.trim() === "") return;
241
+ if (firstNonEmpty === -1) firstNonEmpty = i;
242
+ lastNonEmpty = i;
243
+ });
244
+
245
+ const kept: string[] = [];
246
+ const parsed: RouteLine[] = [];
247
+ let edgeOnly = true;
248
+ for (let i = 0; i < lines.length; i++) {
249
+ const terminator = parts[2 * i + 1];
250
+ const line = lines[i]!;
251
+ const atEdge = i === firstNonEmpty || i === lastNonEmpty;
252
+ const placed = positions === "any" || (positions === "edges" ? atEdge : i === firstNonEmpty);
253
+ if (!placed || !isRecognisable(line, fenced[i]!)) {
254
+ kept.push(line);
255
+ if (terminator !== undefined) kept.push(terminator);
256
+ continue;
257
+ }
258
+ if (!atEdge) edgeOnly = false;
259
+ parsed.push(parseFields(ROUTE_LINE_RE.exec(line)?.[1] ?? ""));
260
+ }
261
+ if (parsed.length === 0) {
262
+ return { line: null, count: 0, stripped: kept.join(""), conflict: false, edgeOnly: true };
263
+ }
264
+ const conflict = new Set(parsed.map(canonical)).size > 1;
265
+ return {
266
+ line: conflict ? resolveConflict(parsed) : parsed[0]!,
267
+ count: parsed.length,
268
+ stripped: kept.join(""),
269
+ conflict,
270
+ edgeOnly,
271
+ };
272
+ }
273
+ const RISK_ORDER: readonly Risk[] = RISKS;
274
+
275
+ function maxRisk(a: Risk, b: Risk): Risk {
276
+ return RISK_ORDER.indexOf(a) >= RISK_ORDER.indexOf(b) ? a : b;
277
+ }
278
+
279
+ /**
280
+ * L3: merge a route line over rules facts. Class and scope override; risk may
281
+ * only rise; needs are unioned (and completed by the class's implied needs and
282
+ * by `network` ⇒ `shell`). A valid class makes the route line the source and
283
+ * sets confidence 0.9; without one, confidence and source stay the base's.
284
+ */
285
+ export function applyRouteLine(base: TaskFacts, line: RouteLine): TaskFacts {
286
+ const taskClass = line.class ?? base.class;
287
+ const needs = new Set<Need>([...base.needs, ...(line.needs ?? []), ...CLASS_IMPLIED_NEEDS[taskClass]]);
288
+ if (needs.has("network")) needs.add("shell");
289
+ const hasClass = line.class !== undefined;
290
+ return {
291
+ class: taskClass,
292
+ risk: maxRisk(base.risk, line.risk ?? base.risk),
293
+ scope: line.scope ?? base.scope,
294
+ needs: NEEDS.filter((need) => needs.has(need)),
295
+ confidence: hasClass ? CONFIDENCE.routeLine : base.confidence,
296
+ source: hasClass ? (line.detection ? "plan" : "route-line") : base.source,
297
+ };
298
+ }