claude-code-token-optimization-by-tool-call 0.0.0-stage → 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/src/hook.mjs ADDED
@@ -0,0 +1,321 @@
1
+ // Claude Code PreToolUse hook: route executor Bash commands (tests, builds,
2
+ // installs, lint, git writes) through run, so a success costs `0` in context.
3
+ //
4
+ // decide(event, opts) -> null (leave the command alone) or the hook output object.
5
+ // Pure apart from the rule loader passed in opts.
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+
10
+ // Claude Code checks permissions against the rewritten command, so a user's
11
+ // `Bash(npm test:*)` rule no longer matches once the command is wrapped. The
12
+ // hook therefore wraps only what the user's own rules already allow (and
13
+ // says `allow` for it), or everything when the mode skips permission checks.
14
+ const BYPASS_MODES = new Set(['bypassPermissions']);
15
+ const NEVER_MODES = new Set(['plan']);
16
+
17
+ // Programs whose output is the data the agent asked for: never wrapped, even
18
+ // as one segment of a pipeline (`npm test | tail` already filters).
19
+ const READ_PROGRAMS = new Set([
20
+ 'cat', 'head', 'tail', 'less', 'more', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack', 'sed', 'awk', 'gawk',
21
+ 'jq', 'yq', 'wc', 'sort', 'uniq', 'cut', 'tr', 'column', 'ls', 'tree', 'find', 'fd', 'stat', 'file', 'diff',
22
+ 'cmp', 'xxd', 'od', 'hexdump', 'strings', 'tee', 'nl', 'bat', 'readlink', 'realpath', 'which', 'type',
23
+ ]);
24
+ const GIT_WRITE = new Set([
25
+ 'commit', 'push', 'fetch', 'pull', 'rebase', 'merge', 'cherry-pick', 'revert', 'reset', 'checkout', 'switch',
26
+ 'restore', 'add', 'rm', 'mv', 'stash', 'worktree', 'clone', 'tag', 'am', 'apply', 'gc', 'submodule',
27
+ ]);
28
+ // Package-manager subcommands that print data rather than run work.
29
+ const PM_READ = new Set([
30
+ 'list', 'ls', 'll', 'why', 'view', 'info', 'show', 'outdated', 'audit', 'config', 'bin', 'root', 'store',
31
+ 'licenses', 'explain', 'search', 'pack', 'help', 'prefix', 'whoami', 'ping', 'doctor', '--version', '-v',
32
+ ]);
33
+ const TOOLS = new Set([
34
+ 'jest', 'vitest', 'mocha', 'ava', 'tap', 'playwright', 'cypress', 'tsc', 'vue-tsc', 'eslint', 'prettier',
35
+ 'biome', 'oxlint', 'stylelint', 'next', 'nest', 'vite', 'webpack', 'rollup', 'esbuild', 'tsup', 'turbo',
36
+ 'nx', 'lerna', 'make', 'cmake', 'ninja', 'mvn', 'gradle', './gradlew', './mvnw', 'ant', 'pytest', 'tox',
37
+ 'nox', 'mypy', 'pyright', 'ruff', 'black', 'flake8', 'pylint', 'isort', 'golangci-lint', 'rspec', 'rake',
38
+ 'phpunit', 'composer', 'bundle', 'dotnet', 'swift', 'xcodebuild', 'flutter', 'mix', 'sbt', 'bazel',
39
+ ]);
40
+ const PIP_LIKE = new Set(['pip', 'pip3']);
41
+ const PY_MODULES = new Set(['pytest', 'unittest', 'pip', 'build', 'mypy', 'ruff', 'black', 'flake8', 'pylint', 'isort', 'tox', 'compileall']);
42
+
43
+ /**
44
+ * Split a shell command into segments on && || ; | & and newlines outside
45
+ * quotes. Returns [{ text, op }] where op is the operator that ends the
46
+ * segment ('' for the last). Returns null for input it will not reason about
47
+ * (heredocs, unbalanced quotes).
48
+ */
49
+ export function splitSegments(cmd) {
50
+ if (/<<-?\s*['"]?\w/.test(cmd)) return null;
51
+ const segs = [];
52
+ let cur = '';
53
+ let q = null;
54
+ for (let i = 0; i < cmd.length; i++) {
55
+ const c = cmd[i];
56
+ if (q) {
57
+ cur += c;
58
+ if (c === '\\' && q === '"' && i + 1 < cmd.length) cur += cmd[++i];
59
+ else if (c === q) q = null;
60
+ continue;
61
+ }
62
+ if (c === '\\' && i + 1 < cmd.length) {
63
+ cur += c + cmd[++i];
64
+ continue;
65
+ }
66
+ if (c === "'" || c === '"' || c === '`') {
67
+ q = c;
68
+ cur += c;
69
+ continue;
70
+ }
71
+ const two = cmd.slice(i, i + 2);
72
+ let op = null;
73
+ if (two === '&&' || two === '||') op = two;
74
+ else if (c === '|' && cmd[i + 1] === '&') op = '|&';
75
+ else if (c === '&' && (cmd[i + 1] === '>' || cmd[i - 1] === '>' || cmd[i - 1] === '<')) op = null;
76
+ else if (c === ';' || c === '|' || c === '&' || c === '\n') op = c;
77
+ if (op) {
78
+ segs.push({ text: cur.trim(), op });
79
+ cur = '';
80
+ i += op.length - 1;
81
+ continue;
82
+ }
83
+ cur += c;
84
+ }
85
+ if (q) return null;
86
+ segs.push({ text: cur.trim(), op: '' });
87
+ return segs.filter((s, k) => s.text || k < segs.length - 1);
88
+ }
89
+
90
+ // Words of a segment, quote-aware enough to find the program and subcommand.
91
+ function words(seg) {
92
+ const out = [];
93
+ const re = /'[^']*'|"(?:\\.|[^"\\])*"|\S+/g;
94
+ let m;
95
+ while ((m = re.exec(seg))) out.push(m[0].replace(/^(['"])(.*)\1$/s, '$2'));
96
+ return out;
97
+ }
98
+
99
+ /** The program and its following words, after env assignments and wrappers. */
100
+ export function programOf(seg) {
101
+ let w = words(seg);
102
+ for (;;) {
103
+ while (w.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0])) w = w.slice(1);
104
+ if (w[0] === 'env') {
105
+ w = w.slice(1);
106
+ while (w.length && (w[0].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]))) w = w[0] === '-C' || w[0] === '-u' ? w.slice(2) : w.slice(1);
107
+ continue;
108
+ }
109
+ if (w[0] === 'time' || w[0] === 'nice' || w[0] === 'command') {
110
+ w = w.slice(1);
111
+ continue;
112
+ }
113
+ if (w[0] === 'timeout') {
114
+ w = w.slice(1);
115
+ while (w.length && w[0].startsWith('-')) w = w.slice(1);
116
+ w = w.slice(1); // the duration
117
+ continue;
118
+ }
119
+ break;
120
+ }
121
+ // `git -C dir x`, `pnpm -C dir x`, `pnpm --filter pkg x`: drop the option and its value
122
+ if (w.length > 1 && ['git', 'npm', 'pnpm', 'yarn', 'bun'].includes(w[0])) {
123
+ const rest = [];
124
+ for (let i = 1; i < w.length; i++) {
125
+ if (rest.length === 0 && ['-C', '--dir', '--prefix', '--filter', '-F', '--cwd', '-c', '-w', '--workspace'].includes(w[i])) i++;
126
+ else if (rest.length === 0 && w[i].startsWith('-') && w[0] !== 'git') continue;
127
+ else rest.push(w[i]);
128
+ }
129
+ w = [w[0], ...rest];
130
+ }
131
+ return w;
132
+ }
133
+
134
+ /** 'exec' | 'read' | 'cd' | 'wrapped' | 'other' for one segment. */
135
+ export function classifySegment(seg, extra = null) {
136
+ const w = programOf(seg);
137
+ const [p, a, b] = w;
138
+ if (!p) return 'other';
139
+ if (p === 'cd' || p === 'pushd') return 'cd';
140
+ if (/(^|\/)run\.mjs$/.test(p) || /(^|\/)run\.mjs$/.test(a ?? '') || p === 'run-tool') return 'wrapped';
141
+ if (extra && extra.test(seg.trim())) return 'exec';
142
+ if (READ_PROGRAMS.has(p)) return 'read';
143
+ if (p === 'git') return GIT_WRITE.has(a) ? 'exec' : 'read';
144
+ if (['npm', 'pnpm', 'yarn', 'bun'].includes(p)) {
145
+ if (!a) return p === 'yarn' ? 'exec' : 'other';
146
+ if (PM_READ.has(a)) return 'read';
147
+ if (['exec', 'x', 'dlx', 'run', 'run-script'].includes(a) && b && READ_PROGRAMS.has(b)) return 'read';
148
+ return 'exec';
149
+ }
150
+ if (p === 'npx' || p === 'bunx') return a && !READ_PROGRAMS.has(a) && !a.startsWith('-') ? 'exec' : 'other';
151
+ if (p === 'node' || p === 'deno') return w.includes('--test') || a === 'test' ? 'exec' : 'other';
152
+ if (/^python(3(\.\d+)?)?$/.test(p)) return a === '-m' && PY_MODULES.has(b) ? 'exec' : 'other';
153
+ if (PIP_LIKE.has(p)) return ['install', 'uninstall', 'download', 'wheel'].includes(a) ? 'exec' : 'read';
154
+ if (p === 'uv' || p === 'poetry' || p === 'pipenv') return ['sync', 'install', 'add', 'remove', 'lock', 'build', 'pip'].includes(a) ? 'exec' : 'other';
155
+ if (p === 'go') return ['build', 'test', 'vet', 'mod', 'install', 'get', 'generate'].includes(a) ? 'exec' : 'other';
156
+ if (p === 'cargo') return ['build', 'test', 'check', 'clippy', 'fmt', 'install', 'update', 'fetch', 'nextest'].includes(a) ? 'exec' : 'other';
157
+ if (p === 'docker' || p === 'podman') {
158
+ if (a === 'build' || a === 'pull' || a === 'push') return 'exec';
159
+ if (a === 'buildx' && b === 'build') return 'exec';
160
+ if (a === 'compose' && ['build', 'pull', 'up', 'down'].includes(b)) return 'exec';
161
+ return 'other';
162
+ }
163
+ if (p === 'dotnet') return ['build', 'test', 'restore', 'publish', 'format'].includes(a) ? 'exec' : 'other';
164
+ if (TOOLS.has(p)) return 'exec';
165
+ return 'other';
166
+ }
167
+
168
+ const SHELL_STATE =
169
+ /^(?:[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=\S*\s*$|[A-Za-z_][A-Za-z0-9_]*=(?:\$\(|`|'|")|(?:export|local|declare|typeset|readonly|unset|set|shopt|source|\.|alias|trap|read|eval|exec|function|for|while|until|if|then|else|elif|do|done|fi|case|esac|select)\b|[({}]|\w+\s*\(\)\s*\{?)/;
170
+
171
+ const shq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
172
+ const DEFAULT_BASH_TIMEOUT_MS = 120000;
173
+ const TIMEOUT_MARGIN_SEC = 5;
174
+
175
+ /**
176
+ * Plan for one command: the pipelines it is made of, each with `wrap` set
177
+ * when it runs through run, or null when nothing is wrapped.
178
+ *
179
+ * Each pipeline is wrapped on its own, so `a; b` keeps a's failure visible
180
+ * (one wrapper around both would report only b's exit code), and `cd`, reads
181
+ * and anything unknown stay in the outer shell untouched. A pipeline is
182
+ * wrapped when it starts with an executor and every later stage is a filter
183
+ * (`npm test 2>&1 | tail -80`): run's pipefail then reports the executor's
184
+ * exit code, and a success still prints `0`.
185
+ */
186
+ export function plan(command, extra = null) {
187
+ const segs = splitSegments(command);
188
+ if (!segs || !segs.length) return null;
189
+ // a `&` puts work in the background: leave the whole command alone
190
+ if (segs.some((s) => s.op === '&')) return null;
191
+ // A wrapped pipeline runs in a new bash: it cannot see a shell variable or
192
+ // function set earlier in the command, and control flow would be cut apart.
193
+ if (segs.some((s) => SHELL_STATE.test(s.text))) return null;
194
+ const kinds = segs.map((s) => classifySegment(s.text, extra));
195
+ if (kinds.includes('wrapped')) return null;
196
+ const pipelines = [];
197
+ let cur = null;
198
+ segs.forEach((s, k) => {
199
+ if (!cur) cur = { stages: [], kinds: [], op: '' };
200
+ cur.stages.push(s.text);
201
+ cur.kinds.push(kinds[k]);
202
+ if (s.op === '|' || s.op === '|&') cur.stages[cur.stages.length - 1] += s.op === '|&' ? ' 2>&1' : '';
203
+ else {
204
+ cur.op = s.op;
205
+ pipelines.push(cur);
206
+ cur = null;
207
+ }
208
+ });
209
+ for (const p of pipelines) {
210
+ p.text = p.stages.join(' | ');
211
+ p.wrap = p.kinds[0] === 'exec' && p.kinds.slice(1).every((k) => k === 'read');
212
+ }
213
+ if (!pipelines.some((p) => p.wrap)) return null;
214
+ return pipelines;
215
+ }
216
+
217
+ // Claude Code rule `Bash(x)`: `x:*` or `x *` is a prefix match, `*` elsewhere a
218
+ // wildcard, anything else exact. Returns a predicate over one segment.
219
+ function ruleMatcher(rule) {
220
+ const m = /^Bash(?:\((.*)\))?$/s.exec(rule.trim());
221
+ if (!m) return null;
222
+ if (m[1] === undefined || m[1] === '*' || m[1] === '') return () => true;
223
+ const r = m[1];
224
+ if (r.endsWith(':*')) {
225
+ const pre = r.slice(0, -2);
226
+ return (s) => s === pre || s.startsWith(pre + ' ');
227
+ }
228
+ if (r.includes('*')) {
229
+ const rx = new RegExp('^' + r.split('*').map((x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$', 's');
230
+ return (s) => rx.test(s);
231
+ }
232
+ return (s) => s === r;
233
+ }
234
+
235
+ /** Read Bash allow/ask/deny rules from the settings files Claude Code loads. */
236
+ export function loadRules({ cwd = process.cwd(), env = process.env, home = os.homedir() } = {}) {
237
+ const project = env.CLAUDE_PROJECT_DIR || cwd;
238
+ const files = [
239
+ '/etc/claude-code/managed-settings.json',
240
+ path.join(home, '.claude', 'settings.json'),
241
+ path.join(project, '.claude', 'settings.json'),
242
+ path.join(project, '.claude', 'settings.local.json'),
243
+ ];
244
+ const rules = { allow: [], ask: [], deny: [] };
245
+ for (const f of files) {
246
+ let j;
247
+ try {
248
+ j = JSON.parse(fs.readFileSync(f, 'utf8'));
249
+ } catch {
250
+ continue;
251
+ }
252
+ for (const k of Object.keys(rules)) for (const r of j?.permissions?.[k] ?? []) if (typeof r === 'string' && /^Bash\b/.test(r)) rules[k].push(r);
253
+ }
254
+ return rules;
255
+ }
256
+
257
+ /**
258
+ * true when the user's rules allow every stage of every pipeline and none is
259
+ * asked or denied. The hook's `allow` covers the whole rewritten command, so
260
+ * unwrapped parts must pass too; only `cd` and the filters after a wrapped
261
+ * executor (they read its output, nothing else) need no rule.
262
+ */
263
+ export function allowedByRules(pipelines, rules) {
264
+ const fns = (list) => list.map(ruleMatcher).filter(Boolean);
265
+ const allow = fns(rules.allow);
266
+ const block = fns([...rules.ask, ...rules.deny]);
267
+ return pipelines.every((p) =>
268
+ p.stages.every((stage, k) => {
269
+ const t = stage.trim();
270
+ if (!t) return true;
271
+ if (block.some((f) => f(t))) return false;
272
+ if (p.wrap && k > 0) return true;
273
+ return classifySegment(t) === 'cd' || allow.some((f) => f(t));
274
+ }),
275
+ );
276
+ }
277
+
278
+ /**
279
+ * @param event the PreToolUse hook input
280
+ * @param opts { runPath, env, rules } rules: { allow, ask, deny } or a loader
281
+ */
282
+ export function decide(event, opts = {}) {
283
+ const env = opts.env ?? process.env;
284
+ const mode = (env.RUN_TOOL_HOOK || '').toLowerCase();
285
+ if (mode === 'off' || event?.tool_name !== 'Bash') return null;
286
+ const input = event.tool_input ?? {};
287
+ if (input.run_in_background || typeof input.command !== 'string') return null;
288
+ const pmode = event.permission_mode || 'default';
289
+ if (NEVER_MODES.has(pmode)) return null;
290
+ let extra = null;
291
+ if (env.RUN_TOOL_HOOK_EXTRA) {
292
+ try {
293
+ extra = new RegExp(env.RUN_TOOL_HOOK_EXTRA);
294
+ } catch {
295
+ extra = null;
296
+ }
297
+ }
298
+ const p = plan(input.command, extra);
299
+ if (!p) return null;
300
+
301
+ let decision;
302
+ if (mode === 'always' || BYPASS_MODES.has(pmode)) decision = undefined;
303
+ else {
304
+ const rules = typeof opts.rules === 'function' ? opts.rules(event) : opts.rules ?? loadRules({ cwd: event.cwd, env });
305
+ if (!allowedByRules(p, rules)) return null;
306
+ decision = 'allow';
307
+ }
308
+
309
+ const bashMs = Number(input.timeout) > 0 ? Number(input.timeout) : DEFAULT_BASH_TIMEOUT_MS;
310
+ const timeoutSec = Math.max(1, Math.floor(bashMs / 1000) - TIMEOUT_MARGIN_SEC);
311
+ const runPath = opts.runPath;
312
+ const command = p
313
+ .map((x) => (x.wrap ? `node ${shq(runPath)} --explain-success --timeout ${timeoutSec} -- ${shq(x.text)}` : x.text) + (x.op ? ` ${x.op === '\n' ? ';' : x.op}` : ''))
314
+ .join(' ');
315
+ const out = { hookEventName: 'PreToolUse', updatedInput: { ...input, command } };
316
+ if (decision) {
317
+ out.permissionDecision = decision;
318
+ out.permissionDecisionReason = 'run-tool: allowed by your Bash rules; output goes to a log';
319
+ }
320
+ return { hookSpecificOutput: out };
321
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ // Library entry: the pieces a host tool imports instead of keeping its own copy.
2
+ export { clean, stripAnsi, stripCiMarkers, resolveCR, toLines, tailLines, headLines, cutLine } from './clean.mjs';
3
+ export { extract, successLine, outputSize, largeOutput, largeOutputLine, largeOutputThreshold, LARGE_OUTPUT_BYTES, DEFAULT_BUDGET } from './extract.mjs';
4
+ export { run, lastLog, logDir, DEFAULT_TIMEOUT_SEC } from './exec.mjs';
5
+ export { decide as hookDecision } from './hook.mjs';
@@ -0,0 +1,37 @@
1
+ // docker build (BuildKit) failures.
2
+
3
+ const FENCE = /^-{6}\s*$/;
4
+ const ERROR_LINE = /^ERROR:|^ERROR \[|failed to solve|^error: failed to/i;
5
+
6
+ export default {
7
+ name: 'docker',
8
+ hint: /\bdocker\b|\bbuildx\b|\bpodman\b/,
9
+ detect(lines) {
10
+ let s = 0;
11
+ let fence = 0;
12
+ for (const l of lines) {
13
+ if (/failed to solve|^ERROR \[/.test(l)) return 0.9;
14
+ if (FENCE.test(l)) fence++;
15
+ if (/^#\d+ \[/.test(l)) s = Math.max(s, 0.4);
16
+ }
17
+ if (fence >= 2 && s) s = 0.7;
18
+ return s;
19
+ },
20
+ blocks(lines) {
21
+ const out = [];
22
+ for (let i = 0; i < lines.length; i++) {
23
+ const l = lines[i];
24
+ if (FENCE.test(l)) {
25
+ let j = i + 1;
26
+ while (j < lines.length && !FENCE.test(lines[j]) && j - i < 60) j++;
27
+ if (j < lines.length && FENCE.test(lines[j])) {
28
+ out.push({ start: i, end: j, priority: 1 });
29
+ i = j;
30
+ continue;
31
+ }
32
+ }
33
+ if (ERROR_LINE.test(l)) out.push({ start: i, end: i, priority: 1 });
34
+ }
35
+ return out;
36
+ },
37
+ };
@@ -0,0 +1,61 @@
1
+ // ESLint stylish formatter: a file header line, then ` line:col error msg rule` rows.
2
+
3
+ const ROW = /^\s+\d+:\d+\s+(error|warning)\s/;
4
+ const ERROR_ROW = /^\s+\d+:\d+\s+error\s/;
5
+ const HEADER = /^(?:[A-Za-z]:\\|\/|\.{1,2}\/|[\w@.-]+\/)?[^\s:]+\.[A-Za-z0-9]+$/;
6
+ const SUMMARY = /^\s*✖ \d+ problems? \(\d+ errors?, \d+ warnings?\)/;
7
+
8
+ export default {
9
+ name: 'eslint',
10
+ hint: /\beslint\b|\blint\b/,
11
+ // headers of files that have errors come with the parser blocks; the rest
12
+ // (warning-only files) must not come back through the context fill
13
+ noise: (l) => ROW.test(l) && !ERROR_ROW.test(l) || HEADER.test(l.trim()) && l.trim() === l,
14
+ detect(lines) {
15
+ let rows = 0;
16
+ let headed = false;
17
+ let summary = false;
18
+ for (let i = 0; i < lines.length; i++) {
19
+ if (ERROR_ROW.test(lines[i])) {
20
+ rows++;
21
+ // walk back over rows to the header
22
+ let k = i - 1;
23
+ while (k >= 0 && ROW.test(lines[k])) k--;
24
+ if (k >= 0 && HEADER.test(lines[k].trim())) headed = true;
25
+ }
26
+ if (SUMMARY.test(lines[i])) summary = true;
27
+ }
28
+ if (rows && headed) return 0.9;
29
+ if (summary) return 0.75;
30
+ return 0;
31
+ },
32
+ blocks(lines) {
33
+ const out = [];
34
+ let header = -1;
35
+ let headerEmitted = false;
36
+ for (let i = 0; i < lines.length; i++) {
37
+ const l = lines[i];
38
+ if (SUMMARY.test(l)) {
39
+ // summary and the "potentially fixable" line after it
40
+ const end = lines[i + 1] && /fixable/.test(lines[i + 1]) ? i + 1 : i;
41
+ out.push({ start: i, end, priority: 2 });
42
+ continue;
43
+ }
44
+ if (ROW.test(l)) {
45
+ if (ERROR_ROW.test(l)) {
46
+ if (header >= 0 && !headerEmitted) {
47
+ out.push({ start: header, end: header, priority: 1 });
48
+ headerEmitted = true;
49
+ }
50
+ out.push({ start: i, end: i, priority: 1 });
51
+ }
52
+ continue;
53
+ }
54
+ if (HEADER.test(l.trim()) && l.trim() === l) {
55
+ header = i;
56
+ headerEmitted = false;
57
+ }
58
+ }
59
+ return out;
60
+ },
61
+ };
@@ -0,0 +1,71 @@
1
+ // Fallback: error-regex hits with -2/+5 lines of context, merged.
2
+
3
+ const HIT = [
4
+ /\berror\b/i,
5
+ /ERR!/,
6
+ /\bfatal\b/i,
7
+ /\bpanic\b/i,
8
+ /Exception/,
9
+ /Traceback/,
10
+ /\bFAIL(ED)?\b/,
11
+ /[✕✗✘×]/,
12
+ /AssertionError/,
13
+ /^\s*not ok\b/,
14
+ /Cannot find/i,
15
+ /No such file/i,
16
+ /command not found/i,
17
+ /Permission denied/i,
18
+ /ENOENT/,
19
+ /EACCES/,
20
+ /ECONNREFUSED/,
21
+ /timed out/i,
22
+ /exit(ed)? (with )?code [1-9]/i,
23
+ ];
24
+
25
+ const NEGATIVE = [
26
+ /\b0 errors?\b/i,
27
+ /\bno errors?\b/i,
28
+ /warning/i,
29
+ /deprecat/i,
30
+ /hydration/i,
31
+ /--error/,
32
+ ];
33
+
34
+ // `errorCode` / `ErrorCode` identifiers in source-looking lines.
35
+ const ERROR_CODE_IDENT = /[eE]rrorCodes?\b|\b\w+[eE]rrorCode\w*/;
36
+ const SOURCE_LOOKING = /[;{}=]|^\s*\d+\s*[|│]|^\s*(const|let|var|import|export|return|if|case)\b/;
37
+ // `error.ts` etc. file names in listings.
38
+ const ERROR_FILE = /\b[\w.-]*error\.(?:ts|js|tsx|jsx|mjs|cjs)\b/gi;
39
+
40
+ export function isHit(line) {
41
+ if (line.length > 4000) line = line.slice(0, 4000);
42
+ for (const re of NEGATIVE) if (re.test(line)) return false;
43
+ if (ERROR_CODE_IDENT.test(line) && SOURCE_LOOKING.test(line)) return false;
44
+ let probe = line;
45
+ if (ERROR_FILE.test(line)) {
46
+ ERROR_FILE.lastIndex = 0;
47
+ probe = line.replace(ERROR_FILE, '');
48
+ }
49
+ ERROR_FILE.lastIndex = 0;
50
+ for (const re of HIT) if (re.test(probe)) return true;
51
+ return false;
52
+ }
53
+
54
+ export default {
55
+ name: 'generic',
56
+ detect() {
57
+ return 0.1;
58
+ },
59
+ blocks(lines) {
60
+ const out = [];
61
+ for (let i = 0; i < lines.length; i++) {
62
+ if (!isHit(lines[i])) continue;
63
+ const start = Math.max(0, i - 2);
64
+ const end = Math.min(lines.length - 1, i + 5);
65
+ const prev = out[out.length - 1];
66
+ if (prev && start <= prev.end + 1) prev.end = Math.max(prev.end, end);
67
+ else out.push({ start, end, priority: 0, hit: i });
68
+ }
69
+ return out;
70
+ },
71
+ };
@@ -0,0 +1,47 @@
1
+ // git porcelain errors: fatal:, error:, merge conflicts, rejected pushes.
2
+
3
+ const LINE = /^fatal:|^error:|CONFLICT \(|^Automatic merge failed|! \[rejected\]|! \[remote rejected\]|^\s*Merge conflict in |^Could not apply |^Rebasing .*\bconflict|^Your local changes to the following files would be overwritten|^Please commit your changes/;
4
+ const STRONG = /^fatal:|CONFLICT \(|! \[(remote )?rejected\]|^Automatic merge failed|^Could not apply /;
5
+ const HINT = /^hint:/;
6
+
7
+ export default {
8
+ name: 'git',
9
+ hint: /\bgit\b/,
10
+ // hint: lines beyond the two kept per run are noise
11
+ noise: (l) => HINT.test(l),
12
+ detect(lines) {
13
+ let s = 0;
14
+ for (const l of lines) {
15
+ if (STRONG.test(l)) s = Math.max(s, 0.8);
16
+ else if (/^error: /.test(l)) s = Math.max(s, 0.5);
17
+ else if (HINT.test(l)) s = Math.max(s, 0.45);
18
+ }
19
+ return s;
20
+ },
21
+ blocks(lines) {
22
+ const out = [];
23
+ for (let i = 0; i < lines.length; i++) {
24
+ const l = lines[i];
25
+ if (HINT.test(l)) {
26
+ // fold a run of hint: lines to its first two
27
+ let j = i;
28
+ while (j + 1 < lines.length && HINT.test(lines[j + 1])) j++;
29
+ out.push({ start: i, end: Math.min(j, i + 1), priority: 0.5 });
30
+ i = j;
31
+ continue;
32
+ }
33
+ if (/^\s+\S/.test(l)) {
34
+ // indented continuation (file lists) directly under an error/fatal line
35
+ const prev = out[out.length - 1];
36
+ if (prev && prev.end === i - 1 && prev.priority === 1 && i - prev.start < 12) prev.end = i;
37
+ continue;
38
+ }
39
+ if (LINE.test(l)) {
40
+ const prev = out[out.length - 1];
41
+ if (prev && prev.end >= i - 1 && prev.priority === 1) prev.end = i;
42
+ else out.push({ start: i, end: i, priority: 1 });
43
+ }
44
+ }
45
+ return out;
46
+ },
47
+ };
@@ -0,0 +1,53 @@
1
+ // go test / go build.
2
+ import { isBlank } from './util.mjs';
3
+
4
+ const FAIL_TEST = /^\s*--- FAIL: /;
5
+ const FAIL_PKG = /^FAIL\t|^FAIL$|^FAIL\s+\S+\s+[\d.]+s/;
6
+ const PANIC = /^panic: /;
7
+ const BUILD_ERR = /^\S+\.go:\d+:\d+: /;
8
+
9
+ export default {
10
+ name: 'go',
11
+ hint: /\bgo\s+(test|build|vet|run)\b/,
12
+ detect(lines) {
13
+ let s = 0;
14
+ for (const l of lines) {
15
+ if (FAIL_TEST.test(l) || PANIC.test(l)) return 0.9;
16
+ if (FAIL_PKG.test(l)) s = Math.max(s, 0.8);
17
+ else if (BUILD_ERR.test(l)) s = Math.max(s, 0.7);
18
+ }
19
+ return s;
20
+ },
21
+ blocks(lines) {
22
+ const out = [];
23
+ for (let i = 0; i < lines.length; i++) {
24
+ const l = lines[i];
25
+ if (FAIL_TEST.test(l)) {
26
+ // with -v the test's own log lines come before the --- FAIL line
27
+ let start = i;
28
+ while (start > 0 && /^\s{4}\S/.test(lines[start - 1]) && i - start < 20) start--;
29
+ let end = i;
30
+ const ind = /^\s*/.exec(l)[0].length;
31
+ while (end + 1 < lines.length && /^\s+\S/.test(lines[end + 1]) && /^\s*/.exec(lines[end + 1])[0].length > ind && end - i < 40) end++;
32
+ out.push({ start, end, priority: 1 });
33
+ i = end;
34
+ } else if (PANIC.test(l)) {
35
+ // panic message, the goroutine header and the first frames
36
+ let end = i;
37
+ let frames = 0;
38
+ for (let j = i + 1; j < lines.length && frames < 8; j++) {
39
+ if (isBlank(lines[j]) && end > i + 1 && frames > 0) break;
40
+ end = j;
41
+ if (/^\s+\S/.test(lines[j])) frames++;
42
+ }
43
+ out.push({ start: i, end, priority: 1.5 });
44
+ i = end;
45
+ } else if (BUILD_ERR.test(l)) {
46
+ out.push({ start: i > 0 && /^# /.test(lines[i - 1]) ? i - 1 : i, end: i, priority: 1 });
47
+ } else if (FAIL_PKG.test(l)) {
48
+ out.push({ start: i, end: i, priority: 2 });
49
+ }
50
+ }
51
+ return out;
52
+ },
53
+ };
@@ -0,0 +1,36 @@
1
+ // Parser registry and selection.
2
+ import tap from './tap.mjs';
3
+ import jestVitest from './jest-vitest.mjs';
4
+ import playwright from './playwright.mjs';
5
+ import tsc from './tsc.mjs';
6
+ import eslint from './eslint.mjs';
7
+ import nextjsBuild from './nextjs-build.mjs';
8
+ import python from './python.mjs';
9
+ import go from './go.mjs';
10
+ import rust from './rust.mjs';
11
+ import npmPnpm from './npm-pnpm.mjs';
12
+ import docker from './docker.mjs';
13
+ import git from './git.mjs';
14
+ import prettier from './prettier.mjs';
15
+ import generic from './generic.mjs';
16
+
17
+ export const PARSERS = [tap, jestVitest, playwright, tsc, eslint, nextjsBuild, python, go, rust, npmPnpm, docker, git, prettier];
18
+ export { generic, npmPnpm };
19
+
20
+ const MIN_SCORE = 0.5;
21
+ const TIE = 0.05;
22
+
23
+ /**
24
+ * Score every parser on the output content. The highest score >= 0.5 wins;
25
+ * the command only breaks near-ties. Returns { winner, scores } where winner
26
+ * may be null (generic).
27
+ */
28
+ export function pickParser(lines, command = '') {
29
+ const scores = PARSERS.map((p) => ({ parser: p, score: p.detect(lines) || 0 }));
30
+ const eligible = scores.filter((s) => s.score >= MIN_SCORE).sort((a, b) => b.score - a.score);
31
+ if (!eligible.length) return { winner: null, scores };
32
+ const top = eligible[0].score;
33
+ const tied = eligible.filter((s) => top - s.score <= TIE);
34
+ const hinted = tied.find((s) => s.parser.hint && s.parser.hint.test(command));
35
+ return { winner: (hinted || tied[0]).parser, scores };
36
+ }