Repository navigation
Expand file tree
/
Copy pathrust_runtime_dispatch.cjs
More file actions
97 lines (88 loc) · 4.21 KB
/
Copy pathrust_runtime_dispatch.cjs
File metadata and controls
97 lines (88 loc) · 4.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env node
'use strict';
// Canonical non-blocking Claude-shape lifecycle binding. It never resolves `codeguard` from PATH or falls back to Python.
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const pluginRoot = fs.existsSync(path.join(__dirname, '..', 'runtime', 'codeguard_runtime.cjs'))
? path.resolve(__dirname, '..') : path.resolve(__dirname, '..', '..');
const { activeBinary } = require(path.join(pluginRoot, 'runtime', 'codeguard_runtime.cjs'));
const EVENTS = new Map([
['session-start', 'SessionStart'],
['user-prompt-submit', 'UserPromptSubmit'],
['post-tool-use', 'PostToolUse'],
['post-tool-use-failure', 'PostToolUseFailure'],
['stop', 'Stop'],
]);
// 恢复命令是给用户直接复制执行的;插件路径可能含空格(macOS 的 Application Support)
// 或单引号,未转义会被 shell 拆成多个参数。按 POSIX 规则用单引号包裹,内部单引号转义。
function shellQuote(value) {
return `'${String(value).replace(/'/g, "'\\''")}'`;
}
function incomplete(event, reason) {
const safe = /^[a-z_]+$/.test(reason) ? reason : 'runtime_unavailable';
// hooks 在用户 workspace 里运行,而管理器位于已安装插件根目录;相对路径会让照抄的用户
// 得到 MODULE_NOT_FOUND,生命周期就永久卡在未完成。必须给出可直接执行的绝对路径。
const manager = shellQuote(path.join(pluginRoot, 'runtime', 'codeguard_runtime.cjs'));
const message = `CodeGuard Rust 运行时未完成(${safe});本次源码检查未运行,交付未评估。请用 Node 18+ 执行 node ${manager} verify;支持的 macOS arm64 上显式运行 node ${manager} install --download。运行时可用后,使用同一入口 exec init ABS_PROJECT --apply 初始化修复任务,或 exec next ABS_PROJECT 获取指引。`;
return event === 'stop'
? { systemMessage: message }
: { hookSpecificOutput: { hookEventName: EVENTS.get(event), additionalContext: message } };
}
function readInput() {
const pieces = [];
const buffer = Buffer.allocUnsafe(64 * 1024);
let total = 0;
for (;;) {
const length = fs.readSync(0, buffer, 0, buffer.length, null);
if (length === 0) break;
total += length;
if (total > 1024 * 1024) throw new Error('host_input_too_large');
pieces.push(Buffer.from(buffer.subarray(0, length)));
}
return Buffer.concat(pieces);
}
function projectRoot() {
const configured = process.env.CLAUDE_PROJECT_DIR;
const value = configured && path.isAbsolute(configured) ? configured : process.cwd();
return fs.realpathSync(value);
}
function run(event) {
if (!EVENTS.has(event)) throw new Error('event_unsupported');
const input = readInput();
const binary = activeBinary();
const root = projectRoot();
const result = spawnSync(binary, ['hook', 'claude', event, root, '--timeout=5s', '--format=json'], {
input, encoding: 'utf8', shell: false, timeout: 8000, maxBuffer: 16 * 1024,
env: process.env,
});
if (result.error || result.signal || result.status !== 0) throw new Error('runtime_execution_failed');
let output;
try { output = JSON.parse(result.stdout); } catch { throw new Error('runtime_response_invalid'); }
if (event === 'stop') {
if (typeof output.systemMessage !== 'string'
&& output.hookSpecificOutput?.hookEventName !== 'Stop') {
throw new Error('runtime_response_invalid');
}
} else if (output.hookSpecificOutput?.hookEventName !== EVENTS.get(event)
|| typeof output.hookSpecificOutput.additionalContext !== 'string') {
throw new Error('runtime_response_invalid');
}
return output;
}
if (require.main === module) {
const event = process.argv[2];
try {
process.stdout.write(JSON.stringify(run(event)) + '\n');
} catch (error) {
const reason = typeof error.message === 'string' && error.message.startsWith('codeguard runtime incomplete: ')
? error.message.slice('codeguard runtime incomplete: '.length)
: error.message;
if (EVENTS.has(event)) process.stdout.write(JSON.stringify(incomplete(event, reason)) + '\n');
else {
process.stderr.write('CodeGuard Rust 宿主事件无效。\n');
process.exitCode = 2;
}
}
}
module.exports = { run };