opencode-model-router 2.2.0 → 2.4.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 (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -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 +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -0,0 +1,594 @@
1
+ /**
2
+ * Task classifier (M2) — composition. Design section 6 of
3
+ * `docs/qa/cost-aware-routing/phase-1.2.md`.
4
+ *
5
+ * `classify` / `classifyMany` run the deterministic rules, apply the `[route]`
6
+ * line, and consult a model backend ONLY when the rules are unsure (D4). They
7
+ * never throw and always settle within `timeoutMs + INDEX_TIMEOUT_GRACE_MS`
8
+ * of a hung backend: every failure leaves the rules facts (or `UNKNOWN_FACTS`
9
+ * with confidence 0, which never switches a model, D9).
10
+ */
11
+
12
+ import type { RouterConfig } from "../../router/config";
13
+ import { createHostBackend } from "./backends/host";
14
+ import { createOpenAICompatibleBackend } from "./backends/openai-compatible";
15
+ import {
16
+ raceTimeout,
17
+ reasonOf,
18
+ round2,
19
+ safeWarn,
20
+ } from "./backends/shared";
21
+ import { createTypeSafeBackend } from "./backends/typesafe";
22
+ import { applyRouteLine, parseRouteLine, type RouteLinePositions } from "./route-line";
23
+ import { analyzeRules, needMatchesOf, type NeedMatch } from "./rules";
24
+
25
+ export type { NeedMatch } from "./rules";
26
+ import { hasCredentialSignal } from "./scrub";
27
+ import { buildClassifierState, classifierStateRawParts } from "./state";
28
+ import {
29
+ BACKEND_IDS,
30
+ CLASS_BASE_RISK,
31
+ CLASS_IMPLIED_NEEDS,
32
+ CLASS_OPTIONS,
33
+ CONFIDENCE,
34
+ INDEX_TIMEOUT_GRACE_MS,
35
+ MAX_BATCH_ITEMS,
36
+ RULES_MAX_CHARS,
37
+ NEEDS,
38
+ RISKS,
39
+ SCOPES,
40
+ TASK_CLASSES,
41
+ UNKNOWN_FACTS,
42
+ type BackendResult,
43
+ type BackendStatus,
44
+ type ClassifierBackend,
45
+ type ClassifierLogger,
46
+ type ClassifierSettings,
47
+ type ClassifierState,
48
+ type ClassifyInput,
49
+ type ClassifyResult,
50
+ type EnvLike,
51
+ type FetchLike,
52
+ type HostGenerate,
53
+ type Need,
54
+ type Risk,
55
+ type RouteLineParse,
56
+ type Scope,
57
+ type TaskClass,
58
+ type TaskFacts,
59
+ } from "./types";
60
+
61
+ export * from "./types";
62
+
63
+ export interface ClassifyDeps {
64
+ readonly cfg: Pick<RouterConfig, "taskPatterns">;
65
+ /** Resolved, preset overrides applied. */
66
+ readonly settings: ClassifierSettings;
67
+ readonly minClassConfidence: number;
68
+ /** From `createClassifierBackend`, built once per config load. */
69
+ readonly backend: ClassifierBackend | null;
70
+ readonly logger: ClassifierLogger;
71
+ /** Uniform [0, 1) source for the option shuffle and nonces; default `Math.random`. */
72
+ readonly random?: () => number;
73
+ /**
74
+ * Where a `[route]` line is recognised (A22): `first` (default) = only the first
75
+ * non-empty line of the prompt; `edges` = first or last; `any` = anywhere
76
+ * outside fences, quotes and indented code (tests and tooling).
77
+ */
78
+ readonly routeLinePositions?: RouteLinePositions;
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Helpers
83
+ // ---------------------------------------------------------------------------
84
+
85
+ const BACKEND_STATUSES: readonly BackendStatus[] = ["ok", "disagree", "invalid", "timeout", "error", "disabled"];
86
+
87
+ function maxOf<T extends string>(order: readonly T[], ...values: T[]): T {
88
+ let best = values[0]!;
89
+ for (const value of values) {
90
+ if (order.indexOf(value) > order.indexOf(best)) best = value;
91
+ }
92
+ return best;
93
+ }
94
+
95
+ function orderedNeeds(needs: Iterable<Need>): Need[] {
96
+ const set = new Set<Need>(needs);
97
+ return NEEDS.filter((need) => set.has(need));
98
+ }
99
+
100
+ function synthetic(status: BackendStatus, reason: string, latencyMs: number): BackendResult {
101
+ return {
102
+ facts: { class: "other", confidence: 0, source: "unknown" },
103
+ raw: null,
104
+ status,
105
+ reason,
106
+ latencyMs,
107
+ calls: 0,
108
+ };
109
+ }
110
+
111
+ const BACKEND_SOURCES: readonly string[] = [...BACKEND_IDS, "unknown"];
112
+
113
+ function isNonNegativeNumber(value: unknown): value is number {
114
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
115
+ }
116
+
117
+ /**
118
+ * A backend result is trusted only when every field the merge or the decision
119
+ * log reads is well formed: status, class, confidence in [0, 1], source, the
120
+ * optional risk and scope, and the bookkeeping numbers (QA-1.2-20).
121
+ */
122
+ function isValidResult(value: unknown): value is BackendResult {
123
+ if (typeof value !== "object" || value === null) return false;
124
+ const r = value as Partial<BackendResult>;
125
+ if (typeof r.status !== "string" || !BACKEND_STATUSES.includes(r.status)) return false;
126
+ if (!isNonNegativeNumber(r.latencyMs) || !isNonNegativeNumber(r.calls)) return false;
127
+ if (r.raw !== null && typeof r.raw !== "string") return false;
128
+ if (r.reason !== undefined && typeof r.reason !== "string") return false;
129
+ const facts = r.facts;
130
+ if (typeof facts !== "object" || facts === null) return false;
131
+ if (!TASK_CLASSES.includes(facts.class)) return false;
132
+ const confidence = facts.confidence;
133
+ if (typeof confidence !== "number" || !Number.isFinite(confidence) || confidence < 0 || confidence > 1) {
134
+ return false;
135
+ }
136
+ if (!BACKEND_SOURCES.includes(facts.source)) return false;
137
+ if (facts.risk !== undefined && !RISKS.includes(facts.risk)) return false;
138
+ if (facts.scope !== undefined && !SCOPES.includes(facts.scope)) return false;
139
+ return true;
140
+ }
141
+ /** The classes a backend may pick: those the rules matched (search and recon are one family); null = any. */
142
+ function allowedClasses(matched: readonly TaskClass[]): ReadonlySet<TaskClass> | null {
143
+ if (matched.length === 0) return null;
144
+ const allowed = new Set<TaskClass>(matched);
145
+ if (allowed.has("search") || allowed.has("recon")) {
146
+ allowed.add("search");
147
+ allowed.add("recon");
148
+ }
149
+ return allowed;
150
+ }
151
+
152
+ interface MergeContext {
153
+ readonly matched: readonly TaskClass[];
154
+ }
155
+
156
+ interface Merged {
157
+ readonly facts: TaskFacts;
158
+ /** The backend's `ok` label is not a class the rules matched (A19). */
159
+ readonly rejected: boolean;
160
+ /** The backend's `ok` label, whatever became of it. */
161
+ readonly label?: TaskClass;
162
+ /** A matched label that differs from the rules class: kept in the trace only (QA-1.2-27). */
163
+ readonly disagrees: boolean;
164
+ }
165
+
166
+ /**
167
+ * Step 5 merge: what a backend result does to the rules facts (A19, QA-1.2-27).
168
+ *
169
+ * The rules class always stands in `facts`. The backend can only AGREE with it
170
+ * (same class, not `other`): then confidence rises to at least 0.8 and its risk,
171
+ * scope and needs are merged in. A label the rules did not match is `rejected`;
172
+ * a matched label that differs from the rules class is recorded in the trace
173
+ * (`label`, `disagrees`) and nothing else: a class the engine would have to
174
+ * trust at a confidence below `minClassConfidence` must not exist in `facts`, so
175
+ * no outcome can later be recorded under it.
176
+ */
177
+ function mergeBackend(facts: TaskFacts, result: BackendResult, ctx: MergeContext): Merged {
178
+ if (result.status === "disagree") return { facts: { ...facts, confidence: 0 }, rejected: false, disagrees: false };
179
+ if (result.status !== "ok") return { facts, rejected: false, disagrees: false };
180
+
181
+ const label = result.facts.class;
182
+ const allowed = allowedClasses(ctx.matched);
183
+ if (allowed !== null && !allowed.has(label)) return { facts, rejected: true, label, disagrees: false };
184
+ if (label !== facts.class || label === "other") {
185
+ return { facts, rejected: false, label, disagrees: label !== facts.class };
186
+ }
187
+ return {
188
+ facts: {
189
+ class: facts.class,
190
+ risk: maxOf<Risk>(RISKS, facts.risk, CLASS_BASE_RISK[label], result.facts.risk ?? "low"),
191
+ scope: maxOf<Scope>(SCOPES, facts.scope, result.facts.scope ?? "single"),
192
+ needs: orderedNeeds([...facts.needs, ...CLASS_IMPLIED_NEEDS[label]]),
193
+ confidence: Math.max(result.facts.confidence, CONFIDENCE.backendAgreesWithRules),
194
+ source: result.facts.source,
195
+ },
196
+ rejected: false,
197
+ label,
198
+ disagrees: false,
199
+ };
200
+ }
201
+ /** Step 6 invariants: every path ends here. */
202
+ function finalize(facts: TaskFacts): TaskFacts {
203
+ let confidence = Number.isFinite(facts.confidence) ? Math.min(1, Math.max(0, facts.confidence)) : 0;
204
+ if (facts.class === "mechanical" && facts.risk === "high") {
205
+ confidence = Math.min(confidence, CONFIDENCE.mechanicalHighRiskCap);
206
+ }
207
+ return Object.freeze({
208
+ class: facts.class,
209
+ risk: facts.risk,
210
+ scope: facts.scope,
211
+ needs: Object.freeze(orderedNeeds(facts.needs)),
212
+ confidence: round2(confidence),
213
+ source: facts.source,
214
+ });
215
+ }
216
+
217
+ function unknownResult(stripped: string): ClassifyResult {
218
+ return {
219
+ facts: UNKNOWN_FACTS,
220
+ pin: false,
221
+ detection: null,
222
+ stripped,
223
+ trace: {
224
+ rules: UNKNOWN_FACTS,
225
+ routeLine: null,
226
+ routeLines: { count: 0, conflict: false, edgeOnly: true },
227
+ backend: null,
228
+ },
229
+ };
230
+ }
231
+
232
+ /**
233
+ * The prompt with its route lines removed, for the failure paths: whatever broke
234
+ * the classification, the rewritten prompt must not carry a `[route …]` line to
235
+ * the subagent. Its own `try`: stripping may succeed where the rest failed, and
236
+ * if it does fail, a plain line filter (which cannot throw on a string) stands in.
237
+ */
238
+ function strippedOf(input: ClassifyInput, deps: ClassifyDeps): string {
239
+ const prompt = promptOf(input);
240
+ try {
241
+ return parseRouteLine(prompt, routeLineOptions(deps)).stripped;
242
+ } catch (error) {
243
+ safeWarn(deps.logger, `classifier could not strip route lines: ${reasonOf(error)}`);
244
+ return prompt
245
+ .split(/\r?\n/)
246
+ .filter((line) => !/^\s*\[route\b/i.test(line))
247
+ .join("\n");
248
+ }
249
+ }
250
+
251
+ /** The prompt of an input that may be hostile (a throwing getter was already logged by the caller). */
252
+ function promptOf(input: ClassifyInput): string {
253
+ try {
254
+ return typeof input.prompt === "string" ? input.prompt : "";
255
+ } catch {
256
+ // The same access failure is logged by the caller as "classifier failed".
257
+ return "";
258
+ }
259
+ }
260
+
261
+ interface Prepared {
262
+ readonly input: ClassifyInput;
263
+ readonly parsed: RouteLineParse;
264
+ readonly rules: TaskFacts;
265
+ /** Classes the rules matched (A19), highest cost first. */
266
+ readonly matched: readonly TaskClass[];
267
+ readonly facts: TaskFacts;
268
+ }
269
+
270
+ function routeLineOptions(deps: ClassifyDeps): { readonly positions: RouteLinePositions } {
271
+ return { positions: deps.routeLinePositions ?? "first" };
272
+ }
273
+
274
+ /** The text the rules layer reads: the description, then the prompt without its route lines. */
275
+ function ruleTextOf(input: ClassifyInput, parsed: RouteLineParse): string {
276
+ const description = typeof input.description === "string" ? input.description.trim() : "";
277
+ return [description.slice(0, RULES_MAX_CHARS), parsed.stripped.slice(0, RULES_MAX_CHARS)]
278
+ .filter(Boolean)
279
+ .join("\n");
280
+ }
281
+
282
+ /**
283
+ * #84 QA-G-B-3: the needs the rules layer finds in the text of `input` itself, and why (rules.ts `needMatchesOf` on the same text
284
+ * and `cwd` as `classify`; never the class-implied needs). Never calls a backend.
285
+ */
286
+ export function classifyNeedMatches(input: ClassifyInput, deps: Pick<ClassifyDeps, "routeLinePositions">): NeedMatch[] {
287
+ const parsed = parseRouteLine(typeof input.prompt === "string" ? input.prompt : "", { positions: deps.routeLinePositions ?? "first" });
288
+ return needMatchesOf(ruleTextOf(input, parsed), { ...(input.cwd === undefined ? {} : { cwd: input.cwd }) });
289
+ }
290
+
291
+ /** Steps 1–3: route line, rules, route line applied. */
292
+ function prepare(input: ClassifyInput, deps: ClassifyDeps): Prepared {
293
+ const parsed = parseRouteLine(typeof input.prompt === "string" ? input.prompt : "", routeLineOptions(deps));
294
+ const ruleText = ruleTextOf(input, parsed);
295
+ const analysis = analyzeRules(ruleText, deps.cfg, { cwd: input.cwd });
296
+ const rules = analysis.facts;
297
+ const facts = parsed.line ? applyRouteLine(rules, parsed.line) : rules;
298
+ return { input, parsed, rules, matched: analysis.matched, facts };
299
+ }
300
+
301
+ /** Step 4: only unsure rules facts go to a backend. */
302
+ function isGated(facts: TaskFacts, deps: ClassifyDeps): boolean {
303
+ return (
304
+ deps.backend !== null &&
305
+ deps.settings.backend !== "rules" &&
306
+ facts.source === "rules" &&
307
+ facts.confidence < deps.minClassConfidence
308
+ );
309
+ }
310
+
311
+ /**
312
+ * Policy gate (QA-1.2-1): a task that names a credential, or contains something
313
+ * the scrubber had to redact, never reaches a backend; the rules facts stand.
314
+ */
315
+ function mentionsCredentials(prepared: Prepared, acceptanceIncluded: boolean): boolean {
316
+ const description = typeof prepared.input.description === "string" ? prepared.input.description : "";
317
+ const raw = classifierStateRawParts({ description, prompt: prepared.parsed.stripped });
318
+ return [raw.description, acceptanceIncluded ? raw.acceptance : null, raw.body].some((part) => part !== null && hasCredentialSignal(part));
319
+ }
320
+
321
+ function resultOf(
322
+ prepared: Prepared,
323
+ backend: ClassifierBackend | null,
324
+ outcome: BackendResult | null,
325
+ options: { readonly skipped?: "credentials" } = {},
326
+ ): ClassifyResult {
327
+ const skipped = options.skipped;
328
+ const merged: Merged =
329
+ outcome === null
330
+ ? { facts: prepared.facts, rejected: false, disagrees: false }
331
+ : mergeBackend(prepared.facts, outcome, { matched: prepared.matched });
332
+ return {
333
+ facts: finalize(merged.facts),
334
+ pin: prepared.parsed.line?.pin ?? false,
335
+ detection: prepared.parsed.line?.detection ?? null,
336
+ stripped: prepared.parsed.stripped,
337
+ trace: {
338
+ rules: prepared.rules,
339
+ routeLine: prepared.parsed.line,
340
+ routeLines: {
341
+ count: prepared.parsed.count,
342
+ conflict: prepared.parsed.conflict,
343
+ edgeOnly: prepared.parsed.edgeOnly,
344
+ // QA-P12-2-2 (P2.1): surface a malformed first route line; absent otherwise (tier rows copy only the three fields above).
345
+ ...(prepared.parsed.malformed === true ? { malformed: true as const } : {}),
346
+ },
347
+ ...(skipped ? { backendSkipped: skipped } : {}),
348
+ backend:
349
+ backend === null || outcome === null
350
+ ? null
351
+ : {
352
+ id: backend.id,
353
+ status: outcome.status,
354
+ ...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
355
+ latencyMs: outcome.latencyMs,
356
+ calls: outcome.calls,
357
+ ...(merged.label === undefined ? {} : { label: merged.label }),
358
+ ...(merged.rejected ? { rejected: true as const } : {}),
359
+ ...(merged.disagrees ? { disagrees: true as const } : {}),
360
+ },
361
+ },
362
+ };
363
+ }
364
+
365
+ function logSynthetic(deps: ClassifyDeps, backend: ClassifierBackend, result: BackendResult): void {
366
+ safeWarn(deps.logger, `classifier ${backend.id}: ${result.status} (${result.reason ?? "no reason"})`, {
367
+ latencyMs: result.latencyMs,
368
+ calls: result.calls,
369
+ });
370
+ }
371
+
372
+ function hangBudget(deps: ClassifyDeps): number {
373
+ return deps.settings.timeoutMs + INDEX_TIMEOUT_GRACE_MS;
374
+ }
375
+
376
+ // ---------------------------------------------------------------------------
377
+ // classify
378
+ // ---------------------------------------------------------------------------
379
+
380
+ export async function classify(input: ClassifyInput, deps: ClassifyDeps): Promise<ClassifyResult> {
381
+ try {
382
+ const prepared = prepare(input, deps);
383
+ const backend = deps.backend;
384
+ if (backend === null || !isGated(prepared.facts, deps)) return resultOf(prepared, null, null);
385
+ const state = buildClassifierState(
386
+ { description: input.description, prompt: prepared.parsed.stripped },
387
+ deps.settings.maxStateChars,
388
+ );
389
+ if (mentionsCredentials(prepared, state.acceptanceIncluded)) return resultOf(prepared, null, null, { skipped: "credentials" });
390
+ const random = deps.random ?? Math.random;
391
+ const budget = hangBudget(deps);
392
+ const raced = await raceTimeout(
393
+ (async () => backend.classify(state, { choices: CLASS_OPTIONS, random }))(),
394
+ budget,
395
+ );
396
+ let outcome: BackendResult;
397
+ if (raced.kind === "value" && isValidResult(raced.v)) {
398
+ outcome = raced.v;
399
+ } else {
400
+ // The backend broke its contract (hung, rejected or returned garbage): the rules facts stand.
401
+ outcome =
402
+ raced.kind === "value"
403
+ ? synthetic("invalid", "malformed backend result", 0)
404
+ : raced.kind === "error"
405
+ ? synthetic("error", reasonOf(raced.e), 0)
406
+ : synthetic("timeout", `backend did not settle within ${budget} ms`, budget);
407
+ logSynthetic(deps, backend, outcome);
408
+ }
409
+ return resultOf(prepared, backend, outcome);
410
+ } catch (error) {
411
+ safeWarn(deps.logger, `classifier failed: ${reasonOf(error)}`);
412
+ return unknownResult(strippedOf(input, deps));
413
+ }
414
+ }
415
+
416
+ // ---------------------------------------------------------------------------
417
+ // classifyMany
418
+ // ---------------------------------------------------------------------------
419
+
420
+ interface GatedItem {
421
+ readonly index: number;
422
+ readonly prepared: Prepared;
423
+ readonly state: ClassifierState;
424
+ }
425
+
426
+ export async function classifyMany(
427
+ inputs: readonly ClassifyInput[],
428
+ deps: ClassifyDeps,
429
+ ): Promise<ClassifyResult[]> {
430
+ const list: readonly ClassifyInput[] = Array.isArray(inputs) ? inputs : [];
431
+ const results: Array<ClassifyResult | undefined> = list.map(() => undefined);
432
+ const prepared: Array<Prepared | undefined> = list.map(() => undefined);
433
+
434
+ try {
435
+ // Steps 1–3, one try per item: a failure costs only that item.
436
+ list.forEach((input, index) => {
437
+ try {
438
+ prepared[index] = prepare(input, deps);
439
+ } catch (error) {
440
+ safeWarn(deps.logger, `classifier failed: ${reasonOf(error)}`);
441
+ results[index] = unknownResult(strippedOf(input, deps));
442
+ }
443
+ });
444
+
445
+ const backend = deps.backend;
446
+ const gated: GatedItem[] = [];
447
+ const skipped = new Set<number>();
448
+ prepared.forEach((item, index) => {
449
+ if (item === undefined || backend === null || !isGated(item.facts, deps)) return;
450
+ try {
451
+ const input = list[index]!;
452
+ const state = buildClassifierState(
453
+ { description: input.description, prompt: item.parsed.stripped },
454
+ deps.settings.maxStateChars,
455
+ );
456
+ if (mentionsCredentials(item, state.acceptanceIncluded)) {
457
+ skipped.add(index);
458
+ return;
459
+ }
460
+ gated.push({ index, prepared: item, state });
461
+ } catch (error) {
462
+ safeWarn(deps.logger, `classifier failed: ${reasonOf(error)}`);
463
+ }
464
+ });
465
+
466
+ const outcomes = new Map<number, BackendResult>();
467
+ if (backend !== null && gated.length > 0) {
468
+ const random = deps.random ?? Math.random;
469
+ const budget = hangBudget(deps);
470
+ // A failed chunk (QA-1.2-10) means the backend is down or broken: asking it again for each remaining
471
+ // chunk would only burn one timeout per chunk, so the rest of the plan keeps its rules facts.
472
+ let skipRest: BackendResult | null = null;
473
+ for (let from = 0; from < gated.length; from += MAX_BATCH_ITEMS) {
474
+ const chunk = gated.slice(from, from + MAX_BATCH_ITEMS);
475
+ if (skipRest !== null) {
476
+ const skippedAnswer = skipRest;
477
+ chunk.forEach((item) => outcomes.set(item.index, skippedAnswer));
478
+ continue;
479
+ }
480
+ const states = chunk.map((item) => item.state);
481
+ const raced = await raceTimeout(
482
+ (async () => backend.classifyMany(states, { choices: CLASS_OPTIONS, random }))(),
483
+ budget,
484
+ );
485
+ let answers: BackendResult[];
486
+ if (raced.kind === "timeout") {
487
+ const failed = synthetic("timeout", `backend did not settle within ${budget} ms`, budget);
488
+ logSynthetic(deps, backend, failed);
489
+ answers = chunk.map(() => failed);
490
+ } else if (raced.kind === "error") {
491
+ const failed = synthetic("error", reasonOf(raced.e), 0);
492
+ logSynthetic(deps, backend, failed);
493
+ answers = chunk.map(() => failed);
494
+ } else if (Array.isArray(raced.v) && raced.v.length === chunk.length) {
495
+ answers = raced.v.map((entry: unknown) =>
496
+ isValidResult(entry) ? entry : synthetic("invalid", "malformed backend result", 0),
497
+ );
498
+ } else {
499
+ const failed = synthetic("invalid", "malformed backend batch result", 0);
500
+ logSynthetic(deps, backend, failed);
501
+ answers = chunk.map(() => failed);
502
+ }
503
+ chunk.forEach((item, i) => outcomes.set(item.index, answers[i]!));
504
+ const failedChunk =
505
+ raced.kind !== "value" ||
506
+ !Array.isArray(raced.v) ||
507
+ raced.v.length !== chunk.length ||
508
+ answers.every((a) => a.status === "timeout" || a.status === "error" || a.status === "disabled");
509
+ if (failedChunk && from + MAX_BATCH_ITEMS < gated.length) {
510
+ skipRest = synthetic("disabled", "skipped: the previous batch failed", 0);
511
+ safeWarn(
512
+ deps.logger,
513
+ `classifier ${backend.id}: skipping ${gated.length - from - MAX_BATCH_ITEMS} remaining items after a failed batch`,
514
+ );
515
+ }
516
+ }
517
+ }
518
+
519
+ prepared.forEach((item, index) => {
520
+ if (item === undefined) return;
521
+ results[index] = resultOf(
522
+ item,
523
+ backend,
524
+ outcomes.get(index) ?? null,
525
+ skipped.has(index) ? { skipped: "credentials" as const } : {},
526
+ );
527
+ });
528
+ } catch (error) {
529
+ safeWarn(deps.logger, `classifier failed: ${reasonOf(error)}`);
530
+ }
531
+
532
+ return results.map((result, index) => {
533
+ if (result !== undefined) return result;
534
+ const item = prepared[index];
535
+ return item === undefined
536
+ ? unknownResult(strippedOf(list[index]!, deps))
537
+ : resultOf(item, null, null);
538
+ });
539
+ }
540
+
541
+ // ---------------------------------------------------------------------------
542
+ // createClassifierBackend
543
+ // ---------------------------------------------------------------------------
544
+
545
+ export interface ClassifierBackendDeps {
546
+ readonly generate?: HostGenerate;
547
+ readonly fetch?: FetchLike;
548
+ readonly env?: EnvLike;
549
+ readonly logger: ClassifierLogger;
550
+ readonly now?: () => number;
551
+ }
552
+
553
+ /**
554
+ * Build the configured backend once per config load (the log-once set and the
555
+ * `response_format` memo live on the instance). Missing API keys are NOT
556
+ * checked here: `apiKeyEnv` is read at call time, so setting the variable later
557
+ * enables the backend without a reload.
558
+ */
559
+ export function createClassifierBackend(
560
+ settings: ClassifierSettings,
561
+ deps: ClassifierBackendDeps,
562
+ ): ClassifierBackend | null {
563
+ const { logger, now } = deps;
564
+ switch (settings.backend) {
565
+ case "rules":
566
+ return null;
567
+ case "host":
568
+ if (deps.generate === undefined) {
569
+ safeWarn(logger, "classifier: host classifier needs the v2 plugin context; using rules");
570
+ return null;
571
+ }
572
+ return createHostBackend({ generate: deps.generate, settings, logger, now });
573
+ case "openai-compatible":
574
+ case "typesafe": {
575
+ const fetchFn = deps.fetch ?? defaultFetch();
576
+ if (fetchFn === null) {
577
+ safeWarn(logger, `classifier: ${settings.backend} needs fetch, which is not available; using rules`);
578
+ return null;
579
+ }
580
+ const env: EnvLike = deps.env ?? process.env;
581
+ return settings.backend === "typesafe"
582
+ ? createTypeSafeBackend({ fetch: fetchFn, env, settings, logger, now })
583
+ : createOpenAICompatibleBackend({ fetch: fetchFn, env, settings, logger, now });
584
+ }
585
+ default:
586
+ safeWarn(logger, `classifier: unknown backend ${String(settings.backend)}; using rules`);
587
+ return null;
588
+ }
589
+ }
590
+
591
+ function defaultFetch(): FetchLike | null {
592
+ if (typeof globalThis.fetch !== "function") return null;
593
+ return (url, init) => globalThis.fetch(url, init);
594
+ }