opencode-model-router 1.1.16 → 1.2.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.
@@ -0,0 +1,180 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Trajectory scorecard — pure module, no fs/network/SDK/process.env
3
+ // ---------------------------------------------------------------------------
4
+
5
+ export interface TrajectoryToolEvent {
6
+ tool: string;
7
+ readOnly: boolean;
8
+ producing?: boolean;
9
+ blocked?: boolean;
10
+ selfScript?: boolean;
11
+ deliverable?: boolean;
12
+ ok?: boolean;
13
+ redundant?: boolean;
14
+ }
15
+
16
+ export interface TrajectoryState {
17
+ sessionID: string;
18
+ tier: string | null;
19
+ toolCallCount: number;
20
+ readCount: number;
21
+ execCount: number;
22
+ selfScriptCount: number;
23
+ redundantCount: number;
24
+ blockedCount: number;
25
+ deliverableExecuted: boolean;
26
+ ttfa: number | null;
27
+ stopReason: string | null;
28
+ // Layer 2/3 scaffolding fields (populated in later waves)
29
+ dodSource: "explicit" | "inferred" | "annotation" | null;
30
+ verdict: "PASS" | "FAIL" | "SKIPPED" | null;
31
+ verifyMethod: "deterministic" | "checker" | "none" | null;
32
+ graderTier: string | null;
33
+ attempts: number;
34
+ escalations: number;
35
+ finalTier: string | null;
36
+ costUnits: number;
37
+ }
38
+
39
+ export function createTrajectory(
40
+ sessionID: string,
41
+ tier?: string | null,
42
+ ): TrajectoryState {
43
+ return {
44
+ sessionID,
45
+ tier: tier ?? null,
46
+ toolCallCount: 0,
47
+ readCount: 0,
48
+ execCount: 0,
49
+ selfScriptCount: 0,
50
+ redundantCount: 0,
51
+ blockedCount: 0,
52
+ deliverableExecuted: false,
53
+ ttfa: null,
54
+ stopReason: null,
55
+ dodSource: null,
56
+ verdict: null,
57
+ verifyMethod: null,
58
+ graderTier: null,
59
+ attempts: 0,
60
+ escalations: 0,
61
+ finalTier: null,
62
+ costUnits: 0,
63
+ };
64
+ }
65
+
66
+ export function recordToolEvent(
67
+ state: TrajectoryState,
68
+ event: TrajectoryToolEvent,
69
+ ): void {
70
+ state.toolCallCount += 1;
71
+
72
+ if (event.blocked) {
73
+ state.blockedCount += 1;
74
+ }
75
+
76
+ if (event.selfScript) {
77
+ state.selfScriptCount += 1;
78
+ }
79
+
80
+ if (event.redundant) {
81
+ state.redundantCount += 1;
82
+ }
83
+
84
+ const producing = event.producing ?? !event.readOnly;
85
+
86
+ if (event.readOnly) {
87
+ state.readCount += 1;
88
+ }
89
+
90
+ if (producing) {
91
+ state.execCount += 1;
92
+ if (state.ttfa === null) {
93
+ state.ttfa = state.toolCallCount;
94
+ }
95
+ }
96
+
97
+ if (event.deliverable) {
98
+ state.deliverableExecuted = true;
99
+ }
100
+ }
101
+
102
+ export function setStopReason(state: TrajectoryState, reason: string): void {
103
+ if (state.stopReason === null) {
104
+ state.stopReason = reason;
105
+ }
106
+ }
107
+
108
+ export function trajectoryMetrics(
109
+ state: TrajectoryState,
110
+ ): Record<string, unknown> {
111
+ const readExecRatio =
112
+ state.execCount === 0
113
+ ? state.readCount
114
+ : state.readCount / state.execCount;
115
+
116
+ return {
117
+ ttfa: state.ttfa,
118
+ read_exec_ratio: readExecRatio,
119
+ self_script_count: state.selfScriptCount,
120
+ deliverable_executed: state.deliverableExecuted,
121
+ tool_call_count: state.toolCallCount,
122
+ stop_reason: state.stopReason,
123
+ dod_source: state.dodSource,
124
+ verdict: state.verdict,
125
+ verify_method: state.verifyMethod,
126
+ grader_tier: state.graderTier,
127
+ attempts: state.attempts,
128
+ escalations: state.escalations,
129
+ final_tier: state.finalTier,
130
+ cost_units: state.costUnits,
131
+ };
132
+ }
133
+
134
+ export function dumpTrajectory(state: TrajectoryState): string {
135
+ return `[trajectory ${state.sessionID}] ${JSON.stringify(trajectoryMetrics(state))}`;
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // Per-instance store factory — mirrors src/router/sessions.ts pattern
140
+ // ---------------------------------------------------------------------------
141
+
142
+ export function createTrajectoryStore() {
143
+ const store = new Map<string, TrajectoryState>();
144
+
145
+ function ensureState(sessionID: string, tier?: string | null): TrajectoryState {
146
+ let s = store.get(sessionID);
147
+ if (!s) {
148
+ s = createTrajectory(sessionID, tier);
149
+ store.set(sessionID, s);
150
+ }
151
+ return s;
152
+ }
153
+
154
+ return {
155
+ ensure(sessionID: string, tier?: string | null): TrajectoryState {
156
+ return ensureState(sessionID, tier);
157
+ },
158
+
159
+ get(sessionID: string): TrajectoryState | undefined {
160
+ return store.get(sessionID);
161
+ },
162
+
163
+ recordToolEvent(sessionID: string, event: TrajectoryToolEvent): void {
164
+ const s = ensureState(sessionID);
165
+ recordToolEvent(s, event);
166
+ },
167
+
168
+ setStopReason(sessionID: string, reason: string): void {
169
+ const s = store.get(sessionID);
170
+ if (!s) return;
171
+ setStopReason(s, reason);
172
+ },
173
+
174
+ dump(sessionID: string): string | null {
175
+ const s = store.get(sessionID);
176
+ if (!s) return null;
177
+ return dumpTrajectory(s);
178
+ },
179
+ };
180
+ }
@@ -0,0 +1,224 @@
1
+ // src/verify/checker.ts
2
+ //
3
+ // Temperature pinning is a WIRING concern (chat.params keyed to the grader session),
4
+ // out of scope for this pure module.
5
+ // Producer != grader is enforced structurally (GraderDispatch MUST create a FRESH session
6
+ // each call) AND defensively here by sessionID inequality check (step 5).
7
+
8
+ import type { Verdict } from "./types";
9
+ import { scrubText } from "../guard/scrub";
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Public types
13
+ // ---------------------------------------------------------------------------
14
+
15
+ export interface ArtefactView {
16
+ finalReturnText: string;
17
+ changedFiles: { path: string; status: string }[];
18
+ declaredOutputs: string[];
19
+ }
20
+
21
+ export interface GraderRequest {
22
+ tier: string;
23
+ system: string;
24
+ prompt: string;
25
+ }
26
+
27
+ export interface GraderResult {
28
+ sessionID: string;
29
+ text: string;
30
+ }
31
+
32
+ /** MUST create a FRESH session each call */
33
+ export interface GraderDispatch {
34
+ (req: GraderRequest): Promise<GraderResult>;
35
+ }
36
+
37
+ export interface CheckerDeps {
38
+ dispatchGrader: GraderDispatch;
39
+ ladder?: string[]; // default ["fast","medium","heavy"]
40
+ minGraderTier?: string | null; // optional floor
41
+ }
42
+
43
+ export interface CheckerInput {
44
+ criteria: string[];
45
+ artefact: ArtefactView;
46
+ producerTier: string;
47
+ producerSessionID: string;
48
+ }
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Tier helpers
52
+ // ---------------------------------------------------------------------------
53
+
54
+ export function tierRank(tier: string, ladder: string[]): number {
55
+ const i = ladder.indexOf(tier);
56
+ return i < 0 ? ladder.length : i; // unknown tier ranks highest = safe
57
+ }
58
+
59
+ export function atLeastProducerTier(
60
+ producerTier: string,
61
+ opts?: { ladder?: string[]; minGraderTier?: string | null }
62
+ ): string {
63
+ const ladder = opts?.ladder ?? ["fast", "medium", "heavy"];
64
+ let idx = tierRank(producerTier, ladder);
65
+ if (opts?.minGraderTier != null) {
66
+ idx = Math.max(idx, tierRank(opts.minGraderTier, ladder));
67
+ }
68
+ const clamped = Math.min(idx, ladder.length - 1);
69
+ return ladder[clamped] ?? producerTier;
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Prompt builder
74
+ // ---------------------------------------------------------------------------
75
+
76
+ const GRADER_SYSTEM =
77
+ 'You are an independent, skeptical verification grader. You did NOT produce this work and have no stake in it. Evaluate ONLY whether the artefact satisfies EACH acceptance criterion below. For every criterion, cite concrete evidence from the artefact. If the evidence is missing, ambiguous, partial, or you are uncertain for ANY reason, you MUST fail that criterion. Default to FAIL. Do not give the benefit of the doubt. Output ONLY a single JSON object on one line: {"pass": boolean, "reasons": string[]}. Set pass=true ONLY if every criterion is satisfied with cited evidence; otherwise pass=false with a reason per failed criterion.';
78
+
79
+ export function buildGradingPrompt(input: CheckerInput): { system: string; prompt: string } {
80
+ const lines: string[] = [];
81
+
82
+ lines.push("## Acceptance criteria (ALL must be satisfied)");
83
+ for (let i = 0; i < input.criteria.length; i++) {
84
+ lines.push(`${i + 1}. ${input.criteria[i]}`);
85
+ }
86
+
87
+ lines.push("");
88
+ lines.push("## Artefact to evaluate");
89
+ lines.push("### Final return text");
90
+ lines.push(scrubText(input.artefact.finalReturnText) || "(empty)");
91
+
92
+ lines.push("");
93
+ lines.push("### Changed files");
94
+ if (input.artefact.changedFiles.length > 0) {
95
+ for (const f of input.artefact.changedFiles) {
96
+ lines.push(`- ${f.status} ${scrubText(f.path)}`);
97
+ }
98
+ } else {
99
+ lines.push("(none)");
100
+ }
101
+
102
+ lines.push("");
103
+ lines.push("### Declared outputs");
104
+ if (input.artefact.declaredOutputs.length > 0) {
105
+ for (const o of input.artefact.declaredOutputs) {
106
+ lines.push(`- ${scrubText(o)}`);
107
+ }
108
+ } else {
109
+ lines.push("(none)");
110
+ }
111
+
112
+ lines.push("");
113
+ lines.push("Respond with the JSON verdict now.");
114
+
115
+ return { system: GRADER_SYSTEM, prompt: lines.join("\n") };
116
+ }
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // Verdict parser
120
+ // ---------------------------------------------------------------------------
121
+
122
+ export function parseGraderVerdict(text: string): { pass: boolean; reasons: string[] } | null {
123
+ try {
124
+ let raw: string | null = null;
125
+
126
+ // Try fenced ```json ... ``` first
127
+ const fenced = /```json\s*([\s\S]*?)\s*```/.exec(text);
128
+ if (fenced) {
129
+ raw = fenced[1] ?? null;
130
+ } else {
131
+ // First "{" to last "}"
132
+ const start = text.indexOf("{");
133
+ const end = text.lastIndexOf("}");
134
+ if (start !== -1 && end !== -1 && end > start) {
135
+ raw = text.slice(start, end + 1);
136
+ }
137
+ }
138
+
139
+ if (raw === null) return null;
140
+
141
+ const result = JSON.parse(raw) as unknown;
142
+ if (typeof result !== "object" || result === null) return null;
143
+
144
+ const r = result as Record<string, unknown>;
145
+ if (typeof r["pass"] !== "boolean") return null;
146
+
147
+ if (!("reasons" in r) || r["reasons"] === undefined) {
148
+ return { pass: r["pass"] as boolean, reasons: [] };
149
+ }
150
+
151
+ if (!Array.isArray(r["reasons"])) return null;
152
+ for (const item of r["reasons"]) {
153
+ if (typeof item !== "string") return null;
154
+ }
155
+
156
+ return { pass: r["pass"] as boolean, reasons: r["reasons"] as string[] };
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // Main
164
+ // ---------------------------------------------------------------------------
165
+
166
+ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promise<Verdict> {
167
+ // 1. Empty criteria
168
+ if (input.criteria.length === 0) {
169
+ return { pass: false, method: "none", skipped: true, reasons: ["no criteria to grade"] };
170
+ }
171
+
172
+ // 2. Determine grader tier
173
+ const graderTier = atLeastProducerTier(input.producerTier, {
174
+ ladder: deps.ladder,
175
+ minGraderTier: deps.minGraderTier,
176
+ });
177
+
178
+ // 3. Build prompt
179
+ const { system, prompt } = buildGradingPrompt(input);
180
+
181
+ // 4. Dispatch grader
182
+ let res: GraderResult;
183
+ try {
184
+ res = await deps.dispatchGrader({ tier: graderTier, system, prompt });
185
+ } catch (err) {
186
+ return {
187
+ pass: false,
188
+ method: "checker",
189
+ reasons: [scrubText("grader dispatch failed: " + String(err))],
190
+ };
191
+ }
192
+
193
+ // 5. Independence check (fail-closed)
194
+ if (res.sessionID === input.producerSessionID || !res.sessionID) {
195
+ return {
196
+ pass: false,
197
+ method: "checker",
198
+ reasons: [
199
+ "grader session is not independent of the producer (producer=grader); refusing to accept",
200
+ ],
201
+ };
202
+ }
203
+
204
+ // 6. Parse verdict
205
+ const parsed = parseGraderVerdict(res.text);
206
+ if (parsed === null) {
207
+ return {
208
+ pass: false,
209
+ method: "checker",
210
+ reasons: [
211
+ "could not parse grader verdict; defaulting to FAIL",
212
+ scrubText(res.text.slice(0, 300)),
213
+ ],
214
+ };
215
+ }
216
+
217
+ // 7. Return verdict
218
+ return {
219
+ pass: parsed.pass === true,
220
+ method: "checker",
221
+ reasons: parsed.reasons.map(scrubText),
222
+ evidence: scrubText("grader=" + graderTier),
223
+ };
224
+ }