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