-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Expand file tree
/
Copy pathbun-runner.js
More file actions
224 lines (197 loc) · 7.37 KB
/
Copy pathbun-runner.js
File metadata and controls
224 lines (197 loc) · 7.37 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env node
import { spawnSync, spawn } from 'child_process';
import { existsSync, readFileSync, mkdirSync, appendFileSync, writeFileSync } from 'fs';
import { join, dirname, resolve } from 'path';
import { homedir } from 'os';
import { fileURLToPath } from 'url';
const IS_WINDOWS = process.platform === 'win32';
const __bun_runner_dirname = dirname(fileURLToPath(import.meta.url));
const RESOLVED_PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || resolve(__bun_runner_dirname, '..');
function fixBrokenScriptPath(argPath) {
if (argPath.startsWith('/scripts/') && !existsSync(argPath)) {
const fixedPath = join(RESOLVED_PLUGIN_ROOT, argPath);
if (existsSync(fixedPath)) {
return fixedPath;
}
}
return argPath;
}
function findBun() {
const pathCheck = IS_WINDOWS
? spawnSync('where bun', {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
shell: true
})
: spawnSync('which', ['bun'], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
});
if (pathCheck.status === 0 && pathCheck.stdout.trim()) {
if (IS_WINDOWS) {
const bunCmdPath = pathCheck.stdout.split('\n').find(line => line.trim().endsWith('bun.cmd'));
if (bunCmdPath) {
return bunCmdPath.trim();
}
}
return 'bun';
}
const bunPaths = IS_WINDOWS
? [join(homedir(), '.bun', 'bin', 'bun.exe')]
: [
join(homedir(), '.bun', 'bin', 'bun'),
'/usr/local/bin/bun',
'/opt/homebrew/bin/bun',
'/home/linuxbrew/.linuxbrew/bin/bun'
];
for (const bunPath of bunPaths) {
if (existsSync(bunPath)) {
return bunPath;
}
}
return null;
}
function isPluginDisabledInClaudeSettings() {
try {
const configDir = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
const settingsPath = join(configDir, 'settings.json');
if (!existsSync(settingsPath)) return false;
const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
// No optional chaining (?.) here: this launcher must parse on the oldest
// Node that any host might invoke it with. Some Claude Code installs run
// hooks under a bundled pre-ES2020 Node whose ESM loader throws
// "SyntaxError: Unexpected token '.'" on `?.` (issue #2791).
return Boolean(
settings &&
settings.enabledPlugins &&
settings.enabledPlugins['claude-mem@thedotmack'] === false
);
} catch {
return false;
}
}
if (isPluginDisabledInClaudeSettings()) {
process.exit(0);
}
const args = process.argv.slice(2);
if (args.length === 0) {
console.error('Usage: node bun-runner.js <script> [args...]');
process.exit(1);
}
args[0] = fixBrokenScriptPath(args[0]);
const bunPath = findBun();
if (!bunPath) {
console.error('Error: Bun not found. Please install Bun: https://bun.sh');
console.error('After installation, restart your terminal.');
process.exit(1);
}
function collectStdin() {
return new Promise((resolve) => {
if (process.stdin.isTTY) {
resolve(null);
return;
}
const chunks = [];
process.stdin.on('data', (chunk) => chunks.push(chunk));
process.stdin.on('end', () => {
resolve(chunks.length > 0 ? Buffer.concat(chunks) : null);
});
process.stdin.on('error', () => {
resolve(null);
});
setTimeout(() => {
process.stdin.removeAllListeners();
process.stdin.pause();
resolve(chunks.length > 0 ? Buffer.concat(chunks) : null);
}, 5000);
});
}
const stdinData = await collectStdin();
const spawnOptions = {
stdio: ['pipe', 'inherit', 'inherit'],
windowsHide: true,
env: process.env
};
let spawnCmd = bunPath;
let spawnArgs = args;
if (IS_WINDOWS) {
const quote = (s) => `"${String(s).replace(/"/g, '\\"')}"`;
spawnOptions.shell = true;
spawnCmd = [bunPath, ...args].map(quote).join(' ');
spawnArgs = [];
}
const child = spawn(spawnCmd, spawnArgs, spawnOptions);
if (child.stdin) {
if (stdinData && stdinData.length > 0) {
child.stdin.write(stdinData);
child.stdin.end();
} else {
// Lifecycle subcommands (start, stop, restart, status) never consume stdin —
// they manage the worker daemon, not hook payloads. Killing the child here
// prevents the daemon from starting/stopping on platforms where Claude Code
// doesn't pipe a payload for SessionStart (e.g. Windows CC ≤ 2.1.145).
const lifecycleCommands = ['start', 'stop', 'restart', 'status'];
const isLifecycle = lifecycleCommands.some(cmd => args.includes(cmd));
if (isLifecycle) {
// Lifecycle commands don't need stdin — close pipe and let child run.
try { child.stdin.end(); } catch {}
} else {
// Non-lifecycle hooks with empty stdin are a no-op. Cursor (and the Claude
// Code ↔ Cursor bridge) routinely invoke shell/MCP hooks without a payload;
// issue #2188 diagnostics (CAPTURE_BROKEN + runner-errors.log) produced
// persistent false positives on macOS. Set CLAUDE_MEM_STRICT_STDIN=1 to
// restore the #2188 failure surface for WSL/bash debugging.
if (process.env.CLAUDE_MEM_STRICT_STDIN === '1') {
const dataDir = process.env.CLAUDE_MEM_DATA_DIR || join(homedir(), '.claude-mem');
const payloadType = stdinData === null
? 'null (no data event or stream error)'
: stdinData === undefined
? 'undefined'
: Buffer.isBuffer(stdinData) && stdinData.length === 0
? 'empty Buffer (zero bytes received)'
: `unexpected (${typeof stdinData})`;
const payloadByteLength = (stdinData && typeof stdinData.length === 'number')
? stdinData.length
: 0;
const diagnostic = [
`[bun-runner] empty stdin payload received — issue #2188`,
` script: ${args[0]}`,
` payload byte length: ${payloadByteLength}`,
` payload type: ${payloadType}`,
` platform: ${process.platform}`,
` shell: ${process.env.SHELL || 'n/a'}`,
` stdin TTY: ${process.stdin.isTTY === true ? 'true' : process.stdin.isTTY === false ? 'false' : 'undefined'}`,
` timestamp: ${new Date().toISOString()}`,
` CLAUDE_PLUGIN_ROOT: ${RESOLVED_PLUGIN_ROOT}`,
].join('\n');
console.error(diagnostic);
try {
const logsDir = join(dataDir, 'logs');
mkdirSync(logsDir, { recursive: true });
appendFileSync(join(logsDir, 'runner-errors.log'), diagnostic + '\n\n');
mkdirSync(dataDir, { recursive: true });
writeFileSync(join(dataDir, 'CAPTURE_BROKEN'), diagnostic + '\n');
} catch (writeErr) {
console.error(`[bun-runner] failed to persist diagnostic: ${writeErr && writeErr.message ? writeErr.message : writeErr}`);
}
}
try { child.stdin.end(); } catch {}
try { child.kill(); } catch {}
process.exit(0);
}
}
}
child.on('error', (err) => {
// EXCEPTION to CLAUDE.md exit-0-on-error: Bun-not-found is a user environment
// problem, not a hook execution failure. Surfacing exit 1 here forces Claude
// Code to display the stderr message rather than silently retrying. This runs
// before any hook handler, so the exit-0 tab-management rationale doesn't apply.
console.error(`Failed to start Bun: ${err.message}`);
process.exit(1);
});
child.on('close', (code, signal) => {
if ((signal || code > 128) && args.includes('start')) {
process.exit(0);
}
process.exit(code || 0);
});