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,343 @@
1
+ import { fingerprintToolCall } from "./fingerprint";
2
+ import { READ_ONLY_TOOLS } from "../router/sessions";
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // Types
6
+ // ---------------------------------------------------------------------------
7
+
8
+ export interface GuardPolicy {
9
+ budget: number;
10
+ readDraftCap: number;
11
+ sameOpRetryCap: number;
12
+ blockSelfScript: boolean;
13
+ deliverableFirst: boolean;
14
+ deliverableSignal?: string | null;
15
+ deliverablePath?: string | null;
16
+ deliverableIsScript?: boolean;
17
+ /** opt-in; default false. When true, WRITE/EDIT/PATCH/MULTIEDIT to a script-extension path is treated as self_script. Off by default because writing source files is the normal coding deliverable. */
18
+ blockScriptWrites?: boolean;
19
+ }
20
+
21
+ export interface GuardCall {
22
+ tool: string;
23
+ args?: Record<string, unknown>;
24
+ }
25
+
26
+ export type GuardKind = "finish" | "read" | "mutation" | "self_script" | "other";
27
+
28
+ export interface GuardDecision {
29
+ allow: boolean;
30
+ guard: string | null;
31
+ observation: string | null;
32
+ }
33
+
34
+ export interface GuardState {
35
+ budget: number;
36
+ toolCallCount: number;
37
+ readCount: number;
38
+ execCount: number;
39
+ selfScriptCount: number;
40
+ redundantCount: number;
41
+ blockedCount: number;
42
+ consecutiveNonProducing: number;
43
+ deliverableExecuted: boolean;
44
+ ttfa: number | null;
45
+ seen: Map<string, number>;
46
+ lastBlock: string | null;
47
+ }
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // Regex constants
51
+ // ---------------------------------------------------------------------------
52
+
53
+ const SCRIPT_EXT_RE = /\.(mjs|sh|py|js|ts|cjs|bash)\b/i;
54
+ const HEREDOC_RE = /<<-?\s*['"]?[A-Za-z_]/;
55
+ const REDIRECT_SCRIPT_RE = />\s*\S+\.(mjs|sh|py|js|ts|cjs|bash)\b/i;
56
+ const INLINE_SCRIPT_RE = /\b(node|python3?|deno|bun)\s+-(e|c)\b/i;
57
+ const CAT_WRITE_RE = /\bcat\s+>\s*\S/i;
58
+ const BASH_C_RE = /\bbash\s+-c\b/i;
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Write tools set (module-level)
62
+ // ---------------------------------------------------------------------------
63
+
64
+ const WRITE_TOOLS = new Set(["write", "edit", "patch", "multiedit"]);
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // newGuardState
68
+ // ---------------------------------------------------------------------------
69
+
70
+ export function newGuardState(policy: GuardPolicy): GuardState {
71
+ return {
72
+ budget: policy.budget,
73
+ toolCallCount: 0,
74
+ readCount: 0,
75
+ execCount: 0,
76
+ selfScriptCount: 0,
77
+ redundantCount: 0,
78
+ blockedCount: 0,
79
+ consecutiveNonProducing: 0,
80
+ deliverableExecuted: false,
81
+ ttfa: null,
82
+ seen: new Map(),
83
+ lastBlock: null,
84
+ };
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // isSelfScript
89
+ // ---------------------------------------------------------------------------
90
+
91
+ export function isSelfScript(call: GuardCall, policy: GuardPolicy): boolean {
92
+ const args = call.args ?? {};
93
+ const target = String(args.filePath ?? args.path ?? args.file ?? "");
94
+
95
+ // Intent exemption: deliverableIsScript === true => never self-script
96
+ if (policy.deliverableIsScript === true) return false;
97
+
98
+ // deliverablePath exemption
99
+ if (policy.deliverablePath != null && policy.deliverablePath !== "") {
100
+ if (target === policy.deliverablePath) return false;
101
+ }
102
+
103
+ // bash/shell ad-hoc execution (DEFAULT signal, always evaluated)
104
+ if (call.tool === "bash" || call.tool === "shell") {
105
+ const cmd = String(args.command ?? args.cmd ?? "");
106
+ if (!cmd) return false;
107
+ return (
108
+ HEREDOC_RE.test(cmd) ||
109
+ REDIRECT_SCRIPT_RE.test(cmd) ||
110
+ INLINE_SCRIPT_RE.test(cmd) ||
111
+ CAT_WRITE_RE.test(cmd) ||
112
+ BASH_C_RE.test(cmd)
113
+ );
114
+ }
115
+
116
+ // WRITE-to-script (OPT-IN): only when blockScriptWrites === true
117
+ if (WRITE_TOOLS.has(call.tool)) {
118
+ if (policy.blockScriptWrites !== true) return false;
119
+ return SCRIPT_EXT_RE.test(target);
120
+ }
121
+
122
+ return false;
123
+ }
124
+
125
+ // ---------------------------------------------------------------------------
126
+ // classify
127
+ // ---------------------------------------------------------------------------
128
+
129
+ const FINISH_TOOLS = new Set(["finish", "return", "task_complete"]);
130
+ const MUTATION_TOOLS = new Set(["write", "edit", "patch", "bash", "multiedit"]);
131
+
132
+ export function classify(call: GuardCall, policy: GuardPolicy): GuardKind {
133
+ if (FINISH_TOOLS.has(call.tool)) return "finish";
134
+ if (isSelfScript(call, policy)) return "self_script";
135
+ if (READ_ONLY_TOOLS.has(call.tool)) return "read";
136
+ if (MUTATION_TOOLS.has(call.tool)) return "mutation";
137
+ return "other";
138
+ }
139
+
140
+ // ---------------------------------------------------------------------------
141
+ // evaluateGuards
142
+ // ---------------------------------------------------------------------------
143
+
144
+ export function evaluateGuards(
145
+ state: GuardState,
146
+ call: GuardCall,
147
+ policy: GuardPolicy,
148
+ ): GuardDecision {
149
+ const fp = fingerprintToolCall(call.tool, call.args);
150
+ let kind = classify(call, policy);
151
+
152
+ // If blockSelfScript is false, treat self_script as mutation
153
+ if (kind === "self_script" && policy.blockSelfScript === false) {
154
+ kind = "mutation";
155
+ }
156
+
157
+ // CLAUSE 1: finish
158
+ if (kind === "finish") {
159
+ return { allow: true, guard: null, observation: null };
160
+ }
161
+
162
+ // CLAUSE 2: self_script
163
+ if (kind === "self_script") {
164
+ return {
165
+ allow: false,
166
+ guard: "anti_self_script",
167
+ observation:
168
+ "DENIED: do not author or run a throwaway script. Do the task directly — write/edit the real target file, or run the actual build/test command.",
169
+ };
170
+ }
171
+
172
+ // CLAUSE 3: budget
173
+ if (state.toolCallCount >= state.budget) {
174
+ return {
175
+ allow: false,
176
+ guard: "iteration_cap",
177
+ observation: `DENIED: tool-call budget ${state.budget} exhausted. Stop now and emit your final answer with what you have.`,
178
+ };
179
+ }
180
+
181
+ // CLAUSE 4: redundancy
182
+ if (kind === "read" && (state.seen.get(fp) ?? 0) >= policy.sameOpRetryCap) {
183
+ return {
184
+ allow: false,
185
+ guard: "redundant_read",
186
+ observation: `DENIED: you already ran this exact read (${fp}). Reuse the result you already have; take a producing action or finish.`,
187
+ };
188
+ }
189
+
190
+ // CLAUSE 5: read_budget
191
+ if (kind === "read" && state.consecutiveNonProducing >= policy.readDraftCap) {
192
+ return {
193
+ allow: false,
194
+ guard: "read_budget",
195
+ observation: `DENIED: read/draft budget exhausted (${policy.readDraftCap} consecutive non-producing actions). Take a producing action now (write/edit) or finish.`,
196
+ };
197
+ }
198
+
199
+ // CLAUSE 6: deliverable_first
200
+ if (
201
+ policy.deliverableFirst !== false &&
202
+ policy.deliverableSignal != null &&
203
+ state.deliverableExecuted === false &&
204
+ (kind === "read" || kind === "other")
205
+ ) {
206
+ return {
207
+ allow: false,
208
+ guard: "deliverable_first",
209
+ observation: `DENIED: you have not produced the deliverable yet. Your next action must be the deliverable (${policy.deliverableSignal}) before further exploration.`,
210
+ };
211
+ }
212
+
213
+ // CLAUSE 7: allow
214
+ return { allow: true, guard: null, observation: null };
215
+ }
216
+
217
+ // ---------------------------------------------------------------------------
218
+ // updateState
219
+ // ---------------------------------------------------------------------------
220
+
221
+ export function updateState(
222
+ state: GuardState,
223
+ call: GuardCall,
224
+ opts: { ok: boolean },
225
+ policy: GuardPolicy,
226
+ ): GuardState {
227
+ const kind = classify(call, policy);
228
+
229
+ // finish: no count
230
+ if (kind === "finish") return state;
231
+
232
+ state.toolCallCount += 1;
233
+
234
+ const fp = fingerprintToolCall(call.tool, call.args);
235
+
236
+ if (kind === "self_script") {
237
+ state.selfScriptCount += 1;
238
+ state.consecutiveNonProducing += 1;
239
+ return state;
240
+ }
241
+
242
+ if (kind === "mutation") {
243
+ state.execCount += 1;
244
+ state.consecutiveNonProducing = 0;
245
+ if (opts.ok && !state.deliverableExecuted) {
246
+ state.deliverableExecuted = true;
247
+ state.ttfa = state.toolCallCount;
248
+ }
249
+ return state;
250
+ }
251
+
252
+ if (kind === "read") {
253
+ state.readCount += 1;
254
+ state.consecutiveNonProducing += 1;
255
+ state.seen.set(fp, (state.seen.get(fp) ?? 0) + 1);
256
+ return state;
257
+ }
258
+
259
+ // other
260
+ state.consecutiveNonProducing += 1;
261
+ return state;
262
+ }
263
+
264
+ // ---------------------------------------------------------------------------
265
+ // recordBlock
266
+ // ---------------------------------------------------------------------------
267
+
268
+ export function recordBlock(
269
+ state: GuardState,
270
+ decision: GuardDecision,
271
+ ): GuardState {
272
+ state.lastBlock = decision.guard;
273
+ state.blockedCount += 1;
274
+ if (decision.guard === "redundant_read") state.redundantCount += 1;
275
+ return state;
276
+ }
277
+
278
+ // ---------------------------------------------------------------------------
279
+ // forcingMessage
280
+ // ---------------------------------------------------------------------------
281
+
282
+ export function forcingMessage(state: GuardState, policy: GuardPolicy): string {
283
+ const deliverable =
284
+ policy.deliverableSignal == null
285
+ ? "n/a"
286
+ : state.deliverableExecuted
287
+ ? "ran"
288
+ : "NOT RUN";
289
+
290
+ const next =
291
+ policy.deliverableSignal != null && !state.deliverableExecuted
292
+ ? `run the deliverable (${policy.deliverableSignal})`
293
+ : "take a producing action (write/edit) or emit your final answer";
294
+
295
+ return `[budget ${state.toolCallCount}/${state.budget} | deliverable=${deliverable} | reads_since_produce=${state.consecutiveNonProducing}] NEXT: ${next}`;
296
+ }
297
+
298
+ // ---------------------------------------------------------------------------
299
+ // trajectoryMetrics
300
+ // ---------------------------------------------------------------------------
301
+
302
+ export function trajectoryMetrics(state: GuardState): Record<string, unknown> {
303
+ return {
304
+ ttfa: state.ttfa,
305
+ read_exec_ratio:
306
+ state.execCount === 0 ? state.readCount : state.readCount / state.execCount,
307
+ self_script_count: state.selfScriptCount,
308
+ tool_call_count: state.toolCallCount,
309
+ deliverable_executed: state.deliverableExecuted,
310
+ blocked_count: state.blockedCount,
311
+ redundant_count: state.redundantCount,
312
+ consecutive_non_producing: state.consecutiveNonProducing,
313
+ };
314
+ }
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // observationOk
318
+ // ---------------------------------------------------------------------------
319
+
320
+ const ERROR_PREFIXES = [
321
+ "DENIED",
322
+ "BLOCKED",
323
+ "Error",
324
+ "error:",
325
+ "ERROR",
326
+ "Exception",
327
+ "Traceback",
328
+ "FAIL",
329
+ "failed:",
330
+ ];
331
+
332
+ /**
333
+ * Heuristic: did a tool result indicate success? Used by the after-hook to set
334
+ * `ok` for updateState so a FAILED mutation does not mark the deliverable as
335
+ * executed. Mirrors the reference observationOk: empty/non-string => ok (no
336
+ * evidence of failure); otherwise false only when the (left-trimmed) text
337
+ * starts with a known error prefix.
338
+ */
339
+ export function observationOk(output: unknown): boolean {
340
+ const s = typeof output === "string" ? output.trimStart() : "";
341
+ if (s.length === 0) return true;
342
+ return !ERROR_PREFIXES.some((p) => s.startsWith(p));
343
+ }
@@ -0,0 +1,34 @@
1
+ /** Regex patterns that flag progress narration without production. */
2
+ export const NARRATION_PATTERNS: RegExp[] = [
3
+ // "Still writing the X", "Still implementing the Y"
4
+ /\bstill\s+(writing|implementing|working on|adding|creating|fixing|building|refactoring|handling)\s+(the\s+)?\w+/gi,
5
+ // "Now I'll write the X", "Now writing the Y"
6
+ /\bnow\s+(i['']ll\s+)?(writ|implement|add|creat|work|fix|build|handl|refactor|updat|mov)\w*\s+(the\s+)?\w+/gi,
7
+ // "Let me write X", "Let me implement Y"
8
+ /\blet\s+me\s+(write|implement|add|create|fix|build|handle|refactor|work on|move|update|set up)\s+(the\s+)?\w+/gi,
9
+ // "I'll write the X", "I'll now implement Y"
10
+ /\bi['']ll\s+(now\s+)?(write|implement|add|create|fix|build|handle|refactor|set up|work on|move|update)\s+(the\s+)?\w+/gi,
11
+ // "Going to fix the X"
12
+ /\bgoing\s+to\s+(write|implement|add|create|fix|build|handle|refactor|set up|work on|move|update)\s+(the\s+)?\w+/gi,
13
+ // "Continuing with X", "Continuing by adding Y"
14
+ /\bcontinuing\s+(with|by\s+\w+ing)\s+(the\s+)?\w+/gi,
15
+ ];
16
+
17
+ /** Returns matched narration phrases, deduped and capped. Empty array = no narration detected. */
18
+ export function detectNarration(text: string): string[] {
19
+ if (text.length < 20) return [];
20
+ const seen = new Set<string>();
21
+ const out: string[] = [];
22
+ for (const pattern of NARRATION_PATTERNS) {
23
+ const matches = text.match(pattern);
24
+ if (!matches) continue;
25
+ for (const m of matches) {
26
+ const trimmed = m.trim().toLowerCase();
27
+ if (seen.has(trimmed)) continue;
28
+ seen.add(trimmed);
29
+ out.push(m.trim());
30
+ if (out.length >= 5) return out;
31
+ }
32
+ }
33
+ return out;
34
+ }
@@ -0,0 +1,26 @@
1
+ const KEYVALUE_RE =
2
+ /(\b(?:api[_-]?key|apikey|secret|token|password|passwd|pwd|authorization)\b\s*[:=]\s*)['"]?[A-Za-z0-9._\-]{6,}['"]?/gi;
3
+
4
+ const TOKEN_PATTERNS: RegExp[] = [
5
+ /\bsk-ant-[A-Za-z0-9_\-]{16,}/g, // Anthropic
6
+ /\bsk-[A-Za-z0-9_\-]{20,}/g, // OpenAI-style
7
+ /\bgh[posru]_[A-Za-z0-9]{20,}/g, // GitHub tokens (ghp_/gho_/ghu_/ghs_/ghr_)
8
+ /\bAKIA[0-9A-Z]{16}\b/g, // AWS access key id
9
+ /\bAIza[0-9A-Za-z_\-]{20,}/g, // Google API key
10
+ /\bxox[baprs]-[A-Za-z0-9\-]{10,}/g, // Slack
11
+ /\beyJ[A-Za-z0-9._\-]{20,}/g, // JWT (header starts eyJ)
12
+ /\bBearer\s+[A-Za-z0-9._\-]+/gi, // bearer tokens
13
+ ];
14
+
15
+ /**
16
+ * Redacts common secret/token shapes from a string before it is shown to a
17
+ * model, written to a log, or placed in a thrown error. Conservative by design:
18
+ * it targets recognisable key/token shapes and `key=value` secrets, and does NOT
19
+ * touch ordinary file paths or prose. Pure; safe on any input.
20
+ */
21
+ export function scrubText(input: string): string {
22
+ if (typeof input !== "string" || input.length === 0) return input;
23
+ let out = input.replace(KEYVALUE_RE, "$1[REDACTED]");
24
+ for (const re of TOKEN_PATTERNS) out = out.replace(re, "[REDACTED]");
25
+ return out;
26
+ }
@@ -0,0 +1,39 @@
1
+ import { newGuardState } from "./guards";
2
+ import type { GuardState, GuardPolicy } from "./guards";
3
+
4
+ /**
5
+ * Per-plugin-instance store of guard state, keyed by sessionID. Mirrors the
6
+ * pattern of createSessionStore/createTrajectoryStore: no module-level
7
+ * singletons, so concurrent subagent sessions never share mutable state (M7).
8
+ * Also holds a per-session "pending note" used by advisory mode to defer a
9
+ * banner from the before-hook to the after-hook (where output is mutable).
10
+ */
11
+ export function createGuardStore() {
12
+ const states = new Map<string, GuardState>();
13
+ const pendingNotes = new Map<string, string>();
14
+ return {
15
+ ensure(sessionID: string, policy: GuardPolicy): GuardState {
16
+ let s = states.get(sessionID);
17
+ if (!s) {
18
+ s = newGuardState(policy);
19
+ states.set(sessionID, s);
20
+ }
21
+ return s;
22
+ },
23
+ get(sessionID: string): GuardState | undefined {
24
+ return states.get(sessionID);
25
+ },
26
+ setPendingNote(sessionID: string, note: string): void {
27
+ pendingNotes.set(sessionID, note);
28
+ },
29
+ takePendingNote(sessionID: string): string | undefined {
30
+ const n = pendingNotes.get(sessionID);
31
+ if (n !== undefined) pendingNotes.delete(sessionID);
32
+ return n;
33
+ },
34
+ clear(sessionID: string): void {
35
+ states.delete(sessionID);
36
+ pendingNotes.delete(sessionID);
37
+ },
38
+ };
39
+ }