perf(hooks): run run-with-flags in-process from plugin bootstrap

plugin-hook-bootstrap.js spawned a second node process just to start
run-with-flags.js, for every hook. Call its new runHook() export
directly instead. Same env, args, stdout passthrough and exit code.

Refs #2834
This commit is contained in:
Shaurya committed 2026-11-03 12:20:13 +05:30
1 parent b38be6a7f6
commit 8b2f7ebe07
3 files changed
+81 -29

No files matched your search

+22 -1
View File
@@ -189,6 +189,24 @@ function spawnNode(rootDir, relPath, raw, args, options = {}) {
return withComparisonInput(result, Buffer.from(raw, 'utf8'));
}
// Almost every plugin hook targets run-with-flags.js, which only reads stdin
// and dispatches. Call it in-process instead of paying a second Node startup
// (~50-100 ms) on every hook. Same env and inputs the child would have seen.
async function runWithFlagsInProcess(rootDir, target, raw, args, options) {
ensureAgentDataHomeEnv();
process.env.CLAUDE_PLUGIN_ROOT = rootDir;
process.env.ECC_PLUGIN_ROOT = rootDir;
process.env.ECC_HOOK_INPUT_MAX_BYTES = String(options.maxStdin);
const [hookId, relScriptPath, profilesCsv] = args;
const { runHook } = require(target);
const { stdout, exitCode } = await runHook(hookId, relScriptPath, profilesCsv, {
raw,
truncated: options.truncated,
hookContext: options.hookContext || {},
});
return withComparisonInput({ status: exitCode, stdout }, Buffer.from(raw, 'utf8'));
}
// spawnShell is not used by any hook in the shipped hooks.json configuration
// (all hooks use 'node' mode). It is provided for third-party plugins that
// register shell-backed hooks. Plugins should supply .ps1 scripts on Windows
@@ -283,7 +301,10 @@ async function main() {
let result;
try {
if (mode === 'node') {
if (mode === 'node' && path.basename(relPath) === 'run-with-flags.js') {
const target = resolveTarget(rootDir, relPath);
result = await runWithFlagsInProcess(rootDir, target, raw, args, { maxStdin, truncated, hookContext });
} else if (mode === 'node') {
result = spawnNode(rootDir, relPath, raw, args, { maxStdin, truncated, hookContext });
} else if (mode === 'shell') {
result = spawnShell(rootDir, relPath, raw, args, { maxStdin, truncated, hookContext });
+32 -28
View File
@@ -193,10 +193,12 @@ function buildDryRunPreview(hookId, relScriptPath, profilesCsv, raw) {
return parts.join(' ') + '\n';
}
async function main() {
const [, , hookId, relScriptPath, profilesCsv] = process.argv;
const { raw, truncated, hookContext } = await readStdinRaw();
/**
* Runs one hook and returns { stdout, exitCode } instead of exiting, so
* plugin-hook-bootstrap.js can call it in-process rather than spawning a
* second Node process per hook.
*/
async function runHook(hookId, relScriptPath, profilesCsv, { raw, truncated, hookContext }) {
// Oversized payloads: never echo the truncated string — a JSON document
// cut mid-stream is treated by the harness as a hook failure, blocking the
// tool call (#2222). Empty stdout + exit 0 means "no opinion", so
@@ -209,20 +211,17 @@ async function main() {
}
if (!hookId || !relScriptPath) {
exitWithStdout('', 0);
return;
return { stdout: '', exitCode: 0 };
}
if (!isHookEnabled(hookId, { profiles: profilesCsv })) {
exitWithStdout('', 0);
return;
return { stdout: '', exitCode: 0 };
}
if (isDryRun()) {
const preview = buildDryRunPreview(hookId, relScriptPath, profilesCsv, raw);
process.stderr.write(preview);
exitWithStdout('', 0);
return;
return { stdout: '', exitCode: 0 };
}
const pluginRoot = getPluginRoot();
@@ -232,21 +231,18 @@ async function main() {
// Prevent path traversal outside the plugin root
if (!scriptPath.startsWith(resolvedRoot + path.sep)) {
process.stderr.write(`[Hook] Path traversal rejected for ${hookId}: ${scriptPath}\n`);
exitWithStdout('', 0);
return;
return { stdout: '', exitCode: 0 };
}
if (!fs.existsSync(scriptPath)) {
process.stderr.write(`[Hook] Script not found for ${hookId}: ${scriptPath}\n`);
exitWithStdout('', 0);
return;
return { stdout: '', exitCode: 0 };
}
const truncationBlock = truncated ? truncatedInputResult(hookId, MAX_STDIN) : null;
if (truncationBlock) {
writeStderr(truncationBlock.stderr);
exitWithStdout(truncationBlock.stdout, truncationBlock.exitCode);
return;
return { stdout: truncationBlock.stdout, exitCode: truncationBlock.exitCode };
}
// Prefer direct require() when the hook exports a run(rawInput) function.
@@ -294,12 +290,11 @@ async function main() {
...(truncated ? hookContext : {})
});
const result = resolveHookResult(output);
exitWithStdout(sanitizeEcho(result.stdout), result.exitCode);
return { stdout: sanitizeEcho(result.stdout), exitCode: result.exitCode };
} catch (runErr) {
process.stderr.write(`[Hook] run() error for ${hookId}: ${runErr.message}\n`);
exitWithStdout('', 0);
return { stdout: '', exitCode: 0 };
}
return;
}
// Legacy path: spawn a child Node process for hooks without run() export
@@ -315,8 +310,7 @@ async function main() {
const remaining = deadline - Date.now();
if (remaining <= 0) {
writeStderr(`[Hook] lifecycle time budget exhausted for ${hookId}; skipping legacy hook`);
exitWithStdout('', 0);
return;
return { stdout: '', exitCode: 0 };
}
const result = spawnSync(process.execPath, [scriptPath], {
input: raw,
@@ -340,14 +334,24 @@ async function main() {
if (result.error || result.signal || result.status === null) {
const failureDetail = result.error ? result.error.message : result.signal ? `terminated by signal ${result.signal}` : 'missing exit status';
writeStderr(`[Hook] legacy hook execution failed for ${hookId}: ${failureDetail}`);
exitWithStdout(legacyStdout, 1);
return;
return { stdout: legacyStdout, exitCode: 1 };
}
exitWithStdout(legacyStdout, Number.isInteger(result.status) ? result.status : 0);
return { stdout: legacyStdout, exitCode: Number.isInteger(result.status) ? result.status : 0 };
}
main().catch(err => {
process.stderr.write(`[Hook] run-with-flags error: ${err.message}\n`);
process.exit(0);
});
async function main() {
const [, , hookId, relScriptPath, profilesCsv] = process.argv;
const input = await readStdinRaw();
const result = await runHook(hookId, relScriptPath, profilesCsv, input);
exitWithStdout(result.stdout, result.exitCode);
}
if (require.main === module) {
main().catch(err => {
process.stderr.write(`[Hook] run-with-flags error: ${err.message}\n`);
process.exit(0);
});
}
module.exports = { runHook };
+27
View File
@@ -169,6 +169,33 @@ process.stdout.write(JSON.stringify({
}
})) passed++; else failed++;
if (test('node mode runs run-with-flags.js in-process instead of spawning a second node', () => {
const root = createTempDir();
try {
writeFile(root, path.join('scripts', 'hooks', 'run-with-flags.js'), `
module.exports.runHook = async (hookId, relScriptPath, profilesCsv, input) => ({
stdout: JSON.stringify({ pid: process.pid, hookId, relScriptPath, profilesCsv, raw: input.raw }),
exitCode: 2,
});
`);
const result = run(
['node', path.join('scripts', 'hooks', 'run-with-flags.js'), 'pre:test', 'scripts/hooks/x.js', 'standard'],
{ root, input: 'payload' }
);
const parsed = JSON.parse(result.stdout);
assert.strictEqual(result.status, 2, result.stderr);
assert.strictEqual(parsed.pid, result.pid);
assert.deepStrictEqual(
[parsed.hookId, parsed.relScriptPath, parsed.profilesCsv, parsed.raw],
['pre:test', 'scripts/hooks/x.js', 'standard', 'payload']
);
} finally {
cleanup(root);
}
})) passed++; else failed++;
if (test('node mode emits empty stdout when child exits cleanly without stdout', () => {
const root = createTempDir();
try {