opencode-model-router 1.1.16 → 1.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.
@@ -0,0 +1,319 @@
1
+ // src/verify/deterministic.ts
2
+ // Deterministic verifier: runs DoD checks using injected seams (no real fs/exec imports).
3
+ // PURE: no Node built-ins; all I/O goes through DeterministicDeps seams.
4
+
5
+ import type { Check, DoD } from "./dod";
6
+ import type { Verdict, DeterministicDeps, MutexRegistry, ExecResult } from "./types";
7
+ import { scrubText } from "../guard/scrub";
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // MutexRegistry — per-key serialization via promise-chaining
11
+ // ---------------------------------------------------------------------------
12
+
13
+ export function createMutexRegistry(): MutexRegistry {
14
+ const chains = new Map<string, Promise<unknown>>();
15
+ return {
16
+ runExclusive<T>(key: string, fn: () => Promise<T>): Promise<T> {
17
+ const prev = chains.get(key) ?? Promise.resolve();
18
+ const run = prev.then(() => fn(), () => fn());
19
+ // Tail swallows errors so the lock never wedges; run still rejects/resolves with fn's result.
20
+ chains.set(key, run.then(() => {}, () => {}));
21
+ return run;
22
+ },
23
+ };
24
+ }
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Command validation
28
+ // ---------------------------------------------------------------------------
29
+
30
+ export const DEFAULT_ALLOWLIST = [
31
+ "npm", "npx", "pnpm", "yarn", "bun", "node",
32
+ "tsc", "tsx", "vitest", "jest", "eslint", "prettier",
33
+ ];
34
+
35
+ // Any shell-chaining / redirection / substitution metacharacter.
36
+ // eslint-disable-next-line no-useless-escape
37
+ export const FORBIDDEN_SHELL = /[;&|`$><\n]|\$\(|&&|\|\|/;
38
+
39
+ // Interpreters that can execute arbitrary inline code via a flag. An allowlisted
40
+ // interpreter must not be turned into an arbitrary-code runner (e.g. `node -e ...`).
41
+ const INTERPRETERS = new Set([
42
+ "node", "deno", "bun", "tsx", "ts-node", "python", "python3", "ruby", "perl",
43
+ ]);
44
+ // Inline-eval / inline-print flags: -e, -c, -p, --eval, --print (with optional =value).
45
+ const EVAL_FLAG_RE = /^-(e|c|p)$|^--(eval|print)(=|$)/i;
46
+
47
+ export function isCommandAllowed(command: string, allowlist: string[]): boolean {
48
+ const trimmed = command.trim();
49
+ if (!trimmed || FORBIDDEN_SHELL.test(command)) return false;
50
+ const tokens = trimmed.split(/\s+/);
51
+ const firstToken = tokens[0];
52
+ const parts = firstToken.split(/[/\\]/);
53
+ const basename = parts[parts.length - 1];
54
+ if (!allowlist.includes(basename)) return false;
55
+ // Strip a Windows executable suffix before the interpreter check.
56
+ const interpreterBase = basename.replace(/\.(exe|cmd|bat)$/i, "");
57
+ if (INTERPRETERS.has(interpreterBase)) {
58
+ for (const t of tokens.slice(1)) {
59
+ if (EVAL_FLAG_RE.test(t)) return false;
60
+ }
61
+ }
62
+ return true;
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Shape check (exported for unit testing)
67
+ // ---------------------------------------------------------------------------
68
+
69
+ export function shapeMismatch(
70
+ schemaVal: unknown,
71
+ targetVal: unknown,
72
+ path = "",
73
+ ): string | null {
74
+ if (schemaVal !== null && typeof schemaVal === "object" && !Array.isArray(schemaVal)) {
75
+ // schema is a plain object
76
+ if (targetVal === null || typeof targetVal !== "object" || Array.isArray(targetVal)) {
77
+ return `${path || "<root>"}: expected object`;
78
+ }
79
+ const schemaObj = schemaVal as Record<string, unknown>;
80
+ const targetObj = targetVal as Record<string, unknown>;
81
+ for (const k of Object.keys(schemaObj)) {
82
+ if (!(k in targetObj)) return `${path}${k}: missing`;
83
+ const nested = shapeMismatch(schemaObj[k], targetObj[k], `${path}${k}.`);
84
+ if (nested !== null) return nested;
85
+ }
86
+ return null;
87
+ } else if (Array.isArray(schemaVal)) {
88
+ if (!Array.isArray(targetVal)) return `${path || "<root>"}: expected array`;
89
+ return null; // presence of array suffices; elements/length not checked
90
+ } else {
91
+ // primitive
92
+ if (typeof schemaVal !== typeof targetVal) {
93
+ return `${path || "<root>"}: expected ${typeof schemaVal}, got ${typeof targetVal}`;
94
+ }
95
+ return null;
96
+ }
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Internal runner result
101
+ // ---------------------------------------------------------------------------
102
+
103
+ interface CheckResult {
104
+ ok: boolean;
105
+ reason?: string;
106
+ evidence?: string;
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // Per-kind runners
111
+ // ---------------------------------------------------------------------------
112
+
113
+ async function runFileExists(check: Check, deps: DeterministicDeps): Promise<CheckResult> {
114
+ try {
115
+ if (!check.path) return { ok: false, reason: "fileExists check missing 'path'" };
116
+ const ok = await deps.fs.fileExists(check.path);
117
+ if (ok) return { ok: true, evidence: `exists: ${check.path}` };
118
+ return { ok: false, reason: `file not found: ${check.path}` };
119
+ } catch (err) {
120
+ return { ok: false, reason: `fileExists check errored: ${scrubText(String(err))}` };
121
+ }
122
+ }
123
+
124
+ async function runRun(
125
+ check: Check,
126
+ deps: DeterministicDeps,
127
+ allowlist: string[],
128
+ timeoutMs: number,
129
+ ): Promise<CheckResult> {
130
+ try {
131
+ if (!check.command) return { ok: false, reason: "run check missing 'command'" };
132
+ if (!isCommandAllowed(check.command, allowlist)) {
133
+ return { ok: false, reason: `command not allowlisted: ${check.command}` };
134
+ }
135
+ const r: ExecResult = await deps.exec(check.command, { cwd: deps.cwd, timeoutMs });
136
+ if (r.timedOut) {
137
+ return { ok: false, reason: `run timed out after ${timeoutMs}ms: ${check.command}` };
138
+ }
139
+ const out = r.stdout + "\n" + r.stderr;
140
+ if (check.expect !== undefined && !out.includes(check.expect)) {
141
+ return {
142
+ ok: false,
143
+ reason: `expected substring not found: "${check.expect}"`,
144
+ evidence: out.slice(0, 2000),
145
+ };
146
+ }
147
+ const ok = r.code === 0;
148
+ if (!ok) {
149
+ return {
150
+ ok: false,
151
+ reason: `command exited ${r.code}: ${check.command}`,
152
+ evidence: out.slice(0, 2000),
153
+ };
154
+ }
155
+ return { ok: true, evidence: `exit 0: ${check.command}` };
156
+ } catch (err) {
157
+ return { ok: false, reason: `run check errored: ${scrubText(String(err))}` };
158
+ }
159
+ }
160
+
161
+ function resolveRepoCommand(
162
+ check: Check,
163
+ kind: "testsPass" | "buildPasses" | "lintClean",
164
+ defaults: DeterministicDeps["defaults"],
165
+ ): string {
166
+ if (check.command) return check.command;
167
+ if (kind === "testsPass") return defaults?.testCommand ?? "npm test";
168
+ if (kind === "buildPasses") return defaults?.buildCommand ?? "npm run build";
169
+ return defaults?.lintCommand ?? "npm run lint";
170
+ }
171
+
172
+ async function runCommandCheck(
173
+ check: Check,
174
+ kind: "testsPass" | "buildPasses" | "lintClean",
175
+ deps: DeterministicDeps,
176
+ allowlist: string[],
177
+ timeoutMs: number,
178
+ ): Promise<CheckResult> {
179
+ const command = resolveRepoCommand(check, kind, deps.defaults);
180
+
181
+ const fn = async (): Promise<CheckResult> => {
182
+ try {
183
+ if (!isCommandAllowed(command, allowlist)) {
184
+ return { ok: false, reason: `command not allowlisted: ${command}` };
185
+ }
186
+ const r: ExecResult = await deps.exec(command, { cwd: deps.cwd, timeoutMs });
187
+ if (r.timedOut) {
188
+ return { ok: false, reason: `${kind} timed out after ${timeoutMs}ms: ${command}` };
189
+ }
190
+ const out = r.stdout + "\n" + r.stderr;
191
+ const ok = r.code === 0;
192
+ if (!ok) {
193
+ return {
194
+ ok: false,
195
+ reason: `command exited ${r.code}: ${command}`,
196
+ evidence: out.slice(0, 2000),
197
+ };
198
+ }
199
+ return { ok: true, evidence: `exit 0: ${command}` };
200
+ } catch (err) {
201
+ return { ok: false, reason: `${kind} check errored: ${scrubText(String(err))}` };
202
+ }
203
+ };
204
+
205
+ if (deps.mutex) {
206
+ return deps.mutex.runExclusive(deps.cwd, fn);
207
+ }
208
+ return fn();
209
+ }
210
+
211
+ async function runSchemaMatch(check: Check, deps: DeterministicDeps): Promise<CheckResult> {
212
+ try {
213
+ if (!check.path || !check.schema) {
214
+ return { ok: false, reason: "schemaMatch requires 'path' and 'schema'" };
215
+ }
216
+
217
+ const targetRaw = await deps.fs.readFile(check.path);
218
+ let targetVal: unknown;
219
+ try {
220
+ targetVal = JSON.parse(targetRaw);
221
+ } catch {
222
+ return { ok: false, reason: `target is not valid JSON: ${check.path}` };
223
+ }
224
+
225
+ let schemaVal: unknown;
226
+ if (check.schema.trim().startsWith("{")) {
227
+ try {
228
+ schemaVal = JSON.parse(check.schema);
229
+ } catch {
230
+ return { ok: false, reason: "schema is not valid JSON" };
231
+ }
232
+ } else {
233
+ const schemaRaw = await deps.fs.readFile(check.schema);
234
+ try {
235
+ schemaVal = JSON.parse(schemaRaw);
236
+ } catch {
237
+ return { ok: false, reason: "schema is not valid JSON" };
238
+ }
239
+ }
240
+
241
+ const mismatch = shapeMismatch(schemaVal, targetVal);
242
+ if (mismatch !== null) {
243
+ return { ok: false, reason: `schema mismatch at ${mismatch}`, evidence: mismatch };
244
+ }
245
+ return { ok: true };
246
+ } catch (err) {
247
+ return { ok: false, reason: `schemaMatch check errored: ${scrubText(String(err))}` };
248
+ }
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // runDeterministic
253
+ // ---------------------------------------------------------------------------
254
+
255
+ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promise<Verdict> {
256
+ const checks = dod.checks ?? [];
257
+
258
+ if (checks.length === 0) {
259
+ return {
260
+ pass: false,
261
+ method: "none",
262
+ skipped: true,
263
+ reasons: ["no deterministic checks to run"],
264
+ };
265
+ }
266
+
267
+ const timeoutMs = deps.timeoutMs ?? 120000;
268
+ const allowlist = deps.allowlist ?? DEFAULT_ALLOWLIST;
269
+ const results: CheckResult[] = [];
270
+
271
+ // Sequential for deterministic mutex semantics and stable evidence order.
272
+ for (const check of checks) {
273
+ let result: CheckResult;
274
+
275
+ switch (check.kind) {
276
+ case "fileExists":
277
+ result = await runFileExists(check, deps);
278
+ break;
279
+ case "run":
280
+ result = await runRun(check, deps, allowlist, timeoutMs);
281
+ break;
282
+ case "testsPass":
283
+ case "buildPasses":
284
+ case "lintClean":
285
+ result = await runCommandCheck(check, check.kind, deps, allowlist, timeoutMs);
286
+ break;
287
+ case "schemaMatch":
288
+ result = await runSchemaMatch(check, deps);
289
+ break;
290
+ default: {
291
+ // Defensive: TypeScript proves this is unreachable; guards runtime extensions.
292
+ const exhaustive: never = check.kind;
293
+ result = { ok: false, reason: `unknown check kind: ${exhaustive}` };
294
+ break;
295
+ }
296
+ }
297
+
298
+ results.push(result);
299
+ }
300
+
301
+ const allPass = results.every(r => r.ok);
302
+
303
+ const reasons: string[] = allPass
304
+ ? [`all ${checks.length} deterministic checks passed`]
305
+ : results
306
+ .filter(r => !r.ok)
307
+ .map(r => scrubText(r.reason ?? "check failed"));
308
+
309
+ const evidenceParts = results.map(r => r.evidence ?? "").filter(e => e.length > 0);
310
+ const rawEvidence = evidenceParts.length > 0 ? evidenceParts.join("\n---\n") : undefined;
311
+ const evidence = rawEvidence !== undefined ? scrubText(rawEvidence) : undefined;
312
+
313
+ return {
314
+ pass: allPass,
315
+ method: "deterministic",
316
+ reasons,
317
+ ...(evidence !== undefined ? { evidence } : {}),
318
+ };
319
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * src/verify/dispatch.ts — PURE helpers shared by both Layer-2 wirings
3
+ * (Option (i) verify-dispatch around the built-in `task` tool, and Option (ii)
4
+ * the plugin-owned `delegate` tool). No fs/network/SDK here; the live adapters
5
+ * (exec/fs/grader) are built in index.ts from PluginInput and injected.
6
+ */
7
+ import type { RouterConfig } from "../router/config";
8
+ import { getActiveTiers } from "../router/protocol";
9
+ import { parseDoDFromDispatch, inferDoD } from "./dod";
10
+ import type { DoD, InferHints } from "./dod";
11
+
12
+ /** Tools that mutate the workspace (mirrors the guard taxonomy). */
13
+ const WRITE_TOOLS = new Set(["write", "edit", "patch", "multiedit"]);
14
+
15
+ export interface ChangedFile {
16
+ path: string;
17
+ status: string;
18
+ }
19
+
20
+ /** Derive a {path,status} record from a write/edit tool call, or null. */
21
+ export function extractChangedFile(tool: string, args: unknown): ChangedFile | null {
22
+ if (!WRITE_TOOLS.has(tool)) return null;
23
+ const a = (args ?? {}) as Record<string, unknown>;
24
+ const path =
25
+ typeof a.filePath === "string"
26
+ ? a.filePath
27
+ : typeof a.path === "string"
28
+ ? a.path
29
+ : typeof a.file === "string"
30
+ ? a.file
31
+ : "";
32
+ if (!path) return null;
33
+ const status = tool === "write" ? "written" : "modified";
34
+ return { path, status };
35
+ }
36
+
37
+ /**
38
+ * Per-session changed-file tracker. We attribute changed files to a delegation
39
+ * by observing that session's own edit/write tool calls (ADR 0002 D3 — NOT a
40
+ * global git diff), which is concurrency-safe under interleaved subagents.
41
+ */
42
+ export function createChangedFileStore() {
43
+ const bySession = new Map<string, Map<string, string>>();
44
+ return {
45
+ record(sessionID: string, tool: string, args: unknown): void {
46
+ const cf = extractChangedFile(tool, args);
47
+ if (!cf) return;
48
+ let m = bySession.get(sessionID);
49
+ if (!m) {
50
+ m = new Map();
51
+ bySession.set(sessionID, m);
52
+ }
53
+ // "written" (created) is stickier than a later "modified".
54
+ const prev = m.get(cf.path);
55
+ m.set(cf.path, prev === "written" ? "written" : cf.status);
56
+ },
57
+ get(sessionID: string): ChangedFile[] {
58
+ const m = bySession.get(sessionID);
59
+ if (!m) return [];
60
+ return [...m.entries()].map(([path, status]) => ({ path, status }));
61
+ },
62
+ clear(sessionID: string): void {
63
+ bySession.delete(sessionID);
64
+ },
65
+ };
66
+ }
67
+
68
+ const TASK_RESULT_RE = /<task_result>\s*([\s\S]*?)\s*<\/task_result>/i;
69
+
70
+ /**
71
+ * Parse the built-in `task` tool's after-hook output: the child's final return
72
+ * is wrapped in <task_result>...</task_result> and the child session id lives in
73
+ * output.metadata.sessionId (spike capability C).
74
+ */
75
+ export function parseTaskResult(output: unknown): {
76
+ finalReturnText: string;
77
+ childSessionID: string | null;
78
+ } {
79
+ const o = (output ?? {}) as Record<string, unknown>;
80
+ const raw = typeof o.output === "string" ? o.output : "";
81
+ const m = raw.match(TASK_RESULT_RE);
82
+ const finalReturnText = (m ? m[1] : raw).trim();
83
+ const meta = (o.metadata ?? {}) as Record<string, unknown>;
84
+ const childSessionID =
85
+ typeof meta.sessionId === "string"
86
+ ? meta.sessionId
87
+ : typeof meta.sessionID === "string"
88
+ ? meta.sessionID
89
+ : null;
90
+ return { finalReturnText, childSessionID };
91
+ }
92
+
93
+ /**
94
+ * Build the DoD for a delegation from its dispatch text: an explicit
95
+ * [acceptance] block wins; otherwise auto-infer a minimal, non-vacuous DoD
96
+ * (M2 default). `acceptance` (if provided) is parsed for the block first.
97
+ */
98
+ export function buildDelegationDoD(
99
+ args: { prompt?: string; description?: string; acceptance?: string },
100
+ hints: InferHints = {},
101
+ ): DoD {
102
+ const blockSource = args.acceptance ?? args.prompt ?? args.description ?? "";
103
+ const explicit = parseDoDFromDispatch(blockSource);
104
+ if (explicit) return explicit;
105
+ const dispatch = args.prompt ?? args.description ?? "";
106
+ return inferDoD(dispatch, "", hints);
107
+ }
108
+
109
+ /** Resolve a tier name to {providerID, modelID} for client.session.prompt. */
110
+ export function tierModel(
111
+ cfg: RouterConfig,
112
+ tierName: string,
113
+ ): { providerID: string; modelID: string } | null {
114
+ const tiers = getActiveTiers(cfg);
115
+ const t = tiers[tierName];
116
+ if (!t || typeof t.model !== "string") return null;
117
+ const slash = t.model.indexOf("/");
118
+ if (slash <= 0 || slash >= t.model.length - 1) return null;
119
+ return {
120
+ providerID: t.model.slice(0, slash),
121
+ modelID: t.model.slice(slash + 1),
122
+ };
123
+ }
124
+
125
+ /** Decide whether a built-in `task` tool call should be verify-dispatched (Option i). */
126
+ export function shouldVerifyTask(
127
+ tool: string,
128
+ mode: string,
129
+ require: string | undefined,
130
+ ): boolean {
131
+ if (tool !== "task") return false;
132
+ if (mode === "off") return false;
133
+ if ((require ?? "whenDoDPresent") === "never") return false;
134
+ return true;
135
+ }
136
+
137
+ /** Build the advisory forcing note appended to a task result the gate did not accept. */
138
+ export function buildForcingNote(
139
+ reasons: string[],
140
+ escalation?: { producerTier?: string; nextTier?: string | null },
141
+ ): string {
142
+ const body =
143
+ reasons.length > 0
144
+ ? reasons.map((r) => `- ${r}`).join("\n")
145
+ : "- (no reasons provided)";
146
+ const next =
147
+ escalation?.nextTier
148
+ ? `NEXT: address the above, then re-run via \`Task(subagent_type="${escalation.nextTier}")\`` +
149
+ `${escalation.producerTier ? ` (escalated from ${escalation.producerTier})` : ""}; ` +
150
+ `do not treat the prior result as complete.`
151
+ : `NEXT: address the above and re-run the delegation; do not treat the prior result as complete.`;
152
+ return (
153
+ `[router \u26a0 NOT ACCEPTED] The delegated result was not accepted by independent verification:\n` +
154
+ `${body}\n` +
155
+ next
156
+ );
157
+ }
158
+
159
+ /** Suffix appended to an accepted delegate-tool result. */
160
+ export function buildAcceptedSuffix(method: string): string {
161
+ return `\n\n[router \u2713 accepted: ${method}]`;
162
+ }