@acemarke/diffloupe 0.1.0 → 0.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.
- package/README.md +202 -135
- package/dist/index.js +596 -535
- package/dist/review-core/opencode/governor.ts +670 -0
- package/dist/review-core/opencode/tools.md +104 -0
- package/dist/review-core/system.md +52 -0
- package/dist/wasm/tree-sitter-cpp.wasm +0 -0
- package/dist/wasm/tree-sitter-tsx.wasm +0 -0
- package/dist/wasm/tree-sitter-typescript.wasm +0 -0
- package/dist/wasm/web-tree-sitter.wasm +0 -0
- package/dist/web/assets/arktype-bg7F_Ihs.js +34 -0
- package/dist/web/assets/diffs-D52k9AsX.js +157 -0
- package/dist/web/assets/index-Bh_riWuX.css +1 -0
- package/dist/web/assets/index-Bhh-mxRf.js +12 -0
- package/dist/web/assets/langs/c-B7uRR5me.js +1 -0
- package/dist/web/assets/langs/cmake-Bj61d0ZC.js +1 -0
- package/dist/web/assets/langs/cpp-CsVjRphN.js +1 -0
- package/dist/web/assets/langs/css-C8fQr_0Q.js +1 -0
- package/dist/web/assets/langs/diff-woXpYk--.js +1 -0
- package/dist/web/assets/langs/docker-IyjqRm3v.js +1 -0
- package/dist/web/assets/langs/glsl-D4jN2Gfq.js +1 -0
- package/dist/web/assets/langs/go-rLFTqkRN.js +1 -0
- package/dist/web/assets/langs/graphql-CraUZO0h.js +1 -0
- package/dist/web/assets/langs/html-DA4kSGiR.js +1 -0
- package/dist/web/assets/langs/ini-B5eOa1yu.js +1 -0
- package/dist/web/assets/langs/java-BXcb2rRD.js +1 -0
- package/dist/web/assets/langs/javascript-BgS3c2Ky.js +1 -0
- package/dist/web/assets/langs/json-qhed-kSA.js +1 -0
- package/dist/web/assets/langs/json5-BR5RXkoi.js +1 -0
- package/dist/web/assets/langs/jsonc-CYpm1nAK.js +1 -0
- package/dist/web/assets/langs/jsx-Bz0zcwM4.js +1 -0
- package/dist/web/assets/langs/make-Dixweg8N.js +1 -0
- package/dist/web/assets/langs/markdown-BYOwaDjH.js +1 -0
- package/dist/web/assets/langs/objective-cpp-BsSzOQcm.js +1 -0
- package/dist/web/assets/langs/plain-text-BONI54VU.js +1 -0
- package/dist/web/assets/langs/postcss-BXeXVLqQ.js +1 -0
- package/dist/web/assets/langs/powershell-QtSnmXcu.js +1 -0
- package/dist/web/assets/langs/python-gzcpVVnB.js +1 -0
- package/dist/web/assets/langs/regexp-Cw_s_VJJ.js +1 -0
- package/dist/web/assets/langs/rust-DpiIf5JO.js +1 -0
- package/dist/web/assets/langs/scss-CHVQqdPx.js +1 -0
- package/dist/web/assets/langs/shellscript-CLZ0U2zV.js +1 -0
- package/dist/web/assets/langs/sql-CEbI0hMM.js +1 -0
- package/dist/web/assets/langs/svelte-CfPQtCMR.js +1 -0
- package/dist/web/assets/langs/toml-CcmNWLt0.js +1 -0
- package/dist/web/assets/langs/tsx-udAQXfEw.js +1 -0
- package/dist/web/assets/langs/typescript-bsJCZSQ-.js +1 -0
- package/dist/web/assets/langs/vue-DEcQttJD.js +1 -0
- package/dist/web/assets/langs/xml-D5JPTzE5.js +1 -0
- package/dist/web/assets/langs/yaml-rwi0_p6S.js +1 -0
- package/dist/web/assets/react-jlQz0HNM.js +9 -0
- package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/dist/web/assets/router-DvNvfdSS.js +2 -0
- package/dist/web/assets/shiki-CbbI7yl6.js +153 -0
- package/dist/web/assets/state-a-GRkbSP.js +1 -0
- package/dist/web/assets/themes/pierre-dark-CpLgRqie.js +1 -0
- package/dist/web/assets/themes/pierre-light-CoaEpmwp.js +1 -0
- package/dist/web/assets/unused-C8e4aDKx.js +1 -0
- package/dist/web/assets/worker-uPqQ0MJ1.js +164 -0
- package/dist/web/index.html +26 -0
- package/package.json +34 -15
|
@@ -0,0 +1,670 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spend governor for the OpenCode runner.
|
|
3
|
+
*
|
|
4
|
+
* The `claude` binary took `--max-budget-usd` and stopped itself. OpenCode has
|
|
5
|
+
* no equivalent, so the cap is enforced from inside the session instead. This
|
|
6
|
+
* file is copied into the runner's config directory by pipeline.ts and loaded by
|
|
7
|
+
* OpenCode as a plugin; it is not part of the pipeline's own module graph, and
|
|
8
|
+
* the types below are hand-written against the V2 plugin API rather than
|
|
9
|
+
* imported, because `@opencode/plugin` is not a dependency of this repository.
|
|
10
|
+
* `Plugin.define` is the identity function, so a plain `{ id, setup }` default
|
|
11
|
+
* export is the same thing.
|
|
12
|
+
*
|
|
13
|
+
* Stopping by killing the process was the obvious approach and is the wrong one:
|
|
14
|
+
* a slice delivers its findings by writing a JSON file as its last act, so a
|
|
15
|
+
* kill throws away everything the turn had already established. Every stage here
|
|
16
|
+
* is chosen to leave that write reachable.
|
|
17
|
+
*
|
|
18
|
+
* Two limits, cost and elapsed time, drive three stages. Whichever is closer to
|
|
19
|
+
* being reached is the one in force, so a limit that is not configured simply
|
|
20
|
+
* never becomes the binding one:
|
|
21
|
+
*
|
|
22
|
+
* - At `NUDGE_AT` of the limit, a wrap-up notice is appended to the result of
|
|
23
|
+
* each tool call. The agent is still free to work; it just knows the clock is
|
|
24
|
+
* running and can choose to land.
|
|
25
|
+
* - At the limit, every tool except the file write is refused. The refusal is
|
|
26
|
+
* delivered to the model as a tool error, so it reads as an instruction
|
|
27
|
+
* rather than a malfunction, and the one remaining action is the one that
|
|
28
|
+
* delivers findings. Once the findings file exists the write is refused too,
|
|
29
|
+
* which leaves no tool to call and ends the session on its own.
|
|
30
|
+
* - At `ABORT_AT` of the limit the session is interrupted outright, and only
|
|
31
|
+
* while the findings file is still missing. Interrupting is confined to the
|
|
32
|
+
* case where there was nothing to lose: an agent that keeps retrying refused
|
|
33
|
+
* tools instead of writing. `steps` in the agent config is the backstop if
|
|
34
|
+
* even that does not settle it.
|
|
35
|
+
*
|
|
36
|
+
* Time is a limit and not just a proxy for cost because on a cheap model the two
|
|
37
|
+
* come apart completely. Measured on one slice of PR #13202: the same unit that
|
|
38
|
+
* cost Opus 5 $1.58 in 22 steps cost GLM-5.3-Flash $0.10 in 46 steps, and was
|
|
39
|
+
* still going at thirteen minutes. Against a $3 budget every cost stage here
|
|
40
|
+
* stayed inert for the whole run while the thing that needed bounding ran away.
|
|
41
|
+
* Per-step latency barely differs between the two models; step count is what
|
|
42
|
+
* differs, and on a model priced thirty times lower only the clock notices.
|
|
43
|
+
*
|
|
44
|
+
* Every message the governor sends to the model rides on a tool result or a tool
|
|
45
|
+
* error, and never on the system prompt. The system prompt is the prefix of the
|
|
46
|
+
* prompt cache, so appending to it invalidates the cache and the whole context
|
|
47
|
+
* is re-sent at full price. Measured on one slice of PR #13202: injecting the
|
|
48
|
+
* notice into the system prompt dropped cache reads from 85k to 6k, rewrote 83k
|
|
49
|
+
* of cache, and took the per-step cost from $0.05 to $0.54. A governor that
|
|
50
|
+
* makes overspending ten times more expensive is worse than no governor. Tool
|
|
51
|
+
* results append after the cached prefix and cost nothing extra.
|
|
52
|
+
*
|
|
53
|
+
* The same plugin also governs shell use, for the same reason and by the same
|
|
54
|
+
* mechanism. Cost on this runner tracks step count almost exactly, so an agent
|
|
55
|
+
* that reads the codebase in `sed` fragments and searches it with `git grep`
|
|
56
|
+
* costs several times what one using the structured tools costs, and reviews it
|
|
57
|
+
* worse. The tool guidance says so and is partly ignored, so the rules below say
|
|
58
|
+
* it again at the point of use.
|
|
59
|
+
*
|
|
60
|
+
* Two jobs here are not governing at all, and live in this plugin because it is
|
|
61
|
+
* the only code of ours inside the OpenCode process:
|
|
62
|
+
*
|
|
63
|
+
* - Accounting. `opencode run --format json` leaves the final step of a session
|
|
64
|
+
* out of its stream — the text-only step that ends the turn never gets a
|
|
65
|
+
* `step_finish` line — so a total summed from stdout is short by one step on
|
|
66
|
+
* every call. The step events this plugin receives include that step, so the
|
|
67
|
+
* governor writes the authoritative totals to `REVIEW_GOVERNOR_USAGE_FILE`.
|
|
68
|
+
* - Waiting for tilth. MCP servers connect in the background, and a session
|
|
69
|
+
* that starts first gets its first model requests without the MCP tools in
|
|
70
|
+
* the tool list. A reviewer whose first two steps are offered only the shell
|
|
71
|
+
* and the built-in readers starts the habit the rules below exist to break.
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
import { appendFileSync, existsSync, writeFileSync } from "node:fs";
|
|
75
|
+
|
|
76
|
+
/** Fraction of the binding limit at which tool results carry the wrap-up notice. */
|
|
77
|
+
const NUDGE_AT = 0.75;
|
|
78
|
+
/** Multiple of the binding limit at which an agent with no findings file is interrupted. */
|
|
79
|
+
const ABORT_AT = 2;
|
|
80
|
+
/**
|
|
81
|
+
* Ceiling on any single shell command, in milliseconds.
|
|
82
|
+
*
|
|
83
|
+
* OpenCode's own shell timeout defaults to 120 seconds, and the model may ask for
|
|
84
|
+
* more or for none at all, so the cap is applied here. Measured on one slice of
|
|
85
|
+
* PR #13202: a filesystem-wide `find` burned 111 seconds and returned nothing, a
|
|
86
|
+
* fifth of that run's wall time in one call. Nothing a reviewer legitimately
|
|
87
|
+
* runs takes twenty seconds — the commands that would are builds and tests, and
|
|
88
|
+
* the review checkout has no dependencies installed to run them with. Unlike the
|
|
89
|
+
* pattern rules below, this bounds the damage from commands nobody anticipated.
|
|
90
|
+
*/
|
|
91
|
+
const MAX_SHELL_MS = 20_000;
|
|
92
|
+
/** Times a warned shell pattern is tipped before it is refused outright. */
|
|
93
|
+
const WARN_LIMIT = 3;
|
|
94
|
+
/** Longest the first model request is held back waiting for the MCP tools to register. */
|
|
95
|
+
const TOOL_WAIT_MS = 30_000;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A shell pattern the reviewer should not be using, and what to use instead.
|
|
99
|
+
*
|
|
100
|
+
* `match` and `except` are tested against the command at the head of a shell
|
|
101
|
+
* segment, never against a pipe target: `... | grep foo` is filtering another
|
|
102
|
+
* command's output, which no tool here replaces.
|
|
103
|
+
*/
|
|
104
|
+
type ShellRule = {
|
|
105
|
+
/** Short identifier, used in counts, log lines and test names. */
|
|
106
|
+
name: string;
|
|
107
|
+
match: RegExp;
|
|
108
|
+
/** If this also matches, the segment passes silently. */
|
|
109
|
+
except?: RegExp;
|
|
110
|
+
/** One sentence, delivered to the model verbatim. */
|
|
111
|
+
tip: string;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const SHELL_RULES: ShellRule[] = [
|
|
115
|
+
{
|
|
116
|
+
name: "bash-search",
|
|
117
|
+
// `git grep` is included deliberately: it was eleven of fourteen shell
|
|
118
|
+
// calls on one measured slice, and it is exactly what tilth_tilth_search
|
|
119
|
+
// does better.
|
|
120
|
+
match: /^(?:rg|grep|egrep|fgrep|ag|git\s+grep)\b/,
|
|
121
|
+
// Counting matches and listing matching files are answers the structured
|
|
122
|
+
// search does not give as directly, so those flags pass.
|
|
123
|
+
except: /(?:^|\s)-(?:c|l|-count|-files-with-matches|-files)\b/,
|
|
124
|
+
tip: "use tilth_tilth_search to search the code (kind:content for text, kind:regex for patterns, kind:symbol for definitions, kind:callers for call sites) — it ranks results and returns definitions first. Filtering another command's output with grep is fine.",
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
name: "bash-find",
|
|
128
|
+
match: /^(?:find|fd)\b/,
|
|
129
|
+
// find used to run an action rather than to list files.
|
|
130
|
+
except: /\s-(?:exec|execdir|ok|okdir|delete)\b/,
|
|
131
|
+
tip: "use tilth_tilth_files with a glob pattern to locate files.",
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
name: "bash-read",
|
|
135
|
+
// Reading a file through the shell: cat with a file argument, or a slice
|
|
136
|
+
// taken with sed/head/tail. Excludes heredocs, stdin, and redirects, which
|
|
137
|
+
// are writes rather than reads.
|
|
138
|
+
match: /^(?:cat\s+(?!<<|-\s|-$)\S|sed\s+-n\b|head\b|tail\b)/,
|
|
139
|
+
except: /[<>]/,
|
|
140
|
+
tip: "use tilth_tilth_read instead — `mode: \"full\"` for a file under review, `paths` to read several at once, `sections` for ranges of a file you have already read. A review assembled from line-range fragments misses the defects that span a file.",
|
|
141
|
+
},
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* A built-in tool that duplicates a tilth tool, and what to use instead.
|
|
146
|
+
*
|
|
147
|
+
* The shell rules above only ever see the shell tool's `command`, so they are
|
|
148
|
+
* blind to OpenCode's own search tools. On one measured slice a model refused
|
|
149
|
+
* its fourth `rg` switched to the built-in `grep` and used it six more times; on
|
|
150
|
+
* another it skipped the shell entirely and went straight to `grep` nine times,
|
|
151
|
+
* drawing no rule at all. Steering away from the shell while leaving an
|
|
152
|
+
* unpoliced tool that does the same thing just moves the traffic.
|
|
153
|
+
*/
|
|
154
|
+
type BuiltinRule = {
|
|
155
|
+
name: string;
|
|
156
|
+
tip: string;
|
|
157
|
+
/**
|
|
158
|
+
* Tipped every time but never refused. Reading a file is the core activity of
|
|
159
|
+
* a review, and a reviewer refused the ability to read has no move left that
|
|
160
|
+
* gets the job done.
|
|
161
|
+
*/
|
|
162
|
+
adviseOnly?: boolean;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const BUILTIN_RULES: Record<string, BuiltinRule> = {
|
|
166
|
+
grep: {
|
|
167
|
+
name: "builtin-search",
|
|
168
|
+
tip: "use tilth_tilth_search rather than the plain grep tool — it ranks results, returns definitions before usages, and takes kind:content, kind:regex, kind:symbol and kind:callers. Comma-separate up to five symbols to answer several questions in one call.",
|
|
169
|
+
},
|
|
170
|
+
glob: {
|
|
171
|
+
name: "builtin-files",
|
|
172
|
+
tip: "use tilth_tilth_files to locate files by pattern.",
|
|
173
|
+
},
|
|
174
|
+
read: {
|
|
175
|
+
name: "builtin-read",
|
|
176
|
+
adviseOnly: true,
|
|
177
|
+
tip: "prefer tilth_tilth_read — it takes `paths` to read several files in one call and `mode: \"full\"` to force whole-file content for anything under review.",
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/** Classify a built-in tool call: warned, or fine. */
|
|
182
|
+
const checkBuiltinTool = (tool: string): { rule: string; tip: string; adviseOnly: boolean } | null => {
|
|
183
|
+
const hit = BUILTIN_RULES[tool];
|
|
184
|
+
return hit ? { rule: hit.name, tip: hit.tip, adviseOnly: hit.adviseOnly === true } : null;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Shell commands refused on sight, with no warning ladder.
|
|
189
|
+
*
|
|
190
|
+
* Reserved for commands that cannot produce a useful answer, so there is no
|
|
191
|
+
* cost to refusing the first one. A filesystem-wide `find` qualifies: the
|
|
192
|
+
* review checkout is a bare git worktree with no dependencies installed, so
|
|
193
|
+
* searching outside it finds nothing that is under review, and the one measured
|
|
194
|
+
* instance spent 111 seconds to return zero bytes.
|
|
195
|
+
*/
|
|
196
|
+
const isFilesystemWideFind = (core: string): boolean => {
|
|
197
|
+
if (!/^(?:find|fd)\b/.test(core)) return false;
|
|
198
|
+
const cwd = process.cwd();
|
|
199
|
+
return core
|
|
200
|
+
.split(/\s+/)
|
|
201
|
+
.slice(1)
|
|
202
|
+
.some((tok) => {
|
|
203
|
+
const t = tok.replace(/^['"]/, "").replace(/['"]$/, "");
|
|
204
|
+
if (t.startsWith("~") || t.startsWith("$HOME")) return true;
|
|
205
|
+
if (!t.startsWith("/")) return false;
|
|
206
|
+
return t !== cwd && !t.startsWith(cwd + "/");
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Split a command line into segments and mark each with the separator that
|
|
212
|
+
* introduced it, so pipe targets can be skipped. Quoted regions are stepped
|
|
213
|
+
* over, because a separator inside a search pattern is not a separator.
|
|
214
|
+
*/
|
|
215
|
+
const splitSegments = (cmd: string): { sep: string; text: string }[] => {
|
|
216
|
+
const out: { sep: string; text: string }[] = [];
|
|
217
|
+
let sep = "";
|
|
218
|
+
let start = 0;
|
|
219
|
+
let quote = "";
|
|
220
|
+
for (let i = 0; i < cmd.length; i++) {
|
|
221
|
+
const c = cmd[i];
|
|
222
|
+
if (quote) {
|
|
223
|
+
if (c === quote) quote = "";
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (c === "'" || c === '"') {
|
|
227
|
+
quote = c;
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
const two = cmd.slice(i, i + 2);
|
|
231
|
+
const found = two === "&&" || two === "||" ? two : c === ";" || c === "|" ? c : "";
|
|
232
|
+
if (!found) continue;
|
|
233
|
+
out.push({ sep, text: cmd.slice(start, i) });
|
|
234
|
+
sep = found;
|
|
235
|
+
i += found.length - 1;
|
|
236
|
+
start = i + 1;
|
|
237
|
+
}
|
|
238
|
+
out.push({ sep, text: cmd.slice(start) });
|
|
239
|
+
return out;
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
/** Strip leading environment assignments and wrappers that hide the real command. */
|
|
243
|
+
const commandCore = (segment: string): string =>
|
|
244
|
+
segment
|
|
245
|
+
.trim()
|
|
246
|
+
.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)+/, "")
|
|
247
|
+
.replace(/^(?:command|timeout\s+\S+|env|nohup|xargs)\s+/, "")
|
|
248
|
+
.trim();
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Log-shaped files, including rotated ones. Reading a log through the shell is
|
|
252
|
+
* analysis, not code reading, and the structured tools are not a better fit.
|
|
253
|
+
*
|
|
254
|
+
* Deliberately narrower than the desktop version of these rules, which also
|
|
255
|
+
* exempts anything under `/tmp`. The review checkout itself lives in `/tmp`, so
|
|
256
|
+
* that exemption here would switch every rule off for every file under review.
|
|
257
|
+
*/
|
|
258
|
+
const isLogLikeTarget = (target: string): boolean =>
|
|
259
|
+
/\.(?:log|out|err|jsonl|ndjson|csv|tsv)(?:\.\d+)?$/i.test(
|
|
260
|
+
target.replace(/^['"]/, "").replace(/['"]$/, ""),
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* File-argument tokens of a command: skip the command name, flags, quoted
|
|
265
|
+
* tokens (search patterns) and bare words with neither a slash nor an
|
|
266
|
+
* extension. A heuristic — a miss only means the rule fires as it would have.
|
|
267
|
+
*/
|
|
268
|
+
const fileArgs = (core: string): string[] =>
|
|
269
|
+
core
|
|
270
|
+
.split(/\s+/)
|
|
271
|
+
.slice(1)
|
|
272
|
+
.filter(
|
|
273
|
+
(tok) =>
|
|
274
|
+
tok.length > 0 &&
|
|
275
|
+
!tok.startsWith("-") &&
|
|
276
|
+
!/^['"]/.test(tok) &&
|
|
277
|
+
(tok.includes("/") || /\.[A-Za-z0-9]+$/.test(tok)),
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
/** Classify a shell command: refused outright, warned, or fine. */
|
|
281
|
+
const checkShellCommand = (cmd: string): { rule: string; tip: string; deny: boolean } | null => {
|
|
282
|
+
for (const segment of splitSegments(cmd)) {
|
|
283
|
+
if (segment.sep === "|") continue;
|
|
284
|
+
const core = commandCore(segment.text);
|
|
285
|
+
|
|
286
|
+
if (isFilesystemWideFind(core))
|
|
287
|
+
return {
|
|
288
|
+
rule: "find-outside-checkout",
|
|
289
|
+
deny: true,
|
|
290
|
+
tip: "search outside the review checkout, which is a bare worktree with no dependencies installed and nothing else of yours on disk. Stay inside the checkout and use tilth_tilth_files.",
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
for (const rule of SHELL_RULES) {
|
|
294
|
+
if (rule.except?.test(core)) continue;
|
|
295
|
+
if (!rule.match.test(core)) continue;
|
|
296
|
+
const args = fileArgs(core);
|
|
297
|
+
if (args.length > 0 && args.every(isLogLikeTarget)) continue;
|
|
298
|
+
return { rule: rule.name, tip: rule.tip, deny: false };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return null;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Content parts that are not blocks in the provider's sense. A message can end
|
|
306
|
+
* with one of these after its last real block.
|
|
307
|
+
*/
|
|
308
|
+
const isFramePart = (type: string): boolean => type === "effort" || type.startsWith("step");
|
|
309
|
+
const isThinkingPart = (type: string): boolean => type === "reasoning" || type === "thinking";
|
|
310
|
+
|
|
311
|
+
type ContentPart = { type?: string };
|
|
312
|
+
type RepairableMessage = { role?: string; content?: readonly ContentPart[] };
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Drop a thinking block left at the end of an assistant message.
|
|
316
|
+
*
|
|
317
|
+
* Anthropic refuses any request whose history contains an assistant message
|
|
318
|
+
* whose final block is `thinking`, with `messages.N: The final block in an
|
|
319
|
+
* assistant message cannot be "thinking"`. The refusal is fatal: it happens
|
|
320
|
+
* while rebuilding the whole history, so the session cannot continue and the
|
|
321
|
+
* slice delivers nothing. Measured on PR #13202 under OpenCode V1 it killed two
|
|
322
|
+
* consecutive runs at step 9 and step 5, $1.12 for no review. Whether V2 can
|
|
323
|
+
* still produce such a history is not established, so the guard stays; it only
|
|
324
|
+
* ever acts on a request that would otherwise fail.
|
|
325
|
+
*
|
|
326
|
+
* Dropping the block is safe: Anthropic requires thinking blocks be preserved
|
|
327
|
+
* only where they precede a tool call in the same turn, and a block in final
|
|
328
|
+
* position by definition precedes nothing.
|
|
329
|
+
*
|
|
330
|
+
* The history's messages may be frozen, so an affected message is replaced in
|
|
331
|
+
* the array with a copy rather than edited in place.
|
|
332
|
+
*/
|
|
333
|
+
const repairTrailingThinking = (messages: RepairableMessage[]): number => {
|
|
334
|
+
let repaired = 0;
|
|
335
|
+
for (let i = 0; i < messages.length; i++) {
|
|
336
|
+
const message = messages[i];
|
|
337
|
+
if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
|
|
338
|
+
const content = message.content;
|
|
339
|
+
let last = content.length - 1;
|
|
340
|
+
while (last >= 0 && isFramePart(content[last]?.type ?? "")) last--;
|
|
341
|
+
if (last < 0 || !isThinkingPart(content[last]?.type ?? "")) continue;
|
|
342
|
+
const copy = Object.assign(Object.create(Object.getPrototypeOf(message)), message, {
|
|
343
|
+
content: content.filter((_, j) => j !== last),
|
|
344
|
+
});
|
|
345
|
+
messages[i] = copy;
|
|
346
|
+
repaired++;
|
|
347
|
+
}
|
|
348
|
+
return repaired;
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
type Tokens = {
|
|
352
|
+
input?: number;
|
|
353
|
+
output?: number;
|
|
354
|
+
reasoning?: number;
|
|
355
|
+
cache?: { read?: number; write?: number };
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
type StepData = { sessionID?: string; cost?: number; tokens?: Tokens };
|
|
359
|
+
|
|
360
|
+
export type ToolBefore = { tool: string; sessionID?: string; id?: string; input: unknown };
|
|
361
|
+
type ToolAfter = { tool: string; sessionID?: string; id?: string; input?: unknown } & (
|
|
362
|
+
| { status: "completed"; result: { content?: unknown } }
|
|
363
|
+
| { status: "error"; error?: unknown }
|
|
364
|
+
);
|
|
365
|
+
|
|
366
|
+
/** The slice of the V2 plugin context this plugin uses. */
|
|
367
|
+
export type GovernorContext = {
|
|
368
|
+
event: {
|
|
369
|
+
subscribe(options: { signal: AbortSignal }): AsyncIterable<{ type?: string; data?: unknown }>;
|
|
370
|
+
};
|
|
371
|
+
tool: {
|
|
372
|
+
hook(name: "execute.before", fn: (e: ToolBefore) => void | Promise<void>): unknown;
|
|
373
|
+
hook(name: "execute.after", fn: (e: ToolAfter) => void | Promise<void>): unknown;
|
|
374
|
+
list(): Promise<readonly { id: string }[]>;
|
|
375
|
+
};
|
|
376
|
+
session: {
|
|
377
|
+
hook(name: "prompt", fn: (e: unknown) => void | Promise<void>): unknown;
|
|
378
|
+
hook(name: "context", fn: (e: { messages: RepairableMessage[] }) => void | Promise<void>): unknown;
|
|
379
|
+
interrupt(input: { sessionID: string }): Promise<unknown>;
|
|
380
|
+
};
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
/** Append text to a tool result, whichever of its two shapes the result has. */
|
|
384
|
+
const appendToResult = (result: { content?: unknown }, text: string) => {
|
|
385
|
+
if (typeof result.content === "string") {
|
|
386
|
+
result.content += text;
|
|
387
|
+
} else if (Array.isArray(result.content)) {
|
|
388
|
+
result.content.push({ type: "text", text });
|
|
389
|
+
} else {
|
|
390
|
+
result.content = text;
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
395
|
+
|
|
396
|
+
async function setup(ctx: GovernorContext) {
|
|
397
|
+
const budget = Number(process.env.REVIEW_GOVERNOR_BUDGET_USD ?? 0);
|
|
398
|
+
const deadlineMs = Number(process.env.REVIEW_GOVERNOR_DEADLINE_MS ?? 0);
|
|
399
|
+
const outFile = process.env.REVIEW_GOVERNOR_OUT_FILE ?? "";
|
|
400
|
+
const logFile = process.env.REVIEW_GOVERNOR_LOG ?? "";
|
|
401
|
+
const usageFile = process.env.REVIEW_GOVERNOR_USAGE_FILE ?? "";
|
|
402
|
+
const waitForTools = process.env.REVIEW_GOVERNOR_WAIT_FOR_TOOLS ?? "";
|
|
403
|
+
const expectTools = (process.env.REVIEW_GOVERNOR_EXPECT_TOOLS ?? "").split(",").filter(Boolean);
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Taken when the plugin loads, which is process start: the whole point is to
|
|
407
|
+
* bound the call the pipeline is waiting on, and that clock starts before the
|
|
408
|
+
* first token.
|
|
409
|
+
*/
|
|
410
|
+
const startedAt = Date.now();
|
|
411
|
+
let spent = 0;
|
|
412
|
+
let sessionID = "";
|
|
413
|
+
let aborted = false;
|
|
414
|
+
let waited = false;
|
|
415
|
+
const usage = {
|
|
416
|
+
costUsd: 0,
|
|
417
|
+
numTurns: 0,
|
|
418
|
+
usage: {
|
|
419
|
+
input_tokens: 0,
|
|
420
|
+
output_tokens: 0,
|
|
421
|
+
reasoning_tokens: 0,
|
|
422
|
+
cache_read_input_tokens: 0,
|
|
423
|
+
cache_creation_input_tokens: 0,
|
|
424
|
+
},
|
|
425
|
+
};
|
|
426
|
+
/**
|
|
427
|
+
* Times each shell rule has been tipped. Plugin-wide rather than keyed by
|
|
428
|
+
* session, because one pipeline invocation is one process running one
|
|
429
|
+
* session; the point is to interrupt a habit within a single review.
|
|
430
|
+
*/
|
|
431
|
+
const warnCounts = new Map<string, number>();
|
|
432
|
+
/** Start times by call ID, so the log can carry how long each tool took. */
|
|
433
|
+
const started = new Map<string, number>();
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Written straight to a file rather than through OpenCode's logger, so that a
|
|
437
|
+
* governor decision can still be read back when the run is being diagnosed
|
|
438
|
+
* precisely because the session went wrong.
|
|
439
|
+
*/
|
|
440
|
+
const log = (event: string, extra: Record<string, unknown> = {}) => {
|
|
441
|
+
if (!logFile) return;
|
|
442
|
+
try {
|
|
443
|
+
appendFileSync(logFile, JSON.stringify({ t: Date.now(), event, spent, ...extra }) + "\n");
|
|
444
|
+
} catch {
|
|
445
|
+
/* diagnostics are never worth failing a review over */
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
/** No limit of either kind configured means no governing: every stage is inert. */
|
|
450
|
+
const capped = budget > 0 || deadlineMs > 0;
|
|
451
|
+
const elapsedMs = () => Date.now() - startedAt;
|
|
452
|
+
/**
|
|
453
|
+
* How far along the binding limit is, as a fraction. An unconfigured limit
|
|
454
|
+
* contributes zero and so can never be the binding one; with both set, the
|
|
455
|
+
* one nearer its ceiling decides, which is what makes cost and time a single
|
|
456
|
+
* ladder rather than two that have to agree.
|
|
457
|
+
*/
|
|
458
|
+
const pressure = () =>
|
|
459
|
+
Math.max(budget > 0 ? spent / budget : 0, deadlineMs > 0 ? elapsedMs() / deadlineMs : 0);
|
|
460
|
+
/** Which limit is in force, for messages the model reads. */
|
|
461
|
+
const binding = (): "cost" | "time" =>
|
|
462
|
+
deadlineMs > 0 && (budget <= 0 || elapsedMs() / deadlineMs >= spent / budget) ? "time" : "cost";
|
|
463
|
+
/** One clause naming the limit that is out, in the units it is measured in. */
|
|
464
|
+
const limitNote = () =>
|
|
465
|
+
binding() === "time"
|
|
466
|
+
? `Time limit reached: ${Math.round(elapsedMs() / 1000)}s of ${Math.round(deadlineMs / 1000)}s`
|
|
467
|
+
: `Budget exhausted: $${spent.toFixed(2)} of $${budget.toFixed(2)}`;
|
|
468
|
+
const over = () => capped && pressure() >= 1;
|
|
469
|
+
const delivered = () => outFile !== "" && existsSync(outFile);
|
|
470
|
+
|
|
471
|
+
const onStep = async (step: StepData) => {
|
|
472
|
+
if (step.sessionID) sessionID = step.sessionID;
|
|
473
|
+
const cost = step.cost ?? 0;
|
|
474
|
+
spent += cost;
|
|
475
|
+
usage.costUsd += cost;
|
|
476
|
+
usage.numTurns += 1;
|
|
477
|
+
usage.usage.input_tokens += step.tokens?.input ?? 0;
|
|
478
|
+
usage.usage.output_tokens += step.tokens?.output ?? 0;
|
|
479
|
+
usage.usage.reasoning_tokens += step.tokens?.reasoning ?? 0;
|
|
480
|
+
usage.usage.cache_read_input_tokens += step.tokens?.cache?.read ?? 0;
|
|
481
|
+
usage.usage.cache_creation_input_tokens += step.tokens?.cache?.write ?? 0;
|
|
482
|
+
if (usageFile) {
|
|
483
|
+
try {
|
|
484
|
+
writeFileSync(usageFile, JSON.stringify(usage));
|
|
485
|
+
} catch {
|
|
486
|
+
/* the stream total is the fallback */
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
log("step", { cost, ms: elapsedMs(), tokens: step.tokens ?? null });
|
|
490
|
+
|
|
491
|
+
if (!capped || aborted || pressure() < ABORT_AT) return;
|
|
492
|
+
if (delivered()) return;
|
|
493
|
+
if (!sessionID) return;
|
|
494
|
+
aborted = true;
|
|
495
|
+
log("abort", { sessionID });
|
|
496
|
+
try {
|
|
497
|
+
await ctx.session.interrupt({ sessionID });
|
|
498
|
+
} catch (error) {
|
|
499
|
+
log("abort-failed", { error: error instanceof Error ? error.message : String(error) });
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
|
|
503
|
+
const events = new AbortController();
|
|
504
|
+
void (async () => {
|
|
505
|
+
try {
|
|
506
|
+
for await (const event of ctx.event.subscribe({ signal: events.signal })) {
|
|
507
|
+
// A failed step can still have been billed, and says so when it was.
|
|
508
|
+
if (event.type === "session.step.ended" || event.type === "session.step.failed") {
|
|
509
|
+
const data = (event.data ?? {}) as StepData;
|
|
510
|
+
if (event.type === "session.step.failed" && data.cost === undefined) continue;
|
|
511
|
+
await onStep(data);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
} catch (error) {
|
|
515
|
+
if (!events.signal.aborted) {
|
|
516
|
+
log("events-failed", { error: error instanceof Error ? error.message : String(error) });
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
})();
|
|
520
|
+
|
|
521
|
+
await ctx.session.hook("prompt", async () => {
|
|
522
|
+
if (!waitForTools || waited) return;
|
|
523
|
+
waited = true;
|
|
524
|
+
const begun = Date.now();
|
|
525
|
+
while (Date.now() - begun < TOOL_WAIT_MS) {
|
|
526
|
+
try {
|
|
527
|
+
const ids = (await ctx.tool.list()).map((t) => t.id);
|
|
528
|
+
const matched = ids.filter((id) => id.startsWith(waitForTools));
|
|
529
|
+
if (matched.length) {
|
|
530
|
+
// Builds of one tool can share a version number and differ in what
|
|
531
|
+
// they expose, so the list itself is the record of which one ran.
|
|
532
|
+
const missing = expectTools.filter((id) => !ids.includes(id));
|
|
533
|
+
log("tools-ready", { ms: Date.now() - begun, tools: matched, ...(missing.length ? { missing } : {}) });
|
|
534
|
+
if (missing.length) console.error(`review-governor: guidance names tools this session lacks: ${missing.join(", ")}`);
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
} catch {
|
|
538
|
+
/* keep waiting; the timeout below still bounds it */
|
|
539
|
+
}
|
|
540
|
+
await sleep(250);
|
|
541
|
+
}
|
|
542
|
+
log("tools-missing", { prefix: waitForTools, ms: Date.now() - begun });
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
await ctx.session.hook("context", (request) => {
|
|
546
|
+
// Mutating the message list is not the same as mutating the system
|
|
547
|
+
// prompt: these are the turns after the cached prefix, so a repair here
|
|
548
|
+
// does not invalidate the cache.
|
|
549
|
+
try {
|
|
550
|
+
const repaired = repairTrailingThinking(request.messages ?? []);
|
|
551
|
+
if (repaired > 0) log("repair-trailing-thinking", { repaired });
|
|
552
|
+
} catch (error) {
|
|
553
|
+
log("repair-failed", { error: error instanceof Error ? error.message : String(error) });
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
await ctx.tool.hook("execute.after", (call) => {
|
|
558
|
+
const begun = call.id ? started.get(call.id) : undefined;
|
|
559
|
+
if (call.id) started.delete(call.id);
|
|
560
|
+
// Logged here rather than only in `before`, so that the next command that
|
|
561
|
+
// spends two minutes returning nothing is one line in this file instead of
|
|
562
|
+
// an afternoon decoding the event stream.
|
|
563
|
+
log("tool-done", { tool: call.tool, status: call.status, ms: begun ? Date.now() - begun : null });
|
|
564
|
+
if (call.status !== "completed") return;
|
|
565
|
+
|
|
566
|
+
const input = (call.input ?? {}) as { command?: unknown };
|
|
567
|
+
const command = call.tool === "shell" && typeof input.command === "string" ? input.command : "";
|
|
568
|
+
const shell = command ? checkShellCommand(command) : null;
|
|
569
|
+
const builtin = call.tool === "shell" ? null : checkBuiltinTool(call.tool);
|
|
570
|
+
const hit = shell && !shell.deny ? shell : builtin;
|
|
571
|
+
if (hit) {
|
|
572
|
+
const advise = "adviseOnly" in hit && hit.adviseOnly;
|
|
573
|
+
const n = warnCounts.get(hit.rule) ?? 0;
|
|
574
|
+
// Appended to the tool's own result rather than pushed into the system
|
|
575
|
+
// prompt: same words, no cache invalidation.
|
|
576
|
+
appendToResult(
|
|
577
|
+
call.result,
|
|
578
|
+
`\n\n[tool tip ${advise ? n : `${n}/${WARN_LIMIT}`}] ${hit.tip}` +
|
|
579
|
+
(!advise && n >= WARN_LIMIT ? " Further uses this session will be refused." : ""),
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
if (!capped || over() || pressure() < NUDGE_AT) return;
|
|
584
|
+
// Above the limit this is silent, because the refusal in `execute.before`
|
|
585
|
+
// carries the message.
|
|
586
|
+
const used =
|
|
587
|
+
binding() === "time"
|
|
588
|
+
? `You have used ${Math.round(elapsedMs() / 1000)}s of a ${Math.round(deadlineMs / 1000)}s time limit.`
|
|
589
|
+
: `You have spent $${spent.toFixed(2)} of a $${budget.toFixed(2)} budget.`;
|
|
590
|
+
appendToResult(
|
|
591
|
+
call.result,
|
|
592
|
+
`\n\n[WRAP UP] ${used} ` +
|
|
593
|
+
`Begin wrapping up: finish the investigation you are in the middle of, and write your ` +
|
|
594
|
+
`findings file before the limit runs out. A file with fewer findings is worth far more ` +
|
|
595
|
+
`than no file at all.`,
|
|
596
|
+
);
|
|
597
|
+
log("nudge", { tool: call.tool, binding: binding() });
|
|
598
|
+
});
|
|
599
|
+
|
|
600
|
+
await ctx.tool.hook("execute.before", (call) => {
|
|
601
|
+
if (call.sessionID) sessionID = call.sessionID;
|
|
602
|
+
if (call.id) started.set(call.id, Date.now());
|
|
603
|
+
|
|
604
|
+
if (call.tool === "shell") {
|
|
605
|
+
const input = (call.input ?? {}) as { command?: unknown; timeout?: unknown; background?: unknown };
|
|
606
|
+
const command = typeof input.command === "string" ? input.command : "";
|
|
607
|
+
// Applied to every shell call, including the ones no rule below matches.
|
|
608
|
+
// An unset timeout is the two-minute default and zero means none, so
|
|
609
|
+
// both are capped too.
|
|
610
|
+
const asked = typeof input.timeout === "number" && input.timeout > 0 ? input.timeout : Infinity;
|
|
611
|
+
if (asked > MAX_SHELL_MS) input.timeout = MAX_SHELL_MS;
|
|
612
|
+
// A background command has no timeout at all and outlives the call that
|
|
613
|
+
// started it; nothing a reviewer runs needs one.
|
|
614
|
+
if (input.background) input.background = false;
|
|
615
|
+
|
|
616
|
+
const hit = command ? checkShellCommand(command) : null;
|
|
617
|
+
if (hit) {
|
|
618
|
+
const n = (warnCounts.get(hit.rule) ?? 0) + 1;
|
|
619
|
+
warnCounts.set(hit.rule, n);
|
|
620
|
+
const refuse = hit.deny || n > WARN_LIMIT;
|
|
621
|
+
log("bash-rule", { rule: hit.rule, count: n, refused: refuse, ms: elapsedMs(), command });
|
|
622
|
+
// Throwing hands the message to the model verbatim as the tool's
|
|
623
|
+
// error, which is the only channel that can explain itself. Warned
|
|
624
|
+
// patterns get WARN_LIMIT uses first, because an unattended reviewer
|
|
625
|
+
// refused a tool it was relying on can burn its remaining turns
|
|
626
|
+
// flailing; a refusal it has been told about three times cannot
|
|
627
|
+
// surprise it.
|
|
628
|
+
if (refuse) throw new Error(`Do not ${hit.tip}`);
|
|
629
|
+
}
|
|
630
|
+
} else {
|
|
631
|
+
// Same ladder, applied to the built-in tools that duplicate a tilth
|
|
632
|
+
// tool. Kept separate from the shell path because these have no command
|
|
633
|
+
// string to inspect: the tool's own name is the whole signal.
|
|
634
|
+
const hit = checkBuiltinTool(call.tool);
|
|
635
|
+
if (hit) {
|
|
636
|
+
const n = (warnCounts.get(hit.rule) ?? 0) + 1;
|
|
637
|
+
warnCounts.set(hit.rule, n);
|
|
638
|
+
const refuse = !hit.adviseOnly && n > WARN_LIMIT;
|
|
639
|
+
log("builtin-rule", { rule: hit.rule, tool: call.tool, count: n, refused: refuse, ms: elapsedMs() });
|
|
640
|
+
if (refuse) throw new Error(`Do not ${hit.tip}`);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
if (!over()) {
|
|
645
|
+
log("tool", { tool: call.tool, allowed: true });
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
// Once the findings file is on disk there is nothing left worth paying
|
|
649
|
+
// for, so the write goes too and the agent runs out of moves.
|
|
650
|
+
const allow = call.tool === "write" && !delivered();
|
|
651
|
+
log("tool", { tool: call.tool, allowed: allow });
|
|
652
|
+
if (allow) return;
|
|
653
|
+
throw new Error(
|
|
654
|
+
delivered()
|
|
655
|
+
? `${limitNote()}, and your findings file has been written. This review is complete. ` +
|
|
656
|
+
`Stop calling tools and finish your turn.`
|
|
657
|
+
: `${limitNote()}. The "${call.tool}" tool ` +
|
|
658
|
+
`is switched off. Write your findings file now with what you have already established — ` +
|
|
659
|
+
`that is the only tool still available, and an unwritten file means this review is lost.`,
|
|
660
|
+
);
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
log("setup", { budget, deadlineMs, cwd: process.cwd() });
|
|
664
|
+
return () => events.abort();
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** Exposed for the tests. Not a plugin; OpenCode loads only the default export. */
|
|
668
|
+
export const helpers = { checkShellCommand, checkBuiltinTool, repairTrailingThinking };
|
|
669
|
+
|
|
670
|
+
export default { id: "review-governor", setup };
|