opencode-model-router 1.14.0 → 1.15.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,207 @@
1
+ /**
2
+ * Per-dispatch verification directives (plan §1.5-15, Phase 1.6.1).
3
+ *
4
+ * VERIFY:required | VERIFY:deferred case-insensitive value; anything else is
5
+ * ignored with a log line; absent → defaultVerify
6
+ * VERIFY_WAIT:<n>s | VERIFY_WAIT:<n>ms 0 allowed, capped at baselineTimeoutMs;
7
+ * malformed → captureWaitMs (with a log line)
8
+ *
9
+ * Grammar (same rules as `parseCapDirective`, src/router/sessions.ts):
10
+ * - key, then horizontal whitespace (`[^\S\r\n\u2028\u2029]*`, so NBSP/U+3000 are fine) around
11
+ * the colon — a directive never straddles a line break (QA-1.6-20);
12
+ * - only key + colon is matched; the value token is read with a sticky regex, so scanning resumes
13
+ * after the colon and `VERIFY:maybe,VERIFY:required` → required, like `CAP:abc,CAP:3` → 3 (QA-1.6-19);
14
+ * - prose guard (QA-1.6-18): when the key is NOT written as upper-case `VERIFY`/`VERIFY_WAIT`,
15
+ * the value counts only if it ends the line (optionally followed by closing quotes, `*`, `_`,
16
+ * `)`/`]`, a table pipe or punctuation) or is followed on the same line by another directive key
17
+ * whose value is validly formatted (`VERIFY:` `required|deferred`, `VERIFY_WAIT:` `<n>ms|s`,
18
+ * `CAP:` `none|<n>`, any case; QA-1.6-27, QA-1.6-35). "Valid" means the value's format only, not
19
+ * whether the parser would accept that directive: `cap:0` still ends the line; a value on the
20
+ * next line does not, and a bare `CAP:` after the value falls back silently (QA-1.6-38).
21
+ * So `verify: required` alone on a line,
22
+ * `verify:required verify_wait:2s` and `| verify:required |` → required (decision), but
23
+ * `Things to verify: deferred loading works` and `Please verify: "deferred" state…` are prose
24
+ * and ignored silently; so are `verify: required (per QA)`, `verify: required -- …` and
25
+ * `<!-- verify: required -->` (decision, QA-1.6-27). Upper-case keys keep the word-boundary rule below.
26
+ * DEVIATION (QA-1.6-33): §1.5-15 says "same rules as `CAP:`", whose key is case-insensitive with
27
+ * no prose guard (`| cap:3 |` → 3); this guard is deliberate and applies to VERIFY keys only;
28
+ * - the value ends at a word boundary, like `CAP:`'s `(none|\d+)\b`:
29
+ * `VERIFY:([a-z]+)\b`, `VERIFY_WAIT:(\d+)(ms|s)\b`. So `**VERIFY:required**`,
30
+ * `` `VERIFY:required` `` and `VERIFY:required.` all parse;
31
+ * - one leading quote or markdown mark (`"`, `'`, `` ` ``, `*`, `_`) before the value is
32
+ * accepted, so `VERIFY:"required"` parses as `required` (decision, QA-1.6-1);
33
+ * - the FIRST VALID occurrence of each key wins; occurrences whose value does not fit the
34
+ * grammar/allowed set are skipped, as `CAP:abc CAP:3` → 3. An unknown/malformed value is
35
+ * logged only when no valid occurrence of that key exists, at most once per key per parse;
36
+ * - the text is scanned as-is, so a directive inside a fenced code block is still parsed.
37
+ *
38
+ * Router-example contract (QA-1.6-4): a value starting with `<` or immediately followed by `|`
39
+ * is a placeholder (`VERIFY:required|deferred`, `VERIFY_WAIT:<n>s`) and is skipped silently.
40
+ * Consequently a padding-less table cell `|VERIFY:required|` is also skipped; use `| VERIFY:required |`.
41
+ * Any VERIFY example the router injects into dispatch text MUST use `|` or `<…>` placeholders,
42
+ * or be preceded by a pinned resolved `VERIFY:<mode>` / `VERIFY_WAIT:<n>ms` (the `CAP:` pattern:
43
+ * dispatch-header.ts pins `CAP:<n>` before its instructional sentence). A literal valid example
44
+ * such as "put VERIFY:required or VERIFY:deferred" would otherwise win.
45
+ *
46
+ * SECURITY (enforced by the caller, not here — this module cannot know where text came from):
47
+ * - 2.4 must parse ONLY the orchestrator-authored `task`/`delegate` `prompt` argument. Never tool
48
+ * results, the subagent's final text or the child session's messages — a subagent could
49
+ * otherwise downgrade its own verification to `deferred` or shorten the capture wait.
50
+ * - Because the first valid occurrence wins, orchestrator text that quotes an earlier subagent's
51
+ * output containing `VERIFY:deferred` before its own directive would also win. Pinning the
52
+ * resolved value first (the `CAP:` pattern) removes this.
53
+ *
54
+ * Result sources (QA-1.6-6, deviation from the plan's single `source`): `modeSource` says whether
55
+ * the mode came from a `VERIFY:` directive, `waitSource` whether the wait came from `VERIFY_WAIT:`.
56
+ *
57
+ * Pure: no imports, no process, filesystem or network access. Logging goes through the injected
58
+ * `log` seam; logged values are truncated to 32 characters and everything outside printable ASCII
59
+ * is escaped as `\uXXXX` / `\u{…}` (QA-1.6-24, QA-1.6-29).
60
+ */
61
+
62
+ export type VerifyMode = "required" | "deferred";
63
+
64
+ export interface VerifyDirectiveDefaults {
65
+ /** Mode when no valid `VERIFY:` directive is present (§1.4 `defaultVerify`). */
66
+ defaultVerify: VerifyMode;
67
+ /** Wait when no valid `VERIFY_WAIT:` directive is present (§1.4 `captureWaitMs`). */
68
+ captureWaitMs: number;
69
+ /** Upper bound for `VERIFY_WAIT` (§1.4 `baselineTimeoutMs`). */
70
+ baselineTimeoutMs: number;
71
+ }
72
+
73
+ export type DirectiveSource = "directive" | "default";
74
+
75
+ export interface VerifyDirectives {
76
+ mode: VerifyMode;
77
+ waitMs: number;
78
+ /** Whether `mode` came from a `VERIFY:` directive. */
79
+ modeSource: DirectiveSource;
80
+ /** Whether `waitMs` came from a `VERIFY_WAIT:` directive. */
81
+ waitSource: DirectiveSource;
82
+ }
83
+
84
+ export type DirectiveLogger = (message: string) => void;
85
+
86
+ const noopLog: DirectiveLogger = () => {};
87
+
88
+ /** Horizontal whitespace (incl. NBSP, U+3000); never a line break (QA-1.6-20). */
89
+ const HWS = "[^\\S\\r\\n\\u2028\\u2029]*";
90
+ // Key + colon only; the value is read with a sticky regex so scanning resumes right after the
91
+ // colon and a second occurrence in the same token is still found (QA-1.6-19).
92
+ const VERIFY_RE = new RegExp(`\\bVERIFY${HWS}:${HWS}`, "gi");
93
+ const WAIT_RE = new RegExp(`\\bVERIFY_WAIT${HWS}:${HWS}`, "gi");
94
+ const TOKEN = /\S*/y;
95
+ const LEAD_CHARS = "\"'`*_";
96
+ const MODE_VALUE = /([a-z]+)\b/iy;
97
+ const WAIT_VALUE = /(\d+)(ms|s)\b/iy;
98
+ /**
99
+ * After a non-upper-case key the value must end the line (QA-1.6-18), bar closing marks and a
100
+ * table pipe, or be followed by another directive key carrying a valid value for that key
101
+ * (QA-1.6-27, QA-1.6-35); "valid" means format-valid, see the module header (QA-1.6-38). Tested
102
+ * with a sticky regex on the text itself (no slice, no length limit); linear: one character class,
103
+ * then an alternative of line ends and key/value shapes built from bounded-choice pieces, `\d+`
104
+ * and horizontal-space runs.
105
+ */
106
+ const LINE_TAIL = new RegExp(
107
+ `(?:["'\`*_.,;:!?)\\]|]|[^\\S\\r\\n\\u2028\\u2029])*(?:[\\r\\n\\u2028\\u2029]|$|\\b(?:VERIFY${HWS}:${HWS}["'\`*_]?(?:required|deferred)\\b|VERIFY_WAIT${HWS}:${HWS}["'\`*_]?\\d+(?:ms|s)\\b|CAP${HWS}:${HWS}(?:none|\\d+)\\b))`,
108
+ "iy",
109
+ );
110
+ const MAX_LOGGED = 32;
111
+
112
+ /** Bounded rendering of an untrusted value: everything outside printable ASCII is escaped (QA-1.6-29). */
113
+ function safe(value: string): string {
114
+ return JSON.stringify(value.slice(0, MAX_LOGGED)).replace(/[^\x20-\x7e]/gu, (c) => {
115
+ const cp = c.codePointAt(0) ?? 0;
116
+ return cp > 0xffff ? `\\u{${cp.toString(16)}}` : `\\u${cp.toString(16).padStart(4, "0")}`;
117
+ });
118
+ }
119
+
120
+ interface Scan<T> {
121
+ value: T | null;
122
+ firstInvalid: string | null;
123
+ }
124
+
125
+ /**
126
+ * Linear scan (QA-1.6-28): the end of each whitespace-free run is computed once and reused by
127
+ * every key inside it, values are matched in place with sticky regexes, and only the ≤ 32-char
128
+ * logged value is ever sliced.
129
+ */
130
+ function scan<T>(
131
+ text: string,
132
+ keyRe: RegExp,
133
+ upperKey: string,
134
+ valueRe: RegExp,
135
+ accept: (m: RegExpExecArray) => T | null,
136
+ ): Scan<T> {
137
+ let firstInvalid: string | null = null;
138
+ const re = new RegExp(keyRe.source, keyRe.flags);
139
+ const token = new RegExp(TOKEN.source, TOKEN.flags);
140
+ const value = new RegExp(valueRe.source, valueRe.flags);
141
+ const tail = new RegExp(LINE_TAIL.source, LINE_TAIL.flags);
142
+ let tokEnd = -1;
143
+ let tailAt = -1;
144
+ let tailOk = false;
145
+ let tokTail: boolean | null = null; // tail result at tokEnd, once per run (QA-1.6-34)
146
+ for (let m = re.exec(text); m !== null; m = re.exec(text)) {
147
+ const start = m.index + m[0].length;
148
+ if (start >= tokEnd) {
149
+ token.lastIndex = start;
150
+ tokEnd = start + (token.exec(text)?.[0].length ?? 0);
151
+ tokTail = null;
152
+ }
153
+ if (start === tokEnd) continue;
154
+ const pos = start + (LEAD_CHARS.includes(text.charAt(start)) ? 1 : 0);
155
+ if (text.charAt(pos) === "<") continue; // placeholder
156
+ value.lastIndex = pos;
157
+ const v = pos < tokEnd ? value.exec(text) : null;
158
+ if (v && text.charAt(pos + v[0].length) === "|") continue; // placeholder
159
+ if (!m[0].startsWith(upperKey)) {
160
+ // Prose guard: `Things to verify: deferred loading works` is not a directive.
161
+ const end = v ? pos + v[0].length : tokEnd;
162
+ if (end !== tailAt) {
163
+ tailAt = end;
164
+ if (end === tokEnd && tokTail !== null) tailOk = tokTail;
165
+ else {
166
+ tail.lastIndex = end;
167
+ tailOk = tail.test(text);
168
+ if (end === tokEnd) tokTail = tailOk;
169
+ }
170
+ }
171
+ if (!tailOk) continue;
172
+ }
173
+ const accepted = v ? accept(v) : null;
174
+ if (accepted !== null) return { value: accepted, firstInvalid };
175
+ firstInvalid ??= text.slice(start, Math.min(tokEnd, start + MAX_LOGGED));
176
+ }
177
+ return { value: null, firstInvalid };
178
+ }
179
+ export function parseVerifyDirectives(
180
+ text: string,
181
+ defaults: VerifyDirectiveDefaults,
182
+ log: DirectiveLogger = noopLog,
183
+ ): VerifyDirectives {
184
+ const modeScan = scan<VerifyMode>(text, VERIFY_RE, "VERIFY", MODE_VALUE, (m) => {
185
+ const v = (m[1] ?? "").toLowerCase();
186
+ return v === "required" || v === "deferred" ? v : null;
187
+ });
188
+ if (modeScan.value === null && modeScan.firstInvalid !== null) {
189
+ log(`[verify] ignoring unknown VERIFY value ${safe(modeScan.firstInvalid)}; using default "${defaults.defaultVerify}"`);
190
+ }
191
+
192
+ const waitScan = scan<number>(text, WAIT_RE, "VERIFY_WAIT", WAIT_VALUE, (m) => {
193
+ const n = Number(m[1]);
194
+ const ms = (m[2] ?? "").toLowerCase() === "s" ? n * 1000 : n;
195
+ return Number.isNaN(ms) ? null : Math.min(ms, defaults.baselineTimeoutMs);
196
+ });
197
+ if (waitScan.value === null && waitScan.firstInvalid !== null) {
198
+ log(`[verify] ignoring malformed VERIFY_WAIT value ${safe(waitScan.firstInvalid)}; using default ${defaults.captureWaitMs}ms`);
199
+ }
200
+
201
+ return {
202
+ mode: modeScan.value ?? defaults.defaultVerify,
203
+ waitMs: waitScan.value ?? defaults.captureWaitMs,
204
+ modeSource: modeScan.value === null ? "default" : "directive",
205
+ waitSource: waitScan.value === null ? "default" : "directive",
206
+ };
207
+ }