forked from neovateai/neovate-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.tsx
More file actions
428 lines (373 loc) · 10.1 KB
/
run.tsx
File metadata and controls
428 lines (373 loc) · 10.1 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
import { spawn } from 'child_process';
import os from 'os';
import path from 'path';
import readline from 'readline';
import { z } from 'zod';
import type { Context } from '../context';
import { DirectTransport, MessageBus } from '../messageBus';
import { NodeBridge } from '../nodeBridge';
// ANSI color codes
const GREEN = '\x1b[32m';
const YELLOW = '\x1b[33m';
const DIM = '\x1b[2m';
const RESET = '\x1b[0m';
// Standalone shell commands that should be executed directly
const SHELL_COMMANDS = [
'ls',
'pwd',
'clear',
'whoami',
'date',
'cal',
'top',
'htop',
'history',
'which',
'man',
'touch',
'head',
'tail',
'grep',
'find',
'sort',
'wc',
'diff',
'tar',
'zip',
'unzip',
];
// Command prefixes that indicate shell commands
const SHELL_STARTERS = [
'cd ',
'ls ',
'echo ',
'cat ',
'mkdir ',
'rm ',
'cp ',
'mv ',
'git ',
'npm ',
'node ',
'npx ',
'python',
'pip ',
'brew ',
'curl ',
'wget ',
'chmod ',
'chown ',
'sudo ',
'vi ',
'vim ',
'nano ',
'code ',
'open ',
'export ',
'source ',
'docker ',
'kubectl ',
'aws ',
'gcloud ',
'./',
'/',
'~',
'$',
'>',
'>>',
'|',
'&&',
];
/**
* Detect if input is natural language or a shell command.
* Returns true if it's natural language (needs AI), false if it's a shell command.
*/
function isNaturalLanguage(text: string): boolean {
// Exact match for standalone commands
if (SHELL_COMMANDS.includes(text)) {
return false;
}
// Check if starts with known shell command patterns
if (SHELL_STARTERS.some((starter) => text.startsWith(starter))) {
return false;
}
return true;
}
const SHELL_COMMAND_SYSTEM_PROMPT = `
You are a tool that converts natural language instructions into shell commands.
Your task is to transform user's natural language requests into precise and effective shell commands.
Please follow these rules:
1. If the user directly provides a shell command, return that command as is
2. If the user describes a task in natural language, convert it to the most appropriate shell command
3. Avoid using potentially dangerous commands (such as rm -rf /)
4. Provide complete commands, avoiding placeholders
5. Reply with only one command, don't provide multiple options
6. When no suitable command can be found, return the recommended command directly
## Response Format
Respond with valid JSON only, no additional text or markdown formatting.
Example response:
{
"command": "ls -la",
"explanation": "List all files including hidden ones with detailed information"
}
`;
function askPrompt(rl: readline.Interface, cwd: string): Promise<string> {
return new Promise((resolve) => {
const dirname = path.basename(cwd);
const prompt = `${GREEN}${dirname}${RESET} > `;
rl.question(prompt, (answer) => {
resolve(answer?.trim() ?? '');
});
});
}
async function generateCommand(
messageBus: MessageBus,
prompt: string,
cwd: string,
model?: string,
): Promise<{ command: string; explanation: string } | null> {
process.stdout.write(`${DIM}Generating with ${model}...${RESET}\r`);
try {
const result = await messageBus.request('utils.quickQuery', {
cwd,
userPrompt: prompt,
systemPrompt: SHELL_COMMAND_SYSTEM_PROMPT,
model,
responseFormat: {
type: 'json',
schema: z.toJSONSchema(
z.object({
command: z.string(),
explanation: z.string(),
}),
),
},
});
// Clear the "Generating..." line
process.stdout.write('\x1b[2K\r');
if (!result.success || !result.data?.text) {
console.error('Failed to generate command');
return null;
}
const parsed = JSON.parse(result.data.text);
return {
command: parsed.command,
explanation: parsed.explanation,
};
} catch (error: any) {
process.stdout.write('\x1b[2K\r');
console.error(`Error: ${error.message || 'Failed to generate command'}`);
return null;
}
}
function confirmCommand(
rl: readline.Interface,
command: string,
): Promise<boolean> {
return new Promise((resolve) => {
const prompt = `${YELLOW}→ ${command}${RESET} ${DIM}[Enter/Esc]${RESET} `;
process.stdout.write(prompt);
const stdin = process.stdin;
const wasRaw = stdin.isRaw;
stdin.setRawMode(true);
stdin.resume();
const cleanup = () => {
stdin.removeListener('data', onData);
stdin.setRawMode(wasRaw);
};
const onData = (key: Buffer) => {
const char = key.toString();
// Enter pressed - execute command
if (char === '\r' || char === '\n') {
cleanup();
resolve(true);
return;
}
// Escape pressed - cancel
if (char === '\x1b') {
cleanup();
process.stdout.write(`\n${DIM}Cancelled${RESET}\n\n`);
resolve(false);
return;
}
};
stdin.on('data', onData);
});
}
function executeCommand(
command: string,
cwd: string,
): Promise<{ exitCode: number | null }> {
return new Promise((resolve) => {
const isWindows = os.platform() === 'win32';
const shell = isWindows ? 'cmd.exe' : process.env.SHELL || '/bin/bash';
const shellArgs = isWindows ? ['/c', command] : ['-c', command];
const child = spawn(shell, shellArgs, {
cwd,
stdio: 'inherit',
});
child.on('exit', (code) => {
resolve({ exitCode: code });
});
child.on('error', (err) => {
console.error(`Execution error: ${err.message}`);
resolve({ exitCode: 1 });
});
});
}
/**
* Try to change directory. Returns new cwd if successful, null otherwise.
*/
function tryChangeDirectory(
command: string,
currentCwd: string,
): string | null {
// Match "cd" or "cd <path>"
const cdMatch = command.match(/^cd(?:\s+(.*))?$/);
if (!cdMatch) return null;
let targetPath = cdMatch[1]?.trim();
// "cd" without args goes to home directory
if (!targetPath) {
targetPath = os.homedir();
} else {
// Expand ~ to home directory
if (targetPath.startsWith('~')) {
targetPath = path.join(os.homedir(), targetPath.slice(1));
}
// Resolve relative paths
if (!path.isAbsolute(targetPath)) {
targetPath = path.resolve(currentCwd, targetPath);
}
}
try {
process.chdir(targetPath);
return process.cwd();
} catch (err: any) {
console.error(`cd: ${err.message}`);
return null;
}
}
function printHelp(productName: string) {
console.log(
`
Usage:
${productName} run-2 [options]
Interactive shell command generator. Converts natural language to shell commands.
Options:
-h, --help Show help
-m, --model <model> Specify model to use
Controls:
dirname > prompt Type natural language, press Enter to generate command
→ command [Enter] Press Enter to execute, Ctrl+C to cancel
Ctrl+D Exit the program
`.trim(),
);
}
export async function runRun(context: Context) {
const { default: yargsParser } = await import('yargs-parser');
const argv = yargsParser(process.argv.slice(2), {
alias: {
model: 'm',
help: 'h',
quiet: 'q',
yes: 'y',
},
boolean: ['help', 'quiet', 'yes'],
string: ['model'],
});
if (argv.help) {
printHelp(context.productName.toLowerCase());
return;
}
const model = argv.model || context.config.smallModel || context.config.model;
const quiet = argv.quiet || argv.yes || context.config.quiet;
// Initialize NodeBridge for AI queries
const nodeBridge = new NodeBridge({
contextCreateOpts: {
productName: context.productName,
version: context.version,
argvConfig: {},
plugins: context.plugins,
},
});
const [clientTransport, nodeTransport] = DirectTransport.createPair();
const messageBus = new MessageBus();
messageBus.setTransport(clientTransport);
nodeBridge.messageBus.setTransport(nodeTransport);
// Track current working directory
let cwd = context.cwd;
// Initial prompt from CLI arguments if any
// Note: argv._[0] is 'run', so the prompt is from index 1 onwards
let firstPrompt: string | undefined = argv._.slice(1).join(' ') || undefined;
if (quiet) {
if (!firstPrompt) {
console.error('Error: Prompt is required in quiet mode');
process.exit(1);
}
// Single-shot execution in quiet mode
if (!isNaturalLanguage(firstPrompt)) {
await executeCommand(firstPrompt, cwd);
} else {
const result = await generateCommand(messageBus, firstPrompt, cwd, model);
if (result) {
await executeCommand(result.command, cwd);
}
}
process.exit(0);
}
// Create readline interface for interactive mode
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Handle Ctrl+D to exit
rl.on('close', () => {
console.log('\nBye!');
process.exit(0);
});
// Main loop
while (true) {
let userInput: string;
if (firstPrompt) {
userInput = firstPrompt;
firstPrompt = undefined; // Only use once
} else {
userInput = await askPrompt(rl, cwd);
}
if (userInput === '') {
// Empty input, just continue to next prompt
continue;
}
// Handle exit commands explicitly
if (userInput === 'exit' || userInput === 'quit') {
rl.close();
process.exit(0);
}
// Check if user directly typed a cd command
const newCwd = tryChangeDirectory(userInput, cwd);
if (newCwd !== null) {
cwd = newCwd;
continue;
}
// If it's a shell command, execute directly without AI
if (!isNaturalLanguage(userInput)) {
await executeCommand(userInput, cwd);
console.log();
continue;
}
// Natural language: generate command via AI
const result = await generateCommand(messageBus, userInput, cwd, model);
if (!result) continue;
const confirmed = await confirmCommand(rl, result.command);
if (!confirmed) continue;
process.stdout.write('\n'); // Add newline after confirmation input
// Check if generated command is cd
const cdNewCwd = tryChangeDirectory(result.command, cwd);
if (cdNewCwd !== null) {
cwd = cdNewCwd;
continue;
}
await executeCommand(result.command, cwd);
console.log(); // Add spacing after command output
}
}