-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathask-llm-cli.js
More file actions
executable file
·178 lines (145 loc) · 5.28 KB
/
Copy pathask-llm-cli.js
File metadata and controls
executable file
·178 lines (145 loc) · 5.28 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
#!/usr/bin/env node
// requires ASK_LLM_CLI_ANTHROPIC_API_KEY env var
const fs = require('fs');
const tty = require('tty');
const ANTHROPIC_API_KEY = process.env.ASK_LLM_CLI_ANTHROPIC_API_KEY;
// ANSI color codes
const colors = {
reset: '\x1b[0m',
bold: '\x1b[1m',
red: '\x1b[31m',
green: '\x1b[32m',
};
function clearLine() {
process.stderr.write('\r\x1b[K');
}
function startSpinner(message) {
const frames = [`${message}.`, `${message}..`, `${message}...`];
let i = 0;
process.stderr.write(frames[0]);
const timer = setInterval(() => {
i = (i + 1) % frames.length;
clearLine();
process.stderr.write(frames[i]);
}, 400);
return () => {
clearInterval(timer);
clearLine();
};
}
async function callClaudeAPI(userRequest) {
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
signal: AbortSignal.timeout(30000),
headers: {
'x-api-key': ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01',
'content-type': 'application/json',
},
body: JSON.stringify({
model: 'claude-sonnet-4-6',
max_tokens: 512,
messages: [{role: 'user', content: `You are a command line expert working on MacOS + zsh. The user wants: ${userRequest}`}],
tool_choice: {type: 'tool', name: 'shell_command'},
tools: [{
name: 'shell_command',
description: 'Provide the shell command and its safety classification',
input_schema: {
type: 'object',
properties: {
command: {type: 'string', description: 'The shell command to execute'},
safety: {type: 'string', enum: ['SAFE', 'UNSAFE'], description: 'SAFE if the command is read-only or benign, UNSAFE if it modifies/deletes data or is destructive'},
},
required: ['command', 'safety'],
},
}],
}),
});
if (!response.ok) {
const body = await response.text();
throw new Error(`API request failed (${response.status}): ${body}`);
}
return await response.json();
}
function parseResponse(response) {
const toolUse = response?.content?.find((block) => block.type === 'tool_use');
if (!toolUse) {
const errorMsg = response?.error?.message || 'No tool_use block in response';
throw new Error(`API Error: ${errorMsg}\nRaw response: ${JSON.stringify(response)}`);
}
const {command: cmd, safety} = toolUse.input;
if (!cmd) {
throw new Error(`Empty command in response\nRaw response: ${JSON.stringify(response)}`);
}
const isSafe = safety === 'SAFE';
return {cmd, isSafe};
}
function prompt(question) {
return new Promise((resolve, reject) => {
process.stderr.write(question);
// In command substitution (e.g. cmd=$(ask ...)), stdin is not a TTY.
// Open /dev/tty directly so we can still read a keypress interactively.
let inputStream;
let shouldDestroy = false;
if (process.stdin.isTTY) {
inputStream = process.stdin;
} else {
try {
const fd = fs.openSync('/dev/tty', 'r+');
inputStream = new tty.ReadStream(fd);
shouldDestroy = true;
} catch (e) {
reject(new Error('Cannot open /dev/tty for input'));
return;
}
}
inputStream.setRawMode(true);
inputStream.resume();
const onData = (buffer) => {
const key = buffer.toString();
inputStream.setRawMode(false);
inputStream.pause();
inputStream.removeListener('data', onData);
if (shouldDestroy) inputStream.destroy();
process.stderr.write(key + '\n');
resolve(key);
};
inputStream.once('data', onData);
});
}
async function main() {
const args = process.argv.slice(2);
if (args.length === 0) {
process.stderr.write('Usage: ask <what you want to do>\n');
process.exit(1);
}
if (!ANTHROPIC_API_KEY) {
process.stderr.write('❌ ASK_LLM_CLI_ANTHROPIC_API_KEY environment variable is required\n');
process.exit(1);
}
const userRequest = args.join(' ');
const stopSpinner = startSpinner('⏳ Asking LLM');
try {
const response = await callClaudeAPI(userRequest);
stopSpinner();
let {cmd, isSafe} = parseResponse(response);
if (isSafe) {
process.stdout.write(cmd);
} else {
process.stderr.write(`⚠️ ${colors.bold}${colors.red}WARNING: This command may be dangerous!${colors.reset}\n`);
process.stderr.write(`Command: ${colors.bold}${colors.green}${cmd}${colors.reset}\n`);
const reply = await prompt('Edit/Cancel [e/C] ');
if (reply.toLowerCase() === 'e') {
process.stdout.write(cmd);
} else {
process.stderr.write('❌ Cancelled\n');
process.exit(1);
}
}
} catch (error) {
stopSpinner();
process.stderr.write(`❌ ${error.message}\n`);
process.exit(1);
}
}
main();