@benchcode/cli 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -2
- package/bin/benchcode.js +2599 -0
- package/package.json +15 -4
package/bin/benchcode.js
ADDED
|
@@ -0,0 +1,2599 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* BenchCode - terminal coding agent for the Ahar AI API.
|
|
3
|
+
* Zero dependencies. Needs Node.js 18+. Linux, macOS, Windows, WSL, Termux, FreeBSD.
|
|
4
|
+
* (Built from src/*.js by build.js - edit the parts, not this file.)
|
|
5
|
+
*/
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const os = require('os');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const cp = require('child_process');
|
|
12
|
+
const readline = require('readline');
|
|
13
|
+
const crypto = require('crypto');
|
|
14
|
+
|
|
15
|
+
const VERSION = '1.1.0';
|
|
16
|
+
const DEFAULT_BASE = 'https://api.aharai.qzz.io';
|
|
17
|
+
const DEFAULT_MODEL = 'ahar-pro';
|
|
18
|
+
const IS_WIN = process.platform === 'win32';
|
|
19
|
+
const HOME_DIR = process.env.BENCHCODE_HOME || path.join(os.homedir(), '.benchcode');
|
|
20
|
+
const CONFIG_FILE = path.join(HOME_DIR, 'config.json');
|
|
21
|
+
const STATE_FILE = path.join(HOME_DIR, 'state.json');
|
|
22
|
+
const SESSIONS_DIR = path.join(HOME_DIR, 'sessions');
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------- colors
|
|
25
|
+
const NO_COLOR = !!process.env.NO_COLOR || process.argv.includes('--no-color') || process.env.TERM === 'dumb';
|
|
26
|
+
const TRUECOLOR = !NO_COLOR && (/^(truecolor|24bit)$/i.test(process.env.COLORTERM || '') || !!process.env.WT_SESSION ||
|
|
27
|
+
/iterm|vscode|wezterm|hyper|ghostty/i.test(process.env.TERM_PROGRAM || '') || /kitty|alacritty|direct/i.test(process.env.TERM || '') || IS_WIN);
|
|
28
|
+
|
|
29
|
+
const hex2rgb = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
|
|
30
|
+
function rgbTo256(r, g, b) {
|
|
31
|
+
if (Math.abs(r - g) < 10 && Math.abs(g - b) < 10) {
|
|
32
|
+
const v = (r + g + b) / 3;
|
|
33
|
+
if (v < 4) return 16; if (v > 246) return 231;
|
|
34
|
+
return 232 + Math.min(23, Math.round((v - 8) / 247 * 24));
|
|
35
|
+
}
|
|
36
|
+
const q = (x) => Math.round(x / 255 * 5);
|
|
37
|
+
return 16 + 36 * q(r) + 6 * q(g) + q(b);
|
|
38
|
+
}
|
|
39
|
+
const _seqCache = new Map();
|
|
40
|
+
function colorSeq(kind, hex) { // kind: 38 fg / 48 bg
|
|
41
|
+
const key = kind + hex;
|
|
42
|
+
let s = _seqCache.get(key);
|
|
43
|
+
if (s === undefined) {
|
|
44
|
+
if (NO_COLOR) s = '';
|
|
45
|
+
else {
|
|
46
|
+
const [r, g, b] = hex2rgb(hex);
|
|
47
|
+
s = TRUECOLOR ? `\x1b[${kind};2;${r};${g};${b}m` : `\x1b[${kind};5;${rgbTo256(r, g, b)}m`;
|
|
48
|
+
}
|
|
49
|
+
_seqCache.set(key, s);
|
|
50
|
+
}
|
|
51
|
+
return s;
|
|
52
|
+
}
|
|
53
|
+
const RESET = NO_COLOR ? '' : '\x1b[0m';
|
|
54
|
+
const FG = (hex) => colorSeq(38, hex);
|
|
55
|
+
const BG = (hex) => colorSeq(48, hex);
|
|
56
|
+
const T = { text: '#eeeeee', mut: '#808080', dim: '#5c5c5c', blue: '#5c9cf5', orange: '#f5a742', peach: '#fab283', green: '#7fd88f', red: '#e06c75',
|
|
57
|
+
yellow: '#e5c07b', purple: '#c792ea', cyan: '#56b6c2', panel: '#141414', panel2: '#1c1c1c', panel3: '#262626', code: '#161616', diffAdd: '#15301a', diffDel: '#3a1a1e', black: '#0a0a0a' };
|
|
58
|
+
// style(text, {fg,bg,b,i,u,d})
|
|
59
|
+
function sty(text, o) {
|
|
60
|
+
if (NO_COLOR) return String(text);
|
|
61
|
+
let pre = '';
|
|
62
|
+
if (o.b) pre += '\x1b[1m'; if (o.d) pre += '\x1b[2m'; if (o.i) pre += '\x1b[3m'; if (o.u) pre += '\x1b[4m'; if (o.s) pre += '\x1b[9m';
|
|
63
|
+
if (o.fg) pre += FG(o.fg); if (o.bg) pre += BG(o.bg);
|
|
64
|
+
return pre ? pre + text + RESET : String(text);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// plain-mode (stderr) helpers
|
|
68
|
+
const useColor = !!process.stderr.isTTY && !NO_COLOR;
|
|
69
|
+
const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
70
|
+
const bold = paint(1), dim = paint(2), red = paint(31), green = paint(32), yellow = paint(33), blue = paint(34), magenta = paint(35), cyan = paint(36), gray = paint(90);
|
|
71
|
+
const log = (...a) => process.stderr.write(a.join(' ') + '\n');
|
|
72
|
+
const out = (s) => process.stdout.write(s);
|
|
73
|
+
const sleep = (ms, signal) => new Promise((res) => {
|
|
74
|
+
const t = setTimeout(res, ms);
|
|
75
|
+
if (signal) signal.addEventListener('abort', () => { clearTimeout(t); res(); }, { once: true });
|
|
76
|
+
});
|
|
77
|
+
const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
|
|
78
|
+
const expandHome = (p) => (p === '~' ? os.homedir() : p.startsWith('~/') || p.startsWith('~\\') ? path.join(os.homedir(), p.slice(2)) : p);
|
|
79
|
+
const nf = (n) => String(Math.round(Number(n) || 0)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
80
|
+
const tidyPath = (p) => { const h = os.homedir(); return p === h ? '~' : p.startsWith(h + path.sep) ? '~' + p.slice(h.length) : p; };
|
|
81
|
+
|
|
82
|
+
// ---------------------------------------------------------------- config
|
|
83
|
+
function readJson(file, fallback) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (_) { return fallback; } }
|
|
84
|
+
function writeJson(file, obj, secret) {
|
|
85
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
86
|
+
fs.writeFileSync(file, JSON.stringify(obj, null, 2));
|
|
87
|
+
if (secret) { try { fs.chmodSync(file, 0o600); } catch (_) {} }
|
|
88
|
+
}
|
|
89
|
+
function loadConfig() {
|
|
90
|
+
const c = readJson(CONFIG_FILE, {});
|
|
91
|
+
return {
|
|
92
|
+
apiKey: process.env.BENCHCODE_API_KEY || process.env.AHAR_API_KEY || c.apiKey || '',
|
|
93
|
+
baseUrl: String(process.env.BENCHCODE_BASE_URL || c.baseUrl || DEFAULT_BASE).replace(/\/+$/, ''),
|
|
94
|
+
model: process.env.BENCHCODE_MODEL || c.model || DEFAULT_MODEL,
|
|
95
|
+
agent: c.agent || 'build',
|
|
96
|
+
showThinking: !!c.showThinking,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function saveConfigPatch(patch) { const c = readJson(CONFIG_FILE, {}); Object.assign(c, patch); writeJson(CONFIG_FILE, c, true); }
|
|
100
|
+
|
|
101
|
+
// ---------------------------------------------------------------- text width + ANSI helpers
|
|
102
|
+
function charWidth(cp) {
|
|
103
|
+
if (cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0;
|
|
104
|
+
if (cp < 0x300) return 1;
|
|
105
|
+
if ((cp >= 0x300 && cp <= 0x36f) || (cp >= 0x200b && cp <= 0x200f) || (cp >= 0xfe00 && cp <= 0xfe0f) || (cp >= 0x20d0 && cp <= 0x20ff) || cp === 0x2060 || cp === 0xfeff) return 0;
|
|
106
|
+
if ((cp >= 0x1100 && cp <= 0x115f) || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) || (cp >= 0xf900 && cp <= 0xfaff) ||
|
|
107
|
+
(cp >= 0xfe30 && cp <= 0xfe6f) || (cp >= 0xff00 && cp <= 0xff60) || (cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1f64f) ||
|
|
108
|
+
(cp >= 0x1f900 && cp <= 0x1f9ff) || (cp >= 0x1f680 && cp <= 0x1f6ff) || (cp >= 0x20000 && cp <= 0x3fffd)) return 2;
|
|
109
|
+
return 1;
|
|
110
|
+
}
|
|
111
|
+
const ANSI_RE = /\x1b\[[0-9;:?<>=]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/y;
|
|
112
|
+
function ansiAt(s, i) { ANSI_RE.lastIndex = i; const m = ANSI_RE.exec(s); return m ? m[0] : null; }
|
|
113
|
+
function strWidth(s) {
|
|
114
|
+
let w = 0;
|
|
115
|
+
for (let i = 0; i < s.length;) {
|
|
116
|
+
if (s.charCodeAt(i) === 27) { const a = ansiAt(s, i); if (a) { i += a.length; continue; } }
|
|
117
|
+
const cp = s.codePointAt(i); i += cp > 0xffff ? 2 : 1; w += charWidth(cp);
|
|
118
|
+
}
|
|
119
|
+
return w;
|
|
120
|
+
}
|
|
121
|
+
const stripAnsi = (s) => s.replace(/\x1b\[[0-9;:?<>=]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '');
|
|
122
|
+
const isSgr = (a) => a.endsWith('m') && a.startsWith('\x1b[');
|
|
123
|
+
// text between visible columns [from, to), keeping the colors that were active
|
|
124
|
+
function sliceCols(s, from, to) {
|
|
125
|
+
let col = 0, active = '', res = '', started = false;
|
|
126
|
+
for (let i = 0; i < s.length;) {
|
|
127
|
+
if (s.charCodeAt(i) === 27) {
|
|
128
|
+
const a = ansiAt(s, i);
|
|
129
|
+
if (a) { i += a.length; if (isSgr(a)) { if (a === '\x1b[0m' || a === '\x1b[m') active = ''; else active += a; if (started) res += a; } continue; }
|
|
130
|
+
}
|
|
131
|
+
const cp = s.codePointAt(i); const ch = String.fromCodePoint(cp); i += ch.length;
|
|
132
|
+
const w = charWidth(cp);
|
|
133
|
+
if (col >= to) break;
|
|
134
|
+
if (col >= from && col + w <= to) { if (!started) { started = true; res += active; } res += ch; }
|
|
135
|
+
else if (w === 2 && col < from && col + w > from) { if (!started) { started = true; res += active; } res += ' '; }
|
|
136
|
+
col += w;
|
|
137
|
+
}
|
|
138
|
+
return started && active ? res + '\x1b[0m' : res;
|
|
139
|
+
}
|
|
140
|
+
const padTo = (s, w) => { const sw = strWidth(s); return sw >= w ? s : s + ' '.repeat(w - sw); };
|
|
141
|
+
const fit = (s, w) => { const sw = strWidth(s); return sw > w ? padTo(sliceCols(s, 0, w), w) : s + ' '.repeat(w - sw); };
|
|
142
|
+
// make a background survive inner resets
|
|
143
|
+
const keepBg = (s, bgHex) => (NO_COLOR ? s : BG(bgHex) + s.split('\x1b[0m').join('\x1b[0m' + BG(bgHex)) + RESET);
|
|
144
|
+
// greedy word wrap that understands ANSI codes and wide characters
|
|
145
|
+
function wrapAnsi(s, width) {
|
|
146
|
+
if (width < 1) width = 1;
|
|
147
|
+
const lines = [];
|
|
148
|
+
let cur = '', curW = 0, active = '', brk = -1, brkActive = '', seen = false;
|
|
149
|
+
const push = () => { lines.push(cur + (active && !NO_COLOR ? '\x1b[0m' : '')); };
|
|
150
|
+
for (let i = 0; i < s.length;) {
|
|
151
|
+
if (s.charCodeAt(i) === 27) {
|
|
152
|
+
const a = ansiAt(s, i);
|
|
153
|
+
if (a) { i += a.length; if (isSgr(a)) { if (a === '\x1b[0m' || a === '\x1b[m') active = ''; else active += a; } cur += a; continue; }
|
|
154
|
+
}
|
|
155
|
+
const cpv = s.codePointAt(i); const ch = String.fromCodePoint(cpv); i += ch.length;
|
|
156
|
+
if (ch === '\n') { push(); cur = active; curW = 0; brk = -1; seen = false; continue; }
|
|
157
|
+
const w = charWidth(cpv);
|
|
158
|
+
if (curW + w > width) {
|
|
159
|
+
if (brk >= 0) {
|
|
160
|
+
const head = cur.slice(0, brk - 1), tail = cur.slice(brk);
|
|
161
|
+
lines.push(head + (brkActive && !NO_COLOR ? '\x1b[0m' : ''));
|
|
162
|
+
cur = brkActive + tail; curW = strWidth(tail);
|
|
163
|
+
} else { push(); cur = active; curW = 0; }
|
|
164
|
+
brk = -1; seen = false;
|
|
165
|
+
}
|
|
166
|
+
cur += ch; curW += w;
|
|
167
|
+
if (ch === ' ') { if (seen) { brk = cur.length; brkActive = active; } } else seen = true;
|
|
168
|
+
}
|
|
169
|
+
if (cur !== '' || lines.length === 0) push();
|
|
170
|
+
return lines;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------- syntax highlighting (small, regex based)
|
|
174
|
+
const KW = {
|
|
175
|
+
js: 'const let var function return if else for while do switch case break continue new class extends import export from default async await try catch finally throw typeof instanceof in of this super static get set yield delete void null undefined true false interface type enum implements readonly public private protected as',
|
|
176
|
+
py: 'def class return if elif else for while in not and or is None True False import from as with try except finally raise pass break continue lambda yield global nonlocal async await self del assert print',
|
|
177
|
+
go: 'func package import return if else for range switch case default break continue go defer chan select struct interface map type var const nil true false fallthrough',
|
|
178
|
+
rs: 'fn let mut pub struct enum impl trait use mod match if else for while loop return break continue as in ref self Self const static true false move async await dyn where unsafe crate super',
|
|
179
|
+
c: 'int char float double void long short unsigned signed static const struct union enum typedef sizeof return if else for while do switch case break continue goto extern volatile inline auto register class public private protected namespace using template typename new delete this virtual override final nullptr true false null bool string var abstract interface implements throws throw try catch finally package import',
|
|
180
|
+
sh: 'if then else elif fi for while until do done case esac function in return export local echo cd exit set unset source alias read test',
|
|
181
|
+
sql: 'select from where insert into values update set delete create table drop alter add join left right inner outer on group by order having limit offset as and or not null primary key foreign references index unique distinct union all case when then else end',
|
|
182
|
+
css: '', json: 'true false null', html: '',
|
|
183
|
+
};
|
|
184
|
+
const LANG_MAP = { js: 'js', javascript: 'js', jsx: 'js', ts: 'js', tsx: 'js', typescript: 'js', mjs: 'js', cjs: 'js', node: 'js', py: 'py', python: 'py', go: 'go', golang: 'go', rs: 'rs', rust: 'rs',
|
|
185
|
+
c: 'c', h: 'c', cpp: 'c', 'c++': 'c', cc: 'c', java: 'c', cs: 'c', csharp: 'c', kt: 'c', kotlin: 'c', swift: 'c', php: 'c', dart: 'c', scala: 'c',
|
|
186
|
+
sh: 'sh', bash: 'sh', zsh: 'sh', shell: 'sh', ps1: 'sh', powershell: 'sh', console: 'sh', yaml: 'sh', yml: 'sh', toml: 'sh', dockerfile: 'sh', rb: 'sh', ruby: 'sh',
|
|
187
|
+
sql: 'sql', css: 'css', scss: 'css', json: 'json', jsonc: 'json', html: 'html', xml: 'html', svg: 'html', vue: 'html' };
|
|
188
|
+
const _kwSets = {};
|
|
189
|
+
const kwSet = (l) => _kwSets[l] || (_kwSets[l] = new Set((KW[l] || '').split(/\s+/).filter(Boolean)));
|
|
190
|
+
|
|
191
|
+
function highlightLine(line, langKey) {
|
|
192
|
+
if (NO_COLOR || !langKey) return line;
|
|
193
|
+
const lineComment = langKey === 'py' || langKey === 'sh' ? /^\s*#/ : langKey === 'sql' ? /^\s*--/ : /^\s*(\/\/|\/\*|\*)/;
|
|
194
|
+
if (lineComment.test(line) && langKey !== 'html' && langKey !== 'json') return sty(line, { fg: '#6c7a89', i: true });
|
|
195
|
+
const kws = kwSet(langKey);
|
|
196
|
+
const re = langKey === 'html'
|
|
197
|
+
? /(<!--.*?-->)|(<\/?[A-Za-z][\w:-]*)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')|([\w:-]+)(?==)|(\/?>)/g
|
|
198
|
+
: /(\/\/.*$|\/\*.*?\*\/|(?<![\w$])#.*$|--\s.*$)|("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`(?:[^`\\]|\\.)*`?)|(\b0x[0-9a-fA-F]+\b|\b\d+(?:\.\d+)?\b)|([A-Za-z_$][\w$]*)(\s*\()?/g;
|
|
199
|
+
let res = '', last = 0, m;
|
|
200
|
+
while ((m = re.exec(line))) {
|
|
201
|
+
res += line.slice(last, m.index); last = m.index + m[0].length;
|
|
202
|
+
if (langKey === 'html') {
|
|
203
|
+
if (m[1]) res += sty(m[0], { fg: '#6c7a89', i: true });
|
|
204
|
+
else if (m[2]) res += sty(m[0], { fg: T.red });
|
|
205
|
+
else if (m[3]) res += sty(m[0], { fg: T.green });
|
|
206
|
+
else if (m[4]) res += sty(m[0], { fg: T.yellow });
|
|
207
|
+
else res += sty(m[0], { fg: T.mut });
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (m[1]) { if (langKey === 'json') res += m[0]; else res += sty(m[0], { fg: '#6c7a89', i: true }); }
|
|
211
|
+
else if (m[2]) {
|
|
212
|
+
const isKey = langKey === 'json' && /^\s*:/.test(line.slice(last));
|
|
213
|
+
res += sty(m[0], { fg: isKey ? T.blue : T.green });
|
|
214
|
+
}
|
|
215
|
+
else if (m[3]) res += sty(m[0], { fg: T.orange });
|
|
216
|
+
else if (m[4]) {
|
|
217
|
+
const w = m[4]; const call = !!m[5];
|
|
218
|
+
const lw = langKey === 'sql' ? w.toLowerCase() : w;
|
|
219
|
+
if (kws.has(lw)) res += sty(w, { fg: T.purple }) + (call ? m[5] : '');
|
|
220
|
+
else if (call) res += sty(w, { fg: T.blue }) + m[5];
|
|
221
|
+
else if (/^[A-Z][A-Za-z0-9]+$/.test(w) && langKey !== 'sh') res += sty(w, { fg: T.yellow });
|
|
222
|
+
else res += w;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return res + line.slice(last);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ---------------------------------------------------------------- markdown -> ANSI lines
|
|
229
|
+
function inlineMd(s) {
|
|
230
|
+
if (NO_COLOR) return s.replace(/\*\*(.+?)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1');
|
|
231
|
+
const codes = [];
|
|
232
|
+
s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(sty(' ' + c + ' ', { fg: T.peach, bg: T.panel3 })); return '\u0000' + (codes.length - 1) + '\u0000'; });
|
|
233
|
+
s = s.replace(/!?\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, u) => sty(t, { fg: T.blue, u: true }) + sty(' (' + u + ')', { fg: T.dim }));
|
|
234
|
+
s = s.replace(/\*\*\*(.+?)\*\*\*/g, (_, t) => sty(t, { b: true, i: true }));
|
|
235
|
+
s = s.replace(/\*\*(.+?)\*\*/g, (_, t) => sty(t, { b: true, fg: '#ffffff' }));
|
|
236
|
+
s = s.replace(/__(.+?)__/g, (_, t) => sty(t, { b: true, fg: '#ffffff' }));
|
|
237
|
+
s = s.replace(/(^|[^\w*])\*(?!\s)([^*\n]+?)\*(?![\w*])/g, (_, p, t) => p + sty(t, { i: true }));
|
|
238
|
+
s = s.replace(/(^|[^\w])_(?!\s)([^_\n]+?)_(?![\w])/g, (_, p, t) => p + sty(t, { i: true }));
|
|
239
|
+
s = s.replace(/~~(.+?)~~/g, (_, t) => sty(t, { s: true, d: true }));
|
|
240
|
+
s = s.replace(/https?:\/\/[^\s)<>\u001b]+/g, (u) => sty(u, { fg: T.blue, u: true }));
|
|
241
|
+
return s.replace(/\u0000(\d+)\u0000/g, (_, i) => codes[+i]);
|
|
242
|
+
}
|
|
243
|
+
const splitRow = (l) => l.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim());
|
|
244
|
+
|
|
245
|
+
function renderTable(rows, width) {
|
|
246
|
+
const head = splitRow(rows[0]);
|
|
247
|
+
const body = rows.slice(2).map(splitRow);
|
|
248
|
+
const n = head.length;
|
|
249
|
+
const all = [head].concat(body.map((r) => { const x = r.slice(0, n); while (x.length < n) x.push(''); return x; }));
|
|
250
|
+
const cells = all.map((r) => r.map(inlineMd));
|
|
251
|
+
let cw = new Array(n).fill(3);
|
|
252
|
+
cells.forEach((r) => r.forEach((c, i) => { cw[i] = Math.max(cw[i], strWidth(c)); }));
|
|
253
|
+
const avail = width - (n + 1) - n * 2;
|
|
254
|
+
let sum = cw.reduce((a, b) => a + b, 0);
|
|
255
|
+
if (sum > avail && avail > n * 4) { cw = cw.map((w) => Math.max(4, Math.floor(w * avail / sum))); }
|
|
256
|
+
const line = (l, m, r) => sty(l + cw.map((w) => '─'.repeat(w + 2)).join(m) + r, { fg: T.dim });
|
|
257
|
+
const out_ = [line('┌', '┬', '┐')];
|
|
258
|
+
cells.forEach((r, ri) => {
|
|
259
|
+
const wrapped = r.map((c, i) => wrapAnsi(c, cw[i]));
|
|
260
|
+
const h = Math.max(...wrapped.map((w) => w.length));
|
|
261
|
+
for (let k = 0; k < h; k++) {
|
|
262
|
+
out_.push(sty('│', { fg: T.dim }) + wrapped.map((w, i) => ' ' + padTo(ri === 0 ? sty(w[k] || '', { b: true, fg: T.text }) : w[k] || '', cw[i]) + ' ').join(sty('│', { fg: T.dim })) + sty('│', { fg: T.dim }));
|
|
263
|
+
}
|
|
264
|
+
if (ri === 0) out_.push(line('├', '┼', '┤'));
|
|
265
|
+
});
|
|
266
|
+
out_.push(line('└', '┴', '┘'));
|
|
267
|
+
return out_;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function renderMarkdown(text, width) {
|
|
271
|
+
const W = Math.max(20, width);
|
|
272
|
+
const src = String(text).replace(/\r\n/g, '\n').split('\n');
|
|
273
|
+
const out_ = [];
|
|
274
|
+
for (let i = 0; i < src.length; i++) {
|
|
275
|
+
let line = src[i];
|
|
276
|
+
const fence = line.match(/^\s*(```|~~~)\s*([\w+#.-]*)\s*$/);
|
|
277
|
+
if (fence) {
|
|
278
|
+
const lang = (fence[2] || '').toLowerCase();
|
|
279
|
+
const body = [];
|
|
280
|
+
i++;
|
|
281
|
+
while (i < src.length && !/^\s*(```|~~~)\s*$/.test(src[i])) body.push(src[i++]);
|
|
282
|
+
const key = LANG_MAP[lang] || (lang ? '' : '');
|
|
283
|
+
const inner = W - 2;
|
|
284
|
+
const label = lang ? sty(lang, { fg: T.dim }) : '';
|
|
285
|
+
out_.push(keepBg(fit(' ' + label, W), T.code));
|
|
286
|
+
for (const b of body) {
|
|
287
|
+
const hl = highlightLine(b.replace(/\t/g, ' '), key);
|
|
288
|
+
const parts = strWidth(hl) > inner ? wrapAnsi(hl, inner) : [hl];
|
|
289
|
+
for (const p of parts) out_.push(keepBg(fit(' ' + p, W), T.code));
|
|
290
|
+
}
|
|
291
|
+
out_.push(keepBg(' '.repeat(W), T.code));
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < src.length && /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(src[i + 1])) {
|
|
295
|
+
const rows = [line, src[i + 1]];
|
|
296
|
+
i += 2;
|
|
297
|
+
while (i < src.length && /^\s*\|.*\|\s*$/.test(src[i])) rows.push(src[i++]);
|
|
298
|
+
i--;
|
|
299
|
+
out_.push(...renderTable(rows, W));
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
const h = line.match(/^(#{1,6})\s+(.*)$/);
|
|
303
|
+
if (h) {
|
|
304
|
+
const lvl = h[1].length;
|
|
305
|
+
const body = inlineMd(h[2]);
|
|
306
|
+
if (out_.length && out_[out_.length - 1] !== '') out_.push('');
|
|
307
|
+
const styled = lvl === 1 ? sty(h[2], { b: true, u: true, fg: T.peach }) : lvl === 2 ? sty(h[2], { b: true, fg: T.peach }) : sty(body, { b: true, fg: T.blue });
|
|
308
|
+
out_.push(...wrapAnsi(styled, W));
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { out_.push(sty('─'.repeat(Math.min(W, 60)), { fg: T.dim })); continue; }
|
|
312
|
+
const bq = line.match(/^\s*>\s?(.*)$/);
|
|
313
|
+
if (bq) { for (const w of wrapAnsi(inlineMd(bq[1]), W - 2)) out_.push(sty('▎ ', { fg: T.dim }) + sty(w, { i: true, fg: T.mut })); continue; }
|
|
314
|
+
const li = line.match(/^(\s*)([-*+•]|\d+[.)])\s+(.*)$/);
|
|
315
|
+
if (li) {
|
|
316
|
+
const depth = Math.min(4, Math.floor(li[1].replace(/\t/g, ' ').length / 2));
|
|
317
|
+
const ordered = /\d/.test(li[2]);
|
|
318
|
+
const bullet = ordered ? sty(li[2], { fg: T.blue }) : sty(['•', '◦', '▪', '▫', '·'][depth], { fg: T.blue });
|
|
319
|
+
const ind = ' '.repeat(depth);
|
|
320
|
+
const bw = strWidth(stripAnsi(bullet)) + 1;
|
|
321
|
+
const task = li[3].match(/^\[( |x|X)\]\s+(.*)$/);
|
|
322
|
+
let body = task ? (task[1] === ' ' ? sty('☐ ', { fg: T.mut }) : sty('☑ ', { fg: T.green })) + task[2] : li[3];
|
|
323
|
+
const wrapped = wrapAnsi(inlineMd(body), Math.max(10, W - ind.length - bw));
|
|
324
|
+
wrapped.forEach((w, k) => out_.push(ind + (k === 0 ? (task ? '' : bullet + ' ') : ' '.repeat(task ? 2 : bw)) + w));
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (line.trim() === '') { if (out_.length && out_[out_.length - 1] !== '') out_.push(''); continue; }
|
|
328
|
+
const lead = line.match(/^(\s*)/)[1].length;
|
|
329
|
+
const wrapped = wrapAnsi(' '.repeat(Math.min(lead, 8)) + inlineMd(line.trim()), W);
|
|
330
|
+
out_.push(...wrapped);
|
|
331
|
+
}
|
|
332
|
+
while (out_.length && out_[out_.length - 1] === '') out_.pop();
|
|
333
|
+
return out_;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ---------------------------------------------------------------- fs helpers
|
|
337
|
+
const IGNORE_DIRS = new Set(['.git', 'node_modules', '.hg', '.svn', '__pycache__', '.venv', 'venv', '.next', 'target', '.idea', '.cache', '.gradle', 'coverage', '.pytest_cache', '.mypy_cache', '.turbo', '.parcel-cache']);
|
|
338
|
+
function* walk(root, maxFiles = 30000) {
|
|
339
|
+
const stack = [root];
|
|
340
|
+
let n = 0;
|
|
341
|
+
while (stack.length) {
|
|
342
|
+
const dir = stack.pop();
|
|
343
|
+
let ents;
|
|
344
|
+
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { continue; }
|
|
345
|
+
ents.sort((a, b) => a.name.localeCompare(b.name));
|
|
346
|
+
for (const e of ents) {
|
|
347
|
+
if (e.isSymbolicLink()) continue;
|
|
348
|
+
const abs = path.join(dir, e.name);
|
|
349
|
+
if (e.isDirectory()) { if (!IGNORE_DIRS.has(e.name)) stack.push(abs); }
|
|
350
|
+
else if (e.isFile()) { if (++n > maxFiles) return; yield abs; }
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
355
|
+
function globToRegex(g) {
|
|
356
|
+
let re = '', i = 0;
|
|
357
|
+
while (i < g.length) {
|
|
358
|
+
const ch = g[i];
|
|
359
|
+
if (ch === '*') {
|
|
360
|
+
if (g[i + 1] === '*') { i += 2; if (g[i] === '/') { i++; re += '(?:.*/)?'; } else re += '.*'; continue; }
|
|
361
|
+
re += '[^/]*';
|
|
362
|
+
} else if (ch === '?') re += '[^/]';
|
|
363
|
+
else if (ch === '{') {
|
|
364
|
+
const j = g.indexOf('}', i);
|
|
365
|
+
if (j > 0) { re += '(?:' + g.slice(i + 1, j).split(',').map(escRe).join('|') + ')'; i = j; } else re += '\\{';
|
|
366
|
+
} else re += escRe(ch);
|
|
367
|
+
i++;
|
|
368
|
+
}
|
|
369
|
+
return new RegExp('^' + re + '$');
|
|
370
|
+
}
|
|
371
|
+
const toPosix = (p) => p.split(path.sep).join('/');
|
|
372
|
+
function looksBinary(buf) { const n = Math.min(buf.length, 8000); for (let i = 0; i < n; i++) if (buf[i] === 0) return true; return false; }
|
|
373
|
+
function readTextFile(abs, maxBytes = 4 * 1024 * 1024) {
|
|
374
|
+
const st = fs.statSync(abs);
|
|
375
|
+
if (!st.isFile()) throw new Error('not a regular file');
|
|
376
|
+
if (st.size > maxBytes) throw new Error(`file is too large (${st.size} bytes)`);
|
|
377
|
+
const buf = fs.readFileSync(abs);
|
|
378
|
+
if (looksBinary(buf)) throw new Error('binary file');
|
|
379
|
+
return buf.toString('utf8');
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// ---------------------------------------------------------------- shell
|
|
383
|
+
function detectShell() {
|
|
384
|
+
if (IS_WIN) {
|
|
385
|
+
const cands = [];
|
|
386
|
+
for (const dir of (process.env.PATH || '').split(';')) if (dir) cands.push(path.join(dir, 'bash.exe'));
|
|
387
|
+
for (const b of [process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs')]) {
|
|
388
|
+
if (b) cands.push(path.join(b, 'Git', 'bin', 'bash.exe'), path.join(b, 'Git', 'usr', 'bin', 'bash.exe'));
|
|
389
|
+
}
|
|
390
|
+
for (const c of cands) {
|
|
391
|
+
if (/system32/i.test(c)) continue; // WSL launcher
|
|
392
|
+
try { if (fs.existsSync(c)) return { name: 'bash (Git for Windows)', cmd: c, args: (s) => ['-c', s] }; } catch (_) {}
|
|
393
|
+
}
|
|
394
|
+
const sysroot = process.env.SystemRoot || 'C:\\Windows';
|
|
395
|
+
const ps = path.join(sysroot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
396
|
+
if (fs.existsSync(ps)) return { name: 'PowerShell (use ; instead of &&)', cmd: ps, args: (s) => ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', s] };
|
|
397
|
+
return { name: 'cmd.exe', cmd: process.env.ComSpec || 'cmd.exe', args: (s) => ['/d', '/s', '/c', s], raw: true };
|
|
398
|
+
}
|
|
399
|
+
const prefix = process.env.PREFIX || '';
|
|
400
|
+
for (const c of ['/bin/bash', '/usr/bin/bash', prefix && path.join(prefix, 'bin', 'bash'), '/bin/sh', '/usr/bin/sh', prefix && path.join(prefix, 'bin', 'sh')]) {
|
|
401
|
+
if (c && fs.existsSync(c)) return { name: path.basename(c), cmd: c, args: (s) => ['-c', s] };
|
|
402
|
+
}
|
|
403
|
+
return { name: 'sh', cmd: 'sh', args: (s) => ['-c', s] };
|
|
404
|
+
}
|
|
405
|
+
const SHELL = detectShell();
|
|
406
|
+
function killTree(child) {
|
|
407
|
+
try {
|
|
408
|
+
if (IS_WIN) cp.spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
|
|
409
|
+
else process.kill(-child.pid, 'SIGKILL');
|
|
410
|
+
} catch (_) { try { child.kill('SIGKILL'); } catch (_) {} }
|
|
411
|
+
}
|
|
412
|
+
function truncMiddle(s, head = 4000, tail = 8000) {
|
|
413
|
+
if (s.length <= head + tail + 200) return s;
|
|
414
|
+
return s.slice(0, head) + `\n… [${s.length - head - tail} characters omitted] …\n` + s.slice(-tail);
|
|
415
|
+
}
|
|
416
|
+
function spawnShell(command, cwd) {
|
|
417
|
+
return cp.spawn(SHELL.cmd, SHELL.args(command), {
|
|
418
|
+
cwd, detached: !IS_WIN, windowsHide: true, windowsVerbatimArguments: !!SHELL.raw, stdio: ['ignore', 'pipe', 'pipe'],
|
|
419
|
+
env: Object.assign({}, process.env, { PAGER: 'cat', GIT_PAGER: 'cat', GIT_TERMINAL_PROMPT: '0', CI: process.env.CI || '1', FORCE_COLOR: '0', TERM: process.env.TERM || 'dumb' }),
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
// runs a command; onLine is called for each output line while it runs; setCancel receives a function that kills it
|
|
423
|
+
function runShell(command, { cwd, timeoutMs = 120000, onLine, setCancel } = {}) {
|
|
424
|
+
return new Promise((resolve) => {
|
|
425
|
+
let child;
|
|
426
|
+
try { child = spawnShell(command, cwd); } catch (e) { return resolve({ code: -1, output: 'Failed to start shell: ' + e.message, timedOut: false, aborted: false }); }
|
|
427
|
+
const chunks = [];
|
|
428
|
+
let timedOut = false, aborted = false, partial = '';
|
|
429
|
+
const onData = (d) => {
|
|
430
|
+
chunks.push(d);
|
|
431
|
+
if (!onLine) return;
|
|
432
|
+
partial += d.toString('utf8');
|
|
433
|
+
const parts = partial.split('\n'); partial = parts.pop();
|
|
434
|
+
for (const l of parts) onLine(l.replace(/\r/g, ''));
|
|
435
|
+
};
|
|
436
|
+
child.stdout.on('data', onData);
|
|
437
|
+
child.stderr.on('data', onData);
|
|
438
|
+
const timer = setTimeout(() => { timedOut = true; killTree(child); }, timeoutMs);
|
|
439
|
+
if (setCancel) setCancel(() => { aborted = true; killTree(child); });
|
|
440
|
+
child.on('error', (e) => { clearTimeout(timer); if (setCancel) setCancel(null); resolve({ code: -1, output: 'Failed to run: ' + e.message, timedOut, aborted }); });
|
|
441
|
+
child.on('close', (code) => {
|
|
442
|
+
clearTimeout(timer); if (setCancel) setCancel(null);
|
|
443
|
+
if (partial && onLine) onLine(partial);
|
|
444
|
+
resolve({ code, output: Buffer.concat(chunks).toString('utf8'), timedOut, aborted });
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
const BG_PROCS = new Map();
|
|
449
|
+
process.on('exit', () => { for (const p of BG_PROCS.values()) { try { if (!p.done) killTree(p.child); } catch (_) {} } });
|
|
450
|
+
|
|
451
|
+
// ---------------------------------------------------------------- tool schemas
|
|
452
|
+
const READ_ONLY_TOOLS = new Set(['list_dir', 'read_file', 'search', 'find_files', 'web_fetch', 'web_search', 'todo_write', 'ask_user']);
|
|
453
|
+
const TOOLS = [
|
|
454
|
+
{ name: 'list_dir', description: 'List files and folders in a directory (skips node_modules, .git, etc). Use depth > 1 for a tree.',
|
|
455
|
+
parameters: { type: 'object', properties: { path: { type: 'string', description: 'Directory, default "."' }, depth: { type: 'integer', description: '1-4, default 1' } } } },
|
|
456
|
+
{ name: 'read_file', description: 'Read a text file. Returns numbered lines. Use start_line/end_line for large files.',
|
|
457
|
+
parameters: { type: 'object', properties: { path: { type: 'string' }, start_line: { type: 'integer' }, end_line: { type: 'integer' } }, required: ['path'] } },
|
|
458
|
+
{ name: 'write_file', description: 'Create a file or overwrite it completely. Parent folders are created. Prefer edit_file for small changes.',
|
|
459
|
+
parameters: { type: 'object', properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path', 'content'] } },
|
|
460
|
+
{ name: 'edit_file', description: 'Replace text in an existing file. old_string must match exactly (including indentation) and be unique unless replace_all is true.',
|
|
461
|
+
parameters: { type: 'object', properties: { path: { type: 'string' }, old_string: { type: 'string' }, new_string: { type: 'string' }, replace_all: { type: 'boolean' } }, required: ['path', 'old_string', 'new_string'] } },
|
|
462
|
+
{ name: 'multi_edit', description: 'Apply several edits to one file in order, all or nothing. Each edit is {old_string, new_string, replace_all?}.',
|
|
463
|
+
parameters: { type: 'object', properties: { path: { type: 'string' }, edits: { type: 'array', items: { type: 'object', properties: { old_string: { type: 'string' }, new_string: { type: 'string' }, replace_all: { type: 'boolean' } }, required: ['old_string', 'new_string'] } } }, required: ['path', 'edits'] } },
|
|
464
|
+
{ name: 'move_file', description: 'Move or rename a file or folder.',
|
|
465
|
+
parameters: { type: 'object', properties: { from: { type: 'string' }, to: { type: 'string' } }, required: ['from', 'to'] } },
|
|
466
|
+
{ name: 'delete_file', description: 'Delete a file or folder (folders need recursive=true).',
|
|
467
|
+
parameters: { type: 'object', properties: { path: { type: 'string' }, recursive: { type: 'boolean' } }, required: ['path'] } },
|
|
468
|
+
{ name: 'search', description: 'Search file contents with a regular expression. Returns file:line:text.',
|
|
469
|
+
parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string', description: 'Folder or file, default "."' }, glob: { type: 'string', description: 'Only files matching, e.g. "*.ts" or "src/**/*.py"' }, ignore_case: { type: 'boolean' } }, required: ['pattern'] } },
|
|
470
|
+
{ name: 'find_files', description: 'Find files by glob pattern, e.g. "**/*.test.js" or "*.md".',
|
|
471
|
+
parameters: { type: 'object', properties: { pattern: { type: 'string' }, path: { type: 'string' } }, required: ['pattern'] } },
|
|
472
|
+
{ name: 'run_command', description: `Run a shell command in the project folder (${SHELL.name}) and return its output and exit code. No interactive input. For servers or watchers that never exit use run_background.`,
|
|
473
|
+
parameters: { type: 'object', properties: { command: { type: 'string' }, timeout_seconds: { type: 'integer', description: 'Default 120, max 900' }, cwd: { type: 'string' } }, required: ['command'] } },
|
|
474
|
+
{ name: 'run_background', description: 'Start a long-running command (dev server, watcher) in the background. Returns an id. Read its output with background_output and stop it with kill_background.',
|
|
475
|
+
parameters: { type: 'object', properties: { command: { type: 'string' }, cwd: { type: 'string' } }, required: ['command'] } },
|
|
476
|
+
{ name: 'background_output', description: 'Get new output and status of a background command.',
|
|
477
|
+
parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },
|
|
478
|
+
{ name: 'kill_background', description: 'Stop a background command.',
|
|
479
|
+
parameters: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },
|
|
480
|
+
{ name: 'web_fetch', description: 'Fetch a URL and return its text (HTML is reduced to plain text). Good for documentation.',
|
|
481
|
+
parameters: { type: 'object', properties: { url: { type: 'string' } }, required: ['url'] } },
|
|
482
|
+
{ name: 'web_search', description: 'Search the web and return the top results (title, url, snippet).',
|
|
483
|
+
parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } },
|
|
484
|
+
{ name: 'todo_write', description: 'Keep a visible task list for multi-step work. Send the full list each time. Statuses: pending, in_progress, completed. Keep one item in_progress.',
|
|
485
|
+
parameters: { type: 'object', properties: { todos: { type: 'array', items: { type: 'object', properties: { content: { type: 'string' }, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] } }, required: ['content', 'status'] } } }, required: ['todos'] } },
|
|
486
|
+
{ name: 'ask_user', description: 'Ask the user a question when you need a decision. Optionally give a short list of options. Returns their answer.',
|
|
487
|
+
parameters: { type: 'object', properties: { question: { type: 'string' }, options: { type: 'array', items: { type: 'string' } } }, required: ['question'] } },
|
|
488
|
+
{ name: 'generate_image', description: 'Generate an image from a text prompt and save it to a file (costs extra credits, the user is asked first).',
|
|
489
|
+
parameters: { type: 'object', properties: { prompt: { type: 'string' }, path: { type: 'string', description: 'Where to save, e.g. assets/logo.jpg' } }, required: ['prompt', 'path'] } },
|
|
490
|
+
{ name: 'transcribe_audio', description: 'Transcribe an audio file (mp3, m4a, wav, ogg, up to 24 MB) to text (costs extra credits, the user is asked first).',
|
|
491
|
+
parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] } },
|
|
492
|
+
];
|
|
493
|
+
const toolsFor = (S) => (S.agent === 'plan' ? TOOLS.filter((t) => READ_ONLY_TOOLS.has(t.name)) : TOOLS);
|
|
494
|
+
|
|
495
|
+
const SAFE_CMD = /^(ls|dir|pwd|cat|head|tail|wc|which|where|whoami|date|echo|tree|type|stat|file|du|df|uname|hostname|printenv|node\s+(-v|--version)|npm\s+(-v|--version|ls|list|outdated|view|config\s+get)|python3?\s+(-V|--version)|git\s+(status|diff|log|branch|show|remote|rev-parse|ls-files|blame|describe|tag)(\s|$)|go\s+version|cargo\s+--version|java\s+-version|dotnet\s+--(version|info)|pip3?\s+(list|show|--version)|rg|grep|find|sort|uniq|cut|nl)(\s|$)/i;
|
|
496
|
+
const hasMeta = (s) => /[;&|<>`$\n]|\$\(/.test(s) && !/^[^|;&<>`$\n]*\|\s*(head|tail|wc|sort|uniq|grep|rg)\b[^;&<>`$\n]*$/.test(s);
|
|
497
|
+
const isSafeCommand = (s) => SAFE_CMD.test(s.trim()) && !hasMeta(s.trim()) && !/\b(find)\b.*(-exec|-delete|-ok)/.test(s);
|
|
498
|
+
|
|
499
|
+
// ---------------------------------------------------------------- tool helpers
|
|
500
|
+
const resolveIn = (S, p) => path.resolve(S.cwd, expandHome(String(p || '.')));
|
|
501
|
+
const insideCwd = (S, abs) => { const r = path.relative(S.cwd, abs); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)); };
|
|
502
|
+
const rel = (S, abs) => toPosix(path.relative(S.cwd, abs) || '.');
|
|
503
|
+
function snap(S, abs) {
|
|
504
|
+
let before = null;
|
|
505
|
+
try { const st = fs.statSync(abs); if (st.isFile() && st.size < 8 * 1024 * 1024) before = fs.readFileSync(abs); } catch (_) {}
|
|
506
|
+
S.snapshots.push({ path: abs, before });
|
|
507
|
+
}
|
|
508
|
+
function diffLines(oldS, newS, maxEach = 14) {
|
|
509
|
+
const o = oldS.split('\n'), n = newS.split('\n');
|
|
510
|
+
const lines = [];
|
|
511
|
+
o.slice(0, maxEach).forEach((l) => lines.push({ t: 'del', s: l }));
|
|
512
|
+
if (o.length > maxEach) lines.push({ t: 'text', s: `… ${o.length - maxEach} more removed lines` });
|
|
513
|
+
n.slice(0, maxEach).forEach((l) => lines.push({ t: 'add', s: l }));
|
|
514
|
+
if (n.length > maxEach) lines.push({ t: 'text', s: `… ${n.length - maxEach} more added lines` });
|
|
515
|
+
return lines;
|
|
516
|
+
}
|
|
517
|
+
async function approve(T, kind, title, lines) {
|
|
518
|
+
const S = T.S;
|
|
519
|
+
if (S.auto || S.always.has(kind)) return { ok: true };
|
|
520
|
+
const r = await S.ui.approve({ kind, title, lines: lines || [] });
|
|
521
|
+
if (r.ok && r.always) S.always.add(kind);
|
|
522
|
+
if (!r.ok) T.denied = true;
|
|
523
|
+
return r;
|
|
524
|
+
}
|
|
525
|
+
function htmlToText(html) {
|
|
526
|
+
return html
|
|
527
|
+
.replace(/<(script|style|noscript|svg)[\s\S]*?<\/\1>/gi, '')
|
|
528
|
+
.replace(/<\/(p|div|h[1-6]|li|tr|pre|section|article)>/gi, '\n').replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]+>/g, '')
|
|
529
|
+
.replace(/ /g, ' ').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&')
|
|
530
|
+
.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
531
|
+
}
|
|
532
|
+
async function timedFetch(S, url, opts = {}, ms = 20000) {
|
|
533
|
+
const ctl = new AbortController();
|
|
534
|
+
const t = setTimeout(() => ctl.abort(), ms);
|
|
535
|
+
S.setCancel(() => ctl.abort());
|
|
536
|
+
try { return await fetch(url, Object.assign({ signal: ctl.signal }, opts)); }
|
|
537
|
+
finally { clearTimeout(t); S.setCancel(null); }
|
|
538
|
+
}
|
|
539
|
+
function applyEdits(norm, edits) {
|
|
540
|
+
let text = norm;
|
|
541
|
+
const hunks = [];
|
|
542
|
+
for (let k = 0; k < edits.length; k++) {
|
|
543
|
+
const e = edits[k];
|
|
544
|
+
const o = String(e.old_string ?? '').replace(/\r\n/g, '\n'), n = String(e.new_string ?? '').replace(/\r\n/g, '\n');
|
|
545
|
+
const tag = edits.length > 1 ? ` (edit ${k + 1})` : '';
|
|
546
|
+
if (!o) return { error: 'Error: old_string is empty' + tag + '. Use write_file to replace a whole file.' };
|
|
547
|
+
if (o === n) return { error: 'Error: old_string and new_string are identical' + tag + '.' };
|
|
548
|
+
const count = text.split(o).length - 1;
|
|
549
|
+
if (count === 0) {
|
|
550
|
+
const first = o.split('\n').find((l) => l.trim());
|
|
551
|
+
let hint = '';
|
|
552
|
+
if (first) { const idx = text.split('\n').findIndex((l) => l.includes(first.trim())); if (idx >= 0) hint = ` The first line of old_string does appear near line ${idx + 1}; re-read the file and copy the text exactly (whitespace matters).`; }
|
|
553
|
+
return { error: 'Error: old_string was not found in the file' + tag + '.' + hint };
|
|
554
|
+
}
|
|
555
|
+
if (count > 1 && !e.replace_all) return { error: `Error: old_string matches ${count} places${tag}. Add more surrounding context, or set replace_all to true.` };
|
|
556
|
+
if (e.replace_all) text = text.split(o).join(n);
|
|
557
|
+
else { const i = text.indexOf(o); text = text.slice(0, i) + n + text.slice(i + o.length); }
|
|
558
|
+
hunks.push({ old: o, new: n, count });
|
|
559
|
+
}
|
|
560
|
+
return { text, hunks };
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// ---------------------------------------------------------------- tool implementations
|
|
564
|
+
const toolImpl = {
|
|
565
|
+
async list_dir(T, a) {
|
|
566
|
+
const S = T.S, root = resolveIn(S, a.path);
|
|
567
|
+
const depth = Math.max(1, Math.min(4, parseInt(a.depth, 10) || 1));
|
|
568
|
+
if (!fs.existsSync(root)) return 'Error: path does not exist: ' + a.path;
|
|
569
|
+
const lines = [];
|
|
570
|
+
const rec = (dir, d, prefix) => {
|
|
571
|
+
let ents;
|
|
572
|
+
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { return; }
|
|
573
|
+
ents.sort((x, y) => (y.isDirectory() - x.isDirectory()) || x.name.localeCompare(y.name));
|
|
574
|
+
for (const e of ents) {
|
|
575
|
+
if (lines.length >= 400) return;
|
|
576
|
+
if (e.isDirectory() && IGNORE_DIRS.has(e.name)) { lines.push(`${prefix}${e.name}/ (skipped)`); continue; }
|
|
577
|
+
lines.push(prefix + e.name + (e.isDirectory() ? '/' : ''));
|
|
578
|
+
if (e.isDirectory() && d < depth) rec(path.join(dir, e.name), d + 1, prefix + ' ');
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
rec(root, 1, '');
|
|
582
|
+
return (lines.join('\n') || '(empty directory)') + (lines.length >= 400 ? '\n… (list truncated)' : '');
|
|
583
|
+
},
|
|
584
|
+
|
|
585
|
+
async read_file(T, a) {
|
|
586
|
+
const S = T.S, abs = resolveIn(S, a.path);
|
|
587
|
+
let text;
|
|
588
|
+
try { text = readTextFile(abs); } catch (e) { return `Error reading ${a.path}: ${e.message}`; }
|
|
589
|
+
const all = text.split('\n');
|
|
590
|
+
if (all.length && all[all.length - 1] === '') all.pop();
|
|
591
|
+
const s = Math.max(1, parseInt(a.start_line, 10) || 1);
|
|
592
|
+
const e = Math.min(all.length, parseInt(a.end_line, 10) || s + 1999);
|
|
593
|
+
let body = '';
|
|
594
|
+
for (let i = s; i <= e; i++) body += `${String(i).padStart(5)}\t${all[i - 1]}\n`;
|
|
595
|
+
let note = '';
|
|
596
|
+
if (body.length > 60000) { body = body.slice(0, 60000); note = '\n… (output cut at 60k characters, use start_line/end_line)'; }
|
|
597
|
+
else if (e < all.length) note = `\n… (showing lines ${s}-${e} of ${all.length}, use start_line/end_line for more)`;
|
|
598
|
+
T.summary = `${all.length} lines`;
|
|
599
|
+
return `File: ${rel(S, abs)} (${all.length} lines)\n${body}${note}`;
|
|
600
|
+
},
|
|
601
|
+
|
|
602
|
+
async write_file(T, a) {
|
|
603
|
+
const S = T.S, abs = resolveIn(S, a.path);
|
|
604
|
+
if (typeof a.content !== 'string') return 'Error: content must be a string.';
|
|
605
|
+
const exists = fs.existsSync(abs);
|
|
606
|
+
const outside = !insideCwd(S, abs);
|
|
607
|
+
const lines = a.content.split('\n');
|
|
608
|
+
if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
|
|
609
|
+
T.display = { type: 'write', path: rel(S, abs), total: lines.length, preview: lines.slice(0, 12), overwrite: exists };
|
|
610
|
+
const ok = await approve(T, outside ? 'write-outside' : 'write', `${exists ? 'Overwrite' : 'Create'} ${rel(S, abs)}${outside ? ' (outside project)' : ''}`,
|
|
611
|
+
lines.slice(0, 14).map((s) => ({ t: 'add', s })).concat(lines.length > 14 ? [{ t: 'text', s: `… ${lines.length - 14} more lines` }] : []));
|
|
612
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
613
|
+
try { snap(S, abs); fs.mkdirSync(path.dirname(abs), { recursive: true }); fs.writeFileSync(abs, a.content); } catch (e) { S.snapshots.pop(); return 'Error writing file: ' + e.message; }
|
|
614
|
+
S.changed.set(rel(S, abs), exists ? 'M' : 'A');
|
|
615
|
+
T.summary = `${exists ? 'overwrote' : 'created'} · ${lines.length} lines`;
|
|
616
|
+
return `${exists ? 'Overwrote' : 'Created'} ${rel(S, abs)} (${lines.length} lines).`;
|
|
617
|
+
},
|
|
618
|
+
|
|
619
|
+
async edit_file(T, a) { return doEdit(T, a.path, [{ old_string: a.old_string, new_string: a.new_string, replace_all: a.replace_all }]); },
|
|
620
|
+
async multi_edit(T, a) {
|
|
621
|
+
if (!Array.isArray(a.edits) || !a.edits.length) return 'Error: edits must be a non-empty array.';
|
|
622
|
+
return doEdit(T, a.path, a.edits);
|
|
623
|
+
},
|
|
624
|
+
|
|
625
|
+
async move_file(T, a) {
|
|
626
|
+
const S = T.S, from = resolveIn(S, a.from), to = resolveIn(S, a.to);
|
|
627
|
+
if (!fs.existsSync(from)) return 'Error: source does not exist: ' + a.from;
|
|
628
|
+
if (fs.existsSync(to)) return 'Error: destination already exists: ' + a.to;
|
|
629
|
+
const ok = await approve(T, 'write', `Move ${rel(S, from)} → ${rel(S, to)}`);
|
|
630
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
631
|
+
try {
|
|
632
|
+
if (fs.statSync(from).isFile()) { snap(S, from); S.snapshots.push({ path: to, before: null }); }
|
|
633
|
+
fs.mkdirSync(path.dirname(to), { recursive: true }); fs.renameSync(from, to);
|
|
634
|
+
} catch (e) { return 'Error moving: ' + e.message; }
|
|
635
|
+
S.changed.set(rel(S, to), 'R');
|
|
636
|
+
return `Moved ${rel(S, from)} to ${rel(S, to)}.`;
|
|
637
|
+
},
|
|
638
|
+
|
|
639
|
+
async delete_file(T, a) {
|
|
640
|
+
const S = T.S, abs = resolveIn(S, a.path);
|
|
641
|
+
if (!fs.existsSync(abs)) return 'Error: path does not exist: ' + a.path;
|
|
642
|
+
if (abs === S.cwd || abs === path.parse(abs).root || abs === os.homedir()) return 'Error: refusing to delete that folder.';
|
|
643
|
+
const isDir = fs.statSync(abs).isDirectory();
|
|
644
|
+
if (isDir && !a.recursive) return 'Error: this is a folder. Set recursive=true to delete it and everything inside.';
|
|
645
|
+
const ok = await approve(T, 'delete', `Delete ${rel(S, abs)}${isDir ? '/ and everything inside' : ''}`);
|
|
646
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
647
|
+
try { if (!isDir) snap(S, abs); fs.rmSync(abs, { recursive: true, force: true }); } catch (e) { return 'Error deleting: ' + e.message; }
|
|
648
|
+
S.changed.set(rel(S, abs), 'D');
|
|
649
|
+
return `Deleted ${rel(S, abs)}.`;
|
|
650
|
+
},
|
|
651
|
+
|
|
652
|
+
async search(T, a) {
|
|
653
|
+
const S = T.S, root = resolveIn(S, a.path);
|
|
654
|
+
let re;
|
|
655
|
+
try { re = new RegExp(a.pattern, a.ignore_case ? 'i' : ''); } catch (_) { re = new RegExp(escRe(String(a.pattern)), a.ignore_case ? 'i' : ''); }
|
|
656
|
+
const gre = a.glob ? globToRegex(a.glob) : null;
|
|
657
|
+
const results = [];
|
|
658
|
+
const files = fs.existsSync(root) && fs.statSync(root).isFile() ? [root] : walk(root);
|
|
659
|
+
for (const f of files) {
|
|
660
|
+
const r = toPosix(path.relative(root, f));
|
|
661
|
+
if (gre && !(a.glob.includes('/') ? gre.test(r) : gre.test(path.basename(f)))) continue;
|
|
662
|
+
let text;
|
|
663
|
+
try { const st = fs.statSync(f); if (st.size > 1024 * 1024) continue; const buf = fs.readFileSync(f); if (looksBinary(buf)) continue; text = buf.toString('utf8'); } catch (_) { continue; }
|
|
664
|
+
const lines = text.split('\n');
|
|
665
|
+
for (let i = 0; i < lines.length; i++) {
|
|
666
|
+
if (re.test(lines[i])) {
|
|
667
|
+
results.push(`${rel(S, f)}:${i + 1}:${clip(lines[i].trim(), 240)}`);
|
|
668
|
+
if (results.length >= 100) { T.summary = '100+ matches'; return results.join('\n') + '\n… (stopped at 100 matches, narrow your search)'; }
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
T.summary = results.length + ' matches';
|
|
673
|
+
return results.length ? results.join('\n') : 'No matches.';
|
|
674
|
+
},
|
|
675
|
+
|
|
676
|
+
async find_files(T, a) {
|
|
677
|
+
const S = T.S, root = resolveIn(S, a.path);
|
|
678
|
+
const re = globToRegex(a.pattern);
|
|
679
|
+
const slash = a.pattern.includes('/');
|
|
680
|
+
const found = [];
|
|
681
|
+
for (const f of walk(root)) {
|
|
682
|
+
const r = toPosix(path.relative(root, f));
|
|
683
|
+
if (slash ? re.test(r) : re.test(path.basename(f))) {
|
|
684
|
+
found.push(rel(S, f));
|
|
685
|
+
if (found.length >= 200) { T.summary = '200+ files'; return found.join('\n') + '\n… (stopped at 200 files)'; }
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
T.summary = found.length + ' files';
|
|
689
|
+
return found.length ? found.join('\n') : 'No files matched.';
|
|
690
|
+
},
|
|
691
|
+
|
|
692
|
+
async run_command(T, a) {
|
|
693
|
+
const S = T.S;
|
|
694
|
+
const command = String(a.command || '').trim();
|
|
695
|
+
if (!command) return 'Error: command is empty.';
|
|
696
|
+
const cwd = a.cwd ? resolveIn(S, a.cwd) : S.cwd;
|
|
697
|
+
if (!fs.existsSync(cwd)) return 'Error: cwd does not exist: ' + a.cwd;
|
|
698
|
+
const timeout = Math.max(1, Math.min(900, parseInt(a.timeout_seconds, 10) || 120)) * 1000;
|
|
699
|
+
if (!isSafeCommand(command)) {
|
|
700
|
+
const ok = await approve(T, 'run', 'Run command', command.split('\n').map((s) => ({ t: 'cmd', s })).concat(cwd !== S.cwd ? [{ t: 'text', s: 'in ' + cwd }] : []));
|
|
701
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
702
|
+
}
|
|
703
|
+
const r = await runShell(command, { cwd, timeoutMs: timeout, onLine: (l) => S.ui.toolOutput(T.id, l), setCancel: S.setCancel });
|
|
704
|
+
const o = truncMiddle(r.output.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r\n/g, '\n'));
|
|
705
|
+
if (r.aborted) { S.interrupted = true; return 'Command interrupted by the user.\n' + o; }
|
|
706
|
+
T.summary = 'exit ' + r.code;
|
|
707
|
+
if (r.timedOut) return `Command timed out after ${timeout / 1000}s and was killed.\n` + o;
|
|
708
|
+
return `${o || '(no output)'}\n[exit code ${r.code}]`;
|
|
709
|
+
},
|
|
710
|
+
|
|
711
|
+
async run_background(T, a) {
|
|
712
|
+
const S = T.S;
|
|
713
|
+
const command = String(a.command || '').trim();
|
|
714
|
+
if (!command) return 'Error: command is empty.';
|
|
715
|
+
const cwd = a.cwd ? resolveIn(S, a.cwd) : S.cwd;
|
|
716
|
+
const ok = await approve(T, 'run', 'Run in background', [{ t: 'cmd', s: command }]);
|
|
717
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
718
|
+
let child;
|
|
719
|
+
try { child = spawnShell(command, cwd); } catch (e) { return 'Error: ' + e.message; }
|
|
720
|
+
const id = 'bg' + (BG_PROCS.size + 1);
|
|
721
|
+
const p = { id, child, command, buf: '', read: 0, done: false, code: null };
|
|
722
|
+
BG_PROCS.set(id, p);
|
|
723
|
+
const add = (d) => { p.buf += d.toString('utf8'); if (p.buf.length > 400000) { const cut = p.buf.length - 300000; p.buf = p.buf.slice(cut); p.read = Math.max(0, p.read - cut); } };
|
|
724
|
+
child.stdout.on('data', add); child.stderr.on('data', add);
|
|
725
|
+
child.on('close', (c) => { p.done = true; p.code = c; });
|
|
726
|
+
child.on('error', (e) => { p.done = true; p.code = -1; p.buf += '\n' + e.message; });
|
|
727
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
728
|
+
const chunk = p.buf.slice(p.read); p.read = p.buf.length;
|
|
729
|
+
T.summary = id;
|
|
730
|
+
return `Started ${id}: ${command}\n${p.done ? `(already exited with code ${p.code})\n` : ''}${truncMiddle(chunk, 2000, 4000) || '(no output yet)'}`;
|
|
731
|
+
},
|
|
732
|
+
async background_output(T, a) {
|
|
733
|
+
const p = BG_PROCS.get(String(a.id));
|
|
734
|
+
if (!p) return 'Error: no background command with that id. Known: ' + ([...BG_PROCS.keys()].join(', ') || 'none');
|
|
735
|
+
const chunk = p.buf.slice(p.read); p.read = p.buf.length;
|
|
736
|
+
return `${p.done ? `[exited with code ${p.code}]` : '[still running]'}\n${truncMiddle(chunk, 2000, 8000) || '(no new output)'}`;
|
|
737
|
+
},
|
|
738
|
+
async kill_background(T, a) {
|
|
739
|
+
const p = BG_PROCS.get(String(a.id));
|
|
740
|
+
if (!p) return 'Error: no background command with that id.';
|
|
741
|
+
if (!p.done) killTree(p.child);
|
|
742
|
+
return `Stopped ${p.id}.`;
|
|
743
|
+
},
|
|
744
|
+
|
|
745
|
+
async web_fetch(T, a) {
|
|
746
|
+
const S = T.S;
|
|
747
|
+
let u;
|
|
748
|
+
try { u = new URL(String(a.url)); } catch (_) { return 'Error: invalid URL.'; }
|
|
749
|
+
if (!/^https?:$/.test(u.protocol)) return 'Error: only http and https URLs are allowed.';
|
|
750
|
+
try {
|
|
751
|
+
const r = await timedFetch(S, u, { redirect: 'follow', headers: { 'User-Agent': `benchcode/${VERSION}`, Accept: 'text/html,text/plain,application/json,*/*' } });
|
|
752
|
+
const ct = r.headers.get('content-type') || '';
|
|
753
|
+
let text = await r.text();
|
|
754
|
+
if (/html/i.test(ct)) text = htmlToText(text);
|
|
755
|
+
if (text.length > 24000) text = text.slice(0, 24000) + '\n… (page truncated)';
|
|
756
|
+
T.summary = 'HTTP ' + r.status;
|
|
757
|
+
return `HTTP ${r.status} ${u.href}\n${text}`;
|
|
758
|
+
} catch (e) { return 'Error fetching URL: ' + (e.name === 'AbortError' ? 'timed out or cancelled' : e.message); }
|
|
759
|
+
},
|
|
760
|
+
|
|
761
|
+
async web_search(T, a) {
|
|
762
|
+
const S = T.S;
|
|
763
|
+
const q = String(a.query || '').trim();
|
|
764
|
+
if (!q) return 'Error: query is empty.';
|
|
765
|
+
try {
|
|
766
|
+
const r = await timedFetch(S, 'https://html.duckduckgo.com/html/?q=' + encodeURIComponent(q), { headers: { 'User-Agent': 'Mozilla/5.0 (compatible; benchcode/' + VERSION + ')', Accept: 'text/html' } }, 15000);
|
|
767
|
+
const html = await r.text();
|
|
768
|
+
const items = [];
|
|
769
|
+
const re = /<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?(?:class="result__snippet"[^>]*>([\s\S]*?)<\/a>)?/g;
|
|
770
|
+
let m;
|
|
771
|
+
while ((m = re.exec(html)) && items.length < 8) {
|
|
772
|
+
let href = m[1].replace(/&/g, '&');
|
|
773
|
+
const u = href.match(/[?&]uddg=([^&]+)/); if (u) href = decodeURIComponent(u[1]);
|
|
774
|
+
if (href.startsWith('//')) href = 'https:' + href;
|
|
775
|
+
items.push(`${items.length + 1}. ${htmlToText(m[2])}\n ${href}\n ${htmlToText(m[3] || '')}`);
|
|
776
|
+
}
|
|
777
|
+
T.summary = items.length + ' results';
|
|
778
|
+
return items.length ? items.join('\n') : 'No results (the search page may have blocked this request). Try web_fetch on a specific URL.';
|
|
779
|
+
} catch (e) { return 'Error searching: ' + (e.name === 'AbortError' ? 'timed out or cancelled' : e.message); }
|
|
780
|
+
},
|
|
781
|
+
|
|
782
|
+
async todo_write(T, a) {
|
|
783
|
+
const S = T.S;
|
|
784
|
+
if (!Array.isArray(a.todos)) return 'Error: todos must be an array.';
|
|
785
|
+
S.todos = a.todos.slice(0, 30).map((t) => ({ content: String(t.content || '').slice(0, 160), status: ['pending', 'in_progress', 'completed'].includes(t.status) ? t.status : 'pending' }));
|
|
786
|
+
T.display = { type: 'todos', todos: S.todos };
|
|
787
|
+
const done = S.todos.filter((t) => t.status === 'completed').length;
|
|
788
|
+
T.summary = `${done}/${S.todos.length} done`;
|
|
789
|
+
return 'Todo list updated.';
|
|
790
|
+
},
|
|
791
|
+
|
|
792
|
+
async ask_user(T, a) {
|
|
793
|
+
const S = T.S;
|
|
794
|
+
const opts = Array.isArray(a.options) ? a.options.map(String).slice(0, 8) : [];
|
|
795
|
+
const ans = await S.ui.askUser(String(a.question || ''), opts);
|
|
796
|
+
if (ans === null || ans === undefined) { S.interrupted = true; return 'The user dismissed the question.'; }
|
|
797
|
+
T.summary = clip(ans, 40);
|
|
798
|
+
return 'User answered: ' + ans;
|
|
799
|
+
},
|
|
800
|
+
|
|
801
|
+
async generate_image(T, a) {
|
|
802
|
+
const S = T.S, abs = resolveIn(S, a.path);
|
|
803
|
+
const ok = await approve(T, 'spend', 'Generate image (uses extra credits)', [{ t: 'text', s: clip(String(a.prompt), 200) }, { t: 'text', s: '→ ' + rel(S, abs) }]);
|
|
804
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
805
|
+
try {
|
|
806
|
+
const r = await timedFetch(S, S.baseUrl + '/v1/images/generations', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + S.apiKey }, body: JSON.stringify({ prompt: String(a.prompt), n: 1, resolution: '480' }) }, 120000);
|
|
807
|
+
const j = await r.json().catch(() => ({}));
|
|
808
|
+
if (!r.ok) return 'Error: ' + (j.error && (j.error.message || j.error) || 'HTTP ' + r.status);
|
|
809
|
+
const item = j.data && j.data[0];
|
|
810
|
+
let buf;
|
|
811
|
+
if (item && item.b64_json) buf = Buffer.from(item.b64_json, 'base64');
|
|
812
|
+
else if (item && item.url) { const d = await timedFetch(S, item.url, {}, 60000); buf = Buffer.from(await d.arrayBuffer()); }
|
|
813
|
+
else return 'Error: the image service returned no image.';
|
|
814
|
+
snap(S, abs); fs.mkdirSync(path.dirname(abs), { recursive: true }); fs.writeFileSync(abs, buf);
|
|
815
|
+
S.changed.set(rel(S, abs), 'A');
|
|
816
|
+
T.summary = Math.round(buf.length / 1024) + ' KB';
|
|
817
|
+
return `Saved image to ${rel(S, abs)} (${buf.length} bytes).`;
|
|
818
|
+
} catch (e) { return 'Error generating image: ' + (e.name === 'AbortError' ? 'cancelled' : e.message); }
|
|
819
|
+
},
|
|
820
|
+
|
|
821
|
+
async transcribe_audio(T, a) {
|
|
822
|
+
const S = T.S, abs = resolveIn(S, a.path);
|
|
823
|
+
if (!fs.existsSync(abs)) return 'Error: file does not exist: ' + a.path;
|
|
824
|
+
const st = fs.statSync(abs);
|
|
825
|
+
if (st.size > 24 * 1024 * 1024) return 'Error: file is larger than 24 MB.';
|
|
826
|
+
const ok = await approve(T, 'spend', 'Transcribe audio (uses extra credits)', [{ t: 'text', s: rel(S, abs) }]);
|
|
827
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
828
|
+
try {
|
|
829
|
+
const fd = new FormData();
|
|
830
|
+
fd.append('file', new Blob([fs.readFileSync(abs)]), path.basename(abs));
|
|
831
|
+
fd.append('model', 'whisper-large-v3-turbo');
|
|
832
|
+
const r = await timedFetch(S, S.baseUrl + '/v1/audio/transcriptions', { method: 'POST', headers: { Authorization: 'Bearer ' + S.apiKey }, body: fd }, 180000);
|
|
833
|
+
const j = await r.json().catch(() => ({}));
|
|
834
|
+
if (!r.ok) return 'Error: ' + (j.error && (j.error.message || j.error) || 'HTTP ' + r.status);
|
|
835
|
+
T.summary = (j.text || '').length + ' chars';
|
|
836
|
+
return j.text || '(no speech detected)';
|
|
837
|
+
} catch (e) { return 'Error transcribing: ' + (e.name === 'AbortError' ? 'cancelled' : e.message); }
|
|
838
|
+
},
|
|
839
|
+
};
|
|
840
|
+
|
|
841
|
+
async function doEdit(T, p, edits) {
|
|
842
|
+
const S = T.S, abs = resolveIn(S, p);
|
|
843
|
+
let text;
|
|
844
|
+
try { text = readTextFile(abs); } catch (e) { return `Error reading ${p}: ${e.message}`; }
|
|
845
|
+
const crlf = text.includes('\r\n');
|
|
846
|
+
const r = applyEdits(text.replace(/\r\n/g, '\n'), edits);
|
|
847
|
+
if (r.error) return r.error;
|
|
848
|
+
const outside = !insideCwd(S, abs);
|
|
849
|
+
T.display = { type: 'diff', path: rel(S, abs), hunks: r.hunks.map((h) => ({ old: h.old, new: h.new })) };
|
|
850
|
+
const lines = [];
|
|
851
|
+
r.hunks.forEach((h, i) => { if (i) lines.push({ t: 'text', s: '⋯' }); lines.push(...diffLines(h.old, h.new, 8)); });
|
|
852
|
+
const total = r.hunks.reduce((n, h) => n + h.count, 0);
|
|
853
|
+
const ok = await approve(T, outside ? 'write-outside' : 'edit', `Edit ${rel(S, abs)}${total > 1 ? ` (${total} places)` : ''}${outside ? ' (outside project)' : ''}`, lines);
|
|
854
|
+
if (!ok.ok) return ok.note || 'The user denied this action.';
|
|
855
|
+
let result = r.text;
|
|
856
|
+
if (crlf) result = result.replace(/\n/g, '\r\n');
|
|
857
|
+
try { snap(S, abs); fs.writeFileSync(abs, result); } catch (e) { S.snapshots.pop(); return 'Error writing file: ' + e.message; }
|
|
858
|
+
S.changed.set(rel(S, abs), S.changed.get(rel(S, abs)) === 'A' ? 'A' : 'M');
|
|
859
|
+
T.summary = `${total} change${total > 1 ? 's' : ''}`;
|
|
860
|
+
return `Edited ${rel(S, abs)} (${total} replacement${total > 1 ? 's' : ''}).`;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
function toolSummary(name, a) {
|
|
864
|
+
switch (name) {
|
|
865
|
+
case 'list_dir': return a.path || '.';
|
|
866
|
+
case 'read_file': return `${a.path}${a.start_line ? ':' + a.start_line + (a.end_line ? '-' + a.end_line : '') : ''}`;
|
|
867
|
+
case 'write_file': case 'edit_file': case 'multi_edit': case 'delete_file': return a.path;
|
|
868
|
+
case 'move_file': return `${a.from} → ${a.to}`;
|
|
869
|
+
case 'search': return `/${a.pattern}/${a.glob ? ' in ' + a.glob : ''}`;
|
|
870
|
+
case 'find_files': return a.pattern;
|
|
871
|
+
case 'run_command': case 'run_background': return String(a.command || '').replace(/\n/g, ' ⏎ ');
|
|
872
|
+
case 'web_fetch': return a.url;
|
|
873
|
+
case 'web_search': return a.query;
|
|
874
|
+
case 'background_output': case 'kill_background': return a.id;
|
|
875
|
+
case 'generate_image': return `${a.path}`;
|
|
876
|
+
case 'transcribe_audio': return a.path;
|
|
877
|
+
case 'ask_user': return clip(String(a.question || ''), 80);
|
|
878
|
+
case 'todo_write': return (a.todos || []).length + ' items';
|
|
879
|
+
default: return '';
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// runs one tool call; returns {text, status, display, summary}
|
|
884
|
+
async function execTool(S, call) {
|
|
885
|
+
let args = {};
|
|
886
|
+
try { args = call.arguments ? JSON.parse(call.arguments) : {}; if (!args || typeof args !== 'object') args = {}; }
|
|
887
|
+
catch (_) { return { text: 'Error: the arguments were not valid JSON. Send a valid JSON object.', status: 'error' }; }
|
|
888
|
+
const impl = toolImpl[call.name];
|
|
889
|
+
const T = { S, id: call.id, display: null, summary: '', denied: false };
|
|
890
|
+
if (!impl || (S.agent === 'plan' && !READ_ONLY_TOOLS.has(call.name))) {
|
|
891
|
+
S.ui.toolStart({ id: call.id, name: call.name, args, summary: toolSummary(call.name, args) });
|
|
892
|
+
const msg = !impl ? `Error: unknown tool "${call.name}". Available: ${Object.keys(toolImpl).join(', ')}.` : `Error: "${call.name}" is not available in Plan mode (read-only). Finish the plan and let the user switch to Build mode.`;
|
|
893
|
+
S.ui.toolEnd({ id: call.id, status: 'error', summary: 'unavailable' });
|
|
894
|
+
return { text: msg, status: 'error' };
|
|
895
|
+
}
|
|
896
|
+
S.ui.toolStart({ id: call.id, name: call.name, args, summary: toolSummary(call.name, args) });
|
|
897
|
+
let text, status = 'done';
|
|
898
|
+
try {
|
|
899
|
+
text = String(await impl(T, args));
|
|
900
|
+
if (T.denied) status = 'denied'; else if (/^Error/.test(text)) status = 'error';
|
|
901
|
+
} catch (e) { text = 'Error: ' + (e && e.message ? e.message : String(e)); status = 'error'; }
|
|
902
|
+
S.ui.toolEnd({ id: call.id, status, summary: T.summary || (status === 'error' ? clip(text.replace(/^Error:?\s*/, ''), 60) : ''), display: T.display, text });
|
|
903
|
+
return { text, status };
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// ---------------------------------------------------------------- API helpers
|
|
907
|
+
class ApiError extends Error { constructor(status, msg) { super(msg); this.status = status; } }
|
|
908
|
+
function parseErrBody(text) { try { const j = JSON.parse(text); return (j.error && (j.error.message || j.error)) || j.message || text; } catch (_) { return text; } }
|
|
909
|
+
const hdrs = (key) => ({ Authorization: 'Bearer ' + key, 'User-Agent': 'benchcode/' + VERSION });
|
|
910
|
+
|
|
911
|
+
async function fetchModels(cfg) {
|
|
912
|
+
const r = await fetch(cfg.baseUrl + '/v1/models', { headers: hdrs(cfg.apiKey) });
|
|
913
|
+
const text = await r.text();
|
|
914
|
+
if (!r.ok) throw new ApiError(r.status, String(parseErrBody(text)));
|
|
915
|
+
return (JSON.parse(text).data || []).filter((m) => m && m.id);
|
|
916
|
+
}
|
|
917
|
+
async function fetchAccount(cfg) {
|
|
918
|
+
const ctl = new AbortController(); const t = setTimeout(() => ctl.abort(), 8000);
|
|
919
|
+
try {
|
|
920
|
+
const r = await fetch(cfg.baseUrl + '/v2/account', { headers: hdrs(cfg.apiKey), signal: ctl.signal });
|
|
921
|
+
if (!r.ok) return null;
|
|
922
|
+
const j = await r.json(); j._at = Date.now(); return j;
|
|
923
|
+
} catch (_) { return null; } finally { clearTimeout(t); }
|
|
924
|
+
}
|
|
925
|
+
async function refreshAccount(S) {
|
|
926
|
+
const a = await fetchAccount(S);
|
|
927
|
+
if (a) { S.account = a; if (S.ui && S.ui.redraw) S.ui.redraw(); }
|
|
928
|
+
}
|
|
929
|
+
async function loadModels(S) {
|
|
930
|
+
try { S.models = await fetchModels(S); S.modelInfo = {}; for (const m of S.models) S.modelInfo[m.id] = m; } catch (_) {}
|
|
931
|
+
if (S.ui && S.ui.redraw) S.ui.redraw();
|
|
932
|
+
}
|
|
933
|
+
const modelCost = (S) => { const m = S.modelInfo && S.modelInfo[S.model]; return m && m.credit_cost != null ? Number(m.credit_cost) : 0; };
|
|
934
|
+
|
|
935
|
+
// ---------------------------------------------------------------- browser sign-in (device flow)
|
|
936
|
+
function openBrowser(url) {
|
|
937
|
+
try {
|
|
938
|
+
let c, args;
|
|
939
|
+
if (IS_WIN) { c = 'rundll32'; args = ['url.dll,FileProtocolHandler', url]; }
|
|
940
|
+
else if (process.platform === 'darwin') { c = 'open'; args = [url]; }
|
|
941
|
+
else if (process.env.PREFIX && /termux/.test(process.env.PREFIX)) { c = 'termux-open-url'; args = [url]; }
|
|
942
|
+
else if (fs.existsSync('/proc/version') && /microsoft/i.test(fs.readFileSync('/proc/version', 'utf8'))) { c = 'cmd.exe'; args = ['/c', 'start', '', url.replace(/&/g, '^&')]; }
|
|
943
|
+
else { c = 'xdg-open'; args = [url]; }
|
|
944
|
+
const ch = cp.spawn(c, args, { detached: true, stdio: 'ignore' });
|
|
945
|
+
ch.on('error', () => {}); ch.unref();
|
|
946
|
+
return true;
|
|
947
|
+
} catch (_) { return false; }
|
|
948
|
+
}
|
|
949
|
+
// hooks: { show({url, code, uri}), cancelled(): bool }
|
|
950
|
+
async function deviceLogin(cfg, hooks) {
|
|
951
|
+
const r = await fetch(cfg.baseUrl + '/v2/device/code', {
|
|
952
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'benchcode/' + VERSION },
|
|
953
|
+
body: JSON.stringify({ client: 'benchcode', label: os.hostname().slice(0, 40), platform: process.platform + '/' + os.arch() }),
|
|
954
|
+
});
|
|
955
|
+
const j = await r.json().catch(() => ({}));
|
|
956
|
+
if (!r.ok || !j.device_code) throw new Error((j.error && (j.error.message || j.error)) || 'Could not start sign-in (HTTP ' + r.status + ')');
|
|
957
|
+
const opened = openBrowser(j.verification_uri_complete);
|
|
958
|
+
hooks.show({ url: j.verification_uri_complete, code: j.user_code, uri: j.verification_uri, opened });
|
|
959
|
+
let interval = Math.max(2, j.interval || 2) * 1000;
|
|
960
|
+
const deadline = Date.now() + (j.expires_in || 600) * 1000;
|
|
961
|
+
while (Date.now() < deadline) {
|
|
962
|
+
await sleep(interval);
|
|
963
|
+
if (hooks.cancelled()) throw new Error('cancelled');
|
|
964
|
+
let p, pj;
|
|
965
|
+
try {
|
|
966
|
+
p = await fetch(cfg.baseUrl + '/v2/device/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ device_code: j.device_code }) });
|
|
967
|
+
pj = await p.json().catch(() => ({}));
|
|
968
|
+
} catch (_) { continue; }
|
|
969
|
+
if (p.ok && pj.api_key) return pj;
|
|
970
|
+
if (p.status === 429 || p.status >= 500) continue;
|
|
971
|
+
const code = pj.error && (pj.error.code || pj.error.type || pj.error);
|
|
972
|
+
if (code === 'authorization_pending') continue;
|
|
973
|
+
if (code === 'slow_down') { interval += 3000; continue; }
|
|
974
|
+
if (code === 'access_denied') throw new Error('Sign-in was denied in the browser.');
|
|
975
|
+
if (code === 'expired_token') throw new Error('The sign-in code expired. Try again.');
|
|
976
|
+
throw new Error(String((pj.error && pj.error.message) || pj.error_description || pj.error || 'Sign-in failed (HTTP ' + p.status + ')'));
|
|
977
|
+
}
|
|
978
|
+
throw new Error('Sign-in timed out. Try again.');
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// ---------------------------------------------------------------- model request / stream
|
|
982
|
+
function textToolPrompt(S) {
|
|
983
|
+
const docs = toolsFor(S).map((t) => `- ${t.name}: ${t.description}\n parameters (JSON schema): ${JSON.stringify(t.parameters)}`).join('\n');
|
|
984
|
+
return `\n\n# Tool calling format
|
|
985
|
+
You can call tools. To call one, write exactly this on its own (you may call several in a row):
|
|
986
|
+
<tool_call>{"name": "TOOL_NAME", "arguments": {"param": "value"}}</tool_call>
|
|
987
|
+
Then stop writing and wait. The results come back in the next message inside <tool_result> tags.
|
|
988
|
+
Never invent tool results.
|
|
989
|
+
|
|
990
|
+
# Tools
|
|
991
|
+
${docs}`;
|
|
992
|
+
}
|
|
993
|
+
const safeParse = (s) => { try { return JSON.parse(s || '{}'); } catch (_) { return {}; } };
|
|
994
|
+
const isJson = (s) => { try { JSON.parse(s); return true; } catch (_) { return false; } };
|
|
995
|
+
function buildMessages(S) {
|
|
996
|
+
const sys = { role: 'system', content: buildSystem(S) + (S.textMode && !S._noTools ? textToolPrompt(S) : '') };
|
|
997
|
+
const msgs = [];
|
|
998
|
+
for (const m of S.messages) {
|
|
999
|
+
if (S.textMode) {
|
|
1000
|
+
if (m.role === 'assistant' && m.tool_calls) {
|
|
1001
|
+
const calls = m.tool_calls.map((c) => `<tool_call>${JSON.stringify({ name: c.function.name, arguments: safeParse(c.function.arguments) })}</tool_call>`).join('\n');
|
|
1002
|
+
msgs.push({ role: 'assistant', content: ((m.content || '') + '\n' + calls).trim() });
|
|
1003
|
+
} else if (m.role === 'tool') msgs.push({ role: 'user', content: `<tool_result name="${m.name || ''}">\n${m.content}\n</tool_result>` });
|
|
1004
|
+
else msgs.push({ role: m.role, content: m.content });
|
|
1005
|
+
} else {
|
|
1006
|
+
const c = Object.assign({}, m);
|
|
1007
|
+
delete c.name;
|
|
1008
|
+
if (!(S.sendReasoning && c.tool_calls)) delete c.reasoning_content;
|
|
1009
|
+
msgs.push(c);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return [sys, ...msgs];
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// hides <think>…</think> and <tool_call>…</tool_call> from the visible stream
|
|
1016
|
+
class StreamFilter {
|
|
1017
|
+
constructor(onText, onThink) { this.buf = ''; this.mode = 'text'; this.onText = onText; this.onThink = onThink; }
|
|
1018
|
+
push(s) { this.buf += s; this.drain(false); }
|
|
1019
|
+
end() { this.drain(true); }
|
|
1020
|
+
drain(final) {
|
|
1021
|
+
const TAGS = ['<think>', '<tool_call>'];
|
|
1022
|
+
for (;;) {
|
|
1023
|
+
if (this.mode === 'text') {
|
|
1024
|
+
let at = -1, tag = '';
|
|
1025
|
+
for (const t of TAGS) { const i = this.buf.indexOf(t); if (i >= 0 && (at < 0 || i < at)) { at = i; tag = t; } }
|
|
1026
|
+
if (at >= 0) {
|
|
1027
|
+
if (at > 0) this.onText(this.buf.slice(0, at));
|
|
1028
|
+
this.buf = this.buf.slice(at + tag.length);
|
|
1029
|
+
this.mode = tag === '<think>' ? 'think' : 'tool';
|
|
1030
|
+
continue;
|
|
1031
|
+
}
|
|
1032
|
+
let keep = 0;
|
|
1033
|
+
if (!final) for (const t of TAGS) for (let k = Math.min(t.length - 1, this.buf.length); k > keep; k--) if (this.buf.endsWith(t.slice(0, k))) { keep = k; break; }
|
|
1034
|
+
const emit = this.buf.slice(0, this.buf.length - keep);
|
|
1035
|
+
if (emit) this.onText(emit);
|
|
1036
|
+
this.buf = this.buf.slice(emit.length);
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
const closer = this.mode === 'think' ? '</think>' : '</tool_call>';
|
|
1040
|
+
const j = this.buf.indexOf(closer);
|
|
1041
|
+
if (j >= 0) {
|
|
1042
|
+
if (this.mode === 'think' && j > 0) this.onThink(this.buf.slice(0, j));
|
|
1043
|
+
this.buf = this.buf.slice(j + closer.length); this.mode = 'text'; continue;
|
|
1044
|
+
}
|
|
1045
|
+
let keep = 0;
|
|
1046
|
+
for (let k = Math.min(closer.length - 1, this.buf.length); k > 0; k--) if (this.buf.endsWith(closer.slice(0, k))) { keep = k; break; }
|
|
1047
|
+
const body = this.buf.slice(0, this.buf.length - keep);
|
|
1048
|
+
if (this.mode === 'think' && body) this.onThink(body);
|
|
1049
|
+
this.buf = this.buf.slice(body.length);
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
function extractTextToolCalls(content) {
|
|
1055
|
+
const calls = [];
|
|
1056
|
+
const re = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
|
|
1057
|
+
let m;
|
|
1058
|
+
while ((m = re.exec(content))) {
|
|
1059
|
+
try {
|
|
1060
|
+
const j = JSON.parse(m[1]);
|
|
1061
|
+
const name = j.name || (j.function && j.function.name);
|
|
1062
|
+
const args = j.arguments !== undefined ? j.arguments : j.parameters !== undefined ? j.parameters : j.function && j.function.arguments;
|
|
1063
|
+
if (name) calls.push({ id: 'call_' + crypto.randomBytes(6).toString('hex'), name, arguments: typeof args === 'string' ? args : JSON.stringify(args || {}) });
|
|
1064
|
+
} catch (_) {}
|
|
1065
|
+
}
|
|
1066
|
+
return calls;
|
|
1067
|
+
}
|
|
1068
|
+
const stripThink = (s) => s.replace(/<think>[\s\S]*?<\/think>/g, '').replace(/<think>[\s\S]*$/, '');
|
|
1069
|
+
|
|
1070
|
+
async function callModel(S) {
|
|
1071
|
+
const ui = S.ui;
|
|
1072
|
+
const ctl = new AbortController();
|
|
1073
|
+
let aborted = false;
|
|
1074
|
+
S.setCancel(() => { aborted = true; ctl.abort(); });
|
|
1075
|
+
const flagged = { reasoning: false, tools: false, usage: false };
|
|
1076
|
+
const url = S.baseUrl + '/v1/chat/completions';
|
|
1077
|
+
let attempt = 0, res;
|
|
1078
|
+
try {
|
|
1079
|
+
for (;;) {
|
|
1080
|
+
const body = { model: S.model, messages: buildMessages(S), stream: true };
|
|
1081
|
+
if (!S.noUsage) body.stream_options = { include_usage: true };
|
|
1082
|
+
if (!S.textMode && !S._noTools) { body.tools = toolsFor(S).map((t) => ({ type: 'function', function: t })); body.tool_choice = 'auto'; }
|
|
1083
|
+
ui.status('Thinking');
|
|
1084
|
+
try {
|
|
1085
|
+
res = await fetch(url, { method: 'POST', signal: ctl.signal, headers: Object.assign({ 'Content-Type': 'application/json' }, hdrs(S.apiKey)), body: JSON.stringify(body) });
|
|
1086
|
+
} catch (e) {
|
|
1087
|
+
if (aborted) return { aborted: true };
|
|
1088
|
+
if (attempt++ < 3) { ui.notice(`network problem (${e.cause && e.cause.code || e.message}), retrying…`); await sleep(1500 * attempt, ctl.signal); if (aborted) return { aborted: true }; continue; }
|
|
1089
|
+
throw new ApiError(0, `Could not reach ${S.baseUrl}: ${e.cause && e.cause.code || e.message}`);
|
|
1090
|
+
}
|
|
1091
|
+
if (res.ok) break;
|
|
1092
|
+
const text = await res.text();
|
|
1093
|
+
const msg = String(parseErrBody(text));
|
|
1094
|
+
if (res.status === 400 && !S.noUsage && !flagged.usage && /stream_options|include_usage/i.test(msg)) { flagged.usage = true; S.noUsage = true; continue; }
|
|
1095
|
+
if (res.status === 400 && !S.textMode && !flagged.tools && /tool|function/i.test(msg) && !/reasoning/i.test(msg)) { flagged.tools = true; S.textMode = true; ui.notice('this model has no native tool calling, using text mode'); continue; }
|
|
1096
|
+
if (res.status === 400 && /reasoning/i.test(msg) && !flagged.reasoning) { flagged.reasoning = true; S.sendReasoning = !S.sendReasoning; continue; }
|
|
1097
|
+
if ([429, 502, 503, 504].includes(res.status) && attempt < 4 && !/quota|disabled/i.test(msg)) {
|
|
1098
|
+
const wait = Math.min(30, parseFloat(res.headers.get('retry-after')) || 4 * 2 ** attempt);
|
|
1099
|
+
attempt++;
|
|
1100
|
+
ui.notice(`${res.status === 429 ? 'rate limited' : 'service busy'}, retrying in ${wait}s…`);
|
|
1101
|
+
await sleep(wait * 1000, ctl.signal);
|
|
1102
|
+
if (aborted) return { aborted: true };
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
throw new ApiError(res.status, msg);
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
let content = '', reasoning = '', finish = '', usage = null;
|
|
1109
|
+
const calls = [];
|
|
1110
|
+
const filter = new StreamFilter((t) => { ui.status(null); ui.text(t); }, (t) => ui.think(t));
|
|
1111
|
+
const handle = (j) => {
|
|
1112
|
+
if (j.error) throw new ApiError(j.error.code || 500, String(j.error.message || JSON.stringify(j.error)));
|
|
1113
|
+
if (j.usage) usage = j.usage;
|
|
1114
|
+
const ch = j.choices && j.choices[0];
|
|
1115
|
+
if (!ch) return;
|
|
1116
|
+
const d = ch.delta || ch.message || {};
|
|
1117
|
+
if (typeof d.content === 'string' && d.content) { content += d.content; filter.push(d.content); }
|
|
1118
|
+
const r = d.reasoning_content || d.reasoning;
|
|
1119
|
+
if (typeof r === 'string' && r) { reasoning += r; ui.think(r); }
|
|
1120
|
+
if (Array.isArray(d.tool_calls)) {
|
|
1121
|
+
for (const tc of d.tool_calls) {
|
|
1122
|
+
let idx = tc.index;
|
|
1123
|
+
if (idx === undefined || idx === null) idx = tc.id ? calls.length : Math.max(0, calls.length - 1);
|
|
1124
|
+
if (!calls[idx]) calls[idx] = { id: '', name: '', arguments: '' };
|
|
1125
|
+
const c = calls[idx];
|
|
1126
|
+
if (tc.id && !c.id) c.id = tc.id;
|
|
1127
|
+
if (tc.function) {
|
|
1128
|
+
if (tc.function.name && !c.name) { c.name = tc.function.name; ui.status('Preparing ' + c.name); }
|
|
1129
|
+
if (typeof tc.function.arguments === 'string') c.arguments += tc.function.arguments;
|
|
1130
|
+
else if (tc.function.arguments && typeof tc.function.arguments === 'object') c.arguments = JSON.stringify(tc.function.arguments);
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
if (ch.finish_reason) finish = ch.finish_reason;
|
|
1135
|
+
};
|
|
1136
|
+
const ctype = res.headers.get('content-type') || '';
|
|
1137
|
+
if (/json/.test(ctype) && !/event-stream/.test(ctype)) handle(JSON.parse(await res.text()));
|
|
1138
|
+
else {
|
|
1139
|
+
const reader = res.body.getReader();
|
|
1140
|
+
const dec = new TextDecoder();
|
|
1141
|
+
let buf = '';
|
|
1142
|
+
for (;;) {
|
|
1143
|
+
const { done, value } = await reader.read();
|
|
1144
|
+
if (done) break;
|
|
1145
|
+
buf += dec.decode(value, { stream: true });
|
|
1146
|
+
let nl;
|
|
1147
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
1148
|
+
const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1);
|
|
1149
|
+
if (!line.startsWith('data:')) continue;
|
|
1150
|
+
const data = line.slice(5).trim();
|
|
1151
|
+
if (!data || data === '[DONE]') continue;
|
|
1152
|
+
let j; try { j = JSON.parse(data); } catch (_) { continue; }
|
|
1153
|
+
handle(j);
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
filter.end();
|
|
1158
|
+
ui.status(null);
|
|
1159
|
+
let toolCalls = calls.filter((c) => c && c.name);
|
|
1160
|
+
if (!toolCalls.length) { const fb = extractTextToolCalls(content); if (fb.length) toolCalls = fb; }
|
|
1161
|
+
toolCalls.forEach((c) => { if (!c.id) c.id = 'call_' + crypto.randomBytes(6).toString('hex'); });
|
|
1162
|
+
return { content: stripThink(content).trim(), reasoning, toolCalls, finish, usage };
|
|
1163
|
+
} catch (e) {
|
|
1164
|
+
ui.status(null);
|
|
1165
|
+
if (aborted || e.name === 'AbortError') return { aborted: true };
|
|
1166
|
+
throw e;
|
|
1167
|
+
} finally { S.setCancel(null); }
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// ---------------------------------------------------------------- system prompt
|
|
1171
|
+
function gitInfo(cwd) {
|
|
1172
|
+
try {
|
|
1173
|
+
const run = (a) => cp.execFileSync('git', a, { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 2500 }).toString().trim();
|
|
1174
|
+
const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
1175
|
+
const status = run(['status', '--short']).split('\n').filter(Boolean);
|
|
1176
|
+
return { branch, line: `Git repository: yes, branch "${branch}", ${status.length ? status.length + ' changed file(s)' : 'clean'}` };
|
|
1177
|
+
} catch (_) { return { branch: '', line: 'Git repository: no' }; }
|
|
1178
|
+
}
|
|
1179
|
+
function projectNotes(cwd) {
|
|
1180
|
+
const parts = [];
|
|
1181
|
+
for (const dir of [HOME_DIR, cwd]) {
|
|
1182
|
+
for (const f of ['BENCHCODE.md', 'AGENTS.md', 'CLAUDE.md']) {
|
|
1183
|
+
const p = path.join(dir, f);
|
|
1184
|
+
try { if (fs.existsSync(p)) { parts.push(`## ${dir === cwd ? 'Project' : 'User'} notes (${f})\n` + fs.readFileSync(p, 'utf8').slice(0, 8000)); break; } } catch (_) {}
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return parts.join('\n\n');
|
|
1188
|
+
}
|
|
1189
|
+
function osName() {
|
|
1190
|
+
if (process.env.PREFIX && /termux/.test(process.env.PREFIX)) return 'Android (Termux)';
|
|
1191
|
+
return { win32: 'Windows', darwin: 'macOS', linux: 'Linux', android: 'Android (Termux)', freebsd: 'FreeBSD' }[process.platform] || process.platform;
|
|
1192
|
+
}
|
|
1193
|
+
function buildSystem(S) {
|
|
1194
|
+
if (!S._sysBase) S._sysBase = { git: gitInfo(S.cwd).line, notes: projectNotes(S.cwd) };
|
|
1195
|
+
const plan = S.agent === 'plan';
|
|
1196
|
+
return `You are BenchCode, an expert AI coding agent running in the user's terminal. You help with software engineering: writing, reading, debugging, refactoring and running code, and general work on the user's machine.
|
|
1197
|
+
${plan ? '\n# PLAN MODE (read-only)\nYou may only read, search and browse. You cannot change files or run commands. Investigate the project, then give the user a clear, concrete step-by-step plan (files to touch, what to change, how to verify). Do not claim to have changed anything. When the plan is ready, tell the user to press Tab to switch to Build mode.\n' : ''}
|
|
1198
|
+
# Environment
|
|
1199
|
+
- Working directory: ${S.cwd}
|
|
1200
|
+
- OS: ${osName()} (${os.arch()}), Node ${process.version}
|
|
1201
|
+
- Shell used by run_command: ${SHELL.name}
|
|
1202
|
+
- ${S._sysBase.git}
|
|
1203
|
+
- Today: ${new Date().toISOString().slice(0, 10)}
|
|
1204
|
+
|
|
1205
|
+
# How to work
|
|
1206
|
+
- Understand before changing: explore with list_dir, find_files, search and read_file. Never guess file contents.
|
|
1207
|
+
- For tasks with several steps, keep a todo list with todo_write and update it as you go.
|
|
1208
|
+
- Make small, targeted edits with edit_file (or multi_edit for several in one file). Use write_file for new files or full rewrites.
|
|
1209
|
+
- After changing code, verify it: run the tests, the build, or the program with run_command, and fix what fails.
|
|
1210
|
+
- Use commands that work on this OS and shell. Do not run commands that wait for input or never exit; use run_background for servers.
|
|
1211
|
+
- Use ask_user only when a wrong guess would be costly. Otherwise proceed.
|
|
1212
|
+
- Stay inside the working directory unless asked otherwise. Never run destructive commands (rm -rf, git reset --hard, force pushes, dropping data) unless the user clearly asked.
|
|
1213
|
+
- Never print or commit secrets such as API keys and passwords.
|
|
1214
|
+
- Reply in Markdown. Be concise: do the work, then summarize what changed and what the user must do next. Use code fences only for code. Answer in the user's language.
|
|
1215
|
+
${S._sysBase.notes ? '\n# Notes from the user\n' + S._sysBase.notes : ''}`;
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// ---------------------------------------------------------------- agent loop
|
|
1219
|
+
function estimateTokens(S) {
|
|
1220
|
+
let n = buildSystem(S).length;
|
|
1221
|
+
for (const m of S.messages) n += (m.content ? m.content.length : 0) + (m.tool_calls ? JSON.stringify(m.tool_calls).length : 0);
|
|
1222
|
+
return Math.round(n / 3.6);
|
|
1223
|
+
}
|
|
1224
|
+
function trimContext(S) {
|
|
1225
|
+
const LIMIT = 360000;
|
|
1226
|
+
const size = () => S.messages.reduce((n, m) => n + (m.content ? m.content.length : 0) + (m.tool_calls ? JSON.stringify(m.tool_calls).length : 0), 0);
|
|
1227
|
+
if (size() < LIMIT) return;
|
|
1228
|
+
for (const m of S.messages.slice(0, -6)) {
|
|
1229
|
+
if (m.role === 'tool' && m.content.length > 600) { m.content = m.content.slice(0, 400) + '\n… [old output removed to save context]'; if (size() < LIMIT * 0.8) break; }
|
|
1230
|
+
}
|
|
1231
|
+
if (size() >= LIMIT) S.ui.notice('context is getting large, run /compact to summarize the conversation');
|
|
1232
|
+
}
|
|
1233
|
+
function apiErrorText(e) {
|
|
1234
|
+
const st = e.status;
|
|
1235
|
+
if (st === 401) return 'Invalid or missing API key. Sign in again with /login.';
|
|
1236
|
+
if (st === 402) return String(e.message) + ' (ctrl+p → Buy credits)';
|
|
1237
|
+
if (st === 429) return 'Rate limit reached: ' + e.message + ' (free accounts allow about 15 requests/min, each agent step is one request)';
|
|
1238
|
+
return String(e.message || e);
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
async function agentTurn(S, userText) {
|
|
1242
|
+
const ui = S.ui;
|
|
1243
|
+
S.interrupted = false; S.running = true;
|
|
1244
|
+
try {
|
|
1245
|
+
if (userText !== null) {
|
|
1246
|
+
S.messages.push({ role: 'user', content: userText });
|
|
1247
|
+
ui.userMessage(userText, { msgIndex: S.messages.length - 1, snapIndex: S.snapshots.length });
|
|
1248
|
+
if (!S.title) S.title = clip(userText.split('\n')[0].trim(), 48);
|
|
1249
|
+
}
|
|
1250
|
+
for (let step = 0; step < S.maxSteps; step++) {
|
|
1251
|
+
trimContext(S);
|
|
1252
|
+
ui.assistantStart();
|
|
1253
|
+
let r;
|
|
1254
|
+
try { r = await callModel(S); }
|
|
1255
|
+
catch (e) { ui.assistantEnd({ error: true }); ui.error(apiErrorText(e)); return false; }
|
|
1256
|
+
if (r.aborted) { ui.assistantEnd({ interrupted: true }); return false; }
|
|
1257
|
+
if (r.usage && (r.usage.prompt_tokens || r.usage.total_tokens)) S.ctxTokens = (r.usage.prompt_tokens || 0) + (r.usage.completion_tokens || 0);
|
|
1258
|
+
else S.ctxTokens = estimateTokens(S);
|
|
1259
|
+
S.spent += modelCost(S); S.calls++;
|
|
1260
|
+
ui.assistantEnd({ text: r.content });
|
|
1261
|
+
if (S.ui.afterCall) S.ui.afterCall();
|
|
1262
|
+
const am = { role: 'assistant', content: r.content || '' };
|
|
1263
|
+
if (r.toolCalls.length) {
|
|
1264
|
+
am.tool_calls = r.toolCalls.map((c) => ({ id: c.id, type: 'function', function: { name: c.name, arguments: c.arguments && isJson(c.arguments) ? c.arguments : '{}' } }));
|
|
1265
|
+
if (r.reasoning) am.reasoning_content = r.reasoning;
|
|
1266
|
+
}
|
|
1267
|
+
if (!r.content && !r.toolCalls.length) {
|
|
1268
|
+
ui.error(r.finish === 'length' ? 'The model ran out of output tokens before answering. Try again or switch model.' : 'The model returned an empty reply. Try /retry or another model.');
|
|
1269
|
+
return false;
|
|
1270
|
+
}
|
|
1271
|
+
S.messages.push(am);
|
|
1272
|
+
if (!r.toolCalls.length) return true;
|
|
1273
|
+
for (const c of r.toolCalls) {
|
|
1274
|
+
let text;
|
|
1275
|
+
if (S.interrupted) { text = 'Skipped: the user interrupted.'; }
|
|
1276
|
+
else text = (await execTool(S, c)).text;
|
|
1277
|
+
S.messages.push({ role: 'tool', tool_call_id: c.id, name: c.name, content: text });
|
|
1278
|
+
}
|
|
1279
|
+
if (S.interrupted) { ui.notice('stopped'); return false; }
|
|
1280
|
+
}
|
|
1281
|
+
ui.notice(`Stopped after ${S.maxSteps} steps. Type "continue" to keep going.`);
|
|
1282
|
+
return true;
|
|
1283
|
+
} finally { S.running = false; S.ui.turnEnd && S.ui.turnEnd(); }
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
async function compactSession(S) {
|
|
1287
|
+
if (S.messages.length < 4) { S.ui.notice('Nothing to compact yet.'); return false; }
|
|
1288
|
+
const saved = S.messages, savedMode = S.textMode;
|
|
1289
|
+
S.messages = saved.concat([{ role: 'user', content: 'Summarize this whole conversation so a fresh session can continue the work: the goal, decisions made, files created or changed, commands that matter, what is done and what is still open. Be specific and brief. Do not call tools.' }]);
|
|
1290
|
+
S.textMode = true; S._noTools = true;
|
|
1291
|
+
let r;
|
|
1292
|
+
try { S.ui.assistantStart(); r = await callModel(S); S.ui.assistantEnd({ text: '' }); }
|
|
1293
|
+
catch (e) { S.messages = saved; S.textMode = savedMode; S._noTools = false; S.ui.assistantEnd({ error: true }); S.ui.error(apiErrorText(e)); return false; }
|
|
1294
|
+
S.textMode = savedMode; S._noTools = false;
|
|
1295
|
+
if (r.aborted || !r.content) { S.messages = saved; return false; }
|
|
1296
|
+
S.messages = [{ role: 'user', content: 'Summary of our work so far:\n' + r.content }, { role: 'assistant', content: 'Understood. I have the context and will continue from there.' }];
|
|
1297
|
+
S.snapshots = []; S.blocks.forEach((bl) => { bl.stale = true; }); S.ctxTokens = estimateTokens(S);
|
|
1298
|
+
S.ui.notice('Conversation compacted.');
|
|
1299
|
+
return true;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
// ---------------------------------------------------------------- sessions
|
|
1303
|
+
function newSession(cfg, opts) {
|
|
1304
|
+
const S = {
|
|
1305
|
+
id: Date.now().toString(36) + crypto.randomBytes(2).toString('hex'), title: '',
|
|
1306
|
+
cwd: opts.cwd, baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, model: opts.model || cfg.model, agent: opts.agent || cfg.agent || 'build',
|
|
1307
|
+
auto: !!opts.yes, always: new Set(), changed: new Map(), todos: [], snapshots: [], messages: [], blocks: [],
|
|
1308
|
+
textMode: false, sendReasoning: true, noUsage: false, maxSteps: opts.maxSteps || 40, interrupted: false, running: false, ui: null,
|
|
1309
|
+
account: null, models: [], modelInfo: {}, ctxTokens: 0, spent: 0, calls: 0, created: Date.now(), updated: Date.now(),
|
|
1310
|
+
showThinking: !!cfg.showThinking, _cancel: null, _sysBase: null, git: '',
|
|
1311
|
+
};
|
|
1312
|
+
S.setCancel = (fn) => { S._cancel = fn; };
|
|
1313
|
+
S.abort = () => { S.interrupted = true; const f = S._cancel; S._cancel = null; if (f) f(); };
|
|
1314
|
+
S.git = gitInfo(S.cwd).branch;
|
|
1315
|
+
return S;
|
|
1316
|
+
}
|
|
1317
|
+
const sessionFile = (id) => path.join(SESSIONS_DIR, id + '.json');
|
|
1318
|
+
function saveSession(S) {
|
|
1319
|
+
if (!S.messages.length) return;
|
|
1320
|
+
try {
|
|
1321
|
+
S.updated = Date.now();
|
|
1322
|
+
const blocks = S.blocks.map((b) => (b.type === 'tool' ? Object.assign({}, b, { output: (b.output || []).slice(-40) }) : b));
|
|
1323
|
+
writeJson(sessionFile(S.id), { id: S.id, title: S.title, cwd: S.cwd, model: S.model, agent: S.agent, created: S.created, updated: S.updated, spent: S.spent, calls: S.calls, ctxTokens: S.ctxTokens, todos: S.todos, messages: S.messages, blocks }, true);
|
|
1324
|
+
} catch (_) {}
|
|
1325
|
+
}
|
|
1326
|
+
function listSessions(limit = 60) {
|
|
1327
|
+
let files = [];
|
|
1328
|
+
try { files = fs.readdirSync(SESSIONS_DIR).filter((f) => f.endsWith('.json')).map((f) => ({ f, t: fs.statSync(path.join(SESSIONS_DIR, f)).mtimeMs })); } catch (_) { return []; }
|
|
1329
|
+
files.sort((a, b) => b.t - a.t);
|
|
1330
|
+
const out_ = [];
|
|
1331
|
+
for (const { f } of files.slice(0, limit)) {
|
|
1332
|
+
const j = readJson(path.join(SESSIONS_DIR, f), null);
|
|
1333
|
+
if (j && j.id) out_.push({ id: j.id, title: j.title || '(untitled)', cwd: j.cwd, updated: j.updated || 0, model: j.model, turns: (j.blocks || []).filter((b) => b.type === 'user').length });
|
|
1334
|
+
}
|
|
1335
|
+
return out_;
|
|
1336
|
+
}
|
|
1337
|
+
function loadSessionInto(S, id) {
|
|
1338
|
+
const j = readJson(sessionFile(id), null);
|
|
1339
|
+
if (!j) return false;
|
|
1340
|
+
S.id = j.id; S.title = j.title || ''; S.messages = j.messages || []; S.blocks = (j.blocks || []).map((b) => Object.assign(b, { running: false, stale: b.stale }));
|
|
1341
|
+
S.model = j.model || S.model; S.agent = j.agent || S.agent; S.spent = j.spent || 0; S.calls = j.calls || 0; S.todos = j.todos || []; S.ctxTokens = j.ctxTokens || 0;
|
|
1342
|
+
S.created = j.created || Date.now(); S.snapshots = []; S.changed = new Map(); S.always = new Set(); S.textMode = false;
|
|
1343
|
+
S.blocks.forEach((b) => { if (b.type === 'user') { b.snapIndex = 0; b.noFiles = true; } if (b.type === 'tool' && b.status === 'running') b.status = 'done'; });
|
|
1344
|
+
return true;
|
|
1345
|
+
}
|
|
1346
|
+
// undo this message and everything after it, including file changes. Returns the message text.
|
|
1347
|
+
function revertTo(S, blockIdx) {
|
|
1348
|
+
const b = S.blocks[blockIdx];
|
|
1349
|
+
if (!b || b.type !== 'user' || b.stale) return null;
|
|
1350
|
+
let restored = 0, failed = 0;
|
|
1351
|
+
if (!b.noFiles) {
|
|
1352
|
+
for (let i = S.snapshots.length - 1; i >= (b.snapIndex || 0); i--) {
|
|
1353
|
+
const s = S.snapshots[i];
|
|
1354
|
+
try {
|
|
1355
|
+
if (s.before === null) { if (fs.existsSync(s.path)) fs.rmSync(s.path, { force: true }); }
|
|
1356
|
+
else { fs.mkdirSync(path.dirname(s.path), { recursive: true }); fs.writeFileSync(s.path, s.before); }
|
|
1357
|
+
restored++;
|
|
1358
|
+
} catch (_) { failed++; }
|
|
1359
|
+
}
|
|
1360
|
+
S.snapshots.length = b.snapIndex || 0;
|
|
1361
|
+
}
|
|
1362
|
+
S.messages.length = b.msgIndex;
|
|
1363
|
+
S.blocks.length = blockIdx;
|
|
1364
|
+
S.changed = new Map();
|
|
1365
|
+
for (const s of S.snapshots) S.changed.set(rel(S, s.path), 'M');
|
|
1366
|
+
S.ctxTokens = estimateTokens(S);
|
|
1367
|
+
return { text: b.text, restored, failed };
|
|
1368
|
+
}
|
|
1369
|
+
function forkFrom(S, blockIdx) {
|
|
1370
|
+
const b = S.blocks[blockIdx];
|
|
1371
|
+
if (!b || b.type !== 'user' || b.stale) return null;
|
|
1372
|
+
const F = Object.assign({}, S);
|
|
1373
|
+
F.id = Date.now().toString(36) + crypto.randomBytes(2).toString('hex');
|
|
1374
|
+
F.messages = S.messages.slice(0, b.msgIndex).map((m) => Object.assign({}, m));
|
|
1375
|
+
F.blocks = S.blocks.slice(0, blockIdx).map((x) => Object.assign({}, x));
|
|
1376
|
+
F.snapshots = []; F.changed = new Map(); F.always = new Set(S.always); F.todos = []; F.created = Date.now(); F.spent = 0; F.calls = 0;
|
|
1377
|
+
F.title = (S.title ? S.title + ' (fork)' : '');
|
|
1378
|
+
F.blocks.forEach((x) => { if (x.type === 'user') x.noFiles = true; });
|
|
1379
|
+
F.setCancel = (fn) => { F._cancel = fn; };
|
|
1380
|
+
F.abort = () => { F.interrupted = true; const f = F._cancel; F._cancel = null; if (f) f(); };
|
|
1381
|
+
F._cancel = null; F.ctxTokens = estimateTokens(F);
|
|
1382
|
+
return { session: F, text: b.text };
|
|
1383
|
+
}
|
|
1384
|
+
function copyToClipboard(text) {
|
|
1385
|
+
try { if (process.stdout.isTTY) process.stdout.write('\x1b]52;c;' + Buffer.from(text, 'utf8').toString('base64') + '\x07'); } catch (_) {}
|
|
1386
|
+
const tries = IS_WIN ? [['clip', []]] : process.platform === 'darwin' ? [['pbcopy', []]] : [['wl-copy', []], ['xclip', ['-selection', 'clipboard']], ['xsel', ['-b', '-i']], ['termux-clipboard-set', []]];
|
|
1387
|
+
for (const [c, a] of tries) {
|
|
1388
|
+
try { const r = cp.spawnSync(c, a, { input: IS_WIN ? Buffer.from(text, 'utf16le') : text, timeout: 3000, stdio: ['pipe', 'ignore', 'ignore'] }); if (!r.error && r.status === 0) return true; } catch (_) {}
|
|
1389
|
+
}
|
|
1390
|
+
return false;
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
// ---------------------------------------------------------------- plain UI (one-shot mode, pipes, CI)
|
|
1394
|
+
function askLine(prompt) {
|
|
1395
|
+
return new Promise((resolve) => {
|
|
1396
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: !!process.stdin.isTTY });
|
|
1397
|
+
let done = false;
|
|
1398
|
+
rl.on('line', (l) => { if (!done) { done = true; rl.close(); resolve(l); } });
|
|
1399
|
+
rl.on('close', () => { if (!done) { done = true; resolve(null); } });
|
|
1400
|
+
rl.on('SIGINT', () => { if (!done) { done = true; rl.close(); resolve(null); } });
|
|
1401
|
+
rl.setPrompt(prompt); rl.prompt();
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
class PlainUI {
|
|
1405
|
+
constructor(S) { this.S = S; this.spin = null; this.gotText = false; this.shown = new Map(); this.t0 = 0; }
|
|
1406
|
+
status(label) {
|
|
1407
|
+
if (!process.stderr.isTTY) return;
|
|
1408
|
+
if (!label) { if (this.spin) { clearInterval(this.spin); this.spin = null; process.stderr.write('\r\x1b[K'); } return; }
|
|
1409
|
+
if (this.spin) { this.label = label; return; }
|
|
1410
|
+
this.label = label; this.t0 = Date.now();
|
|
1411
|
+
const f = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; let i = 0;
|
|
1412
|
+
this.spin = setInterval(() => process.stderr.write(`\r${cyan(f[i++ % f.length])} ${dim(this.label + ' ' + Math.floor((Date.now() - this.t0) / 1000) + 's')}\x1b[K`), 90);
|
|
1413
|
+
}
|
|
1414
|
+
text(t) { this.status(null); this.gotText = true; out(t); }
|
|
1415
|
+
think(t) { if (this.S.showThinking) { this.status(null); process.stderr.write(gray(t)); } }
|
|
1416
|
+
notice(m) { this.status(null); log(dim(' ' + m)); }
|
|
1417
|
+
error(m) { this.status(null); log(red('✖ ' + m)); }
|
|
1418
|
+
userMessage() {}
|
|
1419
|
+
assistantStart() { this.gotText = false; }
|
|
1420
|
+
assistantEnd() { this.status(null); if (this.gotText) out('\n'); }
|
|
1421
|
+
toolStart(c) { this.status(null); this.shown.set(c.id, 0); log(`${cyan('●')} ${bold(c.name)} ${gray(clip(c.summary || '', 110))}`); }
|
|
1422
|
+
toolOutput(id, line) { const n = this.shown.get(id) || 0; this.shown.set(id, n + 1); if (n < 30 && line.trim()) log(gray(' │ ') + dim(clip(line, 200))); else if (n === 30) log(gray(' │ … more output hidden')); }
|
|
1423
|
+
toolEnd(r) { const mark = r.status === 'error' ? red('✖') : r.status === 'denied' ? yellow('⊘') : green('✔'); log(` ${mark} ${gray(r.summary || r.status)}`); }
|
|
1424
|
+
async approve(req) {
|
|
1425
|
+
this.status(null);
|
|
1426
|
+
log(yellow('? ') + bold(req.title));
|
|
1427
|
+
for (const l of req.lines.slice(0, 16)) log(' ' + (l.t === 'add' ? green('+ ' + clip(l.s, 160)) : l.t === 'del' ? red('- ' + clip(l.s, 160)) : l.t === 'cmd' ? bold('$ ' + l.s) : gray(clip(l.s, 160))));
|
|
1428
|
+
if (!process.stdin.isTTY) return { ok: false, note: 'Not allowed: this session is non-interactive. The user must re-run with --yes to allow ' + req.kind + ' actions.' };
|
|
1429
|
+
const a = await askLine(` ${yellow('Allow?')} ${dim('[y]es / [n]o / [a]lways ' + req.kind)} › `);
|
|
1430
|
+
if (a === null) { this.S.abort(); return { ok: false, note: 'User interrupted.' }; }
|
|
1431
|
+
const x = a.trim().toLowerCase();
|
|
1432
|
+
if (x === '' || x === 'y' || x === 'yes') return { ok: true };
|
|
1433
|
+
if (x === 'a' || x === 'always') return { ok: true, always: true };
|
|
1434
|
+
if (x === 'n' || x === 'no') return { ok: false, note: 'The user denied this action. Do not retry the same action; ask what they want instead.' };
|
|
1435
|
+
return { ok: false, note: 'The user denied this action and said: ' + a.trim() };
|
|
1436
|
+
}
|
|
1437
|
+
async askUser(q, options) {
|
|
1438
|
+
this.status(null);
|
|
1439
|
+
log(magenta('? ') + bold(q)); options.forEach((o, i) => log(` ${i + 1}) ${o}`));
|
|
1440
|
+
if (!process.stdin.isTTY) return null;
|
|
1441
|
+
const a = await askLine(' › ');
|
|
1442
|
+
if (a === null) return null;
|
|
1443
|
+
const n = parseInt(a, 10);
|
|
1444
|
+
return n >= 1 && n <= options.length ? options[n - 1] : a;
|
|
1445
|
+
}
|
|
1446
|
+
redraw() {}
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
// ================================================================ FULL-SCREEN TUI
|
|
1450
|
+
const GLYPHS = {
|
|
1451
|
+
b: ['# ', '### ', '# #', '# #', '### '], e: [' ## ', '# #', '####', '# ', ' ###'], n: ['### ', '# #', '# #', '# #', '# #'],
|
|
1452
|
+
c: [' ###', '# ', '# ', '# ', ' ###'], h: ['# ', '### ', '# #', '# #', '# #'], o: [' ## ', '# #', '# #', '# #', ' ## '], d: [' #', ' ###', '# #', '# #', ' ###'],
|
|
1453
|
+
};
|
|
1454
|
+
function renderLogo(cols) {
|
|
1455
|
+
const px = cols >= 110 ? 2 : 1, gap = px === 2 ? 2 : 1;
|
|
1456
|
+
const word = 'benchcode', rows_ = [];
|
|
1457
|
+
for (let r = 0; r < 5; r++) {
|
|
1458
|
+
let line = '';
|
|
1459
|
+
for (let li = 0; li < word.length; li++) {
|
|
1460
|
+
const g = GLYPHS[word[li]][r], col = li < 5 ? '#767676' : '#f2f2f2';
|
|
1461
|
+
let seg = '';
|
|
1462
|
+
for (const ch of g) seg += ch === '#' ? '█'.repeat(px) : ' '.repeat(px);
|
|
1463
|
+
line += sty(seg, { fg: col }) + ' '.repeat(gap);
|
|
1464
|
+
}
|
|
1465
|
+
rows_.push(line.trimEnd());
|
|
1466
|
+
}
|
|
1467
|
+
return rows_;
|
|
1468
|
+
}
|
|
1469
|
+
const fmtDur = (sec) => {
|
|
1470
|
+
sec = Math.max(0, Math.floor(sec));
|
|
1471
|
+
const d = Math.floor(sec / 86400), h = Math.floor((sec % 86400) / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60;
|
|
1472
|
+
if (d) return `${d}d ${h}h`; if (h) return `${h}h ${m}m`; if (m) return `${m}m${m < 5 ? ' ' + s + 's' : ''}`; return `${s}s`;
|
|
1473
|
+
};
|
|
1474
|
+
const AGENTS = { build: { name: 'Build', color: T.blue, desc: 'full access: edits files and runs commands' }, plan: { name: 'Plan', color: T.purple, desc: 'read-only: investigates and writes a plan' } };
|
|
1475
|
+
const SLASH = [
|
|
1476
|
+
['new', 'Start a new session'], ['sessions', 'Switch to another session'], ['model', 'Choose a model'], ['agent', 'Switch Build / Plan'], ['credits', 'Credits, free quota and buying'],
|
|
1477
|
+
['undo', 'Undo the last message and its file changes'], ['copy', 'Copy the last response'], ['compact', 'Summarize the conversation to save context'], ['think', 'Show or hide model reasoning'],
|
|
1478
|
+
['auto', 'Toggle auto-approve'], ['init', 'Create BENCHCODE.md for this project'], ['retry', 'Run the last request again'], ['login', 'Sign in with your browser'], ['logout', 'Sign out'],
|
|
1479
|
+
['buy', 'Open the dashboard to buy credits'], ['help', 'Keyboard shortcuts'], ['exit', 'Quit'],
|
|
1480
|
+
];
|
|
1481
|
+
|
|
1482
|
+
class TUI {
|
|
1483
|
+
constructor(S, cfg) {
|
|
1484
|
+
this.S = S; this.cfg = cfg;
|
|
1485
|
+
this.input = { text: '', cur: 0, hist: [], hi: -1, draft: '' };
|
|
1486
|
+
this.scroll = 0; this.lastTotal = 0;
|
|
1487
|
+
this.dialog = null; this.slashSel = 0; this.sel = null; // sel: {idx} user-block selection
|
|
1488
|
+
this.statusLabel = null; this.statusSince = 0; this.cur = null; this.toolMap = new Map();
|
|
1489
|
+
this.last = []; this.pending = null; this.tick = 0; this.anim = null; this.cache = new Map();
|
|
1490
|
+
this.toast = null; this.quitArm = 0; this.hit = []; this.dlgHit = []; this.pasting = null;
|
|
1491
|
+
this.started = S.blocks.length > 0; this.stopped = false; this.accTimer = null; this.mouse = process.env.BENCHCODE_MOUSE !== '0';
|
|
1492
|
+
this.cols = process.stdout.columns || 100; this.rows = process.stdout.rows || 30;
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// ------------------------------------------------------------ lifecycle
|
|
1496
|
+
start() {
|
|
1497
|
+
const o = process.stdout;
|
|
1498
|
+
o.write('\x1b[?1049h\x1b[?25l\x1b[?2004h' + (this.mouse ? '\x1b[?1000h\x1b[?1006h' : '') + '\x1b[2J\x1b[H');
|
|
1499
|
+
if (process.stdin.setRawMode) process.stdin.setRawMode(true);
|
|
1500
|
+
process.stdin.setEncoding('utf8'); process.stdin.resume();
|
|
1501
|
+
process.stdin.on('data', (d) => this.onData(d));
|
|
1502
|
+
o.on('resize', () => { this.cols = o.columns || 100; this.rows = o.rows || 30; this.cache.clear(); this.last = []; o.write('\x1b[2J'); this.schedule(); });
|
|
1503
|
+
this.accTimer = setInterval(() => refreshAccount(this.S), 60000);
|
|
1504
|
+
this.anim = setInterval(() => { this.tick++; if (this.S.running || this.statusLabel || this.toast || this.dialog) this.schedule(); }, 110);
|
|
1505
|
+
const bye = () => this.stop();
|
|
1506
|
+
process.on('exit', bye);
|
|
1507
|
+
for (const sig of ['SIGTERM', 'SIGHUP']) process.on(sig, () => { this.stop(); process.exit(0); });
|
|
1508
|
+
this.schedule();
|
|
1509
|
+
}
|
|
1510
|
+
stop() {
|
|
1511
|
+
if (this.stopped) return; this.stopped = true;
|
|
1512
|
+
clearInterval(this.anim); clearInterval(this.accTimer);
|
|
1513
|
+
try { process.stdout.write('\x1b[?1000l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[?1049l'); if (process.stdin.setRawMode) process.stdin.setRawMode(false); } catch (_) {}
|
|
1514
|
+
}
|
|
1515
|
+
quit() { saveSession(this.S); this.stop(); if (this.S.messages.length) log(dim(`Session saved. Continue with: benchcode -c`)); process.exit(0); }
|
|
1516
|
+
schedule() { if (this.pending || this.stopped) return; this.pending = setTimeout(() => { this.pending = null; try { this.render(); } catch (e) { this.fail(e); } }, 16); }
|
|
1517
|
+
fail(e) { this.stop(); log(red('UI error: ' + (e && e.stack || e))); process.exit(1); }
|
|
1518
|
+
flash(text, ms = 2500) { this.toast = { text, until: Date.now() + ms }; this.schedule(); setTimeout(() => this.schedule(), ms + 50); }
|
|
1519
|
+
|
|
1520
|
+
// ------------------------------------------------------------ UI hooks (called by the agent)
|
|
1521
|
+
status(label) { if (label && !this.statusLabel) this.statusSince = Date.now(); this.statusLabel = label; this.schedule(); }
|
|
1522
|
+
redraw() { this.schedule(); }
|
|
1523
|
+
addBlock(b) { b.v = 0; this.S.blocks.push(b); this.schedule(); return b; }
|
|
1524
|
+
userMessage(text, info) { this.started = true; this.scroll = 0; this.addBlock({ type: 'user', text, msgIndex: info.msgIndex, snapIndex: info.snapIndex }); }
|
|
1525
|
+
assistantStart() { this.cur = this.addBlock({ type: 'assistant', text: '', think: '', agent: this.S.agent, model: this.S.model, running: true }); }
|
|
1526
|
+
text(t) { if (this.cur) { this.cur.text += t; this.cur.v++; this.schedule(); } }
|
|
1527
|
+
think(t) { if (this.cur) { this.cur.think += t; this.cur.v++; this.schedule(); } }
|
|
1528
|
+
assistantEnd(r) {
|
|
1529
|
+
const b = this.cur; this.cur = null; if (!b) return;
|
|
1530
|
+
b.running = false; b.v++;
|
|
1531
|
+
if (r && r.interrupted) b.interrupted = true;
|
|
1532
|
+
if (r && r.error) b.failed = true;
|
|
1533
|
+
if (!b.text.trim() && !b.interrupted) { const i = this.S.blocks.indexOf(b); if (i >= 0) this.S.blocks.splice(i, 1); }
|
|
1534
|
+
this.schedule();
|
|
1535
|
+
}
|
|
1536
|
+
toolStart(c) { const b = this.addBlock({ type: 'tool', id: c.id, name: c.name, summary: c.summary, status: 'running', output: [], result: '' }); this.toolMap.set(c.id, b); }
|
|
1537
|
+
toolOutput(id, line) { const b = this.toolMap.get(id); if (b) { b.output.push(clip(line, 400)); if (b.output.length > 400) b.output.shift(); b.v++; this.schedule(); } }
|
|
1538
|
+
toolEnd(r) {
|
|
1539
|
+
const b = this.toolMap.get(r.id); if (!b) return;
|
|
1540
|
+
b.status = r.status; b.result = r.summary || ''; b.display = r.display ? slimDisplay(r.display) : null; b.v++;
|
|
1541
|
+
if (b.name === 'run_command' && !b.output.length && r.text && r.status !== 'denied') b.output = r.text.split('\n').slice(-12);
|
|
1542
|
+
this.toolMap.delete(r.id); this.schedule();
|
|
1543
|
+
}
|
|
1544
|
+
notice(m) { const l = this.S.blocks[this.S.blocks.length - 1]; if (l && l.type === 'info' && l.text === m) return; this.addBlock({ type: 'info', text: m }); }
|
|
1545
|
+
error(m) { this.addBlock({ type: 'info', level: 'error', text: m }); }
|
|
1546
|
+
afterCall() { clearTimeout(this._accDeb); this._accDeb = setTimeout(() => refreshAccount(this.S), 1200); }
|
|
1547
|
+
turnEnd() { this.statusLabel = null; saveSession(this.S); setTimeout(() => refreshAccount(this.S), 300); this.schedule(); }
|
|
1548
|
+
|
|
1549
|
+
// ------------------------------------------------------------ block rendering
|
|
1550
|
+
renderBlock(b, w, bi) {
|
|
1551
|
+
const pvb = this.S.blocks[bi - 1];
|
|
1552
|
+
const key = w + '|' + (this.sel && this.sel.bi === bi ? 's' : '') + (this.S.showThinking ? 't' : '') + (pvb ? pvb.type[0] : '-');
|
|
1553
|
+
if (!b.running && b.type !== 'tool' || (b.type === 'tool' && b.status !== 'running')) {
|
|
1554
|
+
const c = this.cache.get(b);
|
|
1555
|
+
if (c && c.key === key && c.v === b.v) return c.lines;
|
|
1556
|
+
}
|
|
1557
|
+
let lines;
|
|
1558
|
+
if (b.type === 'user') lines = this.renderUser(b, w, this.sel && this.sel.bi === bi);
|
|
1559
|
+
else if (b.type === 'assistant') { const pv = this.S.blocks[bi - 1]; lines = this.renderAssistant(b, w, !pv || pv.type === 'user' || pv.type === 'info'); }
|
|
1560
|
+
else if (b.type === 'tool') lines = this.renderTool(b, w);
|
|
1561
|
+
else lines = this.renderInfo(b, w);
|
|
1562
|
+
if (!b.running && !(b.type === 'tool' && b.status === 'running')) this.cache.set(b, { key, v: b.v, lines });
|
|
1563
|
+
return lines;
|
|
1564
|
+
}
|
|
1565
|
+
renderUser(b, w, selected) {
|
|
1566
|
+
const bar = sty('▎', { fg: selected ? T.peach : T.blue });
|
|
1567
|
+
const inner = w - 3;
|
|
1568
|
+
const body = [];
|
|
1569
|
+
for (const raw of b.text.split('\n')) body.push(...wrapAnsi(raw.replace(/\t/g, ' ') || ' ', inner));
|
|
1570
|
+
const rows_ = [''].concat(body.slice(0, 40), body.length > 40 ? [sty(`… ${body.length - 40} more lines`, { fg: T.dim })] : [], ['']);
|
|
1571
|
+
const bg = selected ? T.panel3 : T.panel;
|
|
1572
|
+
return [''].concat(rows_.map((l) => bar + keepBg(' ' + fit(l, inner) + ' ', bg)));
|
|
1573
|
+
}
|
|
1574
|
+
renderAssistant(b, w, showHead) {
|
|
1575
|
+
const ag = AGENTS[b.agent] || AGENTS.build;
|
|
1576
|
+
let head = sty(b.running ? (this.tick % 6 < 3 ? '▣' : '▢') : '▣', { fg: b.failed ? T.red : ag.color }) + ' ' + sty(ag.name, { b: true, fg: T.text }) + sty(' · ' + (b.model || ''), { fg: T.mut });
|
|
1577
|
+
if (b.interrupted) head += sty(' · interrupted', { fg: T.mut });
|
|
1578
|
+
const lines = showHead || b.interrupted || b.failed ? ['', ' ' + head] : [''];
|
|
1579
|
+
if (b.think && (this.S.showThinking)) {
|
|
1580
|
+
for (const l of wrapAnsi(b.think.trim(), w - 6).slice(-12)) lines.push(' ' + sty('┆ ' + l, { fg: T.dim, i: true }));
|
|
1581
|
+
} else if (b.running && b.think && !b.text) lines.push(' ' + sty('▸ thinking…', { fg: T.dim, i: true }));
|
|
1582
|
+
if (b.text.trim()) for (const l of renderMarkdown(b.text, w - 4)) lines.push(' ' + l);
|
|
1583
|
+
return lines;
|
|
1584
|
+
}
|
|
1585
|
+
renderInfo(b, w) {
|
|
1586
|
+
const err = b.level === 'error';
|
|
1587
|
+
return wrapAnsi(b.text, w - 6).map((l, i) => ' ' + (i === 0 ? sty(err ? '✖ ' : '· ', { fg: err ? T.red : T.dim }) : ' ') + sty(l, { fg: err ? T.red : T.mut }));
|
|
1588
|
+
}
|
|
1589
|
+
renderTool(b, w) {
|
|
1590
|
+
const meta = {
|
|
1591
|
+
read_file: ['→', 'Read'], list_dir: ['→', 'List'], search: ['✱', 'Search'], find_files: ['✱', 'Glob'], write_file: ['←', 'Write'], edit_file: ['←', 'Edit'], multi_edit: ['←', 'Edit'],
|
|
1592
|
+
move_file: ['↔', 'Move'], delete_file: ['✗', 'Delete'], run_command: ['$', 'Bash'], run_background: ['$', 'Bash (background)'], background_output: ['→', 'Output'], kill_background: ['■', 'Stop'],
|
|
1593
|
+
web_fetch: ['↗', 'Fetch'], web_search: ['≈', 'Web search'], todo_write: ['≡', 'Todos'], ask_user: ['?', 'Ask'], generate_image: ['▣', 'Image'], transcribe_audio: ['♪', 'Transcribe'],
|
|
1594
|
+
}[b.name] || ['◆', b.name];
|
|
1595
|
+
const spin = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'][this.tick % 10];
|
|
1596
|
+
let icon, col;
|
|
1597
|
+
if (b.status === 'running') { icon = spin; col = T.yellow; }
|
|
1598
|
+
else if (b.status === 'error') { icon = '✗'; col = T.red; }
|
|
1599
|
+
else if (b.status === 'denied') { icon = '⊘'; col = T.yellow; }
|
|
1600
|
+
else { icon = meta[0]; col = T.mut; }
|
|
1601
|
+
const tail = b.status === 'running' ? '' : b.result ? sty(' ' + b.result, { fg: b.status === 'error' ? T.red : T.dim }) : '';
|
|
1602
|
+
const sum = clip(b.summary || '', Math.max(10, w - 12 - strWidth(meta[1]) - strWidth(b.result || '')));
|
|
1603
|
+
const lines = [' ' + sty(icon, { fg: col }) + ' ' + sty(meta[1], { fg: b.status === 'running' ? T.text : T.mut, b: b.status === 'running' }) + ' ' + sty(sum, { fg: T.mut }) + tail];
|
|
1604
|
+
const panel = (s, bg) => ' ' + keepBg(' ' + fit(s, w - 8) + ' ', bg || T.panel);
|
|
1605
|
+
if ((b.name === 'run_command' || b.name === 'run_background') && b.output.length) {
|
|
1606
|
+
const shown = b.output.filter((l) => l.trim() !== '');
|
|
1607
|
+
const tailN = b.status === 'running' ? 8 : 10;
|
|
1608
|
+
if (shown.length > tailN) lines.push(panel(sty(`… ${shown.length - tailN} earlier lines`, { fg: T.dim })));
|
|
1609
|
+
for (const l of shown.slice(-tailN)) lines.push(panel(sty(clip(l, w - 10), { fg: T.mut })));
|
|
1610
|
+
}
|
|
1611
|
+
const d = b.display;
|
|
1612
|
+
if (d && d.type === 'diff') {
|
|
1613
|
+
for (const h of d.hunks) {
|
|
1614
|
+
for (const l of h.old.split('\n').slice(0, 10)) lines.push(' ' + keepBg(' ' + fit(sty('- ', { fg: T.red }) + clip(l, w - 14), w - 8) + ' ', T.diffDel));
|
|
1615
|
+
for (const l of h.new.split('\n').slice(0, 10)) lines.push(' ' + keepBg(' ' + fit(sty('+ ', { fg: T.green }) + clip(l, w - 14), w - 8) + ' ', T.diffAdd));
|
|
1616
|
+
}
|
|
1617
|
+
} else if (d && d.type === 'write') {
|
|
1618
|
+
for (const l of d.preview.slice(0, 8)) lines.push(' ' + keepBg(' ' + fit(sty('+ ', { fg: T.green }) + clip(l, w - 14), w - 8) + ' ', T.diffAdd));
|
|
1619
|
+
if (d.total > 8) lines.push(' ' + sty(` … ${d.total - 8} more lines`, { fg: T.dim }));
|
|
1620
|
+
} else if (d && d.type === 'todos') {
|
|
1621
|
+
for (const t of d.todos) lines.push(' ' + (t.status === 'completed' ? sty('☑ ' + t.content, { fg: T.dim, s: true }) : t.status === 'in_progress' ? sty('▶ ' + t.content, { fg: T.blue, b: true }) : sty('☐ ' + t.content, { fg: T.mut })));
|
|
1622
|
+
}
|
|
1623
|
+
return lines;
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
// ------------------------------------------------------------ sidebar
|
|
1627
|
+
sidebar(w, h) {
|
|
1628
|
+
const S = this.S, a = S.account, L = [];
|
|
1629
|
+
const pad = (s) => ' ' + s;
|
|
1630
|
+
const head = (t) => { L.push(''); L.push(pad(sty(t, { b: true, fg: T.text }))); };
|
|
1631
|
+
L.push('');
|
|
1632
|
+
L.push(pad(sty(clip(S.title || 'New session', w - 3), { b: true, fg: T.text })));
|
|
1633
|
+
head('Credits');
|
|
1634
|
+
if (!a) L.push(pad(sty('loading…', { fg: T.dim })));
|
|
1635
|
+
else if (a.unmetered) L.push(pad(sty('unmetered key', { fg: T.mut })));
|
|
1636
|
+
else {
|
|
1637
|
+
const cr = a.credits || 0, cap = (a.free && a.free.cap) || 0, left = (a.free && a.free.left) || 0;
|
|
1638
|
+
L.push(pad(sty(nf(cr), { b: true, fg: cr > 0 ? T.text : T.mut }) + sty(' purchased', { fg: T.mut })));
|
|
1639
|
+
L.push(pad(sty('never expire', { fg: T.dim })));
|
|
1640
|
+
L.push('');
|
|
1641
|
+
const pct = cap ? left / cap : 0;
|
|
1642
|
+
const col = pct > 0.5 ? T.green : pct > 0.2 ? T.yellow : T.red;
|
|
1643
|
+
const n = 12, filled = Math.round(pct * n);
|
|
1644
|
+
L.push(pad(sty('Free today', { fg: T.mut })));
|
|
1645
|
+
L.push(pad(sty('▰'.repeat(filled), { fg: col }) + sty('▱'.repeat(n - filled), { fg: T.dim }) + ' ' + sty(`${left}/${cap}`, { fg: col, b: true })));
|
|
1646
|
+
const secs = a.free && a.free.resets_at ? (Date.parse(a.free.resets_at) - Date.now()) / 1000 : 0;
|
|
1647
|
+
if (secs > 0) L.push(pad(sty('resets in ' + fmtDur(secs), { fg: T.mut })));
|
|
1648
|
+
if (secs > 0) L.push(pad(sty('at 00:00 UTC', { fg: T.dim })));
|
|
1649
|
+
if (cr <= 0 && left <= 0) { L.push(''); L.push(pad(sty('No credits left', { fg: T.red, b: true }))); L.push(pad(sty('/buy to add more', { fg: T.mut }))); }
|
|
1650
|
+
else if (cr <= 0 && left <= 2) { L.push(''); L.push(pad(sty('Running low · /buy', { fg: T.yellow }))); }
|
|
1651
|
+
}
|
|
1652
|
+
head('Context');
|
|
1653
|
+
const win = (S.modelInfo[S.model] && S.modelInfo[S.model].context_length) || 128000;
|
|
1654
|
+
const used = S.ctxTokens || 0;
|
|
1655
|
+
L.push(pad(sty(nf(used), { fg: T.mut }) + sty(' tokens', { fg: T.mut })));
|
|
1656
|
+
L.push(pad(sty(Math.min(100, Math.round(used / win * 100)) + '% used', { fg: T.mut })));
|
|
1657
|
+
L.push(pad(sty(nf(S.spent) + ' credits spent', { fg: T.mut }) + (S.calls ? sty(' · ' + S.calls + ' calls', { fg: T.dim }) : '')));
|
|
1658
|
+
if (S.todos.length) {
|
|
1659
|
+
head('Todo');
|
|
1660
|
+
for (const t of S.todos.slice(0, 10)) {
|
|
1661
|
+
const mark = t.status === 'completed' ? sty('☑ ', { fg: T.green }) : t.status === 'in_progress' ? sty('▶ ', { fg: T.blue }) : sty('☐ ', { fg: T.dim });
|
|
1662
|
+
const txt = clip(t.content, w - 6);
|
|
1663
|
+
L.push(pad(mark + sty(txt, { fg: t.status === 'completed' ? T.dim : t.status === 'in_progress' ? T.text : T.mut, s: t.status === 'completed' })));
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
if (S.changed.size) {
|
|
1667
|
+
head('Files changed');
|
|
1668
|
+
const col = { A: T.green, M: T.yellow, D: T.red, R: T.blue };
|
|
1669
|
+
let n = 0;
|
|
1670
|
+
for (const [f, st] of S.changed) { if (n++ >= 8) break; L.push(pad(sty(st, { fg: col[st] || T.mut, b: true }) + ' ' + sty(clip(f, w - 6), { fg: T.mut }))); }
|
|
1671
|
+
if (S.changed.size > 8) L.push(pad(sty(`+${S.changed.size - 8} more`, { fg: T.dim })));
|
|
1672
|
+
}
|
|
1673
|
+
const foot = [
|
|
1674
|
+
pad(sty(clip(tidyPath(S.cwd), w - 3) + (S.git ? ':' + S.git : ''), { fg: T.mut })),
|
|
1675
|
+
pad(sty('● ', { fg: T.green }) + sty('Bench', { b: true, fg: T.text }) + sty('Code', { b: true, fg: T.text }) + ' ' + sty(VERSION, { fg: T.mut })),
|
|
1676
|
+
];
|
|
1677
|
+
while (L.length < h - foot.length - 1) L.push('');
|
|
1678
|
+
const res = L.slice(0, h - foot.length - 1).concat([''], foot);
|
|
1679
|
+
return res.map((l) => keepBg(fit(l, w), T.panel));
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
// ------------------------------------------------------------ input box
|
|
1683
|
+
inputLayout(w) {
|
|
1684
|
+
const inner = Math.max(5, w - 4), text = this.input.text, vis = [];
|
|
1685
|
+
let idx = 0;
|
|
1686
|
+
for (const line of text.split('\n')) {
|
|
1687
|
+
let start = idx, cur = '', cw = 0;
|
|
1688
|
+
for (const ch of Array.from(line)) {
|
|
1689
|
+
const c = charWidth(ch.codePointAt(0));
|
|
1690
|
+
if (cw + c > inner) { vis.push({ start, end: idx, text: cur }); start = idx; cur = ''; cw = 0; }
|
|
1691
|
+
cur += ch; cw += c; idx += ch.length;
|
|
1692
|
+
}
|
|
1693
|
+
vis.push({ start, end: idx, text: cur });
|
|
1694
|
+
idx += 1;
|
|
1695
|
+
}
|
|
1696
|
+
return vis;
|
|
1697
|
+
}
|
|
1698
|
+
renderInput(w, focused) {
|
|
1699
|
+
const S = this.S, ag = AGENTS[S.agent] || AGENTS.build;
|
|
1700
|
+
const inner = w - 4, vis = this.inputLayout(w);
|
|
1701
|
+
let ci = vis.length - 1;
|
|
1702
|
+
for (let i = 0; i < vis.length; i++) if (this.input.cur >= vis[i].start && this.input.cur <= vis[i].end) { ci = i; if (this.input.cur < vis[i].end || i === vis.length - 1 || vis[i + 1].start !== vis[i].end) break; }
|
|
1703
|
+
const maxRows = Math.min(8, Math.max(1, this.rows - 12));
|
|
1704
|
+
let from = Math.max(0, Math.min(ci - maxRows + 1, vis.length - maxRows));
|
|
1705
|
+
const shown = vis.slice(from, from + maxRows);
|
|
1706
|
+
const rows_ = [];
|
|
1707
|
+
const bar = sty('┃', { fg: ag.color });
|
|
1708
|
+
const rowOf = (s) => bar + keepBg(' ' + fit(s, w - 2) + ' ', T.panel2);
|
|
1709
|
+
rows_.push(rowOf(''));
|
|
1710
|
+
if (!this.input.text && this.dialog === null) {
|
|
1711
|
+
const ph = this.started ? 'Ask anything…' : 'Ask anything… "What is the tech stack of this project?"';
|
|
1712
|
+
rows_.push(rowOf(focused ? sty(' ', { bg: T.text }) + sty(ph, { fg: T.dim }) : sty(ph, { fg: T.dim })));
|
|
1713
|
+
} else {
|
|
1714
|
+
shown.forEach((v, k) => {
|
|
1715
|
+
const li = from + k;
|
|
1716
|
+
if (focused && li === ci && this.dialog === null) {
|
|
1717
|
+
const col = strWidth(this.input.text.slice(v.start, this.input.cur));
|
|
1718
|
+
const chars = Array.from(v.text); let acc = 0, s = '', placed = false;
|
|
1719
|
+
for (const ch of chars) { const cwid = charWidth(ch.codePointAt(0)); if (!placed && acc >= col) { s += sty(ch, { fg: T.black, bg: T.text }); placed = true; } else s += ch; acc += cwid; }
|
|
1720
|
+
if (!placed) s += sty(' ', { bg: T.text });
|
|
1721
|
+
rows_.push(rowOf(sty(s, { fg: T.text })));
|
|
1722
|
+
} else rows_.push(rowOf(sty(v.text, { fg: T.text })));
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
rows_.push(rowOf(''));
|
|
1726
|
+
const minfo = S.modelInfo[S.model];
|
|
1727
|
+
const tag = minfo && minfo.credit_cost != null ? sty(minfo.credit_cost + ' credit' + (minfo.credit_cost == 1 ? '' : 's') + '/req', { fg: T.orange, b: true }) : '';
|
|
1728
|
+
rows_.push(rowOf(sty(ag.name, { b: true, fg: ag.color }) + sty(' · ', { fg: T.dim }) + sty(S.model, { b: true, fg: T.text }) + (tag ? sty(' · ', { fg: T.dim }) + tag : '') + (S.auto ? sty(' · auto-approve', { fg: T.yellow }) : '')));
|
|
1729
|
+
return { lines: rows_, cursorRow: 1 + (ci - from) };
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
// ------------------------------------------------------------ frame
|
|
1733
|
+
hintsRight() { return sty('tab', { b: true, fg: T.text }) + sty(' agents ', { fg: T.mut }) + sty('ctrl+p', { b: true, fg: T.text }) + sty(' commands', { fg: T.mut }); }
|
|
1734
|
+
footerLeft(w) {
|
|
1735
|
+
if (this.sel) return sty('↑↓', { b: true, fg: T.text }) + sty(' select ', { fg: T.mut }) + sty('enter', { b: true, fg: T.text }) + sty(' actions ', { fg: T.mut }) + sty('esc', { b: true, fg: T.text }) + sty(' cancel', { fg: T.mut });
|
|
1736
|
+
if (this.S.running) {
|
|
1737
|
+
const pos = Math.abs(((this.tick % 14) - 7)); let bar = '';
|
|
1738
|
+
for (let i = 0; i < 8; i++) { const d = Math.abs(i - pos); bar += sty(d < 1 ? '■' : '▪', { fg: d < 1 ? T.blue : d < 2 ? '#3d6aa8' : d < 3 ? '#2a4570' : '#1f2f4a' }); }
|
|
1739
|
+
const secs = Math.floor((Date.now() - (this.statusSince || Date.now())) / 1000);
|
|
1740
|
+
return bar + ' ' + sty('esc', { b: true, fg: T.text }) + sty(' interrupt', { fg: T.mut }) + (this.statusLabel ? sty(' ' + this.statusLabel + (secs > 2 ? ' ' + secs + 's' : ''), { fg: T.dim }) : '');
|
|
1741
|
+
}
|
|
1742
|
+
if (this.toast && Date.now() < this.toast.until) return sty(this.toast.text, { fg: T.yellow });
|
|
1743
|
+
let left = sty(tidyPath(this.S.cwd), { fg: T.mut });
|
|
1744
|
+
const a = this.S.account;
|
|
1745
|
+
if (this.cols < 104 && a && !a.unmetered && a.free) {
|
|
1746
|
+
const col = a.free.cap && a.free.left / a.free.cap > 0.2 ? T.green : T.red;
|
|
1747
|
+
left += sty(' ● ', { fg: col }) + sty(`${a.free.left}/${a.free.cap} free · ${nf(a.credits)} cr`, { fg: T.mut });
|
|
1748
|
+
}
|
|
1749
|
+
return left;
|
|
1750
|
+
}
|
|
1751
|
+
chatLines(w) {
|
|
1752
|
+
const all = [];
|
|
1753
|
+
this.S.blocks.forEach((b, bi) => { for (const l of this.renderBlock(b, w, bi)) all.push({ s: l, bi }); });
|
|
1754
|
+
return all;
|
|
1755
|
+
}
|
|
1756
|
+
render() {
|
|
1757
|
+
if (this.stopped) return;
|
|
1758
|
+
const cols = this.cols, rows = this.rows, S = this.S;
|
|
1759
|
+
if (cols < 40 || rows < 10) { process.stdout.write('\x1b[2J\x1b[HTerminal too small'); return; }
|
|
1760
|
+
const frame = new Array(rows).fill('');
|
|
1761
|
+
this.hit = new Array(rows).fill(null);
|
|
1762
|
+
const place = (r, x, s, w) => { if (r < 0 || r >= rows) return; const cur = frame[r] || ''; frame[r] = (x > 0 ? fit(cur, x) : '') + fit(s, w); };
|
|
1763
|
+
let cursor = null;
|
|
1764
|
+
|
|
1765
|
+
if (!this.started && S.blocks.length === 0) {
|
|
1766
|
+
const w = Math.min(cols - 6, 78), x = Math.floor((cols - w) / 2);
|
|
1767
|
+
const logo = renderLogo(cols);
|
|
1768
|
+
const inp = this.renderInput(w, true);
|
|
1769
|
+
const H = 5 + 2 + inp.lines.length + 2 + 2;
|
|
1770
|
+
let y = Math.max(1, Math.floor((rows - H) / 2) - 1);
|
|
1771
|
+
const lw = strWidth(logo[0]);
|
|
1772
|
+
logo.forEach((l, i) => { frame[y + i] = ' '.repeat(Math.max(0, Math.floor((cols - lw) / 2))) + l; });
|
|
1773
|
+
y += 7;
|
|
1774
|
+
const inputTop = y;
|
|
1775
|
+
inp.lines.forEach((l, i) => place(y + i, x, l, w));
|
|
1776
|
+
this.slashOverlay(frame, x, inputTop + 1, w);
|
|
1777
|
+
y += inp.lines.length;
|
|
1778
|
+
const hr = this.hintsRight();
|
|
1779
|
+
frame[y] = ' '.repeat(Math.max(0, x + w - strWidth(hr))) + hr;
|
|
1780
|
+
y += 2;
|
|
1781
|
+
const a = S.account;
|
|
1782
|
+
if (a && !a.unmetered) {
|
|
1783
|
+
const free = a.free || {};
|
|
1784
|
+
const secs = free.resets_at ? (Date.parse(free.resets_at) - Date.now()) / 1000 : 0;
|
|
1785
|
+
const col = free.cap && free.left / free.cap > 0.2 ? T.green : T.red;
|
|
1786
|
+
const line = sty('● ', { fg: col }) + sty(`${free.left}/${free.cap} free today`, { fg: T.mut }) + sty(' · ', { fg: T.dim }) + sty(nf(a.credits) + ' credits', { fg: T.mut }) + (secs > 0 ? sty(' · resets in ' + fmtDur(secs), { fg: T.dim }) : '');
|
|
1787
|
+
frame[y] = ' '.repeat(Math.max(0, Math.floor((cols - strWidth(line)) / 2))) + line;
|
|
1788
|
+
}
|
|
1789
|
+
if (this.toast && Date.now() < this.toast.until) { const t = sty(this.toast.text, { fg: T.yellow }); frame[y + 2] = ' '.repeat(Math.max(0, Math.floor((cols - strWidth(t)) / 2))) + t; }
|
|
1790
|
+
frame[rows - 2] = ' ' + sty(tidyPath(S.cwd) + (S.git ? ':' + S.git : ''), { fg: T.mut });
|
|
1791
|
+
const v = sty(VERSION, { fg: T.mut });
|
|
1792
|
+
frame[rows - 2] = fit(frame[rows - 2], cols - strWidth(v) - 2) + v;
|
|
1793
|
+
} else {
|
|
1794
|
+
const sbW = cols >= 104 ? 38 : 0;
|
|
1795
|
+
const mainW = cols - sbW - 3, x0 = 2;
|
|
1796
|
+
const inp = this.renderInput(mainW, true);
|
|
1797
|
+
const chatH = rows - inp.lines.length - 2;
|
|
1798
|
+
const all = this.chatLines(mainW);
|
|
1799
|
+
if (this.scroll > 0 && all.length > this.lastTotal) this.scroll += all.length - this.lastTotal;
|
|
1800
|
+
this.lastTotal = all.length;
|
|
1801
|
+
if (this.sel && this.sel.reveal) {
|
|
1802
|
+
this.sel.reveal = false;
|
|
1803
|
+
const fi = all.findIndex((x) => x.bi === this.sel.bi);
|
|
1804
|
+
if (fi >= 0) {
|
|
1805
|
+
let li = fi; while (li + 1 < all.length && all[li + 1].bi === this.sel.bi) li++;
|
|
1806
|
+
const top = all.length - chatH - this.scroll;
|
|
1807
|
+
if (fi < top) this.scroll = Math.max(0, all.length - chatH - fi);
|
|
1808
|
+
else if (li >= top + chatH) this.scroll = Math.max(0, all.length - li - 1);
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
const maxScroll = Math.max(0, all.length - chatH);
|
|
1812
|
+
if (this.scroll > maxScroll) this.scroll = maxScroll;
|
|
1813
|
+
let start = Math.max(0, all.length - chatH - this.scroll);
|
|
1814
|
+
if (all.length <= chatH) start = 0;
|
|
1815
|
+
for (let i = 0; i < chatH; i++) {
|
|
1816
|
+
const item = all[start + i];
|
|
1817
|
+
if (item) { place(i, x0, item.s, mainW); this.hit[i] = { bi: item.bi }; }
|
|
1818
|
+
}
|
|
1819
|
+
if (this.scroll > 0) { const t = sty(` ↓ ${this.scroll} line${this.scroll === 1 ? '' : 's'} below · End `, { fg: T.black, bg: T.mut }); place(chatH - 1, x0 + mainW - strWidth(t) - 1, t, strWidth(t)); }
|
|
1820
|
+
inp.lines.forEach((l, i) => place(chatH + 1 + i, x0, l, mainW));
|
|
1821
|
+
const fr = this.hintsRight(), fl = this.footerLeft(mainW);
|
|
1822
|
+
frame[rows - 1] = ' '.repeat(x0) + fit(fl, mainW - strWidth(fr) - 1) + ' ' + fr;
|
|
1823
|
+
if (sbW) { const sb = this.sidebar(sbW, rows); for (let r = 0; r < rows; r++) frame[r] = fit(frame[r], cols - sbW) + sb[r]; }
|
|
1824
|
+
this.slashOverlay(frame, x0, chatH, mainW);
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
// dialogs on top
|
|
1828
|
+
this.dlgHit = [];
|
|
1829
|
+
if (this.dialog) this.drawDialog(frame, cols, rows);
|
|
1830
|
+
|
|
1831
|
+
// write only the rows that changed
|
|
1832
|
+
let buf = '\x1b[?2026h';
|
|
1833
|
+
for (let r = 0; r < rows; r++) {
|
|
1834
|
+
let line = fit(frame[r] || '', cols);
|
|
1835
|
+
if (line !== this.last[r]) { buf += `\x1b[${r + 1};1H${line}${RESET}`; this.last[r] = line; }
|
|
1836
|
+
}
|
|
1837
|
+
buf += '\x1b[?2026l';
|
|
1838
|
+
process.stdout.write(buf);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
function slimDisplay(d) {
|
|
1842
|
+
if (d.type === 'diff') return { type: 'diff', path: d.path, hunks: d.hunks.map((h) => ({ old: h.old.split('\n').slice(0, 12).join('\n'), new: h.new.split('\n').slice(0, 12).join('\n') })).slice(0, 6) };
|
|
1843
|
+
return d;
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
// ================================================================ TUI: keys, dialogs, commands
|
|
1847
|
+
const dimRow = (s) => (NO_COLOR ? s : '\x1b[2m' + s.split('\x1b[0m').join('\x1b[0m\x1b[2m') + '\x1b[0m');
|
|
1848
|
+
const fuzzy = (q, s) => { q = q.toLowerCase(); s = s.toLowerCase(); let i = 0; for (const ch of q) { i = s.indexOf(ch, i); if (i < 0) return false; i++; } return true; };
|
|
1849
|
+
const ago = (ms) => { const s = (Date.now() - ms) / 1000; return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + 'm ago' : s < 129600 ? Math.round(s / 3600) + 'h ago' : Math.round(s / 86400) + 'd ago'; };
|
|
1850
|
+
|
|
1851
|
+
function parseKeys(str) {
|
|
1852
|
+
const ev = []; let i = 0;
|
|
1853
|
+
const CSI = /^\x1b\[([0-9;]*)([A-Za-z~])/, MOUSE = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])/, SS3 = /^\x1bO([A-Za-z])/;
|
|
1854
|
+
while (i < str.length) {
|
|
1855
|
+
const c = str[i];
|
|
1856
|
+
if (c === '\x1b') {
|
|
1857
|
+
const rest = str.slice(i);
|
|
1858
|
+
let m = MOUSE.exec(rest);
|
|
1859
|
+
if (m) { ev.push({ name: 'mouse', b: +m[1], x: +m[2] - 1, y: +m[3] - 1, press: m[4] === 'M' }); i += m[0].length; continue; }
|
|
1860
|
+
m = CSI.exec(rest);
|
|
1861
|
+
if (m) {
|
|
1862
|
+
const p = m[1].split(';').map(Number), mod = (p[1] || 1) - 1, k = { ctrl: !!(mod & 4), alt: !!(mod & 2), shift: !!(mod & 1) };
|
|
1863
|
+
const base = { A: 'up', B: 'down', C: 'right', D: 'left', H: 'home', F: 'end', Z: 'tab' }[m[2]];
|
|
1864
|
+
let name = base;
|
|
1865
|
+
if (m[2] === 'Z') k.shift = true;
|
|
1866
|
+
if (m[2] === '~') name = { 1: 'home', 2: 'insert', 3: 'delete', 4: 'end', 5: 'pageup', 6: 'pagedown', 7: 'home', 8: 'end' }[p[0]];
|
|
1867
|
+
ev.push(Object.assign({ name: name || 'unknown' }, k)); i += m[0].length; continue;
|
|
1868
|
+
}
|
|
1869
|
+
m = SS3.exec(rest);
|
|
1870
|
+
if (m) { ev.push({ name: { A: 'up', B: 'down', C: 'right', D: 'left', H: 'home', F: 'end' }[m[1]] || 'unknown' }); i += m[0].length; continue; }
|
|
1871
|
+
if (rest.length > 1) { const n = rest[1]; if (n === '\r' || n === '\n') ev.push({ name: 'enter', alt: true }); else if (n === '\x7f') ev.push({ name: 'backspace', alt: true }); else ev.push({ name: n, alt: true }); i += 2; continue; }
|
|
1872
|
+
ev.push({ name: 'escape' }); i++; continue;
|
|
1873
|
+
}
|
|
1874
|
+
if (c === '\r') { ev.push({ name: 'enter' }); i++; continue; }
|
|
1875
|
+
if (c === '\n') { ev.push({ name: 'j', ctrl: true }); i++; continue; }
|
|
1876
|
+
if (c === '\t') { ev.push({ name: 'tab' }); i++; continue; }
|
|
1877
|
+
if (c === '\x7f' || c === '\b') { ev.push({ name: 'backspace' }); i++; continue; }
|
|
1878
|
+
const code = c.charCodeAt(0);
|
|
1879
|
+
if (code < 32) { ev.push({ name: String.fromCharCode(code + 96), ctrl: true }); i++; continue; }
|
|
1880
|
+
let j = i, t = '';
|
|
1881
|
+
while (j < str.length && str[j] !== '\x1b' && str.charCodeAt(j) >= 32 && str[j] !== '\x7f') { t += str[j]; j++; }
|
|
1882
|
+
ev.push({ name: 'text', text: t }); i = j;
|
|
1883
|
+
}
|
|
1884
|
+
return ev;
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
Object.assign(TUI.prototype, {
|
|
1888
|
+
// ------------------------------------------------------------ raw input
|
|
1889
|
+
onData(d) {
|
|
1890
|
+
try {
|
|
1891
|
+
if (this.pasting !== null) {
|
|
1892
|
+
const e = d.indexOf('\x1b[201~');
|
|
1893
|
+
if (e < 0) { this.pasting += d; return; }
|
|
1894
|
+
this.pasting += d.slice(0, e); const txt = this.pasting; this.pasting = null;
|
|
1895
|
+
this.onPaste(txt); d = d.slice(e + 6);
|
|
1896
|
+
if (!d) return;
|
|
1897
|
+
}
|
|
1898
|
+
const s = d.indexOf('\x1b[200~');
|
|
1899
|
+
if (s >= 0) {
|
|
1900
|
+
if (s > 0) this.handleEvents(parseKeys(d.slice(0, s)));
|
|
1901
|
+
const rest = d.slice(s + 6), e = rest.indexOf('\x1b[201~');
|
|
1902
|
+
if (e < 0) { this.pasting = rest; return; }
|
|
1903
|
+
this.onPaste(rest.slice(0, e));
|
|
1904
|
+
d = rest.slice(e + 6);
|
|
1905
|
+
if (!d) return;
|
|
1906
|
+
}
|
|
1907
|
+
this.handleEvents(parseKeys(d));
|
|
1908
|
+
} catch (e) { this.fail(e); }
|
|
1909
|
+
},
|
|
1910
|
+
onPaste(txt) {
|
|
1911
|
+
txt = txt.replace(/\r\n?/g, '\n');
|
|
1912
|
+
if (this.dialog) { if (this.dialog.kind === 'list' && this.dialog.search) { this.dialog.filter += txt.replace(/\n/g, ' '); this.dialog.sel = 0; } else if (this.dialog.kind === 'input') { this.dialog.text += txt.replace(/\n/g, ' '); } this.schedule(); return; }
|
|
1913
|
+
this.sel = null; this.insert(txt);
|
|
1914
|
+
},
|
|
1915
|
+
handleEvents(evs) { for (const ev of evs) { if (ev.name === 'mouse') this.onMouse(ev); else if (this.dialog) this.dialogKey(ev); else this.onKey(ev); } this.schedule(); },
|
|
1916
|
+
|
|
1917
|
+
// ------------------------------------------------------------ editor
|
|
1918
|
+
insert(t) { const I = this.input; I.text = I.text.slice(0, I.cur) + t + I.text.slice(I.cur); I.cur += t.length; I.hi = -1; this.slashSel = 0; },
|
|
1919
|
+
lineBounds() { const I = this.input; const s = I.text.lastIndexOf('\n', I.cur - 1) + 1; let e = I.text.indexOf('\n', I.cur); if (e < 0) e = I.text.length; return [s, e]; },
|
|
1920
|
+
wordLeft() { const I = this.input; let i = I.cur; while (i > 0 && /\s/.test(I.text[i - 1])) i--; while (i > 0 && !/\s/.test(I.text[i - 1])) i--; return i; },
|
|
1921
|
+
wordRight() { const I = this.input; let i = I.cur; while (i < I.text.length && /\s/.test(I.text[i])) i++; while (i < I.text.length && !/\s/.test(I.text[i])) i++; return i; },
|
|
1922
|
+
moveVertical(dir) {
|
|
1923
|
+
const vis = this.inputLayout(Math.min(this.cols - 8, 78)), I = this.input;
|
|
1924
|
+
let ci = vis.findIndex((v) => I.cur >= v.start && I.cur <= v.end);
|
|
1925
|
+
if (ci < 0) ci = vis.length - 1;
|
|
1926
|
+
const col = strWidth(I.text.slice(vis[ci].start, I.cur));
|
|
1927
|
+
const ni = ci + dir;
|
|
1928
|
+
if (ni < 0 || ni >= vis.length) return false;
|
|
1929
|
+
const v = vis[ni]; let acc = 0, idx = v.start;
|
|
1930
|
+
for (const ch of Array.from(v.text)) { const w = charWidth(ch.codePointAt(0)); if (acc + w > col) break; acc += w; idx += ch.length; }
|
|
1931
|
+
I.cur = idx; return true;
|
|
1932
|
+
},
|
|
1933
|
+
slashMatches() {
|
|
1934
|
+
const t = this.input.text;
|
|
1935
|
+
if (!t.startsWith('/') || /\s/.test(t) || this.dialog) return [];
|
|
1936
|
+
const q = t.slice(1).toLowerCase();
|
|
1937
|
+
let m = SLASH.filter(([n]) => n.startsWith(q));
|
|
1938
|
+
if (!m.length) m = SLASH.filter(([n, d]) => fuzzy(q, n));
|
|
1939
|
+
return m;
|
|
1940
|
+
},
|
|
1941
|
+
slashOverlay(frame, x, yBottom, w) {
|
|
1942
|
+
const m = this.slashMatches(); if (!m.length) return;
|
|
1943
|
+
const pw = Math.min(w, 66), n = Math.min(m.length, 8);
|
|
1944
|
+
if (this.slashSel >= m.length) this.slashSel = 0;
|
|
1945
|
+
const from = Math.min(Math.max(0, this.slashSel - n + 1), m.length - n);
|
|
1946
|
+
for (let i = 0; i < n; i++) {
|
|
1947
|
+
const [name, desc] = m[from + i], sel = from + i === this.slashSel;
|
|
1948
|
+
const row = yBottom - n + i - 1; if (row < 0) continue;
|
|
1949
|
+
const txt = sel ? sty(' /' + name.padEnd(10) + ' ' + desc, { fg: T.black, bg: T.peach, b: true }) : ' ' + sty('/' + name.padEnd(10), { fg: T.text }) + ' ' + sty(desc, { fg: T.mut });
|
|
1950
|
+
const line = sel ? fit(txt, pw) : keepBg(fit(txt, pw), T.panel3);
|
|
1951
|
+
frame[row] = fit(frame[row] || '', x) + line + sliceCols(frame[row] || '', x + pw, this.cols);
|
|
1952
|
+
}
|
|
1953
|
+
},
|
|
1954
|
+
|
|
1955
|
+
onKey(ev) {
|
|
1956
|
+
const S = this.S, I = this.input, n = ev.name;
|
|
1957
|
+
this.quitArm = n === 'c' && ev.ctrl ? this.quitArm : 0;
|
|
1958
|
+
// global shortcuts
|
|
1959
|
+
if (ev.ctrl && n === 'p') return this.openPalette();
|
|
1960
|
+
if (ev.ctrl && n === 'c') {
|
|
1961
|
+
if (S.running) { S.abort(); this.flash('Interrupted'); return; }
|
|
1962
|
+
if (I.text) { I.text = ''; I.cur = 0; return; }
|
|
1963
|
+
if (Date.now() - this.quitArm < 2000) return this.quit();
|
|
1964
|
+
this.quitArm = Date.now(); this.flash('Press Ctrl+C again to exit'); return;
|
|
1965
|
+
}
|
|
1966
|
+
if (ev.ctrl && n === 'd' && !I.text) return this.quit();
|
|
1967
|
+
if (ev.ctrl && n === 'l') { this.last = []; this.cache.clear(); process.stdout.write('\x1b[2J'); return; }
|
|
1968
|
+
if (n === 'escape') {
|
|
1969
|
+
if (this.sel) { this.sel = null; return; }
|
|
1970
|
+
if (S.running) { S.abort(); this.flash('Interrupted'); return; }
|
|
1971
|
+
return;
|
|
1972
|
+
}
|
|
1973
|
+
const matches = this.slashMatches();
|
|
1974
|
+
if (matches.length) {
|
|
1975
|
+
if (n === 'up') { this.slashSel = (this.slashSel + matches.length - 1) % matches.length; return; }
|
|
1976
|
+
if (n === 'down') { this.slashSel = (this.slashSel + 1) % matches.length; return; }
|
|
1977
|
+
if (n === 'tab' || (n === 'enter' && !ev.alt && matches[this.slashSel] && I.text !== '/' + matches[this.slashSel][0])) {
|
|
1978
|
+
const pick = matches[this.slashSel]; I.text = '/' + pick[0]; I.cur = I.text.length;
|
|
1979
|
+
if (n === 'enter') { return this.submit(); }
|
|
1980
|
+
return;
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
if (this.sel) return this.selectKey(ev);
|
|
1984
|
+
if (n === 'tab') { S.agent = ev.shift ? (S.agent === 'plan' ? 'build' : 'plan') : (S.agent === 'build' ? 'plan' : 'build'); this.flash(`${AGENTS[S.agent].name} mode: ${AGENTS[S.agent].desc}`); return; }
|
|
1985
|
+
if (n === 'pageup') { this.scroll += Math.max(3, this.rows - 8); return; }
|
|
1986
|
+
if (n === 'pagedown') { this.scroll = Math.max(0, this.scroll - Math.max(3, this.rows - 8)); return; }
|
|
1987
|
+
if (n === 'end' && !I.text) { this.scroll = 0; return; }
|
|
1988
|
+
if (n === 'enter') {
|
|
1989
|
+
if (ev.alt) return this.insert('\n');
|
|
1990
|
+
if (I.text.endsWith('\\')) { I.text = I.text.slice(0, -1); I.cur = I.text.length; return this.insert('\n'); }
|
|
1991
|
+
return this.submit();
|
|
1992
|
+
}
|
|
1993
|
+
if (ev.ctrl && n === 'j') return this.insert('\n');
|
|
1994
|
+
if (n === 'text') return this.insert(ev.text);
|
|
1995
|
+
if (n === 'backspace') {
|
|
1996
|
+
if (ev.alt) { const i = this.wordLeft(); I.text = I.text.slice(0, i) + I.text.slice(I.cur); I.cur = i; return; }
|
|
1997
|
+
if (I.cur > 0) { const cp = Array.from(I.text.slice(0, I.cur)).pop(); I.text = I.text.slice(0, I.cur - cp.length) + I.text.slice(I.cur); I.cur -= cp.length; } return;
|
|
1998
|
+
}
|
|
1999
|
+
if (n === 'delete' || (ev.ctrl && n === 'd')) { if (I.cur < I.text.length) { const cp = String.fromCodePoint(I.text.codePointAt(I.cur)); I.text = I.text.slice(0, I.cur) + I.text.slice(I.cur + cp.length); } return; }
|
|
2000
|
+
if (n === 'left') { if (ev.ctrl || ev.alt) { I.cur = this.wordLeft(); return; } if (I.cur > 0) I.cur -= Array.from(I.text.slice(0, I.cur)).pop().length; return; }
|
|
2001
|
+
if (n === 'right') { if (ev.ctrl || ev.alt) { I.cur = this.wordRight(); return; } if (I.cur < I.text.length) I.cur += String.fromCodePoint(I.text.codePointAt(I.cur)).length; return; }
|
|
2002
|
+
if (n === 'home' || (ev.ctrl && n === 'a')) { I.cur = this.lineBounds()[0]; return; }
|
|
2003
|
+
if (n === 'end' || (ev.ctrl && n === 'e')) { I.cur = this.lineBounds()[1]; return; }
|
|
2004
|
+
if (ev.ctrl && n === 'u') { const [s] = this.lineBounds(); I.text = I.text.slice(0, s) + I.text.slice(I.cur); I.cur = s; return; }
|
|
2005
|
+
if (ev.ctrl && n === 'k') { const [, e] = this.lineBounds(); I.text = I.text.slice(0, I.cur) + I.text.slice(e); return; }
|
|
2006
|
+
if (ev.ctrl && n === 'w') { const i = this.wordLeft(); I.text = I.text.slice(0, i) + I.text.slice(I.cur); I.cur = i; return; }
|
|
2007
|
+
if (n === 'up') {
|
|
2008
|
+
if (ev.shift) { this.scroll += 3; return; }
|
|
2009
|
+
if (this.moveVertical(-1)) return;
|
|
2010
|
+
if (!I.text) { const idx = this.lastUserBlock(); if (idx >= 0) { this.sel = { bi: idx, reveal: true }; return; } }
|
|
2011
|
+
if (I.hist.length && I.hi < I.hist.length - 1) { if (I.hi === -1) I.draft = I.text; I.hi++; I.text = I.hist[I.hi]; I.cur = I.text.length; } return;
|
|
2012
|
+
}
|
|
2013
|
+
if (n === 'down') {
|
|
2014
|
+
if (ev.shift) { this.scroll = Math.max(0, this.scroll - 3); return; }
|
|
2015
|
+
if (this.moveVertical(1)) return;
|
|
2016
|
+
if (I.hi >= 0) { I.hi--; I.text = I.hi === -1 ? I.draft : I.hist[I.hi]; I.cur = I.text.length; } return;
|
|
2017
|
+
}
|
|
2018
|
+
},
|
|
2019
|
+
lastUserBlock() { const B = this.S.blocks; for (let i = B.length - 1; i >= 0; i--) if (B[i].type === 'user') return i; return -1; },
|
|
2020
|
+
selectKey(ev) {
|
|
2021
|
+
const B = this.S.blocks, n = ev.name;
|
|
2022
|
+
const step = (d) => { let i = this.sel.bi + d; while (i >= 0 && i < B.length && B[i].type !== 'user') i += d; if (i >= 0 && i < B.length) this.sel = { bi: i, reveal: true }; };
|
|
2023
|
+
if (n === 'up' || n === 'k') return step(-1);
|
|
2024
|
+
if (n === 'down' || n === 'j' || (n === 'text' && ev.text === 'j')) return step(1);
|
|
2025
|
+
if (n === 'text' && ev.text === 'k') return step(-1);
|
|
2026
|
+
if (n === 'enter') { const bi = this.sel.bi; this.sel = null; return this.messageActions(bi); }
|
|
2027
|
+
if (n === 'text') { this.sel = null; this.insert(ev.text); }
|
|
2028
|
+
},
|
|
2029
|
+
onMouse(ev) {
|
|
2030
|
+
if (ev.b === 64 || ev.b === 65) {
|
|
2031
|
+
const d = ev.b === 64 ? 1 : -1;
|
|
2032
|
+
if (this.dialog && this.dialog.kind === 'list') { const items = this.visibleItems(); if (items.length) { this.dialog.sel = Math.max(0, Math.min(items.length - 1, this.dialog.sel - d)); } }
|
|
2033
|
+
else if (!this.dialog) this.scroll = Math.max(0, this.scroll + d * 3);
|
|
2034
|
+
this.schedule(); return;
|
|
2035
|
+
}
|
|
2036
|
+
if (ev.b !== 0 || !ev.press) return;
|
|
2037
|
+
if (this.dialog) {
|
|
2038
|
+
const h = this.dlgHit.find((r) => r.row === ev.y && ev.x >= r.x0 && ev.x < r.x1);
|
|
2039
|
+
if (h && h.act) h.act();
|
|
2040
|
+
else if (h && this.dialog.kind === 'list') { this.dialog.sel = h.idx; this.pickDialog(); }
|
|
2041
|
+
else if (!this.dlgBox || ev.x < this.dlgBox.x || ev.x >= this.dlgBox.x + this.dlgBox.w || ev.y < this.dlgBox.y || ev.y >= this.dlgBox.y + this.dlgBox.h) { if (this.dialog.kind !== 'perm') this.closeDialog(); }
|
|
2042
|
+
this.schedule(); return;
|
|
2043
|
+
}
|
|
2044
|
+
const hit = this.hit[ev.y];
|
|
2045
|
+
if (hit && hit.bi != null && this.S.blocks[hit.bi] && this.S.blocks[hit.bi].type === 'user') this.messageActions(hit.bi);
|
|
2046
|
+
this.schedule();
|
|
2047
|
+
},
|
|
2048
|
+
|
|
2049
|
+
// ------------------------------------------------------------ dialogs
|
|
2050
|
+
closeDialog() { const d = this.dialog; this.dialog = null; if (d && d.onClose) d.onClose(); this.schedule(); },
|
|
2051
|
+
openList(o) { this.dialog = Object.assign({ kind: 'list', filter: '', sel: 0, search: true, width: 62 }, o); const cur = this.dialog.items.findIndex((i) => i.current); if (cur >= 0 && !o.noPreselect) this.dialog.sel = cur; this.schedule(); },
|
|
2052
|
+
visibleItems() {
|
|
2053
|
+
const d = this.dialog; if (!d || d.kind !== 'list') return [];
|
|
2054
|
+
return d.filter ? d.items.filter((i) => !i.disabled && fuzzy(d.filter, i.title + ' ' + (i.desc || ''))) : d.items.filter((i) => !i.disabled);
|
|
2055
|
+
},
|
|
2056
|
+
pickDialog() { const items = this.visibleItems(); const it = items[this.dialog.sel]; if (!it) return; const d = this.dialog; this.dialog = null; if (d.onPick) d.onPick(it); this.schedule(); },
|
|
2057
|
+
dialogKey(ev) {
|
|
2058
|
+
const d = this.dialog, n = ev.name;
|
|
2059
|
+
if (d.kind === 'list') {
|
|
2060
|
+
const items = this.visibleItems();
|
|
2061
|
+
if (n === 'escape') return this.closeDialog();
|
|
2062
|
+
if (n === 'up' || (ev.ctrl && n === 'p')) { d.sel = items.length ? (d.sel + items.length - 1) % items.length : 0; return; }
|
|
2063
|
+
if (n === 'down' || (ev.ctrl && n === 'n')) { d.sel = items.length ? (d.sel + 1) % items.length : 0; return; }
|
|
2064
|
+
if (n === 'pageup') { d.sel = Math.max(0, d.sel - 8); return; }
|
|
2065
|
+
if (n === 'pagedown') { d.sel = Math.min(items.length - 1, d.sel + 8); return; }
|
|
2066
|
+
if (n === 'enter') return this.pickDialog();
|
|
2067
|
+
if (d.search) {
|
|
2068
|
+
if (n === 'backspace') { d.filter = d.filter.slice(0, -1); d.sel = 0; return; }
|
|
2069
|
+
if (n === 'text') { d.filter += ev.text; d.sel = 0; return; }
|
|
2070
|
+
if (ev.ctrl && n === 'u') { d.filter = ''; d.sel = 0; }
|
|
2071
|
+
}
|
|
2072
|
+
return;
|
|
2073
|
+
}
|
|
2074
|
+
if (d.kind === 'perm') {
|
|
2075
|
+
const opts = ['once', 'always', 'deny'];
|
|
2076
|
+
if (n === 'left' || (n === 'tab' && ev.shift)) { d.sel = (d.sel + 2) % 3; return; }
|
|
2077
|
+
if (n === 'right' || n === 'tab') { d.sel = (d.sel + 1) % 3; return; }
|
|
2078
|
+
const fin = (k) => { const r = d.resolve; this.dialog = null; r(k === 'deny' ? { ok: false, note: 'The user denied this action. Do not retry the same action; ask what they want instead.' } : { ok: true, always: k === 'always' }); this.schedule(); };
|
|
2079
|
+
if (n === 'enter') return fin(opts[d.sel]);
|
|
2080
|
+
if (n === 'escape' || (n === 'text' && /^n$/i.test(ev.text))) { this.S.interrupted = n === 'escape' ? true : this.S.interrupted; return fin('deny'); }
|
|
2081
|
+
if (n === 'text' && /^y$/i.test(ev.text)) return fin('once');
|
|
2082
|
+
if (n === 'text' && /^a$/i.test(ev.text)) return fin('always');
|
|
2083
|
+
if (ev.ctrl && n === 'c') { this.S.abort(); return fin('deny'); }
|
|
2084
|
+
return;
|
|
2085
|
+
}
|
|
2086
|
+
if (d.kind === 'input') {
|
|
2087
|
+
if (n === 'escape') { const r = d.resolve; this.dialog = null; r(null); return; }
|
|
2088
|
+
if (n === 'enter') { const r = d.resolve, t = d.text; this.dialog = null; r(t); return; }
|
|
2089
|
+
if (n === 'backspace') { d.text = d.text.slice(0, -1); return; }
|
|
2090
|
+
if (n === 'text') { d.text += ev.text; return; }
|
|
2091
|
+
return;
|
|
2092
|
+
}
|
|
2093
|
+
if (d.kind === 'info') {
|
|
2094
|
+
if (n === 'escape' || n === 'enter' || (n === 'text' && ev.text === 'q')) return this.closeDialog();
|
|
2095
|
+
if (d.onKey) d.onKey(ev);
|
|
2096
|
+
}
|
|
2097
|
+
},
|
|
2098
|
+
drawDialog(frame, cols, rows) {
|
|
2099
|
+
const d = this.dialog;
|
|
2100
|
+
for (let r = 0; r < rows; r++) frame[r] = dimRow(frame[r] || '');
|
|
2101
|
+
const dw = Math.min(cols - 4, d.kind === 'perm' ? 78 : d.kind === 'info' ? 70 : d.width || 62), inner = dw - 4;
|
|
2102
|
+
const L = []; const pushL = (s, extra) => L.push(Object.assign({ s }, extra || {}));
|
|
2103
|
+
const line = (s) => keepBg(' ' + fit(s, inner) + ' ', T.panel);
|
|
2104
|
+
const title = (t, right) => pushL(line(sty(t, { b: true, fg: T.text }) + ' '.repeat(Math.max(1, inner - strWidth(t) - strWidth(right || ''))) + sty(right || '', { fg: T.mut })));
|
|
2105
|
+
pushL(line(''));
|
|
2106
|
+
if (d.kind === 'list') {
|
|
2107
|
+
title(d.title, 'esc');
|
|
2108
|
+
if (d.search) { pushL(line('')); pushL(line(d.filter ? sty(d.filter, { fg: T.text }) + sty(' ', { bg: T.text }) : sty('S', { fg: T.black, bg: T.peach }) + sty('earch', { fg: T.mut }))); }
|
|
2109
|
+
pushL(line(''));
|
|
2110
|
+
const items = this.visibleItems();
|
|
2111
|
+
if (d.sel >= items.length) d.sel = Math.max(0, items.length - 1);
|
|
2112
|
+
const nSec = new Set(items.map((i) => i.section).filter(Boolean)).size;
|
|
2113
|
+
const maxRows = Math.max(3, Math.min(items.length + nSec * 2, rows - 14));
|
|
2114
|
+
let from = Math.max(0, Math.min(d.sel - Math.floor(maxRows / 2), items.length - maxRows));
|
|
2115
|
+
let lastSec = from > 0 ? items[from - 1].section : null;
|
|
2116
|
+
let used = 0;
|
|
2117
|
+
for (let i = from; i < items.length && used < maxRows; i++) {
|
|
2118
|
+
const it = items[i];
|
|
2119
|
+
if (it.section && it.section !== lastSec) { lastSec = it.section; if (used > 0) { pushL(line('')); used++; } pushL(line(sty(it.section, { b: true, fg: T.blue }))); used++; }
|
|
2120
|
+
const sel = i === d.sel;
|
|
2121
|
+
const right = it.key ? sty(it.key, { fg: sel ? '#3a2a1a' : T.mut }) : '';
|
|
2122
|
+
let main = sel ? sty(it.title, { b: true, fg: T.black }) : sty(it.title, { b: true, fg: T.text });
|
|
2123
|
+
if (it.current) main = sty('● ', { fg: sel ? T.black : T.green }) + main;
|
|
2124
|
+
const desc = it.desc ? ' ' + (sel ? sty(it.desc, { fg: '#4a3520' }) : sty(it.desc, { fg: T.mut })) : '';
|
|
2125
|
+
let body = main + desc;
|
|
2126
|
+
const room = inner - strWidth(right) - 1;
|
|
2127
|
+
body = fit(body, room) + ' ' + right;
|
|
2128
|
+
const full = sel ? sty(' ', { bg: T.peach }) + sty(fit(body, inner), { bg: T.peach }) : null;
|
|
2129
|
+
pushL(sel ? sty('', {}) + BG(T.peach) + ' ' + fit(body, inner).split('\x1b[0m').join('\x1b[0m' + BG(T.peach)) + ' ' + RESET : line(body), { idx: i });
|
|
2130
|
+
used++;
|
|
2131
|
+
}
|
|
2132
|
+
if (!items.length) pushL(line(sty('No results', { fg: T.mut })));
|
|
2133
|
+
pushL(line(''));
|
|
2134
|
+
} else if (d.kind === 'perm') {
|
|
2135
|
+
title(d.req.title, '');
|
|
2136
|
+
pushL(line(''));
|
|
2137
|
+
const shown = d.req.lines.slice(0, 12);
|
|
2138
|
+
for (const l of shown) {
|
|
2139
|
+
const txt = clip(l.s.replace(/\t/g, ' '), inner - 4);
|
|
2140
|
+
if (l.t === 'add') pushL(keepBg(' ' + fit(sty('+ ', { fg: T.green }) + txt, inner) + ' ', T.diffAdd));
|
|
2141
|
+
else if (l.t === 'del') pushL(keepBg(' ' + fit(sty('- ', { fg: T.red }) + txt, inner) + ' ', T.diffDel));
|
|
2142
|
+
else if (l.t === 'cmd') pushL(line(sty('$ ', { fg: T.green }) + sty(txt, { b: true, fg: T.text })));
|
|
2143
|
+
else pushL(line(sty(txt, { fg: T.mut })));
|
|
2144
|
+
}
|
|
2145
|
+
if (d.req.lines.length > 12) pushL(line(sty(`… ${d.req.lines.length - 12} more lines`, { fg: T.dim })));
|
|
2146
|
+
pushL(line(''));
|
|
2147
|
+
const labels = [' Allow once ', ' Always allow ', ' Deny '];
|
|
2148
|
+
const btn = labels.map((t, i) => (i === d.sel ? sty(t, { b: true, fg: T.black, bg: i === 2 ? T.red : T.peach }) : sty(t, { fg: T.mut, bg: T.panel3 }))).join(' ');
|
|
2149
|
+
pushL(line(btn), { perm: true });
|
|
2150
|
+
pushL(line(sty('←/→ choose · enter confirm · y once · a always · n deny', { fg: T.dim })));
|
|
2151
|
+
pushL(line(''));
|
|
2152
|
+
} else if (d.kind === 'input') {
|
|
2153
|
+
title(d.title, 'esc');
|
|
2154
|
+
pushL(line(''));
|
|
2155
|
+
for (const l of wrapAnsi(d.prompt || '', inner)) pushL(line(sty(l, { fg: T.mut })));
|
|
2156
|
+
pushL(line(''));
|
|
2157
|
+
pushL(keepBg(' ' + fit(sty('› ', { fg: T.peach }) + sty(d.text, { fg: T.text }) + sty(' ', { bg: T.text }), inner) + ' ', T.panel3));
|
|
2158
|
+
pushL(line(sty('enter send · esc cancel', { fg: T.dim })));
|
|
2159
|
+
pushL(line(''));
|
|
2160
|
+
} else {
|
|
2161
|
+
title(d.title, 'esc');
|
|
2162
|
+
pushL(line(''));
|
|
2163
|
+
for (const l of d.lines) for (const w of (l === '' ? [''] : wrapAnsi(l, inner))) pushL(line(w));
|
|
2164
|
+
pushL(line(''));
|
|
2165
|
+
if (d.footer) pushL(line(sty(d.footer, { fg: T.dim })));
|
|
2166
|
+
pushL(line(''));
|
|
2167
|
+
}
|
|
2168
|
+
const h = L.length, y0 = Math.max(1, Math.floor((rows - h) / 3)), x0 = Math.floor((cols - dw) / 2);
|
|
2169
|
+
this.dlgBox = { x: x0, y: y0, w: dw, h };
|
|
2170
|
+
L.forEach((it, i) => {
|
|
2171
|
+
const r = y0 + i; if (r >= rows) return;
|
|
2172
|
+
frame[r] = fit(sliceCols(frame[r], 0, x0), x0) + fit(it.s, dw) + sliceCols(frame[r], x0 + dw, cols);
|
|
2173
|
+
if (it.idx != null) this.dlgHit.push({ row: r, idx: it.idx, x0, x1: x0 + dw });
|
|
2174
|
+
if (it.perm) {
|
|
2175
|
+
const labels = [' Allow once ', ' Always allow ', ' Deny '], keys = ['once', 'always', 'deny'];
|
|
2176
|
+
let cx = x0 + 2;
|
|
2177
|
+
labels.forEach((t, k) => { const wv = strWidth(t); this.dlgHit.push({ row: r, x0: cx, x1: cx + wv, act: () => { d.sel = k; this.dialogKey({ name: 'enter' }); } }); cx += wv + 2; });
|
|
2178
|
+
}
|
|
2179
|
+
});
|
|
2180
|
+
},
|
|
2181
|
+
|
|
2182
|
+
// hooks that need a dialog
|
|
2183
|
+
approve(req) {
|
|
2184
|
+
return new Promise((resolve) => { this.dialog = { kind: 'perm', req, sel: 0, resolve }; this.schedule(); });
|
|
2185
|
+
},
|
|
2186
|
+
askUser(q, options) {
|
|
2187
|
+
return new Promise((resolve) => {
|
|
2188
|
+
const typed = () => { this.dialog = { kind: 'input', title: 'Question', prompt: q, text: '', resolve }; this.schedule(); };
|
|
2189
|
+
if (!options.length) return typed();
|
|
2190
|
+
const items = options.map((o) => ({ title: o, value: o })).concat([{ title: 'Type your own answer…', value: null }]);
|
|
2191
|
+
this.openList({ title: clip(q, 56), items, search: false, noPreselect: true, onPick: (it) => (it.value === null ? typed() : resolve(it.value)), onClose: () => resolve(null) });
|
|
2192
|
+
});
|
|
2193
|
+
},
|
|
2194
|
+
|
|
2195
|
+
// ------------------------------------------------------------ commands
|
|
2196
|
+
async submit() {
|
|
2197
|
+
const S = this.S, I = this.input, text = I.text.trim();
|
|
2198
|
+
if (!text) return;
|
|
2199
|
+
if (S.running && !text.startsWith('/')) { this.flash('Still working, press esc to interrupt first'); return; }
|
|
2200
|
+
I.hist.unshift(text); I.hist = I.hist.slice(0, 100); I.text = ''; I.cur = 0; I.hi = -1; this.sel = null;
|
|
2201
|
+
if (text.startsWith('/') && !text.includes('\n')) { const [name, ...rest] = text.slice(1).split(/\s+/); return this.command(name.toLowerCase(), rest.join(' ')); }
|
|
2202
|
+
if (text.startsWith('!') && !text.includes('\n')) return this.shellPass(text.slice(1).trim());
|
|
2203
|
+
return this.runTurn(text);
|
|
2204
|
+
},
|
|
2205
|
+
async runTurn(text) {
|
|
2206
|
+
this.started = true; this.scroll = 0;
|
|
2207
|
+
try { await agentTurn(this.S, text); } catch (e) { this.error(String(e && e.message || e)); }
|
|
2208
|
+
saveSession(this.S); this.schedule();
|
|
2209
|
+
},
|
|
2210
|
+
async shellPass(cmd) {
|
|
2211
|
+
if (!cmd) return;
|
|
2212
|
+
this.started = true; this.scroll = 0;
|
|
2213
|
+
const id = 'sh' + Date.now();
|
|
2214
|
+
this.toolStart({ id, name: 'run_command', summary: cmd });
|
|
2215
|
+
const r = await runShell(cmd, { cwd: this.S.cwd, timeoutMs: 300000, onLine: (l) => this.toolOutput(id, l), setCancel: this.S.setCancel });
|
|
2216
|
+
this.toolEnd({ id, status: r.code === 0 ? 'done' : 'error', summary: 'exit ' + r.code, text: r.output });
|
|
2217
|
+
},
|
|
2218
|
+
async command(name, arg) {
|
|
2219
|
+
const S = this.S;
|
|
2220
|
+
switch (name) {
|
|
2221
|
+
case 'new': case 'clear': return this.newSession();
|
|
2222
|
+
case 'sessions': case 'resume': return this.pickSession();
|
|
2223
|
+
case 'model': case 'models': if (arg) { this.setModel(arg); return; } return this.pickModel();
|
|
2224
|
+
case 'agent': return this.pickAgent();
|
|
2225
|
+
case 'credits': case 'usage': return this.showCredits();
|
|
2226
|
+
case 'buy': openBrowser(S.baseUrl + '/dashboard#buy'); return this.flash('Opening the dashboard in your browser…');
|
|
2227
|
+
case 'undo': return this.undoLast();
|
|
2228
|
+
case 'copy': return this.copyLast();
|
|
2229
|
+
case 'compact': if (S.running) return this.flash('Wait for the current response'); this.flash('Summarizing…'); await compactSession(S); saveSession(S); return;
|
|
2230
|
+
case 'think': S.showThinking = !S.showThinking; saveConfigPatch({ showThinking: S.showThinking }); this.cache.clear(); return this.flash('Reasoning ' + (S.showThinking ? 'visible' : 'hidden'));
|
|
2231
|
+
case 'auto': S.auto = !S.auto; return this.flash(S.auto ? 'Auto-approve ON: changes and commands run without asking' : 'Auto-approve OFF');
|
|
2232
|
+
case 'init': return this.runTurn('Explore this project (structure, languages, build and test commands, conventions) and create a BENCHCODE.md in the project root with short notes that will help future sessions. Keep it under 60 lines.');
|
|
2233
|
+
case 'retry': if (!S.messages.length) return this.flash('Nothing to retry'); if (S.running) return; try { await agentTurn(S, null); } catch (e) { this.error(String(e.message || e)); } return saveSession(S);
|
|
2234
|
+
case 'login': return this.loginFlow();
|
|
2235
|
+
case 'logout': saveConfigPatch({ apiKey: '' }); S.apiKey = ''; S.account = null; return this.flash('Signed out. Use /login to sign in again.');
|
|
2236
|
+
case 'help': case '?': return this.showHelp();
|
|
2237
|
+
case 'exit': case 'quit': case 'q': return this.quit();
|
|
2238
|
+
default: this.flash('Unknown command /' + name + ' (try /help)');
|
|
2239
|
+
}
|
|
2240
|
+
},
|
|
2241
|
+
openPalette() {
|
|
2242
|
+
const S = this.S;
|
|
2243
|
+
const mk = (title, key, run, desc) => ({ title, key, desc, run });
|
|
2244
|
+
const items = [
|
|
2245
|
+
Object.assign(mk('Switch model', '/model', () => this.pickModel()), { section: 'Session' }),
|
|
2246
|
+
mk('Switch agent (Build / Plan)', 'tab', () => this.pickAgent()),
|
|
2247
|
+
mk('New session', '/new', () => this.newSession()),
|
|
2248
|
+
mk('Switch session', '/sessions', () => this.pickSession()),
|
|
2249
|
+
mk('Undo last message', '/undo', () => this.undoLast()),
|
|
2250
|
+
mk('Compact conversation', '/compact', () => this.command('compact')),
|
|
2251
|
+
mk('Copy last response', '/copy', () => this.copyLast()),
|
|
2252
|
+
Object.assign(mk('Credits and free quota', '/credits', () => this.showCredits()), { section: 'Account' }),
|
|
2253
|
+
mk('Buy credits', '/buy', () => this.command('buy')),
|
|
2254
|
+
mk('Sign in with browser', '/login', () => this.loginFlow()),
|
|
2255
|
+
mk('Sign out', '/logout', () => this.command('logout')),
|
|
2256
|
+
Object.assign(mk(S.auto ? 'Turn off auto-approve' : 'Turn on auto-approve', '/auto', () => this.command('auto')), { section: 'Settings' }),
|
|
2257
|
+
mk(S.showThinking ? 'Hide model reasoning' : 'Show model reasoning', '/think', () => this.command('think')),
|
|
2258
|
+
mk('Create BENCHCODE.md', '/init', () => this.command('init')),
|
|
2259
|
+
mk('Keyboard shortcuts', '/help', () => this.showHelp()),
|
|
2260
|
+
mk('Exit', 'ctrl+c', () => this.quit()),
|
|
2261
|
+
];
|
|
2262
|
+
this.openList({ title: 'Commands', items, noPreselect: true, onPick: (it) => it.run() });
|
|
2263
|
+
},
|
|
2264
|
+
setModel(id) { const S = this.S; S.model = id; S.textMode = false; saveConfigPatch({ model: id }); this.flash('Model: ' + id); },
|
|
2265
|
+
async pickModel() {
|
|
2266
|
+
const S = this.S;
|
|
2267
|
+
if (!S.models.length) await loadModels(S);
|
|
2268
|
+
if (!S.models.length) return this.flash('Could not load the model list');
|
|
2269
|
+
const tierName = { flash: 'Fast', standard: 'Standard', premium: 'Premium' };
|
|
2270
|
+
const order = { flash: 0, standard: 1, premium: 2 };
|
|
2271
|
+
const list = S.models.slice().sort((a, b) => (order[a.tier] ?? 3) - (order[b.tier] ?? 3) || (a.credit_cost || 9) - (b.credit_cost || 9) || String(a.id).localeCompare(String(b.id)));
|
|
2272
|
+
const items = list.map((m) => ({ title: m.id, desc: m.vision ? 'vision' : '', key: (m.credit_cost != null ? m.credit_cost : '?') + ' cr', section: tierName[m.tier] || 'Other', current: m.id === S.model, value: m.id }));
|
|
2273
|
+
this.openList({ title: 'Select model', items, width: 66, onPick: (it) => this.setModel(it.value) });
|
|
2274
|
+
},
|
|
2275
|
+
pickAgent() {
|
|
2276
|
+
const items = Object.keys(AGENTS).map((k) => ({ title: AGENTS[k].name, desc: AGENTS[k].desc, value: k, current: k === this.S.agent }));
|
|
2277
|
+
this.openList({ title: 'Select agent', items, search: false, onPick: (it) => { this.S.agent = it.value; this.flash(`${AGENTS[it.value].name} mode`); } });
|
|
2278
|
+
},
|
|
2279
|
+
newSession() {
|
|
2280
|
+
const S = this.S;
|
|
2281
|
+
if (S.running) return this.flash('Wait for the current response or press esc');
|
|
2282
|
+
saveSession(S);
|
|
2283
|
+
Object.assign(S, { id: Date.now().toString(36) + crypto.randomBytes(2).toString('hex'), title: '', messages: [], blocks: [], snapshots: [], changed: new Map(), todos: [], ctxTokens: 0, spent: 0, calls: 0, created: Date.now(), textMode: false, always: new Set() });
|
|
2284
|
+
this.cache.clear(); this.started = false; this.scroll = 0; this.sel = null; this.schedule();
|
|
2285
|
+
},
|
|
2286
|
+
pickSession() {
|
|
2287
|
+
const list = listSessions();
|
|
2288
|
+
if (!list.length) return this.flash('No saved sessions yet');
|
|
2289
|
+
const items = list.map((s) => ({ title: s.title, desc: tidyPath(s.cwd || '') + ' · ' + s.turns + ' msg', key: ago(s.updated), value: s.id, current: s.id === this.S.id }));
|
|
2290
|
+
this.openList({ title: 'Sessions', items, width: 78, onPick: (it) => {
|
|
2291
|
+
if (this.S.running) return this.flash('Wait for the current response');
|
|
2292
|
+
saveSession(this.S);
|
|
2293
|
+
if (loadSessionInto(this.S, it.value)) { this.cache.clear(); this.started = true; this.scroll = 0; this.flash('Session loaded'); this.schedule(); }
|
|
2294
|
+
} });
|
|
2295
|
+
},
|
|
2296
|
+
messageActions(bi) {
|
|
2297
|
+
const S = this.S, b = S.blocks[bi];
|
|
2298
|
+
if (!b || b.type !== 'user') return;
|
|
2299
|
+
const items = [
|
|
2300
|
+
{ title: 'Revert', desc: 'undo messages and file changes', value: 'revert' },
|
|
2301
|
+
{ title: 'Copy', desc: 'message text to clipboard', value: 'copy' },
|
|
2302
|
+
{ title: 'Fork', desc: 'create a new session', value: 'fork' },
|
|
2303
|
+
];
|
|
2304
|
+
this.openList({ title: 'Message Actions', items, noPreselect: true, onPick: (it) => {
|
|
2305
|
+
if (it.value === 'copy') { this.flash(copyToClipboard(b.text) ? 'Copied to clipboard' : 'Copy sent to the terminal'); return; }
|
|
2306
|
+
if (S.running) return this.flash('Wait for the current response or press esc');
|
|
2307
|
+
if (b.stale) return this.flash('Not available after /compact');
|
|
2308
|
+
if (it.value === 'revert') {
|
|
2309
|
+
const r = revertTo(S, bi);
|
|
2310
|
+
if (!r) return this.flash('Cannot revert this message');
|
|
2311
|
+
this.cache.clear(); this.input.text = r.text; this.input.cur = r.text.length;
|
|
2312
|
+
this.flash(`Reverted${r.restored ? ` · ${r.restored} file change${r.restored > 1 ? 's' : ''} undone` : ''}${r.failed ? ` (${r.failed} failed)` : ''}`);
|
|
2313
|
+
saveSession(S);
|
|
2314
|
+
} else if (it.value === 'fork') {
|
|
2315
|
+
saveSession(S);
|
|
2316
|
+
const f = bi >= 0 ? forkFrom(S, bi) : null;
|
|
2317
|
+
if (!f) return this.flash('Cannot fork this message');
|
|
2318
|
+
const keep = { setCancel: S.setCancel, abort: S.abort };
|
|
2319
|
+
Object.assign(S, f.session, keep, { _cancel: null });
|
|
2320
|
+
this.cache.clear(); this.input.text = f.text; this.input.cur = f.text.length; this.scroll = 0;
|
|
2321
|
+
this.flash('Forked into a new session'); saveSession(S);
|
|
2322
|
+
}
|
|
2323
|
+
} });
|
|
2324
|
+
},
|
|
2325
|
+
undoLast() {
|
|
2326
|
+
const S = this.S;
|
|
2327
|
+
if (S.running) return this.flash('Wait for the current response or press esc');
|
|
2328
|
+
const bi = this.lastUserBlock();
|
|
2329
|
+
if (bi < 0) return this.flash('Nothing to undo');
|
|
2330
|
+
const b = S.blocks[bi];
|
|
2331
|
+
if (b.stale) return this.flash('Not available after /compact');
|
|
2332
|
+
const r = revertTo(S, bi);
|
|
2333
|
+
this.cache.clear(); this.input.text = r.text; this.input.cur = r.text.length;
|
|
2334
|
+
this.flash(`Undone${r.restored ? ` · ${r.restored} file change${r.restored > 1 ? 's' : ''} restored` : ''}`);
|
|
2335
|
+
saveSession(S);
|
|
2336
|
+
},
|
|
2337
|
+
copyLast() {
|
|
2338
|
+
const B = this.S.blocks; let t = '';
|
|
2339
|
+
for (let i = B.length - 1; i >= 0; i--) if (B[i].type === 'assistant' && B[i].text) { t = B[i].text; break; }
|
|
2340
|
+
if (!t) return this.flash('Nothing to copy');
|
|
2341
|
+
this.flash(copyToClipboard(t) ? 'Copied to clipboard' : 'Copy sent to the terminal');
|
|
2342
|
+
},
|
|
2343
|
+
async showCredits() {
|
|
2344
|
+
await refreshAccount(this.S);
|
|
2345
|
+
const a = this.S.account;
|
|
2346
|
+
const lines = [];
|
|
2347
|
+
if (!a) lines.push(sty('Could not load your account. Check your connection or sign in again with /login.', { fg: T.red }));
|
|
2348
|
+
else if (a.unmetered) lines.push('This key is not metered.');
|
|
2349
|
+
else {
|
|
2350
|
+
const f = a.free || {}, secs = f.resets_at ? (Date.parse(f.resets_at) - Date.now()) / 1000 : 0;
|
|
2351
|
+
lines.push(sty(a.name || '', { b: true, fg: T.text }) + (a.email ? sty(' ' + a.email, { fg: T.mut }) : ''), '');
|
|
2352
|
+
lines.push(sty('Purchased credits ', { fg: T.mut }) + sty(nf(a.credits), { b: true, fg: T.text }) + sty(' never expire', { fg: T.dim }));
|
|
2353
|
+
lines.push(sty('Free today ', { fg: T.mut }) + sty(`${f.left} of ${f.cap} left`, { b: true, fg: f.left > 0 ? T.green : T.red }));
|
|
2354
|
+
if (secs > 0) lines.push(sty('Free credits reset in ', { fg: T.mut }) + sty(fmtDur(secs), { b: true, fg: T.text }) + sty(' (00:00 UTC)', { fg: T.dim }));
|
|
2355
|
+
lines.push('', sty('This session ', { fg: T.mut }) + sty(`${nf(this.S.spent)} credits · ${this.S.calls} calls · ${nf(this.S.ctxTokens)} tokens in context`, { fg: T.text }));
|
|
2356
|
+
lines.push(sty('Total requests ever ', { fg: T.mut }) + sty(nf(a.total_requests || 0), { fg: T.text }));
|
|
2357
|
+
}
|
|
2358
|
+
this.dialog = { kind: 'info', title: 'Credits', lines, footer: 'b buy credits r refresh esc close', onKey: (ev) => {
|
|
2359
|
+
if (ev.name === 'text' && ev.text === 'b') { openBrowser(this.S.baseUrl + '/dashboard#buy'); this.flash('Opening the dashboard…'); }
|
|
2360
|
+
if (ev.name === 'text' && ev.text === 'r') { this.closeDialog(); this.showCredits(); }
|
|
2361
|
+
} };
|
|
2362
|
+
this.schedule();
|
|
2363
|
+
},
|
|
2364
|
+
showHelp() {
|
|
2365
|
+
const k = (a, b) => sty(a.padEnd(18), { b: true, fg: T.text }) + sty(b, { fg: T.mut });
|
|
2366
|
+
this.dialog = { kind: 'info', title: 'Keyboard shortcuts', lines: [
|
|
2367
|
+
k('enter', 'send message'), k('alt+enter / ctrl+j', 'new line (or end a line with \\)'), k('tab', 'switch Build / Plan agent'), k('ctrl+p', 'command palette'),
|
|
2368
|
+
k('esc', 'interrupt the running task'), k('↑ (empty input)', 'select a message: revert, copy, fork'), k('click a message', 'same, with the mouse'),
|
|
2369
|
+
k('pgup / pgdn', 'scroll the conversation'), k('mouse wheel', 'scroll'), k('/', 'slash commands'), k('!command', 'run a shell command yourself'),
|
|
2370
|
+
k('ctrl+c', 'interrupt · twice to exit'), k('ctrl+l', 'redraw screen'), '', sty('Permission prompts: y once, a always, n deny.', { fg: T.dim }),
|
|
2371
|
+
] };
|
|
2372
|
+
},
|
|
2373
|
+
async loginFlow() {
|
|
2374
|
+
if (this.S.running) return this.flash('Wait for the current response');
|
|
2375
|
+
let cancelled = false;
|
|
2376
|
+
const d = { kind: 'info', title: 'Sign in', lines: [sty('Starting…', { fg: T.mut })], footer: 'esc cancel', onClose: () => { cancelled = true; } };
|
|
2377
|
+
this.dialog = d; this.schedule();
|
|
2378
|
+
try {
|
|
2379
|
+
const res = await deviceLogin({ baseUrl: this.S.baseUrl }, {
|
|
2380
|
+
cancelled: () => cancelled,
|
|
2381
|
+
show: ({ url, code, opened }) => {
|
|
2382
|
+
d.lines = [opened ? 'Your browser should open. If not, visit:' : 'Open this link in a browser:', sty(url, { fg: T.blue, u: true }), '', 'and make sure the code matches:', sty(' ' + code, { b: true, fg: T.peach }), '', sty('Waiting for you to approve…', { fg: T.mut })];
|
|
2383
|
+
this.schedule();
|
|
2384
|
+
},
|
|
2385
|
+
});
|
|
2386
|
+
d.onClose = null; if (this.dialog === d) this.dialog = null;
|
|
2387
|
+
saveConfigPatch({ apiKey: res.api_key });
|
|
2388
|
+
this.S.apiKey = res.api_key; this.cfg.apiKey = res.api_key;
|
|
2389
|
+
this.flash('Signed in' + (res.name ? ' as ' + res.name : ''));
|
|
2390
|
+
refreshAccount(this.S); loadModels(this.S);
|
|
2391
|
+
} catch (e) {
|
|
2392
|
+
if (this.dialog === d) { d.onClose = null; this.dialog = null; }
|
|
2393
|
+
if (!cancelled) this.flash('Sign-in failed: ' + e.message, 5000);
|
|
2394
|
+
}
|
|
2395
|
+
this.schedule();
|
|
2396
|
+
},
|
|
2397
|
+
});
|
|
2398
|
+
|
|
2399
|
+
// ================================================================ CLI entry
|
|
2400
|
+
const HELP = `${bold('BenchCode')} ${dim('v' + VERSION)} terminal coding agent for the Ahar AI API
|
|
2401
|
+
|
|
2402
|
+
${bold('Usage')}
|
|
2403
|
+
benchcode open the full-screen interface in this folder
|
|
2404
|
+
benchcode "fix the failing tests" run one task, print the result, exit
|
|
2405
|
+
cat error.log | benchcode "why does this fail?"
|
|
2406
|
+
benchcode login | logout | models | sessions | doctor | update | config
|
|
2407
|
+
|
|
2408
|
+
${bold('Options')}
|
|
2409
|
+
-m, --model <id> model to use (default ${DEFAULT_MODEL}); list with "benchcode models"
|
|
2410
|
+
-c, --continue continue the last session in this folder
|
|
2411
|
+
-y, --yes approve every file change and command automatically
|
|
2412
|
+
--plan start in read-only Plan mode
|
|
2413
|
+
-C, --cwd <dir> work in another folder
|
|
2414
|
+
--max-steps <n> tool-use steps per task (default 40)
|
|
2415
|
+
--plain no full-screen UI (simple scrolling output)
|
|
2416
|
+
--no-color plain colors
|
|
2417
|
+
-v, --version print version
|
|
2418
|
+
-h, --help this help
|
|
2419
|
+
|
|
2420
|
+
${bold('In the interface')}
|
|
2421
|
+
tab switch Build/Plan · ctrl+p commands · / slash commands · esc interrupt
|
|
2422
|
+
↑ on an empty prompt (or click a message): revert, copy or fork it
|
|
2423
|
+
!<command> run a shell command yourself · end a line with \\ for a new line
|
|
2424
|
+
|
|
2425
|
+
${bold('Environment')}
|
|
2426
|
+
BENCHCODE_API_KEY, BENCHCODE_MODEL, BENCHCODE_BASE_URL, BENCHCODE_MOUSE=0, NO_COLOR
|
|
2427
|
+
`;
|
|
2428
|
+
|
|
2429
|
+
function parseArgs(argv) {
|
|
2430
|
+
const o = { prompt: [], cmd: null, yes: false, model: '', cwd: '', maxSteps: 40, help: false, version: false, rest: [], cont: false, plain: false, plan: false, key: false };
|
|
2431
|
+
const subs = new Set(['login', 'logout', 'models', 'sessions', 'doctor', 'update', 'config']);
|
|
2432
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2433
|
+
const a = argv[i];
|
|
2434
|
+
if (i === 0 && subs.has(a)) { o.cmd = a; o.rest = argv.slice(1); if (o.rest.includes('--key')) o.key = true; break; }
|
|
2435
|
+
if (a === '-h' || a === '--help') o.help = true;
|
|
2436
|
+
else if (a === '-v' || a === '--version') o.version = true;
|
|
2437
|
+
else if (a === '-y' || a === '--yes') o.yes = true;
|
|
2438
|
+
else if (a === '-c' || a === '--continue') o.cont = true;
|
|
2439
|
+
else if (a === '--plain') o.plain = true;
|
|
2440
|
+
else if (a === '--plan') o.plan = true;
|
|
2441
|
+
else if (a === '-p' || a === '--print' || a === '--no-color') { /* accepted */ }
|
|
2442
|
+
else if (a === '-m' || a === '--model') o.model = argv[++i] || '';
|
|
2443
|
+
else if (a === '-C' || a === '--cwd') o.cwd = argv[++i] || '';
|
|
2444
|
+
else if (a === '--max-steps') o.maxSteps = Math.max(1, parseInt(argv[++i], 10) || 40);
|
|
2445
|
+
else if (a.startsWith('--model=')) o.model = a.slice(8);
|
|
2446
|
+
else if (a.startsWith('--cwd=')) o.cwd = a.slice(6);
|
|
2447
|
+
else if (a === '--') { o.prompt.push(...argv.slice(i + 1)); break; }
|
|
2448
|
+
else if (a.startsWith('-') && a.length > 1) { log(red('Unknown option: ' + a)); log('Try benchcode --help'); process.exit(2); }
|
|
2449
|
+
else o.prompt.push(a);
|
|
2450
|
+
}
|
|
2451
|
+
return o;
|
|
2452
|
+
}
|
|
2453
|
+
function askSecret(prompt) {
|
|
2454
|
+
return new Promise((resolve) => {
|
|
2455
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: !!process.stdin.isTTY });
|
|
2456
|
+
let muted = false; const orig = rl._writeToOutput;
|
|
2457
|
+
rl._writeToOutput = function (s) { if (!muted) orig.call(rl, s); };
|
|
2458
|
+
process.stderr.write(prompt); muted = true;
|
|
2459
|
+
rl.question('', (a) => { rl.close(); process.stderr.write('\n'); resolve(String(a || '').trim()); });
|
|
2460
|
+
});
|
|
2461
|
+
}
|
|
2462
|
+
function printModels(list, current) {
|
|
2463
|
+
const rows = list.slice().sort((a, b) => (a.credit_cost || 9) - (b.credit_cost || 9) || String(a.id).localeCompare(String(b.id)));
|
|
2464
|
+
log(bold('Model'.padEnd(46)) + bold('Tier'.padEnd(10)) + bold('Credits/request'));
|
|
2465
|
+
for (const m of rows) log((m.id === current ? green('● ') : ' ') + String(m.id).padEnd(44) + String(m.tier || '').padEnd(10) + (m.credit_cost != null ? m.credit_cost : '?') + (m.vision ? dim(' vision') : ''));
|
|
2466
|
+
log(dim('\nEach agent step is one request. Switch with /model <id> or benchcode -m <id>.'));
|
|
2467
|
+
}
|
|
2468
|
+
function cmpVer(a, b) { const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number); for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) - (y[i] || 0); return 0; }
|
|
2469
|
+
async function latestVersion(cfg) {
|
|
2470
|
+
try {
|
|
2471
|
+
const st = readJson(STATE_FILE, {});
|
|
2472
|
+
if (st.lastCheck && Date.now() - st.lastCheck < 20 * 3600 * 1000) return st.latest || null;
|
|
2473
|
+
const ctl = new AbortController(); const t = setTimeout(() => ctl.abort(), 2500);
|
|
2474
|
+
const j = await (await fetch(cfg.baseUrl + '/v2/version', { signal: ctl.signal })).json(); clearTimeout(t);
|
|
2475
|
+
writeJson(STATE_FILE, { lastCheck: Date.now(), latest: j.version }); return j.version || null;
|
|
2476
|
+
} catch (_) { return null; }
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
async function cmdLogin(cfg, o) {
|
|
2480
|
+
if (o && o.key) {
|
|
2481
|
+
log(`Paste an API key from ${cyan(cfg.baseUrl + '/dashboard')}`);
|
|
2482
|
+
const key = await askSecret('API key: ');
|
|
2483
|
+
if (!key) { log(red('No key entered.')); process.exit(1); }
|
|
2484
|
+
try { const list = await fetchModels(Object.assign({}, cfg, { apiKey: key })); saveConfigPatch({ apiKey: key }); log(green('✔ Signed in.') + dim(` ${list.length} models available.`)); }
|
|
2485
|
+
catch (e) { log(red('✖ That key did not work: ' + e.message)); process.exit(1); }
|
|
2486
|
+
return;
|
|
2487
|
+
}
|
|
2488
|
+
log(bold('Sign in to Ahar AI'));
|
|
2489
|
+
try {
|
|
2490
|
+
const res = await deviceLogin(cfg, {
|
|
2491
|
+
cancelled: () => false,
|
|
2492
|
+
show: ({ url, code, opened }) => {
|
|
2493
|
+
log(opened ? 'Opening your browser…' : 'Open this link in a browser:');
|
|
2494
|
+
log(' ' + cyan(url));
|
|
2495
|
+
log('Check that the code shown there is ' + bold(yellow(code)));
|
|
2496
|
+
log(dim('Waiting for approval (Ctrl+C to cancel)…'));
|
|
2497
|
+
},
|
|
2498
|
+
});
|
|
2499
|
+
saveConfigPatch({ apiKey: res.api_key });
|
|
2500
|
+
log(green('✔ Signed in') + (res.name ? ' as ' + bold(res.name) : '') + dim(' (key saved to ' + CONFIG_FILE + ')'));
|
|
2501
|
+
return res.api_key;
|
|
2502
|
+
} catch (e) { log(red('✖ ' + e.message)); log(dim('No browser on this machine? Open the link on your phone, or use: benchcode login --key')); process.exit(1); }
|
|
2503
|
+
}
|
|
2504
|
+
async function cmdDoctor(cfg) {
|
|
2505
|
+
const ok = (m) => log(green('✔ ') + m), bad = (m) => log(red('✖ ') + m);
|
|
2506
|
+
log(bold('BenchCode doctor'));
|
|
2507
|
+
ok(`BenchCode ${VERSION}, Node ${process.version}, ${process.platform}/${os.arch()}`);
|
|
2508
|
+
parseInt(process.versions.node, 10) >= 18 ? ok('Node.js 18+') : bad('Node.js 18 or newer is required');
|
|
2509
|
+
ok('Shell for commands: ' + SHELL.name + ' (' + SHELL.cmd + ')');
|
|
2510
|
+
ok(`Terminal: ${process.stdout.columns || '?'}x${process.stdout.rows || '?'}, ${TRUECOLOR ? 'true color' : '256 colors'}${process.stdout.isTTY ? '' : ' (not a TTY)'}`);
|
|
2511
|
+
try { const r = await fetch(cfg.baseUrl + '/health'); const j = await r.json(); ok(`Server reachable: ${cfg.baseUrl} (${j.version || j.status})`); } catch (e) { bad('Cannot reach ' + cfg.baseUrl + ': ' + (e.cause && e.cause.code || e.message)); }
|
|
2512
|
+
if (!cfg.apiKey) bad('Not signed in. Run: benchcode login');
|
|
2513
|
+
else {
|
|
2514
|
+
try { const l = await fetchModels(cfg); ok(`Signed in, ${l.length} models`); } catch (e) { bad('Sign-in check failed: ' + e.message); }
|
|
2515
|
+
const a = await fetchAccount(cfg);
|
|
2516
|
+
if (a && !a.unmetered) ok(`Credits: ${nf(a.credits)} purchased, ${a.free.left}/${a.free.cap} free today`); else if (!a) bad('Could not load credits (/v2/account)');
|
|
2517
|
+
}
|
|
2518
|
+
try { cp.execFileSync('git', ['--version'], { stdio: 'ignore' }); ok('git found'); } catch (_) { log(yellow('! ') + 'git not found (optional)'); }
|
|
2519
|
+
ok('Config: ' + CONFIG_FILE);
|
|
2520
|
+
}
|
|
2521
|
+
async function cmdUpdate(cfg) {
|
|
2522
|
+
let info;
|
|
2523
|
+
try { info = await (await fetch(cfg.baseUrl + '/v2/version')).json(); } catch (e) { log(red('Could not check for updates: ' + e.message)); process.exit(1); }
|
|
2524
|
+
if (!info || !info.version) { log(red('Update server returned nothing useful.')); process.exit(1); }
|
|
2525
|
+
if (cmpVer(info.version, VERSION) <= 0) { log(green('✔ You are on the latest version (' + VERSION + ').')); return; }
|
|
2526
|
+
log(`Updating ${VERSION} → ${info.version}`);
|
|
2527
|
+
if (__filename.includes('node_modules')) {
|
|
2528
|
+
log('Installed with npm. Running: npm install -g @benchcode/cli@latest');
|
|
2529
|
+
const r = cp.spawnSync(IS_WIN ? 'npm.cmd' : 'npm', ['install', '-g', '@benchcode/cli@latest'], { stdio: 'inherit', shell: IS_WIN });
|
|
2530
|
+
process.exit(r.status || 0);
|
|
2531
|
+
}
|
|
2532
|
+
const r = await fetch(cfg.baseUrl + '/v2/cli.js');
|
|
2533
|
+
if (!r.ok) { log(red('Download failed: HTTP ' + r.status)); process.exit(1); }
|
|
2534
|
+
const code = await r.text();
|
|
2535
|
+
if (info.sha256 && crypto.createHash('sha256').update(code).digest('hex') !== info.sha256) { log(red('Checksum mismatch, update aborted.')); process.exit(1); }
|
|
2536
|
+
const tmp = __filename + '.new';
|
|
2537
|
+
fs.writeFileSync(tmp, code, { mode: 0o755 }); fs.renameSync(tmp, __filename);
|
|
2538
|
+
log(green('✔ Updated to ' + info.version));
|
|
2539
|
+
}
|
|
2540
|
+
async function readStdin() { return new Promise((res) => { let d = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', (c) => (d += c)); process.stdin.on('end', () => res(d)); }); }
|
|
2541
|
+
|
|
2542
|
+
async function main() {
|
|
2543
|
+
const o = parseArgs(process.argv.slice(2));
|
|
2544
|
+
if (o.version) { out(VERSION + '\n'); return; }
|
|
2545
|
+
if (o.help) { log(HELP); return; }
|
|
2546
|
+
if (parseInt(process.versions.node, 10) < 18) { log(red('BenchCode needs Node.js 18 or newer. You have ' + process.version)); process.exit(1); }
|
|
2547
|
+
const cfg = loadConfig();
|
|
2548
|
+
|
|
2549
|
+
if (o.cmd === 'login') { await cmdLogin(cfg, o); return; }
|
|
2550
|
+
if (o.cmd === 'logout') { saveConfigPatch({ apiKey: '' }); log(green('✔ Signed out.')); return; }
|
|
2551
|
+
if (o.cmd === 'doctor') return cmdDoctor(cfg);
|
|
2552
|
+
if (o.cmd === 'update') return cmdUpdate(cfg);
|
|
2553
|
+
if (o.cmd === 'sessions') { const l = listSessions(30); if (!l.length) log('No saved sessions.'); l.forEach((s) => log(`${s.id} ${ago(s.updated).padEnd(9)} ${tidyPath(s.cwd || '').padEnd(32)} ${s.title}`)); return; }
|
|
2554
|
+
if (o.cmd === 'config') {
|
|
2555
|
+
const [verb, k, ...v] = o.rest;
|
|
2556
|
+
if (verb === 'set' && k) { if (!['model', 'baseUrl'].includes(k)) { log(red('Settable keys: model, baseUrl')); process.exit(1); } saveConfigPatch({ [k]: v.join(' ') }); log(green('✔ saved')); return; }
|
|
2557
|
+
log(JSON.stringify({ file: CONFIG_FILE, model: cfg.model, baseUrl: cfg.baseUrl, apiKey: cfg.apiKey ? cfg.apiKey.slice(0, 7) + '…' : '(not signed in)' }, null, 2));
|
|
2558
|
+
return;
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
if (!cfg.apiKey) {
|
|
2562
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY) { log(red('Not signed in.') + ` Run ${bold('benchcode login')} or set BENCHCODE_API_KEY.`); process.exit(1); }
|
|
2563
|
+
log(yellow('You are not signed in yet.'));
|
|
2564
|
+
cfg.apiKey = (await cmdLogin(cfg, {})) || loadConfig().apiKey;
|
|
2565
|
+
if (!cfg.apiKey) process.exit(1);
|
|
2566
|
+
log('');
|
|
2567
|
+
}
|
|
2568
|
+
if (o.cmd === 'models') { try { printModels(await fetchModels(cfg), o.model || cfg.model); } catch (e) { log(red('✖ ' + e.message)); process.exit(1); } return; }
|
|
2569
|
+
|
|
2570
|
+
const cwd = o.cwd ? path.resolve(expandHome(o.cwd)) : process.cwd();
|
|
2571
|
+
if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) { log(red('Folder not found: ' + cwd)); process.exit(1); }
|
|
2572
|
+
try { process.chdir(cwd); } catch (_) {}
|
|
2573
|
+
const S = newSession(cfg, { cwd, model: o.model, yes: o.yes, maxSteps: o.maxSteps, agent: o.plan ? 'plan' : 'build' });
|
|
2574
|
+
|
|
2575
|
+
let prompt = o.prompt.join(' ').trim();
|
|
2576
|
+
if (!process.stdin.isTTY) { const piped = (await readStdin()).trim(); if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped; }
|
|
2577
|
+
|
|
2578
|
+
if (prompt || o.plain || !process.stdout.isTTY) {
|
|
2579
|
+
if (!prompt) { log(red('Give me a task, e.g. benchcode "add tests"') + dim(' (or run without --plain for the full interface)')); process.exit(2); }
|
|
2580
|
+
S.ui = new PlainUI(S);
|
|
2581
|
+
process.on('SIGINT', () => { if (S.running) S.abort(); else process.exit(130); });
|
|
2582
|
+
refreshAccount(S);
|
|
2583
|
+
const okRun = await agentTurn(S, prompt);
|
|
2584
|
+
saveSession(S);
|
|
2585
|
+
process.exit(okRun ? 0 : 1);
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
const ui = new TUI(S, cfg);
|
|
2589
|
+
S.ui = ui;
|
|
2590
|
+
if (o.cont) {
|
|
2591
|
+
const last = listSessions(40).find((s) => s.cwd === cwd) || listSessions(1)[0];
|
|
2592
|
+
if (last && loadSessionInto(S, last.id)) ui.started = true; else log(dim('No earlier session found, starting fresh.'));
|
|
2593
|
+
}
|
|
2594
|
+
ui.start();
|
|
2595
|
+
loadModels(S); refreshAccount(S);
|
|
2596
|
+
latestVersion(cfg).then((v) => { if (v && cmpVer(v, VERSION) > 0) ui.flash(`Update available: ${VERSION} → ${v} (run: benchcode update)`, 6000); });
|
|
2597
|
+
}
|
|
2598
|
+
|
|
2599
|
+
main().catch((e) => { try { if (typeof ui !== 'undefined') ui.stop(); } catch (_) {} log(red('Fatal: ' + (e && e.stack || e))); process.exit(1); });
|