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/LICENSE +21 -0
- package/README.md +359 -2
- package/SPEC.md +230 -0
- package/bin/hook.mjs +20 -0
- package/bin/mcp.mjs +100 -0
- package/bin/run.mjs +79 -0
- package/package.json +58 -4
- package/src/clean.mjs +92 -0
- package/src/exec.mjs +241 -0
- package/src/extract.mjs +319 -0
- package/src/format.mjs +232 -0
- package/src/hook.mjs +321 -0
- package/src/index.mjs +5 -0
- package/src/parsers/docker.mjs +37 -0
- package/src/parsers/eslint.mjs +61 -0
- package/src/parsers/generic.mjs +71 -0
- package/src/parsers/git.mjs +47 -0
- package/src/parsers/go.mjs +53 -0
- package/src/parsers/index.mjs +36 -0
- package/src/parsers/jest-vitest.mjs +95 -0
- package/src/parsers/nextjs-build.mjs +32 -0
- package/src/parsers/npm-pnpm.mjs +25 -0
- package/src/parsers/playwright.mjs +56 -0
- package/src/parsers/prettier.mjs +36 -0
- package/src/parsers/python.mjs +69 -0
- package/src/parsers/rust.mjs +53 -0
- package/src/parsers/tap.mjs +83 -0
- package/src/parsers/tsc.mjs +55 -0
- package/src/parsers/util.mjs +52 -0
- package/src/warnings.mjs +64 -0
package/bin/mcp.mjs
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// MCP stdio server (JSON-RPC 2.0, one JSON message per line) exposing one tool: run.
|
|
3
|
+
import readline from 'node:readline';
|
|
4
|
+
import { run, DEFAULT_TIMEOUT_SEC } from '../src/exec.mjs';
|
|
5
|
+
import { extract, LARGE_OUTPUT_BYTES, largeOutputThreshold } from '../src/extract.mjs';
|
|
6
|
+
|
|
7
|
+
export const PROTOCOL_VERSION = '2025-06-18';
|
|
8
|
+
|
|
9
|
+
export const TOOL = {
|
|
10
|
+
name: 'run',
|
|
11
|
+
description: [
|
|
12
|
+
'Run a shell command and get back only what matters: `0` on success, or on failure a short deterministic extract of the error with L<n> line ranges into the full log on disk.',
|
|
13
|
+
'Use for commands where only pass/fail matters: tests, builds, installs, lint, typecheck, formatters, git commit/push/fetch/rebase/worktree, deploys, migrations.',
|
|
14
|
+
'Do not use to read files or search code (cat, grep, sed, head, git diff/log/show), or when the stdout is the data you need (curl GET bodies, kubectl get, ls, jq): use the normal shell for those.',
|
|
15
|
+
"On failure, read more of the log by line range (sed -n 'A,Bp' <log>), never the whole log.",
|
|
16
|
+
].join(' '),
|
|
17
|
+
inputSchema: {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
command: { type: 'string', description: 'Shell command (run with bash -o pipefail -c).' },
|
|
21
|
+
cwd: { type: 'string', description: 'Working directory. Defaults to the server cwd.' },
|
|
22
|
+
showWarning: { type: 'boolean', default: false, description: 'On success, also list grouped warnings.' },
|
|
23
|
+
timeoutSec: { type: 'number', default: DEFAULT_TIMEOUT_SEC, description: 'Kill the command after this many seconds (exit 124).' },
|
|
24
|
+
largeOutputBytes: { type: 'number', default: LARGE_OUTPUT_BYTES, description: 'Add a large-output warning line when the output is bigger than this many bytes; 0 turns it off.' },
|
|
25
|
+
},
|
|
26
|
+
required: ['command'],
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n');
|
|
31
|
+
const reply = (id, result) => send({ jsonrpc: '2.0', id, result });
|
|
32
|
+
const error = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
|
|
33
|
+
|
|
34
|
+
async function callRun(args = {}) {
|
|
35
|
+
const { command, cwd, showWarning = false, timeoutSec = DEFAULT_TIMEOUT_SEC } = args;
|
|
36
|
+
const large = Number(args.largeOutputBytes);
|
|
37
|
+
const largeOutputBytes = args.largeOutputBytes !== undefined && Number.isFinite(large) && large >= 0 ? large : largeOutputThreshold();
|
|
38
|
+
if (typeof command !== 'string' || !command.trim()) throw Object.assign(new Error('`command` must be a non-empty string'), { code: -32602 });
|
|
39
|
+
if (cwd !== undefined && typeof cwd !== 'string') throw Object.assign(new Error('`cwd` must be a string'), { code: -32602 });
|
|
40
|
+
const t = Number(timeoutSec);
|
|
41
|
+
const r = await run(command, { cwd: cwd || process.cwd(), timeoutSec: Number.isFinite(t) && t > 0 ? t : DEFAULT_TIMEOUT_SEC });
|
|
42
|
+
const text = extract(r.text, { exitCode: r.exitCode, timedOut: r.timedOut, command, logPath: r.logPath, showWarning: !!showWarning, largeOutputBytes });
|
|
43
|
+
return { content: [{ type: 'text', text }], isError: r.exitCode !== 0 };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function handle(msg) {
|
|
47
|
+
const { id, method, params } = msg;
|
|
48
|
+
const isNotification = id === undefined || id === null;
|
|
49
|
+
switch (method) {
|
|
50
|
+
case 'initialize':
|
|
51
|
+
return reply(id, {
|
|
52
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
53
|
+
capabilities: { tools: { listChanged: false } },
|
|
54
|
+
serverInfo: { name: 'run-tool', version: '1.0.0' },
|
|
55
|
+
});
|
|
56
|
+
case 'notifications/initialized':
|
|
57
|
+
case 'notifications/cancelled':
|
|
58
|
+
return;
|
|
59
|
+
case 'ping':
|
|
60
|
+
return reply(id, {});
|
|
61
|
+
case 'tools/list':
|
|
62
|
+
return reply(id, { tools: [TOOL] });
|
|
63
|
+
case 'tools/call': {
|
|
64
|
+
if (params?.name !== 'run') return error(id, -32602, `unknown tool: ${params?.name}`);
|
|
65
|
+
try {
|
|
66
|
+
return reply(id, await callRun(params.arguments));
|
|
67
|
+
} catch (e) {
|
|
68
|
+
if (e.code === -32602) return error(id, -32602, e.message);
|
|
69
|
+
return reply(id, { content: [{ type: 'text', text: `run-tool error: ${e.message}` }], isError: true });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
default:
|
|
73
|
+
if (isNotification) return;
|
|
74
|
+
return error(id, -32601, `Method not found: ${method}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
79
|
+
const pending = new Set();
|
|
80
|
+
rl.on('line', (line) => {
|
|
81
|
+
if (!line.trim()) return;
|
|
82
|
+
let msg;
|
|
83
|
+
try {
|
|
84
|
+
msg = JSON.parse(line);
|
|
85
|
+
} catch {
|
|
86
|
+
return send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
|
|
87
|
+
}
|
|
88
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg) || typeof msg.method !== 'string') {
|
|
89
|
+
return send({ jsonrpc: '2.0', id: msg?.id ?? null, error: { code: -32600, message: 'Invalid Request' } });
|
|
90
|
+
}
|
|
91
|
+
const p = handle(msg).catch((e) => {
|
|
92
|
+
if (msg.id !== undefined) error(msg.id, -32603, e.message);
|
|
93
|
+
});
|
|
94
|
+
pending.add(p);
|
|
95
|
+
p.finally(() => pending.delete(p));
|
|
96
|
+
});
|
|
97
|
+
rl.on('close', async () => {
|
|
98
|
+
await Promise.allSettled([...pending]);
|
|
99
|
+
process.exit(0);
|
|
100
|
+
});
|
package/bin/run.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// run [--show-warning] [--explain-success] [--cwd DIR] [--timeout SEC] [--budget CHARS] [--large-output BYTES] -- <command string>
|
|
3
|
+
// run --last
|
|
4
|
+
import { run, lastLog, DEFAULT_TIMEOUT_SEC } from '../src/exec.mjs';
|
|
5
|
+
import { extract, DEFAULT_BUDGET, largeOutputThreshold } from '../src/extract.mjs';
|
|
6
|
+
|
|
7
|
+
const USAGE = `usage: run [--show-warning] [--explain-success] [--cwd DIR] [--timeout SEC] [--budget CHARS] [--large-output BYTES] -- <command string>
|
|
8
|
+
run --last`;
|
|
9
|
+
|
|
10
|
+
function fail(msg) {
|
|
11
|
+
process.stderr.write(`run: ${msg}\n${USAGE}\n`);
|
|
12
|
+
process.exit(2);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function parseArgs(argv, env = process.env) {
|
|
16
|
+
const opts = { showWarning: false, explainSuccess: false, cwd: undefined, timeoutSec: DEFAULT_TIMEOUT_SEC, budgetChars: DEFAULT_BUDGET, largeOutputBytes: largeOutputThreshold(env), last: false, command: null };
|
|
17
|
+
let i = 0;
|
|
18
|
+
const num = (name, v) => {
|
|
19
|
+
const n = Number(v);
|
|
20
|
+
if (v === undefined || !Number.isFinite(n) || n <= 0) fail(`${name} needs a positive number`);
|
|
21
|
+
return n;
|
|
22
|
+
};
|
|
23
|
+
for (; i < argv.length; i++) {
|
|
24
|
+
const a = argv[i];
|
|
25
|
+
if (a === '--') {
|
|
26
|
+
i++;
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
if (a === '--show-warning') opts.showWarning = true;
|
|
30
|
+
else if (a === '--explain-success') opts.explainSuccess = true;
|
|
31
|
+
else if (a === '--last') opts.last = true;
|
|
32
|
+
else if (a === '--cwd') opts.cwd = argv[++i] ?? fail('--cwd needs a directory');
|
|
33
|
+
else if (a === '--timeout') opts.timeoutSec = num('--timeout', argv[++i]);
|
|
34
|
+
else if (a === '--budget') opts.budgetChars = Math.floor(num('--budget', argv[++i]));
|
|
35
|
+
else if (a === '--large-output') {
|
|
36
|
+
const v = argv[++i];
|
|
37
|
+
opts.largeOutputBytes = v === '0' ? 0 : Math.floor(num('--large-output', v));
|
|
38
|
+
}
|
|
39
|
+
else if (a === '-h' || a === '--help') {
|
|
40
|
+
process.stdout.write(USAGE + '\n');
|
|
41
|
+
process.exit(0);
|
|
42
|
+
} else break; // first non-option: the command starts here
|
|
43
|
+
}
|
|
44
|
+
const rest = argv.slice(i);
|
|
45
|
+
if (rest.length) opts.command = rest.join(' ');
|
|
46
|
+
return opts;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function main() {
|
|
50
|
+
const opts = parseArgs(process.argv.slice(2));
|
|
51
|
+
if (opts.last) {
|
|
52
|
+
const p = lastLog();
|
|
53
|
+
if (!p) {
|
|
54
|
+
process.stderr.write('run: no log yet\n');
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
process.stdout.write(p + '\n');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (!opts.command || !opts.command.trim()) fail('missing command');
|
|
61
|
+
const r = await run(opts.command, { cwd: opts.cwd, timeoutSec: opts.timeoutSec });
|
|
62
|
+
const out = extract(r.text, {
|
|
63
|
+
exitCode: r.exitCode,
|
|
64
|
+
timedOut: r.timedOut,
|
|
65
|
+
command: opts.command,
|
|
66
|
+
logPath: r.logPath,
|
|
67
|
+
budgetChars: opts.budgetChars,
|
|
68
|
+
showWarning: opts.showWarning,
|
|
69
|
+
explainSuccess: opts.explainSuccess,
|
|
70
|
+
largeOutputBytes: opts.largeOutputBytes,
|
|
71
|
+
});
|
|
72
|
+
process.stdout.write(out + '\n');
|
|
73
|
+
process.exitCode = r.exitCode;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
main().catch((e) => {
|
|
77
|
+
process.stderr.write(`run: ${e.stack || e.message}\n`);
|
|
78
|
+
process.exit(1);
|
|
79
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-code-token-optimization-by-tool-call",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Cut Claude Code and AI coding agent token usage: a Claude Code hook, MCP server and CLI that returns one line for passing tests and builds, and a deterministic error extract for failures.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.mjs",
|
|
9
|
+
"./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"run-tool": "bin/run.mjs",
|
|
13
|
+
"run-tool-hook": "bin/hook.mjs",
|
|
14
|
+
"run-tool-mcp": "bin/mcp.mjs"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"bin",
|
|
18
|
+
"src",
|
|
19
|
+
"README.md",
|
|
20
|
+
"SPEC.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"test": "node --test test/",
|
|
25
|
+
"prepublishOnly": "node --test test/"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=20"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"claude-code",
|
|
32
|
+
"claude",
|
|
33
|
+
"anthropic",
|
|
34
|
+
"mcp",
|
|
35
|
+
"mcp-server",
|
|
36
|
+
"hooks",
|
|
37
|
+
"token-optimization",
|
|
38
|
+
"context-window",
|
|
39
|
+
"llm",
|
|
40
|
+
"ai-coding-agent",
|
|
41
|
+
"developer-tools",
|
|
42
|
+
"cli",
|
|
43
|
+
"jest",
|
|
44
|
+
"eslint",
|
|
45
|
+
"typescript"
|
|
46
|
+
],
|
|
47
|
+
"author": "ibrahim-bayer <ibrahimbayer@gmail.com>",
|
|
48
|
+
"license": "MIT",
|
|
49
|
+
"homepage": "https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call#readme",
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call.git"
|
|
53
|
+
},
|
|
54
|
+
"bugs": {
|
|
55
|
+
"url": "https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call/issues"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public"
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/clean.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Output cleaning: ANSI/VT stripping, carriage-return resolution, long-line cut.
|
|
2
|
+
// clean() keeps lines 1:1 with the raw output's lines (no collapsing), so the
|
|
3
|
+
// log written from it can be addressed by line number.
|
|
4
|
+
|
|
5
|
+
// CSI: ESC [ params intermediates final (also the 8-bit C1 form \x9b)
|
|
6
|
+
// OSC: ESC ] ... (BEL | ESC \) (also \x9d)
|
|
7
|
+
// DCS/SOS/PM/APC: ESC P|X|^|_ ... ESC \
|
|
8
|
+
// Single-char escapes: ESC followed by one char in @-Z \ ] ^ _ or charset designators ESC ( B etc.
|
|
9
|
+
const ANSI_RE = new RegExp(
|
|
10
|
+
[
|
|
11
|
+
'(?:\\x1b\\[|\\x9b)[0-?]*[ -/]*[@-~]', // CSI
|
|
12
|
+
'(?:\\x1b\\]|\\x9d)[^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)?', // OSC
|
|
13
|
+
'\\x1b[PX^_][^\\x1b]*(?:\\x1b\\\\)?', // DCS, SOS, PM, APC
|
|
14
|
+
'\\x1b[()*+\\-./][\\x20-\\x7e]', // charset designation
|
|
15
|
+
'\\x1b[\\x20-\\x2f]*[\\x30-\\x7e]', // other 2-char / nF escapes (ESC 7, ESC =, ESC c, ...)
|
|
16
|
+
'\\x1b', // lone ESC at end of chunk
|
|
17
|
+
].join('|'),
|
|
18
|
+
'g',
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
export function stripAnsi(text) {
|
|
22
|
+
return text.replace(ANSI_RE, '');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Keep only the text after the last bare \r on each line. \r\n is a newline.
|
|
26
|
+
export function resolveCR(text) {
|
|
27
|
+
const lines = text.replace(/\r+\n/g, '\n').split('\n');
|
|
28
|
+
for (let i = 0; i < lines.length; i++) {
|
|
29
|
+
const line = lines[i];
|
|
30
|
+
const idx = line.lastIndexOf('\r');
|
|
31
|
+
if (idx !== -1) {
|
|
32
|
+
// A trailing bare \r (e.g. "progress 100%\r") leaves the last visible
|
|
33
|
+
// text in place: take the segment after the last \r that has content.
|
|
34
|
+
const segs = line.split('\r');
|
|
35
|
+
let pick = '';
|
|
36
|
+
for (let j = segs.length - 1; j >= 0; j--) {
|
|
37
|
+
if (segs[j] !== '') { pick = segs[j]; break; }
|
|
38
|
+
}
|
|
39
|
+
lines[i] = pick;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return lines.join('\n');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Remove remaining C0 control chars other than \t and \n (BEL, backspace...).
|
|
46
|
+
function stripControls(text) {
|
|
47
|
+
return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// GitLab CI job logs fold their steps with `section_start:<unix time>:<name>[opts]\r`
|
|
51
|
+
// and `section_end:…\r` markers. A marker that ends its line would survive
|
|
52
|
+
// resolveCR (the text before a trailing \r is kept), so remove markers first.
|
|
53
|
+
const CI_SECTION_RE = /section_(?:start|end):\d{9,}:[\w.-]+(?:\[[^\]\n]*\])?\r/g;
|
|
54
|
+
|
|
55
|
+
export function stripCiMarkers(text) {
|
|
56
|
+
return text.replace(CI_SECTION_RE, '');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function clean(text) {
|
|
60
|
+
return stripControls(resolveCR(stripCiMarkers(stripAnsi(text))));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Last n lines of a text or a line array.
|
|
64
|
+
export function tailLines(textOrLines, n) {
|
|
65
|
+
const lines = typeof textOrLines === 'string' ? toLines(textOrLines) : textOrLines;
|
|
66
|
+
return n > 0 ? lines.slice(-n) : [];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// At most max lines: the first max-1 and one `more(k)` line for the k left out.
|
|
70
|
+
export function headLines(lines, max, more = (k) => `… ${k} more lines`) {
|
|
71
|
+
if (lines.length <= max) return lines;
|
|
72
|
+
const keep = Math.max(0, max - 1);
|
|
73
|
+
return [...lines.slice(0, keep), more(lines.length - keep)];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const MAX_LINE = 400;
|
|
77
|
+
|
|
78
|
+
// Long-line cut. Applied when rendering an extract, never to the log, so the
|
|
79
|
+
// log keeps the complete output.
|
|
80
|
+
export function cutLine(line, max = MAX_LINE) {
|
|
81
|
+
if (line.length <= max) return line;
|
|
82
|
+
return `${line.slice(0, max)}…(+${line.length - max} chars)`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Split text into log lines. A trailing newline terminates the last line and
|
|
86
|
+
// does not start a new one, so lines[N-1] is what `sed -n Np <log>` prints.
|
|
87
|
+
export function toLines(text) {
|
|
88
|
+
if (text === '') return [];
|
|
89
|
+
const lines = text.split('\n');
|
|
90
|
+
if (lines[lines.length - 1] === '') lines.pop();
|
|
91
|
+
return lines;
|
|
92
|
+
}
|
package/src/exec.mjs
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// Spawn a shell command, merge stdout+stderr in arrival order, enforce a
|
|
2
|
+
// timeout on the whole process group, write the cleaned log, apply retention.
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { clean, toLines } from './clean.mjs';
|
|
8
|
+
|
|
9
|
+
export { toLines };
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_TIMEOUT_SEC = 600;
|
|
12
|
+
export const KILL_GRACE_MS = 5000;
|
|
13
|
+
export const LOG_CAP = { maxBytes: 20 * 1024 * 1024, headBytes: 2 * 1024 * 1024, tailBytes: 18 * 1024 * 1024 };
|
|
14
|
+
export const RETENTION = { maxAgeMs: 7 * 24 * 3600 * 1000, maxBytes: 200 * 1024 * 1024 };
|
|
15
|
+
// Raw output larger than this is read as head + tail only, to bound memory.
|
|
16
|
+
const RAW_READ_LIMIT = 64 * 1024 * 1024;
|
|
17
|
+
|
|
18
|
+
export function logDir(env = process.env) {
|
|
19
|
+
return env.RUN_TOOL_LOG_DIR || path.join(os.homedir(), '.cache', 'run-tool', 'logs');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function slug(command) {
|
|
23
|
+
const s = command
|
|
24
|
+
.slice(0, 40)
|
|
25
|
+
.toLowerCase()
|
|
26
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
27
|
+
.replace(/^-+|-+$/g, '');
|
|
28
|
+
return s || 'cmd';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function stamp(d = new Date()) {
|
|
32
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
33
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}T${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Cap the cleaned text: keep the first headBytes and last tailBytes (cut at
|
|
37
|
+
// line boundaries) with one marker line between. Line numbers after the
|
|
38
|
+
// marker no longer match the original output's line numbers.
|
|
39
|
+
export function capText(text, cap = LOG_CAP) {
|
|
40
|
+
const size = Buffer.byteLength(text);
|
|
41
|
+
if (size <= cap.maxBytes) return text;
|
|
42
|
+
const buf = Buffer.from(text);
|
|
43
|
+
let headEnd = buf.lastIndexOf(0x0a, cap.headBytes);
|
|
44
|
+
headEnd = headEnd === -1 ? cap.headBytes : headEnd + 1;
|
|
45
|
+
let tailStart = buf.indexOf(0x0a, buf.length - cap.tailBytes);
|
|
46
|
+
tailStart = tailStart === -1 ? buf.length - cap.tailBytes : tailStart + 1;
|
|
47
|
+
if (tailStart < headEnd) tailStart = headEnd;
|
|
48
|
+
const head = buf.subarray(0, headEnd).toString();
|
|
49
|
+
const tail = buf.subarray(tailStart).toString();
|
|
50
|
+
const omittedBytes = tailStart - headEnd;
|
|
51
|
+
const omittedLines = buf.subarray(headEnd, tailStart).toString().split('\n').length - 1;
|
|
52
|
+
const marker = `[run-tool: log capped, ${omittedLines} lines (${omittedBytes} bytes) omitted here; line numbers below are shifted]\n`;
|
|
53
|
+
return head + marker + tail;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function readRaw(rawPath) {
|
|
57
|
+
const size = fs.statSync(rawPath).size;
|
|
58
|
+
if (size <= RAW_READ_LIMIT) return fs.readFileSync(rawPath).toString('utf8');
|
|
59
|
+
// Huge output: read a generous head and tail only; capText marks the gap.
|
|
60
|
+
const fd = fs.openSync(rawPath, 'r');
|
|
61
|
+
try {
|
|
62
|
+
const headLen = 4 * 1024 * 1024;
|
|
63
|
+
const tailLen = 36 * 1024 * 1024;
|
|
64
|
+
const head = Buffer.alloc(headLen);
|
|
65
|
+
fs.readSync(fd, head, 0, headLen, 0);
|
|
66
|
+
const tail = Buffer.alloc(tailLen);
|
|
67
|
+
fs.readSync(fd, tail, 0, tailLen, size - tailLen);
|
|
68
|
+
// head + tail is still above the 20 MB cap, so capText cuts inside the
|
|
69
|
+
// gap and its marker covers it (its omitted-line count is then a lower bound).
|
|
70
|
+
return head.toString('utf8') + '\n' + tail.toString('utf8');
|
|
71
|
+
} finally {
|
|
72
|
+
fs.closeSync(fd);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Retention: drop logs older than maxAgeMs, then the oldest until the
|
|
77
|
+
// directory's logs total at most maxBytes. `keep` paths are never deleted.
|
|
78
|
+
export function retain(dir, opts = {}) {
|
|
79
|
+
const { maxAgeMs = RETENTION.maxAgeMs, maxBytes = RETENTION.maxBytes, keep = [], now = Date.now() } = opts;
|
|
80
|
+
let entries;
|
|
81
|
+
try {
|
|
82
|
+
entries = fs.readdirSync(dir).filter((n) => n.endsWith('.log'));
|
|
83
|
+
} catch {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
const keepSet = new Set(keep.map((p) => path.resolve(p)));
|
|
87
|
+
const files = [];
|
|
88
|
+
for (const name of entries) {
|
|
89
|
+
const p = path.join(dir, name);
|
|
90
|
+
try {
|
|
91
|
+
const st = fs.statSync(p);
|
|
92
|
+
if (st.isFile()) files.push({ p, mtime: st.mtimeMs, size: st.size });
|
|
93
|
+
} catch {}
|
|
94
|
+
}
|
|
95
|
+
const deleted = [];
|
|
96
|
+
const del = (f) => {
|
|
97
|
+
try {
|
|
98
|
+
fs.unlinkSync(f.p);
|
|
99
|
+
deleted.push(f.p);
|
|
100
|
+
return true;
|
|
101
|
+
} catch {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
let remaining = [];
|
|
106
|
+
for (const f of files) {
|
|
107
|
+
if (!keepSet.has(path.resolve(f.p)) && now - f.mtime > maxAgeMs) del(f);
|
|
108
|
+
else remaining.push(f);
|
|
109
|
+
}
|
|
110
|
+
remaining.sort((a, b) => a.mtime - b.mtime || a.p.localeCompare(b.p));
|
|
111
|
+
let total = remaining.reduce((s, f) => s + f.size, 0);
|
|
112
|
+
for (const f of remaining) {
|
|
113
|
+
if (total <= maxBytes) break;
|
|
114
|
+
if (keepSet.has(path.resolve(f.p))) continue;
|
|
115
|
+
if (del(f)) total -= f.size;
|
|
116
|
+
}
|
|
117
|
+
return deleted;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function groupAlive(pid) {
|
|
121
|
+
try {
|
|
122
|
+
process.kill(-pid, 0);
|
|
123
|
+
return true;
|
|
124
|
+
} catch (e) {
|
|
125
|
+
return e.code === 'EPERM';
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function killGroup(pid, sig) {
|
|
130
|
+
try {
|
|
131
|
+
process.kill(-pid, sig);
|
|
132
|
+
} catch {}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Run a command. Returns { exitCode, timedOut, signal, logPath, text, lines }.
|
|
137
|
+
* `text` is exactly the content of the log file.
|
|
138
|
+
*/
|
|
139
|
+
export async function run(command, opts = {}) {
|
|
140
|
+
const {
|
|
141
|
+
cwd = process.cwd(),
|
|
142
|
+
timeoutSec = DEFAULT_TIMEOUT_SEC,
|
|
143
|
+
env = process.env,
|
|
144
|
+
dir = logDir(env),
|
|
145
|
+
killGraceMs = KILL_GRACE_MS,
|
|
146
|
+
cap = LOG_CAP,
|
|
147
|
+
retention = RETENTION,
|
|
148
|
+
} = opts;
|
|
149
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
150
|
+
const started = new Date();
|
|
151
|
+
const rawPath = path.join(dir, `.raw-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
152
|
+
const fd = fs.openSync(rawPath, 'w');
|
|
153
|
+
let child;
|
|
154
|
+
// node reports a missing cwd as "spawn bash ENOENT", which reads as a missing shell
|
|
155
|
+
let cwdError = null;
|
|
156
|
+
try {
|
|
157
|
+
if (!fs.statSync(cwd).isDirectory()) cwdError = `cwd is not a directory: ${cwd}`;
|
|
158
|
+
} catch {
|
|
159
|
+
cwdError = `cwd does not exist: ${cwd}`;
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
if (cwdError) throw new Error(cwdError);
|
|
163
|
+
child = spawn('bash', ['-o', 'pipefail', '-c', command], {
|
|
164
|
+
cwd,
|
|
165
|
+
env,
|
|
166
|
+
stdio: ['ignore', fd, fd],
|
|
167
|
+
detached: true,
|
|
168
|
+
});
|
|
169
|
+
} catch (e) {
|
|
170
|
+
fs.closeSync(fd);
|
|
171
|
+
fs.writeFileSync(rawPath, cwdError ? `run-tool: ${cwdError}\n` : `run-tool: spawn failed: ${e.message}\n`);
|
|
172
|
+
child = null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
let exitCode = 127;
|
|
176
|
+
let signal = null;
|
|
177
|
+
let timedOut = false;
|
|
178
|
+
if (child) {
|
|
179
|
+
fs.closeSync(fd);
|
|
180
|
+
const result = await new Promise((resolve) => {
|
|
181
|
+
let timer = null;
|
|
182
|
+
let settled = false;
|
|
183
|
+
const finish = (v) => {
|
|
184
|
+
if (settled) return;
|
|
185
|
+
settled = true;
|
|
186
|
+
if (timer) clearTimeout(timer);
|
|
187
|
+
resolve(v);
|
|
188
|
+
};
|
|
189
|
+
child.on('error', (e) => {
|
|
190
|
+
fs.appendFileSync(rawPath, `run-tool: spawn failed: ${e.message}\n`);
|
|
191
|
+
finish({ code: 127, signal: null });
|
|
192
|
+
});
|
|
193
|
+
child.on('exit', (code, sig) => {
|
|
194
|
+
if (!timedOut) return finish({ code, signal: sig });
|
|
195
|
+
// Timed out: wait for the group to die (SIGKILL after the grace period).
|
|
196
|
+
const deadline = Date.now() + killGraceMs;
|
|
197
|
+
const poll = () => {
|
|
198
|
+
if (!groupAlive(child.pid)) return finish({ code, signal: sig });
|
|
199
|
+
if (Date.now() >= deadline) {
|
|
200
|
+
killGroup(child.pid, 'SIGKILL');
|
|
201
|
+
return setTimeout(() => finish({ code, signal: sig }), 50);
|
|
202
|
+
}
|
|
203
|
+
setTimeout(poll, 50);
|
|
204
|
+
};
|
|
205
|
+
poll();
|
|
206
|
+
});
|
|
207
|
+
if (timeoutSec > 0 && Number.isFinite(timeoutSec)) {
|
|
208
|
+
timer = setTimeout(() => {
|
|
209
|
+
timedOut = true;
|
|
210
|
+
killGroup(child.pid, 'SIGTERM');
|
|
211
|
+
// If bash itself ignores SIGTERM, escalate.
|
|
212
|
+
setTimeout(() => {
|
|
213
|
+
if (groupAlive(child.pid)) killGroup(child.pid, 'SIGKILL');
|
|
214
|
+
}, killGraceMs).unref();
|
|
215
|
+
}, timeoutSec * 1000);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
signal = result.signal;
|
|
219
|
+
if (timedOut) exitCode = 124;
|
|
220
|
+
else if (result.code !== null && result.code !== undefined) exitCode = result.code;
|
|
221
|
+
else if (signal) exitCode = 128 + (os.constants.signals[signal] || 0);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const text = capText(clean(readRaw(rawPath)), cap);
|
|
225
|
+
try {
|
|
226
|
+
fs.unlinkSync(rawPath);
|
|
227
|
+
} catch {}
|
|
228
|
+
const logPath = path.join(dir, `${stamp(started)}-${child?.pid ?? process.pid}-${slug(command)}.log`);
|
|
229
|
+
fs.writeFileSync(logPath, text);
|
|
230
|
+
fs.writeFileSync(path.join(dir, 'last'), logPath + '\n');
|
|
231
|
+
retain(dir, { ...retention, keep: [logPath] });
|
|
232
|
+
return { exitCode, timedOut, signal, logPath, text, lines: toLines(text) };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function lastLog(env = process.env) {
|
|
236
|
+
try {
|
|
237
|
+
return fs.readFileSync(path.join(logDir(env), 'last'), 'utf8').trim();
|
|
238
|
+
} catch {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
}
|