-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathinstall-gemini-overlay.mjs
More file actions
471 lines (417 loc) · 15.4 KB
/
Copy pathinstall-gemini-overlay.mjs
File metadata and controls
471 lines (417 loc) · 15.4 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#!/usr/bin/env node
import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
const sourceCliDir = path.join(repoRoot, 'cli');
const defaultInstallRoot = path.join(os.homedir(), '.chiron');
const defaultBinDir = path.join(os.homedir(), '.local', 'bin');
function parseArgs(argv) {
const options = {
installRoot: defaultInstallRoot,
binDir: defaultBinDir,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--install-root') {
options.installRoot = path.resolve(argv[i + 1] ?? '');
i += 1;
continue;
}
if (arg === '--bin-dir') {
options.binDir = path.resolve(argv[i + 1] ?? '');
i += 1;
continue;
}
if (arg === '--help' || arg === '-h') {
options.help = true;
continue;
}
throw new Error(`Unknown argument: ${arg}`);
}
return options;
}
function printHelp() {
console.log(`Chiron Gemini Overlay Installer
Usage:
node cli/bin/install-gemini-overlay.mjs [--install-root ~/.chiron] [--bin-dir ~/.local/bin]
What it does:
1. Copies your current global Gemini CLI into a user-owned overlay directory
2. Copies Chiron enhancer runtime into the same install root
3. Patches the overlay Gemini CLI with double Ctrl+E in-place enhancement
4. Writes ~/.local/bin/gemini to launch the patched overlay everywhere
`);
}
function findGeminiRoot() {
const geminiBin = execFileSync('which', ['gemini'], {
encoding: 'utf8',
}).trim();
if (!geminiBin) {
throw new Error('`gemini` command not found in PATH');
}
const realEntry = execFileSync(
'node',
['-p', `require('fs').realpathSync(${JSON.stringify(geminiBin)})`],
{ encoding: 'utf8' },
).trim();
const parsedWrapperRoot = (() => {
try {
const wrapperSource = readFileSync(realEntry, 'utf8');
const match = wrapperSource.match(/exec node ["'](.+?\/gemini-cli)\/dist\/index\.js["'] "\$@"/);
return match?.[1] ?? null;
} catch {
return null;
}
})();
const candidates = [
path.join(os.homedir(), '.npm-global', 'lib', 'node_modules', '@google', 'gemini-cli'),
parsedWrapperRoot,
path.dirname(path.dirname(realEntry)),
].filter(Boolean);
const geminiRoot = candidates.find((candidate) => {
return (
existsSync(path.join(candidate, 'package.json')) &&
existsSync(path.join(candidate, 'dist', 'src', 'ui', 'components', 'InputPrompt.js'))
);
});
if (!geminiRoot) {
throw new Error(`Could not resolve a Gemini CLI package root from ${geminiBin}`);
}
return {
geminiBin,
realEntry,
geminiRoot,
};
}
async function copyCliRuntime(installRoot) {
const targetCliDir = path.join(installRoot, 'cli');
await fs.mkdir(installRoot, { recursive: true });
await fs.cp(path.join(sourceCliDir, 'bin'), path.join(targetCliDir, 'bin'), {
recursive: true,
force: true,
});
await fs.cp(path.join(sourceCliDir, 'src'), path.join(targetCliDir, 'src'), {
recursive: true,
force: true,
});
return targetCliDir;
}
function patchInputPrompt(source, enhancerPath) {
if (source.includes('CHIRON_DOUBLE_CTRL_E_TIMEOUT_MS')) {
throw new Error('Overlay Gemini CLI already appears to be patched with Chiron');
}
// --- Anchor 1: imports (stable across versions) ---
const importAnchor = "import { useUIActions } from '../contexts/UIActionsContext.js';";
const importBlock = `${importAnchor}
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
const CHIRON_DOUBLE_CTRL_E_TIMEOUT_MS = 500;
const CHIRON_ENHANCER_PATH = ${JSON.stringify(enhancerPath)};`;
// --- Anchor 2: refs after expandedSuggestionIndex (stable across versions) ---
const refsAnchor = " const [expandedSuggestionIndex, setExpandedSuggestionIndex] = useState(-1);";
const refsBlock = `${refsAnchor}
const ctrlEPressCount = useRef(0);
const ctrlETimerRef = useRef(null);
const ctrlEEnhancingRef = useRef(false);`;
// --- Anchor 3: callback injection point ---
// v0.32+ uses useRepeatedKeyPress hook; older versions use manual useCallback.
// We detect which pattern is present and pick the right anchor.
const callbackAnchorLegacy = ` const resetEscapeState = useCallback(() => {
if (escapeTimerRef.current) {
clearTimeout(escapeTimerRef.current);
escapeTimerRef.current = null;
}
escPressCount.current = 0;
setShowEscapePrompt(false);
}, []);`;
// In v0.32+, the cleanup effect only has pasteTimeoutRef (no escapeTimerRef).
const cleanupAnchorModern = ` useEffect(() => () => {
if (pasteTimeoutRef.current) {
clearTimeout(pasteTimeoutRef.current);
}
}, []);`;
const cleanupAnchorLegacy = ` useEffect(() => () => {
if (escapeTimerRef.current) {
clearTimeout(escapeTimerRef.current);
}
if (pasteTimeoutRef.current) {
clearTimeout(pasteTimeoutRef.current);
}
}, []);`;
const isModern = !source.includes(callbackAnchorLegacy);
let callbackAnchor;
let callbackBlock;
let cleanupAnchor;
let cleanupBlock;
let keyResetAnchor;
let keyResetBlock;
if (isModern) {
// v0.32+: inject Chiron callbacks after the cleanup useEffect
callbackAnchor = cleanupAnchorModern;
callbackBlock = `${cleanupAnchorModern}
const resetCtrlEState = useCallback(() => {
if (ctrlETimerRef.current) {
clearTimeout(ctrlETimerRef.current);
ctrlETimerRef.current = null;
}
ctrlEPressCount.current = 0;
}, []);
const runChironEnhancer = useCallback(async (rawInput) => {
const { stdout: enhancedText } = await execFileAsync('node', [CHIRON_ENHANCER_PATH, rawInput], {
cwd: config.getTargetDir(),
env: { ...process.env },
maxBuffer: 10 * 1024 * 1024,
});
return enhancedText.trim();
}, [config]);
const handleCtrlEEnhanceInPlace = useCallback(async () => {
if (ctrlEEnhancingRef.current) {
return;
}
const rawInput = buffer.text.trim();
if (!rawInput) {
return;
}
ctrlEEnhancingRef.current = true;
const savedInput = rawInput;
buffer.setText('🏹 Chiron enhancing... (' + savedInput + ')');
buffer.move('end');
try {
const enhancedText = await runChironEnhancer(savedInput);
if (!enhancedText) {
buffer.setText(savedInput);
buffer.move('end');
return;
}
buffer.setText(enhancedText);
buffer.move('end');
resetCompletionState();
resetReverseSearchCompletionState();
resetCommandSearchCompletionState();
setExpandedSuggestionIndex(-1);
}
catch (error) {
buffer.setText(savedInput);
buffer.move('end');
const message = error instanceof Error ? error.message : 'Chiron enhancement failed';
setQueueErrorMessage(\`Chiron enhance failed: \${message}\`);
}
finally {
ctrlEEnhancingRef.current = false;
}
}, [
buffer,
resetCompletionState,
resetReverseSearchCompletionState,
resetCommandSearchCompletionState,
runChironEnhancer,
setQueueErrorMessage,
]);`;
// In modern version, cleanup already has no escapeTimerRef, so we just add ctrlETimerRef
// But since we used the cleanupAnchor as callbackAnchor, we skip separate cleanup patching.
// Instead we handle ctrlETimerRef cleanup in a separate useEffect injected in the callbackBlock above.
// Actually we need to NOT patch cleanup separately since we already consumed that anchor.
cleanupAnchor = null;
cleanupBlock = null;
// v0.32+: key reset is simpler
keyResetAnchor = ` // Reset ESC count and hide prompt on any non-ESC key
if (key.name !== 'escape') {
resetEscapeState();
}`;
keyResetBlock = `${keyResetAnchor}
const isChironCtrlE = key.name === 'e' && key.ctrl === true && !key.meta && !key.shift;
if (!isChironCtrlE && ctrlEPressCount.current > 0) {
resetCtrlEState();
}`;
} else {
// Legacy (pre v0.32)
callbackAnchor = callbackAnchorLegacy;
callbackBlock = `${callbackAnchorLegacy}
const resetCtrlEState = useCallback(() => {
if (ctrlETimerRef.current) {
clearTimeout(ctrlETimerRef.current);
ctrlETimerRef.current = null;
}
ctrlEPressCount.current = 0;
}, []);
const runChironEnhancer = useCallback(async (rawInput) => {
const { stdout: enhancedText } = await execFileAsync('node', [CHIRON_ENHANCER_PATH, rawInput], {
cwd: config.getTargetDir(),
env: { ...process.env },
maxBuffer: 10 * 1024 * 1024,
});
return enhancedText.trim();
}, [config]);
const handleCtrlEEnhanceInPlace = useCallback(async () => {
if (ctrlEEnhancingRef.current) {
return;
}
const rawInput = buffer.text.trim();
if (!rawInput) {
return;
}
ctrlEEnhancingRef.current = true;
const savedInput = rawInput;
buffer.setText('🏹 Chiron enhancing... (' + savedInput + ')');
buffer.move('end');
try {
const enhancedText = await runChironEnhancer(savedInput);
if (!enhancedText) {
buffer.setText(savedInput);
buffer.move('end');
return;
}
buffer.setText(enhancedText);
buffer.move('end');
resetCompletionState();
resetReverseSearchCompletionState();
resetCommandSearchCompletionState();
setExpandedSuggestionIndex(-1);
}
catch (error) {
buffer.setText(savedInput);
buffer.move('end');
const message = error instanceof Error ? error.message : 'Chiron enhancement failed';
setQueueErrorMessage(\`Chiron enhance failed: \${message}\`);
}
finally {
ctrlEEnhancingRef.current = false;
}
}, [
buffer,
resetCompletionState,
resetReverseSearchCompletionState,
resetCommandSearchCompletionState,
runChironEnhancer,
setQueueErrorMessage,
]);`;
cleanupAnchor = cleanupAnchorLegacy;
cleanupBlock = ` useEffect(() => () => {
if (escapeTimerRef.current) {
clearTimeout(escapeTimerRef.current);
}
if (pasteTimeoutRef.current) {
clearTimeout(pasteTimeoutRef.current);
}
if (ctrlETimerRef.current) {
clearTimeout(ctrlETimerRef.current);
}
}, []);`;
keyResetAnchor = ` // Reset ESC count and hide prompt on any non-ESC key
if (key.name !== 'escape') {
if (escPressCount.current > 0 || showEscapePrompt) {
resetEscapeState();
}
}`;
keyResetBlock = `${keyResetAnchor}
const isChironCtrlE = key.name === 'e' && key.ctrl === true && !key.meta && !key.shift;
if (!isChironCtrlE && ctrlEPressCount.current > 0) {
resetCtrlEState();
}`;
}
// --- Anchor: END key handler (detect return style) ---
const endAnchorModern = ` if (keyMatchers[Command.END](key)) {
buffer.move('end');
return true;
}`;
const endAnchorLegacy = ` if (keyMatchers[Command.END](key)) {
buffer.move('end');
return;
}`;
const hasModernReturn = source.includes(endAnchorModern);
const endAnchor = hasModernReturn ? endAnchorModern : endAnchorLegacy;
const returnStatement = hasModernReturn ? 'return true;' : 'return;';
const endBlock = ` if (isChironCtrlE) {
if (ctrlEPressCount.current === 0) {
ctrlEPressCount.current = 1;
buffer.move('end');
if (ctrlETimerRef.current) {
clearTimeout(ctrlETimerRef.current);
}
ctrlETimerRef.current = setTimeout(() => {
resetCtrlEState();
}, CHIRON_DOUBLE_CTRL_E_TIMEOUT_MS);
}
else {
resetCtrlEState();
void handleCtrlEEnhanceInPlace();
}
${returnStatement}
}
${endAnchor}`;
// Build patch list (skip null entries for modern path where cleanup is merged)
const patches = [
[importAnchor, importBlock],
[refsAnchor, refsBlock],
[callbackAnchor, callbackBlock],
cleanupAnchor ? [cleanupAnchor, cleanupBlock] : null,
[keyResetAnchor, keyResetBlock],
[endAnchor, endBlock],
].filter(Boolean);
let patched = source;
for (const [anchor, replacement] of patches) {
if (!patched.includes(anchor)) {
throw new Error(`Unable to patch overlay Gemini CLI: missing anchor\n${anchor}`);
}
patched = patched.replace(anchor, replacement);
}
return patched;
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
printHelp();
return;
}
const installRoot = options.installRoot;
const binDir = options.binDir;
const overlayGeminiRoot = path.join(installRoot, 'gemini-cli');
const { geminiRoot } = findGeminiRoot();
await fs.mkdir(installRoot, { recursive: true });
await fs.rm(overlayGeminiRoot, { recursive: true, force: true });
await fs.cp(geminiRoot, overlayGeminiRoot, { recursive: true, force: true });
const overlayCliDir = await copyCliRuntime(installRoot);
const enhancerPath = path.join(overlayCliDir, 'bin', 'chiron-enhance.mjs');
const inputPromptPath = path.join(
overlayGeminiRoot,
'dist',
'src',
'ui',
'components',
'InputPrompt.js',
);
const originalSource = await fs.readFile(inputPromptPath, 'utf8');
const patchedSource = patchInputPrompt(originalSource, enhancerPath);
await fs.writeFile(inputPromptPath, patchedSource, 'utf8');
execFileSync('node', ['--check', inputPromptPath], { stdio: 'inherit' });
await fs.mkdir(binDir, { recursive: true });
const wrapperPath = path.join(binDir, 'gemini');
const wrapper = `#!/bin/sh
exec node ${JSON.stringify(path.join(overlayGeminiRoot, 'dist', 'index.js'))} "$@"
`;
await fs.writeFile(wrapperPath, wrapper, { mode: 0o755 });
await fs.chmod(wrapperPath, 0o755);
const version = JSON.parse(
await fs.readFile(path.join(overlayGeminiRoot, 'package.json'), 'utf8'),
).version;
console.log('Installed Chiron Gemini overlay.');
console.log(`Overlay root: ${overlayGeminiRoot}`);
console.log(`Chiron runtime: ${overlayCliDir}`);
console.log(`Wrapper command: ${wrapperPath}`);
console.log(`Gemini CLI version: ${version}`);
console.log('');
console.log('Usage in any directory:');
console.log('1. Start `gemini`.');
console.log('2. Type a rough request.');
console.log('3. Press Ctrl+E once to move to end of line.');
console.log('4. Press Ctrl+E again within 500ms to replace the input with an enhanced prompt.');
}
main().catch((error) => {
console.error(`Failed to install Chiron Gemini overlay: ${error.message}`);
process.exit(1);
});