opencode-model-router 2.2.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 (54) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +35 -3
  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 +118 -31
  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 +486 -38
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1365 -19
  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
@@ -0,0 +1,315 @@
1
+ /**
2
+ * `typesafe` backend: POST `<baseUrl>/v1/systemone` (TypeSafe "choice"
3
+ * questions). The task text goes in the `state` field, which the API treats as
4
+ * data; the class, risk and scope questions are constants. TypeSafe returns a
5
+ * calibrated confidence, so `samples` is ignored (one request per call) and the
6
+ * answer's own confidence is used.
7
+ *
8
+ * The API key is read from `apiKeyEnv` at each call. There is no built-in base
9
+ * URL: sending the state to a host the user never configured would break the D14
10
+ * privacy stance, so a missing `baseUrl` disables the backend with a logged
11
+ * reason (the vendor's documented host is `TYPESAFE_DEFAULT_BASE_URL`).
12
+ *
13
+ * Contract: never throws, never retries, `timeoutMs` enforced by racing a timer
14
+ * and aborting the `fetch` signal.
15
+ */
16
+
17
+ import {
18
+ BACKEND_PROMPT,
19
+ CLASS_OPTIONS,
20
+ CONFIDENCE,
21
+ RISK_OPTIONS,
22
+ RISKS,
23
+ SCOPE_OPTIONS,
24
+ SCOPES,
25
+ type BackendCallOptions,
26
+ type BackendResult,
27
+ type ChoiceOption,
28
+ type ClassifierBackend,
29
+ type ClassifierLogger,
30
+ type ClassifierSettings,
31
+ type ClassifierState,
32
+ type EnvLike,
33
+ type FetchLike,
34
+ type Risk,
35
+ type Scope,
36
+ type TaskClass,
37
+ } from "../types";
38
+ import {
39
+ backendUnavailable,
40
+ checkBaseUrl,
41
+ createRuntime,
42
+ cutRaw,
43
+ disabled,
44
+ disabledMany,
45
+ finish,
46
+ finishMany,
47
+ gatherSamples,
48
+ guarded,
49
+ guardedMany,
50
+ logEffectiveHost,
51
+ parseModelRef,
52
+ reasonOf,
53
+ renderBatchPrompt,
54
+ round2,
55
+ shuffle,
56
+ type Outcome,
57
+ type Settled,
58
+ } from "./shared";
59
+
60
+ /** The vendor's documented API host; documentation and config defaults may point `baseUrl` here. */
61
+ export const TYPESAFE_DEFAULT_BASE_URL = "https://api.typesafe.ai";
62
+
63
+ export interface TypeSafeBackendDeps {
64
+ readonly fetch: FetchLike;
65
+ readonly env: EnvLike;
66
+ readonly settings: ClassifierSettings;
67
+ readonly logger: ClassifierLogger;
68
+ readonly now?: () => number;
69
+ }
70
+
71
+ const BAD_MODEL = "classifier.model is not provider/model[#variant]";
72
+ const NO_BASE_URL = "classifier.baseUrl is not set";
73
+ const NO_KEY = "classifier.apiKeyEnv is not set";
74
+
75
+ interface Endpoint {
76
+ readonly url: string;
77
+ readonly model: string;
78
+ readonly headers: Record<string, string>;
79
+ }
80
+
81
+ interface ChoiceAnswer {
82
+ readonly choice: string | null;
83
+ readonly confidence: number;
84
+ }
85
+
86
+ interface SingleAnswer {
87
+ readonly cls: TaskClass | null;
88
+ readonly confidence: number;
89
+ readonly risk?: Risk;
90
+ readonly scope?: Scope;
91
+ readonly raw: string | null;
92
+ readonly reason?: string;
93
+ }
94
+
95
+ interface BatchAnswer {
96
+ readonly items: ReadonlyArray<{ readonly cls: TaskClass | null; readonly confidence: number }>;
97
+ readonly raw: string | null;
98
+ readonly reason?: string;
99
+ }
100
+
101
+ function asRecord(value: unknown): Record<string, unknown> | null {
102
+ return typeof value === "object" && value !== null && !Array.isArray(value)
103
+ ? (value as Record<string, unknown>)
104
+ : null;
105
+ }
106
+
107
+ function criteria(options: readonly ChoiceOption[]): Record<string, string> {
108
+ const out: Record<string, string> = {};
109
+ for (const option of options) out[option.label] = option.description;
110
+ return out;
111
+ }
112
+
113
+ function readChoice(answers: Record<string, unknown> | null, key: string): ChoiceAnswer | null {
114
+ const answer = asRecord(answers?.[key]);
115
+ if (answer === null) return null;
116
+ const confidence = answer.confidence;
117
+ return {
118
+ choice: typeof answer.choice === "string" ? answer.choice : null,
119
+ confidence:
120
+ typeof confidence === "number" && Number.isFinite(confidence)
121
+ ? round2(Math.min(1, Math.max(0, confidence)))
122
+ : CONFIDENCE.backendSingleSample,
123
+ };
124
+ }
125
+
126
+ function oneOf<T extends string>(values: readonly T[], choice: string | null): T | null {
127
+ return choice !== null ? (values.find((v) => v === choice) ?? null) : null;
128
+ }
129
+
130
+ export function createTypeSafeBackend(deps: TypeSafeBackendDeps): ClassifierBackend {
131
+ const rt = createRuntime("typesafe", deps.logger, deps.now);
132
+ const { settings } = deps;
133
+ logEffectiveHost(rt, settings.baseUrl);
134
+
135
+ /** Resolve URL, key and wire model at call time; a string is the `disabled` reason. */
136
+ function endpoint(): Endpoint | string {
137
+ const baseUrl = settings.baseUrl?.trim() ?? "";
138
+ if (baseUrl === "") return NO_BASE_URL;
139
+ const ref = parseModelRef(settings.model ?? "");
140
+ if (ref === null) return BAD_MODEL;
141
+ if (!settings.apiKeyEnv) return NO_KEY;
142
+ const key = deps.env[settings.apiKeyEnv];
143
+ if (key === undefined || key.trim() === "") return `apiKeyEnv ${settings.apiKeyEnv} is not set`;
144
+ const safe = checkBaseUrl(baseUrl, true);
145
+ if (!safe.ok) return safe.reason;
146
+ return {
147
+ url: baseUrl.replace(/\/+$/, "") + "/v1/systemone",
148
+ model: ref.id,
149
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
150
+ };
151
+ }
152
+
153
+ /** One request. HTTP failures throw (→ `error`); a malformed body returns a reason (→ `invalid`). */
154
+ async function post(
155
+ target: Endpoint,
156
+ body: unknown,
157
+ signal: AbortSignal,
158
+ ): Promise<{ answers: Record<string, unknown> | null; raw: string | null; reason?: string }> {
159
+ const response = await deps.fetch(target.url, {
160
+ method: "POST",
161
+ headers: target.headers,
162
+ body: JSON.stringify(body),
163
+ signal,
164
+ redirect: "error",
165
+ });
166
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
167
+ const text = await response.text();
168
+ let parsed: unknown;
169
+ try {
170
+ parsed = JSON.parse(text);
171
+ } catch {
172
+ return { answers: null, raw: null, reason: "non-JSON response" };
173
+ }
174
+ const answers = asRecord(asRecord(parsed)?.answers);
175
+ if (answers === null) return { answers: null, raw: cutRaw(text), reason: "missing answers" };
176
+ return { answers, raw: cutRaw(text) };
177
+ }
178
+
179
+ return {
180
+ id: "typesafe",
181
+
182
+ async classify(state: ClassifierState, options: BackendCallOptions): Promise<BackendResult> {
183
+ const startedAt = rt.now();
184
+ return guarded(rt, startedAt, async () => {
185
+ const target = endpoint();
186
+ if (typeof target === "string") return disabled(rt, target, startedAt);
187
+ const blocked = backendUnavailable(rt);
188
+ if (blocked !== null) return disabled(rt, blocked, startedAt);
189
+ const classChoices = options.choices.length > 0 ? options.choices : CLASS_OPTIONS;
190
+ const body = {
191
+ state: state.text,
192
+ model: target.model,
193
+ questions: {
194
+ task_class: {
195
+ type: "choice",
196
+ instructions: BACKEND_PROMPT.typesafeClass,
197
+ criteria: criteria(shuffle(classChoices, options.random)),
198
+ },
199
+ task_risk: {
200
+ type: "choice",
201
+ instructions: BACKEND_PROMPT.typesafeRisk,
202
+ criteria: criteria(shuffle(RISK_OPTIONS, options.random)),
203
+ },
204
+ task_scope: {
205
+ type: "choice",
206
+ instructions: BACKEND_PROMPT.typesafeScope,
207
+ criteria: criteria(shuffle(SCOPE_OPTIONS, options.random)),
208
+ },
209
+ },
210
+ };
211
+ const classLabels = classChoices.map((c) => c.label);
212
+ const gathered = await gatherSamples<SingleAnswer>(rt, 1, settings.timeoutMs, new AbortController(), async (_, signal) => {
213
+ const reply = await post(target, body, signal);
214
+ if (reply.answers === null) {
215
+ return { cls: null, confidence: 0, raw: reply.raw, reason: reply.reason };
216
+ }
217
+ const cls = readChoice(reply.answers, "task_class");
218
+ const label = oneOf(classLabels, cls?.choice ?? null);
219
+ if (label === null) {
220
+ return { cls: null, confidence: 0, raw: reply.raw, reason: "task_class answer is not a class label" };
221
+ }
222
+ const risk = oneOf(RISKS, readChoice(reply.answers, "task_risk")?.choice ?? null);
223
+ const scope = oneOf(SCOPES, readChoice(reply.answers, "task_scope")?.choice ?? null);
224
+ return {
225
+ cls: label,
226
+ confidence: cls?.confidence ?? CONFIDENCE.backendSingleSample,
227
+ ...(risk ? { risk } : {}),
228
+ ...(scope ? { scope } : {}),
229
+ raw: reply.raw,
230
+ };
231
+ });
232
+ const only = gathered.settled[0]!;
233
+ let outcome: Outcome;
234
+ if (only.kind === "value" && only.v.cls !== null) {
235
+ outcome = {
236
+ status: "ok",
237
+ label: only.v.cls,
238
+ confidence: only.v.confidence,
239
+ raw: only.v.raw,
240
+ ...(only.v.risk ? { risk: only.v.risk } : {}),
241
+ ...(only.v.scope ? { scope: only.v.scope } : {}),
242
+ };
243
+ } else if (only.kind === "value") {
244
+ outcome = { status: "invalid", raw: only.v.raw, reason: only.v.reason ?? "no class answer" };
245
+ } else if (only.kind === "error") {
246
+ outcome = { status: "error", raw: null, reason: reasonOf(only.e) };
247
+ } else {
248
+ outcome = { status: "timeout", raw: null, reason: `no answer within ${settings.timeoutMs} ms` };
249
+ }
250
+ return finish(rt, outcome, 1, startedAt);
251
+ });
252
+ },
253
+
254
+ async classifyMany(
255
+ states: readonly ClassifierState[],
256
+ options: BackendCallOptions,
257
+ ): Promise<BackendResult[]> {
258
+ if (states.length === 0) return [];
259
+ const startedAt = rt.now();
260
+ return guardedMany(rt, states.length, startedAt, async () => {
261
+ const target = endpoint();
262
+ if (typeof target === "string") return disabledMany(rt, states.length, target, startedAt);
263
+ const blocked = backendUnavailable(rt);
264
+ if (blocked !== null) return disabledMany(rt, states.length, blocked, startedAt);
265
+ const count = states.length;
266
+ const classChoices = options.choices.length > 0 ? options.choices : CLASS_OPTIONS;
267
+ const rendered = renderBatchPrompt(states, classChoices, options.random);
268
+ const described = new Map<string, ChoiceOption>(classChoices.map((c) => [c.label, c]));
269
+ const ordered = rendered.labels.flatMap((label) => {
270
+ const option = described.get(label);
271
+ return option ? [option] : [];
272
+ });
273
+ const questions: Record<string, unknown> = {};
274
+ for (let n = 1; n <= count; n++) {
275
+ questions[`class_${n}`] = {
276
+ type: "choice",
277
+ instructions: BACKEND_PROMPT.typesafeBatchClass.replaceAll("{n}", String(n)),
278
+ criteria: criteria(ordered),
279
+ };
280
+ }
281
+ const body = { state: rendered.blocks, model: target.model, questions };
282
+ const classLabels = classChoices.map((c) => c.label);
283
+ const gathered = await gatherSamples<BatchAnswer>(rt, 1, settings.timeoutMs, new AbortController(), async (_, signal) => {
284
+ const reply = await post(target, body, signal);
285
+ if (reply.answers === null) return { items: [], raw: reply.raw, reason: reply.reason };
286
+ const items = Array.from({ length: count }, (_, i) => {
287
+ const answer = readChoice(reply.answers, `class_${i + 1}`);
288
+ return {
289
+ cls: oneOf(classLabels, answer?.choice ?? null),
290
+ confidence: answer?.confidence ?? CONFIDENCE.backendSingleSample,
291
+ };
292
+ });
293
+ return { items, raw: reply.raw };
294
+ });
295
+ const only: Settled<BatchAnswer> = gathered.settled[0]!;
296
+ const outcomes = states.map((_, i): Outcome => {
297
+ if (only.kind === "value") {
298
+ const item = only.v.items[i];
299
+ if (item?.cls) {
300
+ return { status: "ok", label: item.cls, confidence: item.confidence, raw: only.v.raw };
301
+ }
302
+ return {
303
+ status: "invalid",
304
+ raw: only.v.raw,
305
+ reason: only.v.reason ?? `no valid class_${i + 1} answer`,
306
+ };
307
+ }
308
+ if (only.kind === "error") return { status: "error", raw: null, reason: reasonOf(only.e) };
309
+ return { status: "timeout", raw: null, reason: `no answer within ${settings.timeoutMs} ms` };
310
+ });
311
+ return finishMany(rt, outcomes, 1, startedAt);
312
+ });
313
+ },
314
+ };
315
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Fenced code block scanner (CommonMark subset), shared by the route-line parser
3
+ * (a `[route …]` inside a fence is example text, never a directive — QA-1.2-2)
4
+ * and the D14 state builder (code blocks never leave the machine — QA-1.2-12).
5
+ *
6
+ * Line based and linear: no regex backtracks over the whole text.
7
+ * - an opener is 0–3 spaces, then a run of at least three backticks or tildes;
8
+ * a backtick opener's info string may not contain a backtick (so inline
9
+ * ```code``` is not a fence);
10
+ * - a closer is 0–3 spaces, then a run of the SAME character at least as long
11
+ * as the opener (and so at least three), then only whitespace;
12
+ * - an unclosed fence runs to the end of the text.
13
+ */
14
+
15
+ const OPENER_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
16
+ const CLOSER_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
17
+
18
+ /**
19
+ * For every line, whether it belongs to a fenced block (the opener and closer
20
+ * lines included). `lines` must not carry line terminators.
21
+ */
22
+ export function fenceMask(lines: readonly string[]): boolean[] {
23
+ const mask: boolean[] = new Array<boolean>(lines.length).fill(false);
24
+ let open: { readonly char: string; readonly length: number } | null = null;
25
+ for (let i = 0; i < lines.length; i++) {
26
+ const line = lines[i]!;
27
+ if (open === null) {
28
+ const m = OPENER_RE.exec(line);
29
+ if (m === null) continue;
30
+ const run = m[1]!;
31
+ if (run[0] === "`" && (m[2] ?? "").includes("`")) continue;
32
+ open = { char: run[0]!, length: run.length };
33
+ mask[i] = true;
34
+ continue;
35
+ }
36
+ mask[i] = true;
37
+ const m = CLOSER_RE.exec(line);
38
+ if (m !== null && m[1]![0] === open.char && m[1]!.length >= open.length) open = null;
39
+ }
40
+ return mask;
41
+ }
42
+
43
+ /** Replace every fenced block (unclosed ones to the end) by `placeholder`, one per block. */
44
+ export function replaceFences(text: string, placeholder: string): string {
45
+ const lines = text.split(/\r?\n/);
46
+ const mask = fenceMask(lines);
47
+ if (!mask.includes(true)) return text;
48
+ const out: string[] = [];
49
+ let inside = false;
50
+ for (let i = 0; i < lines.length; i++) {
51
+ if (mask[i]) {
52
+ if (!inside) out.push(placeholder);
53
+ inside = true;
54
+ } else {
55
+ inside = false;
56
+ out.push(lines[i]!);
57
+ }
58
+ }
59
+ return out.join("\n");
60
+ }
61
+
62
+ /** 4+ columns of indentation (tabs count as four), on a line that has content. */
63
+ const INDENTED_LINE_RE = /^(?: {4}|\t| {1,3}\t)/;
64
+
65
+ function isIndentedCode(line: string): boolean {
66
+ return INDENTED_LINE_RE.test(line) && line.trim() !== "";
67
+ }
68
+
69
+ /**
70
+ * Replace every indented code block (QA-1.2-33) by one `placeholder`. A block is a
71
+ * run of lines indented four or more columns; blank lines between two such lines
72
+ * belong to it, blank lines after the last one do not. The CommonMark rule that an
73
+ * indented block cannot interrupt a paragraph is deliberately NOT applied: code
74
+ * pasted straight under a sentence must not reach a backend either.
75
+ */
76
+ export function replaceIndentedBlocks(text: string, placeholder: string): string {
77
+ const lines = text.split(/\r?\n/);
78
+ if (!lines.some(isIndentedCode)) return text;
79
+ const out: string[] = [];
80
+ let i = 0;
81
+ while (i < lines.length) {
82
+ if (!isIndentedCode(lines[i]!)) {
83
+ out.push(lines[i]!);
84
+ i++;
85
+ continue;
86
+ }
87
+ let last = i;
88
+ for (let j = i + 1; j < lines.length; j++) {
89
+ if (isIndentedCode(lines[j]!)) last = j;
90
+ else if (lines[j]!.trim() !== "") break;
91
+ }
92
+ out.push(placeholder);
93
+ i = last + 1;
94
+ }
95
+ return out.join("\n");
96
+ }