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,741 @@
1
+ /**
2
+ * Helpers shared by the three model backends (design section 4, "Shared").
3
+ *
4
+ * Everything here is pure except `raceTimeout` / `gatherSamples` (timers) and
5
+ * the logging helpers. Randomness is always injected.
6
+ */
7
+
8
+ import { scrubAndCut } from "../scrub";
9
+ import {
10
+ BACKEND_PROMPT,
11
+ BREAKER_COOLDOWN_MS,
12
+ BREAKER_FAILURES,
13
+ CONFIDENCE,
14
+ MAX_ABANDONED_REQUESTS,
15
+ RAW_ANSWER_MAX_CHARS,
16
+ type BackendId,
17
+ type BackendResult,
18
+ type BackendStatus,
19
+ type ChoiceOption,
20
+ type ClassifierLogger,
21
+ type ClassifierState,
22
+ type Risk,
23
+ type Scope,
24
+ type TaskClass,
25
+ } from "../types";
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Model reference
29
+ // ---------------------------------------------------------------------------
30
+
31
+ export interface ModelRef {
32
+ readonly providerID: string;
33
+ readonly id: string;
34
+ readonly variant?: string;
35
+ }
36
+
37
+ /** `provider/model[#variant]` → parts, or null. The model id may itself contain `:` and `.`. */
38
+ export function parseModelRef(ref: string): ModelRef | null {
39
+ if (typeof ref !== "string") return null;
40
+ let rest = ref.trim();
41
+ let variant: string | undefined;
42
+ const hash = rest.lastIndexOf("#");
43
+ if (hash > 0) {
44
+ const v = rest.slice(hash + 1).trim();
45
+ if (v !== "") variant = v;
46
+ rest = rest.slice(0, hash);
47
+ }
48
+ const slash = rest.indexOf("/");
49
+ if (slash <= 0) return null;
50
+ const providerID = rest.slice(0, slash).trim();
51
+ const id = rest.slice(slash + 1).trim();
52
+ if (providerID === "" || id === "") return null;
53
+ return variant === undefined ? { providerID, id } : { providerID, id, variant };
54
+ }
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Endpoint safety (A18, QA-1.2-9)
58
+ // ---------------------------------------------------------------------------
59
+
60
+ /** `localhost`, `*.localhost`, 127.0.0.0/8 and ::1: traffic that never leaves the machine. */
61
+ export function isLoopbackHost(hostname: string): boolean {
62
+ const host = hostname.toLowerCase();
63
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
64
+ if (host === "[::1]" || host === "::1") return true;
65
+ return /^127(?:\.\d{1,3}){3}$/.test(host);
66
+ }
67
+
68
+ export type BaseUrlCheck =
69
+ | { readonly ok: true; readonly host: string; readonly protocol: string; readonly loopback: boolean }
70
+ | { readonly ok: false; readonly reason: string };
71
+
72
+ /**
73
+ * Validate a configured base URL. `hasKey`: an API key will be sent, which is
74
+ * refused over plain `http:` unless the host is loopback. Reasons name the host
75
+ * only: never the userinfo, path, query or key.
76
+ */
77
+ export function checkBaseUrl(baseUrl: string, hasKey: boolean): BaseUrlCheck {
78
+ let url: URL;
79
+ try {
80
+ url = new URL(baseUrl);
81
+ } catch {
82
+ return { ok: false, reason: "classifier.baseUrl is not a valid URL" };
83
+ }
84
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
85
+ return { ok: false, reason: "classifier.baseUrl must be an http(s) URL" };
86
+ }
87
+ if (url.username !== "" || url.password !== "") {
88
+ return { ok: false, reason: "classifier.baseUrl must not embed credentials" };
89
+ }
90
+ const loopback = isLoopbackHost(url.hostname);
91
+ if (url.protocol === "http:" && hasKey && !loopback) {
92
+ return {
93
+ ok: false,
94
+ reason: `refusing to send the API key over plain http to non-loopback host ${url.hostname}`,
95
+ };
96
+ }
97
+ return { ok: true, host: url.hostname, protocol: url.protocol, loopback };
98
+ }
99
+
100
+ /** Logged once when a backend is created, so the effective destination of the state is visible. */
101
+ export function logEffectiveHost(rt: BackendRuntime, baseUrl: string | null): void {
102
+ const text = baseUrl?.trim() ?? "";
103
+ if (text === "") {
104
+ safeWarn(rt.logger, `classifier ${rt.id}: effective host unavailable (classifier.baseUrl is not set)`);
105
+ return;
106
+ }
107
+ const check = checkBaseUrl(text, false);
108
+ if (!check.ok) {
109
+ safeWarn(rt.logger, `classifier ${rt.id}: effective host unavailable (${check.reason})`);
110
+ return;
111
+ }
112
+ safeWarn(
113
+ rt.logger,
114
+ `classifier ${rt.id}: effective host ${check.host} (${check.protocol.replace(":", "")}${check.loopback ? ", loopback" : ""})`,
115
+ );
116
+ }
117
+ // ---------------------------------------------------------------------------
118
+ // Randomness
119
+ // ---------------------------------------------------------------------------
120
+
121
+ /** Fisher–Yates on a copy; `random` is a uniform [0, 1) source. */
122
+ export function shuffle<T>(items: readonly T[], random: () => number): T[] {
123
+ const out = items.slice();
124
+ for (let i = out.length - 1; i > 0; i--) {
125
+ const r = random();
126
+ const j = Math.min(i, Math.max(0, Math.floor((Number.isFinite(r) ? r : 0) * (i + 1))));
127
+ const tmp = out[i]!;
128
+ out[i] = out[j]!;
129
+ out[j] = tmp;
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /** 8 lowercase hex chars; marks one call's delimiters so the task text cannot forge them. */
135
+ export function makeNonce(random: () => number): string {
136
+ const r = random();
137
+ const n = Math.min(2 ** 32 - 1, Math.max(0, Math.floor((Number.isFinite(r) ? r : 0) * 2 ** 32)));
138
+ return n.toString(16).padStart(8, "0");
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // Prompt rendering
143
+ // ---------------------------------------------------------------------------
144
+
145
+ export interface RenderedPrompt<L extends string = string> {
146
+ readonly system: string;
147
+ readonly user: string;
148
+ /** `system` + blank line + `user`, for APIs that take one prompt string. */
149
+ readonly prompt: string;
150
+ /** The option labels in the shuffled order of this request. */
151
+ readonly labels: L[];
152
+ }
153
+
154
+ export interface RenderedBatch<L extends string = string> extends RenderedPrompt<L> {
155
+ readonly nonce: string;
156
+ /** The delimited item blocks alone (what TypeSafe sends as `state`). */
157
+ readonly blocks: string;
158
+ }
159
+
160
+ function fill(template: string, values: Readonly<Record<string, string>>): string {
161
+ return template.replace(/\{(\w+)\}/g, (whole, name: string) => values[name] ?? whole);
162
+ }
163
+
164
+ function optionLines(options: readonly ChoiceOption[]): string {
165
+ return options.map((o) => `- ${o.label}: ${o.description}`).join("\n");
166
+ }
167
+
168
+ /** Consumes `random` for the shuffle first, then for the nonce. */
169
+ export function renderSinglePrompt<L extends string>(
170
+ state: ClassifierState,
171
+ choices: readonly ChoiceOption<L>[],
172
+ random: () => number,
173
+ ): RenderedPrompt<L> {
174
+ const ordered = shuffle(choices, random);
175
+ const nonce = makeNonce(random);
176
+ const labels = ordered.map((o) => o.label);
177
+ const system = fill(BACKEND_PROMPT.single, { nonce, options: optionLines(ordered) });
178
+ const user =
179
+ "<<<TASK " +
180
+ nonce +
181
+ "\n" +
182
+ state.text +
183
+ "\nTASK " +
184
+ nonce +
185
+ ">>>\n\n" +
186
+ fill(BACKEND_PROMPT.singleFinal, { labels: labels.join(", ") });
187
+ return { system, user, prompt: system + "\n\n" + user, labels };
188
+ }
189
+
190
+ export function renderBatchPrompt<L extends string>(
191
+ states: readonly ClassifierState[],
192
+ choices: readonly ChoiceOption<L>[],
193
+ random: () => number,
194
+ ): RenderedBatch<L> {
195
+ const ordered = shuffle(choices, random);
196
+ const nonce = makeNonce(random);
197
+ const labels = ordered.map((o) => o.label);
198
+ const count = String(states.length);
199
+ const system = fill(BACKEND_PROMPT.batch, { count, nonce, options: optionLines(ordered) });
200
+ const blocks = states
201
+ .map((s, i) => {
202
+ const n = String(i + 1);
203
+ return "<<<ITEM " + n + " " + nonce + "\n" + s.text + "\nITEM " + n + " " + nonce + ">>>";
204
+ })
205
+ .join("\n\n");
206
+ const user = blocks + "\n\n" + fill(BACKEND_PROMPT.batchFinal, { count, labels: labels.join(", ") });
207
+ return { system, user, prompt: system + "\n\n" + user, labels, nonce, blocks };
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // Answer parsing
212
+ // ---------------------------------------------------------------------------
213
+
214
+ const FENCE_RE = /^```(?:[a-zA-Z0-9_-]*[ \t]*\r?\n)?([\s\S]*?)\r?\n?```$/;
215
+
216
+ function stripFence(text: string): string {
217
+ const t = text.trim();
218
+ const m = FENCE_RE.exec(t);
219
+ return m ? (m[1] ?? "").trim() : t;
220
+ }
221
+
222
+ function asRecord(value: unknown): Record<string, unknown> | null {
223
+ return typeof value === "object" && value !== null && !Array.isArray(value)
224
+ ? (value as Record<string, unknown>)
225
+ : null;
226
+ }
227
+
228
+ /**
229
+ * One label from an answer, or null. Exact match only after trimming quotes,
230
+ * emphasis and trailing punctuation: "implement because…" is invalid.
231
+ */
232
+ export function parseLabel<L extends string>(raw: string, labels: readonly L[]): L | null {
233
+ if (typeof raw !== "string") return null;
234
+ let text = stripFence(raw);
235
+ if (text.startsWith("{")) {
236
+ let parsed: unknown;
237
+ try {
238
+ parsed = JSON.parse(text);
239
+ } catch {
240
+ return null;
241
+ }
242
+ const record = asRecord(parsed);
243
+ if (record === null) return null;
244
+ const field = ["label", "class", "category"]
245
+ .map((key) => record[key])
246
+ .find((v): v is string => typeof v === "string");
247
+ if (field === undefined) return null;
248
+ text = field;
249
+ }
250
+ const cleaned = text.toLowerCase().replace(/^[\s"'`*]+/, "").replace(/[\s"'`*.!]+$/, "");
251
+ return labels.find((l) => l === cleaned) ?? null;
252
+ }
253
+
254
+ const BATCH_LINE_RE = /^\s*(?:item\s*)?(\d+)\s*[:.)-]\s*(.+?)\s*$/i;
255
+
256
+ /** One entry per item, in item order; unparsable or missing items are null. */
257
+ export function parseBatchLabels<L extends string>(
258
+ raw: string,
259
+ count: number,
260
+ labels: readonly L[],
261
+ ): Array<L | null> {
262
+ const out: Array<L | null> = Array.from({ length: count }, () => null);
263
+ if (typeof raw !== "string") return out;
264
+ const text = stripFence(raw);
265
+ if (text.startsWith("{")) {
266
+ let parsed: unknown;
267
+ try {
268
+ parsed = JSON.parse(text);
269
+ } catch {
270
+ parsed = null;
271
+ }
272
+ const list = asRecord(parsed)?.labels;
273
+ if (Array.isArray(list)) {
274
+ for (let i = 0; i < count; i++) {
275
+ const item: unknown = list[i];
276
+ out[i] = typeof item === "string" ? parseLabel(item, labels) : null;
277
+ }
278
+ return out;
279
+ }
280
+ }
281
+ const seen = new Set<number>();
282
+ for (const line of text.split(/\r?\n/)) {
283
+ const m = BATCH_LINE_RE.exec(line);
284
+ if (m === null) continue;
285
+ const n = Number(m[1]);
286
+ if (n < 1 || n > count || seen.has(n)) continue;
287
+ seen.add(n);
288
+ out[n - 1] = parseLabel(m[2] ?? "", labels);
289
+ }
290
+ return out;
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // Voting
295
+ // ---------------------------------------------------------------------------
296
+
297
+ export type VoteResult =
298
+ | { readonly status: "ok"; readonly label: TaskClass; readonly confidence: number }
299
+ | { readonly status: "disagree"; readonly confidence: 0 }
300
+ | { readonly status: "invalid" };
301
+
302
+ export function round2(n: number): number {
303
+ return Math.round(n * 100) / 100;
304
+ }
305
+
306
+ /** `samples = 1`: the label or invalid. `samples = 3`: a label with at least 2 votes wins. */
307
+ export function vote(labels: readonly (TaskClass | null)[], samples: 1 | 3): VoteResult {
308
+ if (samples === 1) {
309
+ const label = labels[0] ?? null;
310
+ return label === null
311
+ ? { status: "invalid" }
312
+ : { status: "ok", label, confidence: CONFIDENCE.backendSingleSample };
313
+ }
314
+ const counts = new Map<TaskClass, number>();
315
+ let valid = 0;
316
+ for (const label of labels) {
317
+ if (label === null) continue;
318
+ valid++;
319
+ counts.set(label, (counts.get(label) ?? 0) + 1);
320
+ }
321
+ let winner: TaskClass | null = null;
322
+ let best = 0;
323
+ for (const [label, n] of counts) {
324
+ if (n > best) {
325
+ best = n;
326
+ winner = label;
327
+ }
328
+ }
329
+ if (winner !== null && best >= 2) {
330
+ return { status: "ok", label: winner, confidence: round2(best / 3) };
331
+ }
332
+ return valid >= 2 ? { status: "disagree", confidence: 0 } : { status: "invalid" };
333
+ }
334
+
335
+ // ---------------------------------------------------------------------------
336
+ // Timeouts
337
+ // ---------------------------------------------------------------------------
338
+
339
+ export type Settled<T> =
340
+ | { readonly kind: "value"; readonly v: T }
341
+ | { readonly kind: "error"; readonly e: unknown }
342
+ | { readonly kind: "timeout" };
343
+
344
+ /**
345
+ * Race `promise` against a timer. Never rejects: the promise is observed through
346
+ * `then(onValue, onError)`, so an abandoned call that rejects later cannot raise
347
+ * an unhandled rejection. The timer is cleared on settle and unref'd when the
348
+ * runtime supports it (a pending classification must not keep the process alive).
349
+ */
350
+ export function raceTimeout<T>(promise: Promise<T>, ms: number): Promise<Settled<T>> {
351
+ return new Promise<Settled<T>>((resolve) => {
352
+ const delay = Number.isFinite(ms) ? Math.max(0, ms) : 0;
353
+ const timer = setTimeout(() => resolve({ kind: "timeout" }), delay);
354
+ (timer as { unref?: () => void }).unref?.();
355
+ Promise.resolve(promise).then(
356
+ (v) => {
357
+ clearTimeout(timer);
358
+ resolve({ kind: "value", v });
359
+ },
360
+ (e: unknown) => {
361
+ clearTimeout(timer);
362
+ resolve({ kind: "error", e });
363
+ },
364
+ );
365
+ });
366
+ }
367
+
368
+ export interface Gathered<T> {
369
+ /** One entry per request, in start order; unsettled ones are `timeout`. */
370
+ readonly settled: Array<Settled<T>>;
371
+ /** The group timer fired before the group finished. */
372
+ readonly timedOut: boolean;
373
+ }
374
+
375
+ /**
376
+ * Start `count` requests together and wait for them as a group for at most
377
+ * `timeoutMs`. The group also ends early when two requests agree (their
378
+ * `agreementKey` is equal and non-null): a majority of three cannot change, so
379
+ * waiting for the third only costs latency. Whatever is still in flight when the
380
+ * group ends is aborted (best effort) and counted as abandoned on the runtime
381
+ * until it settles. Never rejects, never throws.
382
+ */
383
+ export function gatherSamples<T>(
384
+ rt: BackendRuntime,
385
+ count: number,
386
+ timeoutMs: number,
387
+ controller: AbortController,
388
+ start: (index: number, signal: AbortSignal) => Promise<T>,
389
+ agreementKey?: (value: T) => string | null,
390
+ ): Promise<Gathered<T>> {
391
+ return new Promise<Gathered<T>>((resolve) => {
392
+ const slots: Array<Settled<T> | null> = Array.from({ length: count }, () => null);
393
+ const abandoned = new Set<number>();
394
+ const keys = new Map<string, number>();
395
+ let settledCount = 0;
396
+ let done = false;
397
+
398
+ const finishGroup = (timedOut: boolean, early: boolean): void => {
399
+ if (done) return;
400
+ done = true;
401
+ clearTimeout(timer);
402
+ slots.forEach((slot, i) => {
403
+ if (slot === null) abandoned.add(i);
404
+ });
405
+ rt.abandoned += abandoned.size;
406
+ resolve({ settled: slots.map((slot): Settled<T> => slot ?? { kind: "timeout" }), timedOut });
407
+ if (timedOut || early) controller.abort();
408
+ };
409
+
410
+ const onSettled = (index: number, outcome: Settled<T>): void => {
411
+ if (done) {
412
+ if (abandoned.delete(index)) rt.abandoned = Math.max(0, rt.abandoned - 1);
413
+ return;
414
+ }
415
+ slots[index] = outcome;
416
+ settledCount++;
417
+ if (agreementKey !== undefined && outcome.kind === "value") {
418
+ const key = agreementKey(outcome.v);
419
+ if (key !== null) {
420
+ const seen = (keys.get(key) ?? 0) + 1;
421
+ keys.set(key, seen);
422
+ if (seen >= 2 && settledCount < count) {
423
+ finishGroup(false, true);
424
+ return;
425
+ }
426
+ }
427
+ }
428
+ if (settledCount === count) finishGroup(false, false);
429
+ };
430
+
431
+ const delay = Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : 0;
432
+ const timer = setTimeout(() => finishGroup(true, false), delay);
433
+ (timer as { unref?: () => void }).unref?.();
434
+
435
+ for (let i = 0; i < count; i++) {
436
+ (async () => start(i, controller.signal))().then(
437
+ (v) => onSettled(i, { kind: "value", v }),
438
+ (e: unknown) => onSettled(i, { kind: "error", e }),
439
+ );
440
+ }
441
+ });
442
+ }
443
+ // ---------------------------------------------------------------------------
444
+ // Text hygiene
445
+ // ---------------------------------------------------------------------------
446
+
447
+ /** Error → short, scrubbed reason. Never contains state text (errors are not built from it). */
448
+ export function reasonOf(error: unknown): string {
449
+ let message: unknown = error;
450
+ if (typeof error === "object" && error !== null && "message" in error) {
451
+ message = (error as { message?: unknown }).message;
452
+ }
453
+ let text: string;
454
+ try {
455
+ text = String(message);
456
+ } catch {
457
+ text = "unprintable error";
458
+ }
459
+ return scrubAndCut(text, 200);
460
+ }
461
+
462
+ export function cutRaw(text: string): string {
463
+ return scrubAndCut(text, RAW_ANSWER_MAX_CHARS);
464
+ }
465
+
466
+ // ---------------------------------------------------------------------------
467
+ // Outcomes, results and logging
468
+ // ---------------------------------------------------------------------------
469
+
470
+ export interface BackendRuntime {
471
+ readonly id: BackendId;
472
+ readonly logger: ClassifierLogger;
473
+ readonly now: () => number;
474
+ /** `disabled` reasons already logged by this instance. */
475
+ readonly disabledLogged: Set<string>;
476
+ /** Consecutive timeouts/errors (circuit breaker). */
477
+ failures: number;
478
+ /** The breaker keeps the backend disabled until this time (ms, `now`); 0 = closed. */
479
+ openUntil: number;
480
+ /** Requests still in flight after their call ended (timed out, or left behind by an early majority). */
481
+ abandoned: number;
482
+ }
483
+
484
+ export function createRuntime(
485
+ id: BackendId,
486
+ logger: ClassifierLogger,
487
+ now: (() => number) | undefined,
488
+ ): BackendRuntime {
489
+ return { id, logger, now: now ?? Date.now, disabledLogged: new Set(), failures: 0, openUntil: 0, abandoned: 0 };
490
+ }
491
+
492
+ /** Logger calls must not break the never-throws contract of a backend. */
493
+ export function safeWarn(logger: ClassifierLogger, message: string, extra?: Record<string, unknown>): void {
494
+ try {
495
+ logger.warn(message, extra);
496
+ } catch (error) {
497
+ console.error(`[model-router] classifier logger failed: ${reasonOf(error)}`);
498
+ }
499
+ }
500
+
501
+ /** What a backend concluded, before it becomes a `BackendResult`. */
502
+ export interface Outcome {
503
+ readonly status: BackendStatus;
504
+ readonly label?: TaskClass;
505
+ readonly confidence?: number;
506
+ readonly raw: string | null;
507
+ readonly reason?: string;
508
+ readonly risk?: Risk;
509
+ readonly scope?: Scope;
510
+ }
511
+
512
+ export function buildResult(
513
+ rt: BackendRuntime,
514
+ outcome: Outcome,
515
+ calls: number,
516
+ latencyMs: number,
517
+ ): BackendResult {
518
+ const reason = outcome.reason === undefined ? {} : { reason: outcome.reason };
519
+ if (outcome.status === "ok" && outcome.label !== undefined) {
520
+ return {
521
+ facts: {
522
+ class: outcome.label,
523
+ confidence: outcome.confidence ?? CONFIDENCE.backendSingleSample,
524
+ source: rt.id,
525
+ ...(outcome.risk ? { risk: outcome.risk } : {}),
526
+ ...(outcome.scope ? { scope: outcome.scope } : {}),
527
+ },
528
+ raw: outcome.raw,
529
+ status: "ok",
530
+ latencyMs,
531
+ calls,
532
+ };
533
+ }
534
+ if (outcome.status === "disagree") {
535
+ return {
536
+ facts: { class: "other", confidence: 0, source: rt.id },
537
+ raw: outcome.raw,
538
+ status: "disagree",
539
+ ...reason,
540
+ latencyMs,
541
+ calls,
542
+ };
543
+ }
544
+ return {
545
+ facts: { class: "other", confidence: 0, source: "unknown" },
546
+ raw: outcome.raw,
547
+ status: outcome.status === "ok" ? "invalid" : outcome.status,
548
+ ...reason,
549
+ latencyMs,
550
+ calls,
551
+ };
552
+ }
553
+
554
+ /**
555
+ * Log every non-ok result once per occurrence as `classifier <id>: <status> (<reason>)`
556
+ * (one line per distinct status/reason for a batch); `disabled` once per
557
+ * instance and reason. Never logs state text, prompts, keys or headers.
558
+ */
559
+ export function logResults(rt: BackendRuntime, results: readonly BackendResult[]): void {
560
+ const groups = new Map<string, { result: BackendResult; items: number }>();
561
+ for (const result of results) {
562
+ if (result.status === "ok") continue;
563
+ const key = `${result.status}\u0000${result.reason ?? ""}`;
564
+ const group = groups.get(key);
565
+ if (group) group.items++;
566
+ else groups.set(key, { result, items: 1 });
567
+ }
568
+ for (const [key, { result, items }] of groups) {
569
+ if (result.status === "disabled") {
570
+ if (rt.disabledLogged.has(key)) continue;
571
+ rt.disabledLogged.add(key);
572
+ }
573
+ const extra: Record<string, unknown> = { latencyMs: result.latencyMs, calls: result.calls };
574
+ if (results.length > 1) extra.items = items;
575
+ safeWarn(rt.logger, `classifier ${rt.id}: ${result.status} (${result.reason ?? "no reason"})`, extra);
576
+ }
577
+ }
578
+
579
+ // ---------------------------------------------------------------------------
580
+ // Circuit breaker and abandoned-request cap (QA-1.2-10)
581
+ // ---------------------------------------------------------------------------
582
+
583
+ /**
584
+ * Why this instance must not issue a request right now, or null. Stable text, so
585
+ * the once-per-reason `disabled` log does not repeat while the condition holds.
586
+ */
587
+ export function backendUnavailable(rt: BackendRuntime): string | null {
588
+ if (rt.openUntil > rt.now()) {
589
+ return `circuit breaker open after ${BREAKER_FAILURES} consecutive timeouts or errors (${BREAKER_COOLDOWN_MS / 60_000} min cooldown)`;
590
+ }
591
+ if (rt.abandoned >= MAX_ABANDONED_REQUESTS) {
592
+ return `too many abandoned requests still in flight (limit ${MAX_ABANDONED_REQUESTS})`;
593
+ }
594
+ return null;
595
+ }
596
+
597
+ /**
598
+ * Feed one call's statuses to the breaker. A timeout or error is a failure; any
599
+ * answer the server actually gave (ok, disagree, invalid) closes the circuit;
600
+ * `disabled` says nothing. After the cooldown the next call is a trial: a single
601
+ * failure reopens the circuit at once.
602
+ */
603
+ function recordStatuses(rt: BackendRuntime, statuses: readonly BackendStatus[]): void {
604
+ if (statuses.some((s) => s === "ok" || s === "disagree" || s === "invalid")) {
605
+ rt.failures = 0;
606
+ rt.openUntil = 0;
607
+ return;
608
+ }
609
+ if (!statuses.some((s) => s === "timeout" || s === "error")) return;
610
+ rt.failures++;
611
+ if (rt.failures >= BREAKER_FAILURES) {
612
+ rt.openUntil = rt.now() + BREAKER_COOLDOWN_MS;
613
+ safeWarn(
614
+ rt.logger,
615
+ `classifier ${rt.id}: circuit breaker opened after ${rt.failures} consecutive timeouts or errors; no requests for ${BREAKER_COOLDOWN_MS / 60_000} min`,
616
+ );
617
+ }
618
+ }
619
+
620
+ /** A finished single classification: build, log, return. */
621
+ export function finish(rt: BackendRuntime, outcome: Outcome, calls: number, startedAt: number): BackendResult {
622
+ const result = buildResult(rt, outcome, calls, Math.max(0, rt.now() - startedAt));
623
+ recordStatuses(rt, [result.status]);
624
+ logResults(rt, [result]);
625
+ return result;
626
+ }
627
+
628
+ /** A finished batch: build each, log the distinct non-ok outcomes once. */
629
+ export function finishMany(
630
+ rt: BackendRuntime,
631
+ outcomes: readonly Outcome[],
632
+ calls: number,
633
+ startedAt: number,
634
+ ): BackendResult[] {
635
+ const latencyMs = Math.max(0, rt.now() - startedAt);
636
+ const results = outcomes.map((outcome) => buildResult(rt, outcome, calls, latencyMs));
637
+ recordStatuses(rt, results.map((r) => r.status));
638
+ logResults(rt, results);
639
+ return results;
640
+ }
641
+
642
+ // ---------------------------------------------------------------------------
643
+ // Sample resolution (host and openai-compatible)
644
+ // ---------------------------------------------------------------------------
645
+
646
+ export interface SampleAnswer {
647
+ readonly label: TaskClass | null;
648
+ readonly raw: string | null;
649
+ /** Why `label` is null, when the backend knows (non-JSON body, no content…). */
650
+ readonly reason?: string;
651
+ }
652
+
653
+ interface HasRaw {
654
+ readonly raw: string | null;
655
+ readonly reason?: string;
656
+ }
657
+
658
+ /** Combine the settled requests' labels for ONE item into an outcome (vote, then failure mapping). */
659
+ export function resolveOutcome(
660
+ labels: readonly (TaskClass | null)[],
661
+ settled: readonly Settled<HasRaw>[],
662
+ samples: 1 | 3,
663
+ timedOut: boolean,
664
+ timeoutMs: number,
665
+ ): Outcome {
666
+ const verdict = vote(labels, samples);
667
+ let raw: string | null = null;
668
+ for (const s of settled) {
669
+ if (s.kind === "value" && s.v.raw !== null) {
670
+ raw = s.v.raw;
671
+ break;
672
+ }
673
+ }
674
+ if (verdict.status === "ok") {
675
+ return { status: "ok", label: verdict.label, confidence: verdict.confidence, raw };
676
+ }
677
+ if (verdict.status === "disagree") {
678
+ return { status: "disagree", confidence: 0, raw, reason: "samples disagree" };
679
+ }
680
+ if (timedOut) {
681
+ return { status: "timeout", raw, reason: `no answer within ${timeoutMs} ms` };
682
+ }
683
+ for (const s of settled) {
684
+ if (s.kind === "error") return { status: "error", raw, reason: reasonOf(s.e) };
685
+ }
686
+ for (const s of settled) {
687
+ if (s.kind === "value" && s.v.reason !== undefined) return { status: "invalid", raw, reason: s.v.reason };
688
+ }
689
+ return { status: "invalid", raw, reason: "answer is not one of the labels" };
690
+ }
691
+
692
+ /** Result of a call that could not run (misconfiguration). */
693
+ export function disabled(rt: BackendRuntime, reason: string, startedAt: number): BackendResult {
694
+ return finish(rt, { status: "disabled", raw: null, reason }, 0, startedAt);
695
+ }
696
+
697
+ /** `disabled` for every item of a batch. */
698
+ export function disabledMany(
699
+ rt: BackendRuntime,
700
+ count: number,
701
+ reason: string,
702
+ startedAt: number,
703
+ ): BackendResult[] {
704
+ return finishMany(
705
+ rt,
706
+ Array.from({ length: count }, (): Outcome => ({ status: "disabled", raw: null, reason })),
707
+ 0,
708
+ startedAt,
709
+ );
710
+ }
711
+
712
+ /** Belt and braces: wrap a backend body so an unexpected throw becomes an `error` result. */
713
+ export async function guarded(
714
+ rt: BackendRuntime,
715
+ startedAt: number,
716
+ run: () => Promise<BackendResult>,
717
+ ): Promise<BackendResult> {
718
+ try {
719
+ return await run();
720
+ } catch (error) {
721
+ return finish(rt, { status: "error", raw: null, reason: reasonOf(error) }, 0, startedAt);
722
+ }
723
+ }
724
+
725
+ export async function guardedMany(
726
+ rt: BackendRuntime,
727
+ count: number,
728
+ startedAt: number,
729
+ run: () => Promise<BackendResult[]>,
730
+ ): Promise<BackendResult[]> {
731
+ try {
732
+ return await run();
733
+ } catch (error) {
734
+ return finishMany(
735
+ rt,
736
+ Array.from({ length: count }, (): Outcome => ({ status: "error", raw: null, reason: reasonOf(error) })),
737
+ 0,
738
+ startedAt,
739
+ );
740
+ }
741
+ }