@tensorspark/dravix-code 0.0.0-stage → 1.5.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/dist/cli/commands.js +127 -0
- package/dist/cli/index.js +321 -0
- package/dist/cli/repl.js +3433 -0
- package/dist/services/ai.js +296 -0
- package/dist/services/auth.js +67 -0
- package/dist/services/context.js +260 -0
- package/dist/services/conversations.js +79 -0
- package/dist/services/executor.js +944 -0
- package/dist/services/undo.js +181 -0
- package/dist/services/usage.js +60 -0
- package/dist/utils/display.js +265 -0
- package/dist/utils/fileops.js +17 -0
- package/dist/utils/layout.js +82 -0
- package/package.json +38 -4
- package/README.md +0 -3
package/dist/cli/repl.js
ADDED
|
@@ -0,0 +1,3433 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as os from 'os';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import { streamChat, fetchSystemPrompt, FLASH_MODEL } from '../services/ai.js';
|
|
6
|
+
import { buildContext } from '../services/context.js';
|
|
7
|
+
import { parseOps, executeSingleOp, computeDiff } from '../services/executor.js';
|
|
8
|
+
import { handleCommand } from './commands.js';
|
|
9
|
+
import { printOpResult, printError, printInfo, colors } from '../utils/display.js';
|
|
10
|
+
import { saveConversation, loadConversation, listConversations, generateTitle, generateId } from '../services/conversations.js';
|
|
11
|
+
import { getToken } from '../services/auth.js';
|
|
12
|
+
import { checkUsage, reportUsage, estimateTokens, usageBar, fmtNum, formatResetTime } from '../services/usage.js';
|
|
13
|
+
let _serverWebDesignerSkill = '';
|
|
14
|
+
const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
15
|
+
const SLASH_COMMANDS = [
|
|
16
|
+
{ name: '/files', desc: 'List project files and git status' },
|
|
17
|
+
{ name: '/resume', desc: 'Resume a saved conversation' },
|
|
18
|
+
{ name: '/retry', desc: 'Resend your last message' },
|
|
19
|
+
{ name: '/copy', desc: 'Copy last AI response to clipboard' },
|
|
20
|
+
{ name: '/model', desc: 'Show current AI model info' },
|
|
21
|
+
{ name: '/clear', desc: 'Clear screen' },
|
|
22
|
+
{ name: '/whoami', desc: 'Show signed-in user' },
|
|
23
|
+
{ name: '/logout', desc: 'Sign out from Dravix Code' },
|
|
24
|
+
{ name: '/help', desc: 'Show all commands and shortcuts' },
|
|
25
|
+
{ name: '/exit', desc: 'Exit Dravix Code' },
|
|
26
|
+
];
|
|
27
|
+
function detectActiveStreamingOp(response) {
|
|
28
|
+
const tags = [
|
|
29
|
+
{ name: 'write_file', label: 'Writing', self: false },
|
|
30
|
+
{ name: 'edit_file', label: 'Editing', self: false },
|
|
31
|
+
{ name: 'create_folder', label: 'Creating', self: true },
|
|
32
|
+
{ name: 'delete_file', label: 'Deleting', self: true },
|
|
33
|
+
{ name: 'run_command', label: 'Running', self: false },
|
|
34
|
+
{ name: 'read_file', label: 'Reading', self: true },
|
|
35
|
+
{ name: 'read_folder', label: 'Reading', self: true },
|
|
36
|
+
{ name: 'search_code', label: 'Searching', self: true },
|
|
37
|
+
];
|
|
38
|
+
for (const { name, label, self } of tags) {
|
|
39
|
+
const openIdx = response.lastIndexOf(`<${name}`);
|
|
40
|
+
if (openIdx === -1)
|
|
41
|
+
continue;
|
|
42
|
+
const closeIdx = response.indexOf(`</${name}>`, openIdx);
|
|
43
|
+
if (closeIdx !== -1)
|
|
44
|
+
continue;
|
|
45
|
+
if (self && response.indexOf('/>', openIdx) !== -1)
|
|
46
|
+
continue;
|
|
47
|
+
const snippet = response.slice(openIdx, openIdx + 300);
|
|
48
|
+
const pathMatch = snippet.match(/path="([^"]+)"/);
|
|
49
|
+
if (pathMatch)
|
|
50
|
+
return `${label} ${path.basename(pathMatch[1])}`;
|
|
51
|
+
if (name === 'run_command') {
|
|
52
|
+
const m = snippet.match(/^<run_command(?:[^>]*)?>([^\n<]{0,55})/);
|
|
53
|
+
return `${label} ${m?.[1]?.trim() || '...'}`;
|
|
54
|
+
}
|
|
55
|
+
return `${label} ...`;
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
// ── Streaming tag stripper ──────────────────────────────────────
|
|
60
|
+
const OUR_TAGS = ['write_file', 'edit_file', 'create_folder', 'delete_file', 'run_command', 'read_file', 'read_folder', 'search_code', 'design_mode'];
|
|
61
|
+
const MAX_TAG_PREFIX = 15;
|
|
62
|
+
class TagStripper {
|
|
63
|
+
buf = '';
|
|
64
|
+
suppressing = false;
|
|
65
|
+
closingFor = '';
|
|
66
|
+
feed(chunk) {
|
|
67
|
+
let out = '';
|
|
68
|
+
this.buf += chunk;
|
|
69
|
+
while (true) {
|
|
70
|
+
if (this.suppressing) {
|
|
71
|
+
const closeTag = `</${this.closingFor}>`;
|
|
72
|
+
if (this.closingFor === 'create_folder' || this.closingFor === 'delete_file') {
|
|
73
|
+
const si = this.buf.indexOf('/>');
|
|
74
|
+
const ci = this.buf.indexOf(closeTag);
|
|
75
|
+
const end = si !== -1 && (ci === -1 || si < ci) ? si + 2
|
|
76
|
+
: ci !== -1 ? ci + closeTag.length : -1;
|
|
77
|
+
if (end !== -1) {
|
|
78
|
+
this.buf = this.buf.slice(end);
|
|
79
|
+
this.suppressing = false;
|
|
80
|
+
this.closingFor = '';
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
const ci = this.buf.indexOf(closeTag);
|
|
86
|
+
if (ci !== -1) {
|
|
87
|
+
this.buf = this.buf.slice(ci + closeTag.length);
|
|
88
|
+
this.suppressing = false;
|
|
89
|
+
this.closingFor = '';
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const guard = closeTag.length;
|
|
94
|
+
if (this.buf.length > guard)
|
|
95
|
+
this.buf = this.buf.slice(this.buf.length - guard);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
const li = this.buf.indexOf('<');
|
|
100
|
+
if (li === -1) {
|
|
101
|
+
out += this.buf;
|
|
102
|
+
this.buf = '';
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
out += this.buf.slice(0, li);
|
|
106
|
+
this.buf = this.buf.slice(li);
|
|
107
|
+
let found = false;
|
|
108
|
+
for (const name of OUR_TAGS) {
|
|
109
|
+
if (this.buf.startsWith(`<${name}`)) {
|
|
110
|
+
this.suppressing = true;
|
|
111
|
+
this.closingFor = name;
|
|
112
|
+
found = true;
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (found)
|
|
117
|
+
continue;
|
|
118
|
+
const partial = OUR_TAGS.some(n => `<${n}`.startsWith(this.buf.slice(0, Math.min(this.buf.length, `<${n}`.length))));
|
|
119
|
+
if (partial && this.buf.length < MAX_TAG_PREFIX)
|
|
120
|
+
break;
|
|
121
|
+
out += '<';
|
|
122
|
+
this.buf = this.buf.slice(1);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
flush() {
|
|
128
|
+
if (this.suppressing) {
|
|
129
|
+
this.buf = '';
|
|
130
|
+
return '';
|
|
131
|
+
}
|
|
132
|
+
const r = this.buf;
|
|
133
|
+
this.buf = '';
|
|
134
|
+
return r;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// ── Helpers ─────────────────────────────────────────────────────
|
|
138
|
+
function stripAnsi(s) {
|
|
139
|
+
return s.replace(/\x1b\[[0-9;]*m/g, '');
|
|
140
|
+
}
|
|
141
|
+
// ── Syntax highlighter ───────────────────────────────────────────
|
|
142
|
+
const SH = {
|
|
143
|
+
keyword: chalk.hex('#a78bfa'),
|
|
144
|
+
string: chalk.hex('#86efac'),
|
|
145
|
+
comment: chalk.hex('#4b5563'),
|
|
146
|
+
number: chalk.hex('#fb923c'),
|
|
147
|
+
type: chalk.hex('#67e8f9'),
|
|
148
|
+
fn: chalk.hex('#60a5fa'),
|
|
149
|
+
op: chalk.hex('#94a3b8'),
|
|
150
|
+
plain: chalk.hex('#e2e8f0'),
|
|
151
|
+
jsonKey: chalk.hex('#93c5fd'),
|
|
152
|
+
jsonVal: chalk.hex('#86efac'),
|
|
153
|
+
};
|
|
154
|
+
const KW_JS = new Set('break case catch class const continue debugger default delete do else export extends false finally for from function get if import in instanceof let new null of return set static super switch this throw true try typeof undefined var void while with yield async await abstract declare enum interface module namespace override private protected public readonly type'.split(' '));
|
|
155
|
+
const KW_PY = new Set('and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield None True False'.split(' '));
|
|
156
|
+
const KW_GO = new Set('break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var true false nil'.split(' '));
|
|
157
|
+
const KW_RS = new Set('as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type union unsafe use where while'.split(' '));
|
|
158
|
+
function highlightCode(line, lang) {
|
|
159
|
+
const L = lang.toLowerCase();
|
|
160
|
+
// ── JSON ─────────────────────────────────────────────────────
|
|
161
|
+
if (L === 'json' || L === 'jsonc') {
|
|
162
|
+
let r = '';
|
|
163
|
+
let i = 0;
|
|
164
|
+
while (i < line.length) {
|
|
165
|
+
if (line[i] === '"') {
|
|
166
|
+
let j = i + 1;
|
|
167
|
+
while (j < line.length) {
|
|
168
|
+
if (line[j] === '\\') {
|
|
169
|
+
j += 2;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (line[j] === '"') {
|
|
173
|
+
j++;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
j++;
|
|
177
|
+
}
|
|
178
|
+
const tok = line.slice(i, j);
|
|
179
|
+
let k = j;
|
|
180
|
+
while (k < line.length && line[k] === ' ')
|
|
181
|
+
k++;
|
|
182
|
+
r += (line[k] === ':') ? SH.jsonKey(tok) : SH.jsonVal(tok);
|
|
183
|
+
i = j;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (line.startsWith('//', i)) {
|
|
187
|
+
r += SH.comment(line.slice(i));
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
const nm = line.slice(i).match(/^-?\d+\.?\d*(?:[eE][+-]?\d+)?/);
|
|
191
|
+
if (nm && (i === 0 || !/\w/.test(line[i - 1]))) {
|
|
192
|
+
r += SH.number(nm[0]);
|
|
193
|
+
i += nm[0].length;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const bm = line.slice(i).match(/^(true|false|null)\b/);
|
|
197
|
+
if (bm) {
|
|
198
|
+
r += SH.keyword(bm[0]);
|
|
199
|
+
i += bm[0].length;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
r += SH.op(line[i]);
|
|
203
|
+
i++;
|
|
204
|
+
}
|
|
205
|
+
return r;
|
|
206
|
+
}
|
|
207
|
+
// ── Choose keyword set ────────────────────────────────────────
|
|
208
|
+
const KW = L === 'py' || L === 'python' ? KW_PY
|
|
209
|
+
: L === 'go' ? KW_GO
|
|
210
|
+
: L === 'rs' || L === 'rust' ? KW_RS
|
|
211
|
+
: KW_JS;
|
|
212
|
+
const lineComStarts = (L === 'py' || L === 'python' || L === 'sh' || L === 'bash' || L === 'shell' || L === 'zsh') ? ['#']
|
|
213
|
+
: (L === 'lua' || L === 'sql') ? ['--']
|
|
214
|
+
: ['//', '#'];
|
|
215
|
+
// ── Tokenize ─────────────────────────────────────────────────
|
|
216
|
+
let result = '';
|
|
217
|
+
let i = 0;
|
|
218
|
+
while (i < line.length) {
|
|
219
|
+
// Line comment
|
|
220
|
+
const lc = lineComStarts.find(s => line.startsWith(s, i));
|
|
221
|
+
if (lc) {
|
|
222
|
+
result += SH.comment(line.slice(i));
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
// Block comment /* */
|
|
226
|
+
if (line.startsWith('/*', i)) {
|
|
227
|
+
const end = line.indexOf('*/', i + 2);
|
|
228
|
+
result += SH.comment(end >= 0 ? line.slice(i, end + 2) : line.slice(i));
|
|
229
|
+
i = end >= 0 ? end + 2 : line.length;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
// String / template literal
|
|
233
|
+
if (line[i] === '"' || line[i] === "'" || line[i] === '`') {
|
|
234
|
+
const q = line[i];
|
|
235
|
+
let j = i + 1;
|
|
236
|
+
while (j < line.length) {
|
|
237
|
+
if (line[j] === '\\') {
|
|
238
|
+
j += 2;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (line[j] === q) {
|
|
242
|
+
j++;
|
|
243
|
+
break;
|
|
244
|
+
}
|
|
245
|
+
j++;
|
|
246
|
+
}
|
|
247
|
+
result += SH.string(line.slice(i, j));
|
|
248
|
+
i = j;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
// Number
|
|
252
|
+
if (/\d/.test(line[i]) && (i === 0 || !/[\w$]/.test(line[i - 1]))) {
|
|
253
|
+
const m = line.slice(i).match(/^(?:0x[\da-fA-F]+|0b[01]+|\d+\.?\d*(?:[eE][+-]?\d+)?)/);
|
|
254
|
+
if (m) {
|
|
255
|
+
result += SH.number(m[0]);
|
|
256
|
+
i += m[0].length;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
// Identifier / keyword / type / function
|
|
261
|
+
if (/[a-zA-Z_$]/.test(line[i])) {
|
|
262
|
+
let j = i;
|
|
263
|
+
while (j < line.length && /[\w$]/.test(line[j]))
|
|
264
|
+
j++;
|
|
265
|
+
const word = line.slice(i, j);
|
|
266
|
+
if (KW.has(word)) {
|
|
267
|
+
result += SH.keyword(word);
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
let k = j;
|
|
271
|
+
while (k < line.length && line[k] === ' ')
|
|
272
|
+
k++;
|
|
273
|
+
if (line[k] === '(')
|
|
274
|
+
result += SH.fn(word);
|
|
275
|
+
else if (/^[A-Z]/.test(word))
|
|
276
|
+
result += SH.type(word);
|
|
277
|
+
else
|
|
278
|
+
result += SH.plain(word);
|
|
279
|
+
}
|
|
280
|
+
i = j;
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
result += SH.op(line[i]);
|
|
284
|
+
i++;
|
|
285
|
+
}
|
|
286
|
+
return result;
|
|
287
|
+
}
|
|
288
|
+
// ── Markdown renderer (line-buffered, streaming-safe) ───────────
|
|
289
|
+
function applyInline(text) {
|
|
290
|
+
return text
|
|
291
|
+
.replace(/\*\*(.+?)\*\*|__(.+?)__/g, (_, a, b) => chalk.bold(a ?? b))
|
|
292
|
+
.replace(/`([^`\n]+)`/g, (_, c) => '`' + chalk.hex('#fbbf24')(c) + '`')
|
|
293
|
+
.replace(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, (_, t) => chalk.italic(t));
|
|
294
|
+
}
|
|
295
|
+
class MarkdownRenderer {
|
|
296
|
+
lineBuf = '';
|
|
297
|
+
inCodeBlock = false;
|
|
298
|
+
codeLines = [];
|
|
299
|
+
codeLang = '';
|
|
300
|
+
blankCount = 0;
|
|
301
|
+
inTable = false;
|
|
302
|
+
tableRows = [];
|
|
303
|
+
format(chunk) {
|
|
304
|
+
// Strip \r to normalise Windows/mixed line endings
|
|
305
|
+
const clean = chunk.replace(/\r/g, '');
|
|
306
|
+
let out = '';
|
|
307
|
+
for (const c of clean) {
|
|
308
|
+
if (c === '\n') {
|
|
309
|
+
out += this.processLine(this.lineBuf);
|
|
310
|
+
this.lineBuf = '';
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
this.lineBuf += c;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
318
|
+
flush() {
|
|
319
|
+
let out = '';
|
|
320
|
+
if (this.lineBuf) {
|
|
321
|
+
out += this.processLine(this.lineBuf);
|
|
322
|
+
this.lineBuf = '';
|
|
323
|
+
}
|
|
324
|
+
if (this.inTable) {
|
|
325
|
+
out += this.renderTable();
|
|
326
|
+
this.inTable = false;
|
|
327
|
+
}
|
|
328
|
+
if (this.inCodeBlock) {
|
|
329
|
+
out += this.renderCodeBlock();
|
|
330
|
+
this.inCodeBlock = false;
|
|
331
|
+
}
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
processLine(raw) {
|
|
335
|
+
// ── Inside code block ──────────────────────────────────────
|
|
336
|
+
if (this.inCodeBlock) {
|
|
337
|
+
if (raw.trimEnd() === '```') {
|
|
338
|
+
this.inCodeBlock = false;
|
|
339
|
+
return this.renderCodeBlock();
|
|
340
|
+
}
|
|
341
|
+
this.codeLines.push(raw);
|
|
342
|
+
return '';
|
|
343
|
+
}
|
|
344
|
+
// ── Opening code fence ─────────────────────────────────────
|
|
345
|
+
if (raw.startsWith('```')) {
|
|
346
|
+
this.inCodeBlock = true;
|
|
347
|
+
this.codeLang = raw.slice(3).trim();
|
|
348
|
+
this.codeLines = [];
|
|
349
|
+
return '';
|
|
350
|
+
}
|
|
351
|
+
// ── Table row ─────────────────────────────────────────────
|
|
352
|
+
if (raw.startsWith('|')) {
|
|
353
|
+
this.inTable = true;
|
|
354
|
+
const allCells = raw.split('|').slice(1, -1).map(c => c.trim());
|
|
355
|
+
const isSep = allCells.length > 0 && allCells.every(c => /^:?-+:?$/.test(c));
|
|
356
|
+
if (!isSep && allCells.length > 0) {
|
|
357
|
+
this.tableRows.push(allCells);
|
|
358
|
+
}
|
|
359
|
+
return '';
|
|
360
|
+
}
|
|
361
|
+
if (this.inTable) {
|
|
362
|
+
this.inTable = false;
|
|
363
|
+
return this.renderTable() + this.processLine(raw);
|
|
364
|
+
}
|
|
365
|
+
// ── Blank line (collapse 3+ to 2) ─────────────────────────
|
|
366
|
+
if (!raw.trim()) {
|
|
367
|
+
this.blankCount++;
|
|
368
|
+
return this.blankCount <= 2 ? '\n' : '';
|
|
369
|
+
}
|
|
370
|
+
// ── Heading # / ## / ### ──────────────────────────────────
|
|
371
|
+
const hm = raw.match(/^(#{1,3})\s+(.+)$/);
|
|
372
|
+
if (hm) {
|
|
373
|
+
const lvl = hm[1].length;
|
|
374
|
+
const title = hm[2];
|
|
375
|
+
const paint = lvl === 1 ? chalk.bold.hex('#818cf8')
|
|
376
|
+
: lvl === 2 ? chalk.bold.hex('#a78bfa')
|
|
377
|
+
: chalk.bold.hex('#c4b5fd');
|
|
378
|
+
const prefix = this.blankCount === 0 ? '\n' : '';
|
|
379
|
+
this.blankCount = 0;
|
|
380
|
+
return prefix + ' ' + paint(title) + '\n';
|
|
381
|
+
}
|
|
382
|
+
this.blankCount = 0;
|
|
383
|
+
// ── Unordered list - or * ─────────────────────────────────
|
|
384
|
+
const ulm = raw.match(/^(\s*)[-*]\s+(.+)$/);
|
|
385
|
+
if (ulm) {
|
|
386
|
+
const indent = ' '.repeat(Math.floor(ulm[1].length / 2) + 1);
|
|
387
|
+
return indent + colors.muted('·') + ' ' + colors.ai(applyInline(ulm[2])) + '\n';
|
|
388
|
+
}
|
|
389
|
+
// ── Ordered list 1. ──────────────────────────────────────
|
|
390
|
+
const olm = raw.match(/^(\s*)(\d+)\.\s+(.+)$/);
|
|
391
|
+
if (olm) {
|
|
392
|
+
const indent = ' '.repeat(Math.floor(olm[1].length / 2) + 1);
|
|
393
|
+
return indent + colors.muted(olm[2] + '.') + ' ' + colors.ai(applyInline(olm[3])) + '\n';
|
|
394
|
+
}
|
|
395
|
+
// ── Blockquote > ─────────────────────────────────────────
|
|
396
|
+
const bqm = raw.match(/^>\s?(.*)$/);
|
|
397
|
+
if (bqm) {
|
|
398
|
+
return ' ' + colors.dim('│') + ' ' + colors.muted(applyInline(bqm[1])) + '\n';
|
|
399
|
+
}
|
|
400
|
+
// ── Horizontal rule --- / *** ─────────────────────────────
|
|
401
|
+
if (/^[-*_]{3,}\s*$/.test(raw.trim())) {
|
|
402
|
+
return ' ' + colors.dim('─'.repeat(Math.min((process.stdout.columns ?? 80) - 4, 72))) + '\n';
|
|
403
|
+
}
|
|
404
|
+
// ── Normal text ───────────────────────────────────────────
|
|
405
|
+
// Wrap text before right edge, but with minimal margin
|
|
406
|
+
const termWidth = process.stdout.columns ?? 80;
|
|
407
|
+
const maxTextWidth = termWidth - 1; // just 1 char from right edge
|
|
408
|
+
const rawText = applyInline(raw);
|
|
409
|
+
if (rawText.length > maxTextWidth) {
|
|
410
|
+
// Word-wrap at spaces, keeping lines close to edge
|
|
411
|
+
const words = rawText.split(' ');
|
|
412
|
+
let line = '';
|
|
413
|
+
let result = ' ';
|
|
414
|
+
for (const word of words) {
|
|
415
|
+
if (line.length + word.length + 1 > maxTextWidth && line.length > 0) {
|
|
416
|
+
result += line.trimEnd() + '\n ';
|
|
417
|
+
line = word + ' ';
|
|
418
|
+
}
|
|
419
|
+
else {
|
|
420
|
+
line += word + ' ';
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
result += line.trimEnd();
|
|
424
|
+
return colors.ai(result) + '\n';
|
|
425
|
+
}
|
|
426
|
+
return ' ' + colors.ai(rawText) + '\n';
|
|
427
|
+
}
|
|
428
|
+
renderTable() {
|
|
429
|
+
const rows = this.tableRows;
|
|
430
|
+
this.tableRows = [];
|
|
431
|
+
if (rows.length === 0)
|
|
432
|
+
return '';
|
|
433
|
+
// Filter out separator rows (--- | --- | ---)
|
|
434
|
+
const dataRows = rows.filter(r => !r.every(c => /^:?-+:?$/.test(c.trim())));
|
|
435
|
+
if (dataRows.length === 0)
|
|
436
|
+
return '';
|
|
437
|
+
const cols = Math.max(...dataRows.map(r => r.length));
|
|
438
|
+
const termW = process.stdout.columns ?? 80;
|
|
439
|
+
// max usable width per column (distribute evenly, min 6)
|
|
440
|
+
const maxColW = Math.max(6, Math.floor((termW - 4 - (cols + 1)) / cols));
|
|
441
|
+
const widths = Array(cols).fill(0);
|
|
442
|
+
for (const row of dataRows) {
|
|
443
|
+
for (let i = 0; i < cols; i++) {
|
|
444
|
+
// Strip markdown formatting for width calculation
|
|
445
|
+
const rawCell = (row[i] ?? '').replace(/\*\*/g, '').replace(/`/g, '').trim();
|
|
446
|
+
const cellLen = Math.min(rawCell.length, maxColW);
|
|
447
|
+
widths[i] = Math.max(widths[i], cellLen + 2);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
const bar = (l, m, r) => colors.dim(' ' + l + widths.map(w => '─'.repeat(w)).join(m) + r);
|
|
451
|
+
let out = '\n' + bar('┌', '┬', '┐') + '\n';
|
|
452
|
+
for (let ri = 0; ri < dataRows.length; ri++) {
|
|
453
|
+
const row = dataRows[ri];
|
|
454
|
+
const cells = widths.map((w, i) => {
|
|
455
|
+
const raw = (row[i] ?? '').trim();
|
|
456
|
+
// Strip markdown for display but keep formatting
|
|
457
|
+
const plain = raw.replace(/\*\*/g, '').replace(/`/g, '');
|
|
458
|
+
const cell = plain.length > w - 2 ? plain.slice(0, w - 3) + '…' : plain;
|
|
459
|
+
const pad = w - cell.length - 1;
|
|
460
|
+
// Apply formatting to the cell content
|
|
461
|
+
const formatted = applyInline(raw);
|
|
462
|
+
const text = ri === 0 ? chalk.bold.white(cell) : colors.ai(cell);
|
|
463
|
+
return ' ' + text + ' '.repeat(Math.max(pad, 0));
|
|
464
|
+
});
|
|
465
|
+
out += colors.dim(' │') + cells.join(colors.dim('│')) + colors.dim('│') + '\n';
|
|
466
|
+
if (ri === 0 && dataRows.length > 1)
|
|
467
|
+
out += bar('├', '┼', '┤') + '\n';
|
|
468
|
+
}
|
|
469
|
+
out += bar('└', '┴', '┘') + '\n';
|
|
470
|
+
return out;
|
|
471
|
+
}
|
|
472
|
+
renderCodeBlock() {
|
|
473
|
+
const lang = this.codeLang;
|
|
474
|
+
const lines = this.codeLines;
|
|
475
|
+
// If code block content is a markdown table, render it as a table
|
|
476
|
+
const nonEmpty = lines.filter(l => l.trim());
|
|
477
|
+
if (nonEmpty.length > 0 && nonEmpty.every(l => l.trimStart().startsWith('|'))) {
|
|
478
|
+
for (const line of lines) {
|
|
479
|
+
if (!line.trim())
|
|
480
|
+
continue;
|
|
481
|
+
const allCells = line.split('|').slice(1, -1).map(c => c.trim());
|
|
482
|
+
const isSep = allCells.length > 0 && allCells.every(c => /^:?-+:?$/.test(c));
|
|
483
|
+
if (!isSep && allCells.length > 0)
|
|
484
|
+
this.tableRows.push(allCells);
|
|
485
|
+
}
|
|
486
|
+
if (this.tableRows.length > 0)
|
|
487
|
+
return this.renderTable();
|
|
488
|
+
}
|
|
489
|
+
const termW = process.stdout.columns ?? 80;
|
|
490
|
+
const maxInner = Math.min(termW - 8, 80);
|
|
491
|
+
const maxLen = lines.length > 0 ? Math.max(...lines.map(l => l.length)) : 0;
|
|
492
|
+
const inner = Math.max(maxLen, lang.length + 4, 20, 0);
|
|
493
|
+
const capped = Math.min(inner, maxInner);
|
|
494
|
+
const dashAfterLang = Math.max(0, capped - lang.length - 2);
|
|
495
|
+
const top = lang
|
|
496
|
+
? colors.dim(' ╭─ ') + colors.primary(lang) + colors.dim(' ' + '─'.repeat(dashAfterLang))
|
|
497
|
+
: colors.dim(' ╭' + '─'.repeat(capped + 2));
|
|
498
|
+
const bot = colors.dim(' ╰' + '─'.repeat(capped + 2));
|
|
499
|
+
const canHighlight = lang && !['text', 'txt', 'plain', 'output', 'log'].includes(lang.toLowerCase());
|
|
500
|
+
let out = '\n' + top + '\n';
|
|
501
|
+
for (const l of lines) {
|
|
502
|
+
const display = l.length > capped ? l.slice(0, capped - 1) + '…' : l;
|
|
503
|
+
const colorized = canHighlight ? highlightCode(display, lang) : colors.text(display);
|
|
504
|
+
out += colors.dim(' │ ') + colorized + '\n';
|
|
505
|
+
}
|
|
506
|
+
out += bot + '\n';
|
|
507
|
+
return out;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
// ── Targeted section finder — finds proper HTML container boundaries ──
|
|
511
|
+
function findSectionBlocks(content, keywords) {
|
|
512
|
+
const lines = content.split('\n');
|
|
513
|
+
const seen = new Set();
|
|
514
|
+
const out = [];
|
|
515
|
+
for (const kw of keywords) {
|
|
516
|
+
if (kw.length < 3)
|
|
517
|
+
continue;
|
|
518
|
+
const kwL = kw.toLowerCase();
|
|
519
|
+
for (let i = 0; i < lines.length; i++) {
|
|
520
|
+
if (seen.has(i))
|
|
521
|
+
continue;
|
|
522
|
+
if (!lines[i].toLowerCase().includes(kwL))
|
|
523
|
+
continue;
|
|
524
|
+
// ── Go UP: find enclosing container opening tag ──────────────
|
|
525
|
+
let startIdx = Math.max(0, i - 3);
|
|
526
|
+
const kwIndent = (lines[i].match(/^(\s*)/)?.[1] ?? '').length;
|
|
527
|
+
for (let j = i - 1; j >= Math.max(0, i - 60); j--) {
|
|
528
|
+
const trimmed = lines[j].trim();
|
|
529
|
+
const lineIndent = (lines[j].match(/^(\s*)/)?.[1] ?? '').length;
|
|
530
|
+
// Opening block tag at same or lower indent level
|
|
531
|
+
if (lineIndent <= kwIndent && /<(section|div|article|main|header|footer|ul|ol)\b[^>]*>/.test(trimmed)) {
|
|
532
|
+
startIdx = j;
|
|
533
|
+
break;
|
|
534
|
+
}
|
|
535
|
+
// CSS section comment /* ═══ ... ═══ */
|
|
536
|
+
if (lineIndent <= kwIndent && /\/\*.*[═=─\-]{2,}/.test(trimmed)) {
|
|
537
|
+
startIdx = Math.max(0, j);
|
|
538
|
+
break;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
// ── Go DOWN: find matching closing tag ───────────────────────
|
|
542
|
+
const openMatch = lines[startIdx].match(/<(section|div|article|main|header|footer|ul|ol)\b/);
|
|
543
|
+
let endIdx = Math.min(lines.length - 1, i + 180);
|
|
544
|
+
if (openMatch) {
|
|
545
|
+
const tag = openMatch[1];
|
|
546
|
+
let depth = 0;
|
|
547
|
+
for (let j = startIdx; j <= Math.min(lines.length - 1, i + 300); j++) {
|
|
548
|
+
depth += (lines[j].match(new RegExp(`<${tag}[\\s>]`, 'g')) ?? []).length;
|
|
549
|
+
depth -= (lines[j].match(new RegExp(`</${tag}>`, 'g')) ?? []).length;
|
|
550
|
+
if (depth <= 0 && j > startIdx) {
|
|
551
|
+
endIdx = j;
|
|
552
|
+
break;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const block = lines.slice(startIdx, endIdx + 1).join('\n');
|
|
557
|
+
out.push({ keyword: kw, lineNo: i + 1, block, startLine: startIdx + 1, endLine: endIdx + 1 });
|
|
558
|
+
for (let j = startIdx; j <= endIdx; j++)
|
|
559
|
+
seen.add(j);
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return out;
|
|
564
|
+
}
|
|
565
|
+
function normalizeResponse(text) {
|
|
566
|
+
return text.replace(/```[\w]*\n?(<(?:write_file|edit_file|delete_file|create_folder|run_command|read_file|read_folder|search_code)[\s\S]*?(?:<\/(?:write_file|edit_file|run_command)>|<(?:delete_file|create_folder|read_file|read_folder|search_code)[^>]*\/>))\n?```/g, '$1');
|
|
567
|
+
}
|
|
568
|
+
function opLabel(op, cwd) {
|
|
569
|
+
const exists = op.path ? fs.existsSync(path.resolve(cwd, op.path)) : false;
|
|
570
|
+
switch (op.type) {
|
|
571
|
+
case 'write': return exists ? `Modify file: ${op.path}` : `Create file: ${op.path}`;
|
|
572
|
+
case 'edit': return `Edit file: ${op.path}`;
|
|
573
|
+
case 'mkdir': return `Create folder: ${op.path}`;
|
|
574
|
+
case 'delete': return `Delete: ${op.path}`;
|
|
575
|
+
case 'run': return `Run command: ${op.command}`;
|
|
576
|
+
default: return op.path ?? '';
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
function opKey(op, cwd) {
|
|
580
|
+
const exists = op.path ? fs.existsSync(path.resolve(cwd, op.path)) : false;
|
|
581
|
+
if (op.type === 'write')
|
|
582
|
+
return exists ? 'modify' : 'create';
|
|
583
|
+
return op.type;
|
|
584
|
+
}
|
|
585
|
+
// ── Permission prompt ───────────────────────────────────────────
|
|
586
|
+
function opStyle(label) {
|
|
587
|
+
const l = label.toLowerCase();
|
|
588
|
+
if (l.startsWith('create folder'))
|
|
589
|
+
return { icon: '+', paint: colors.success };
|
|
590
|
+
if (l.startsWith('create'))
|
|
591
|
+
return { icon: '+', paint: colors.success };
|
|
592
|
+
if (l.startsWith('delete'))
|
|
593
|
+
return { icon: '!', paint: colors.error };
|
|
594
|
+
if (l.startsWith('run'))
|
|
595
|
+
return { icon: '$', paint: colors.primary };
|
|
596
|
+
return { icon: '~', paint: colors.warn };
|
|
597
|
+
}
|
|
598
|
+
const OPT_LABELS_DEFAULT = ['Apply this change', 'Apply to all changes', 'Skip this change'];
|
|
599
|
+
const OPT_LABELS_RUN = ['Yes, run it', 'No, skip'];
|
|
600
|
+
const SEP = '─'.repeat(40);
|
|
601
|
+
function clearMenu(lines) {
|
|
602
|
+
process.stdout.write('\x1b[2K');
|
|
603
|
+
for (let i = 0; i < lines; i++) {
|
|
604
|
+
process.stdout.write('\x1b[1A\x1b[2K');
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
// Returns number of terminal lines printed (for clearing after acceptance)
|
|
608
|
+
function printDiffPreview(op, cwd) {
|
|
609
|
+
let printed = 0;
|
|
610
|
+
try {
|
|
611
|
+
const cols = process.stdout.columns ?? 80;
|
|
612
|
+
const maxW = Math.min(cols - 12, 120);
|
|
613
|
+
const clip = (t) => t.length > maxW ? t.slice(0, maxW - 1) + '…' : t;
|
|
614
|
+
let diff = null;
|
|
615
|
+
if (op.type === 'write' && op.path && op.content !== undefined) {
|
|
616
|
+
const fp = path.resolve(cwd, op.path);
|
|
617
|
+
const old = fs.existsSync(fp) ? fs.readFileSync(fp, 'utf-8') : '';
|
|
618
|
+
diff = computeDiff(old, op.content);
|
|
619
|
+
}
|
|
620
|
+
else if (op.type === 'edit' && op.path && op.find !== undefined && op.replace !== undefined) {
|
|
621
|
+
// Find real line offset in file so line numbers match actual file
|
|
622
|
+
const rawDiff = computeDiff(op.find, op.replace);
|
|
623
|
+
try {
|
|
624
|
+
const fp = path.resolve(cwd, op.path);
|
|
625
|
+
if (fs.existsSync(fp)) {
|
|
626
|
+
const fileContent = fs.readFileSync(fp, 'utf-8');
|
|
627
|
+
const idx = fileContent.indexOf(op.find.trim());
|
|
628
|
+
const offset = idx >= 0 ? fileContent.slice(0, idx).split('\n').length - 1 : 0;
|
|
629
|
+
diff = rawDiff.map(d => ({ ...d, lineNo: d.lineNo + offset }));
|
|
630
|
+
}
|
|
631
|
+
else {
|
|
632
|
+
diff = rawDiff;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
diff = rawDiff;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
if (!diff)
|
|
640
|
+
return 0;
|
|
641
|
+
const adds = diff.filter(d => d.kind === 'add').length;
|
|
642
|
+
const removes = diff.filter(d => d.kind === 'remove').length;
|
|
643
|
+
if (adds === 0 && removes === 0)
|
|
644
|
+
return 0;
|
|
645
|
+
const statStr = [
|
|
646
|
+
removes > 0 ? colors.error.bold(`-${removes}`) : '',
|
|
647
|
+
adds > 0 ? colors.success.bold(`+${adds}`) : '',
|
|
648
|
+
].filter(Boolean).join(' ');
|
|
649
|
+
const writeLine = (s) => { process.stdout.write(s + '\n'); printed++; };
|
|
650
|
+
process.stdout.write('\n');
|
|
651
|
+
printed++;
|
|
652
|
+
writeLine(colors.warn(' ~') +
|
|
653
|
+
colors.subtext(' ') +
|
|
654
|
+
colors.text(op.path ?? '') +
|
|
655
|
+
(statStr ? ' ' + statStr : ''));
|
|
656
|
+
const CONTEXT = 2;
|
|
657
|
+
const show = new Uint8Array(diff.length);
|
|
658
|
+
for (let i = 0; i < diff.length; i++) {
|
|
659
|
+
if (diff[i].kind !== 'context') {
|
|
660
|
+
for (let c = Math.max(0, i - CONTEXT); c <= Math.min(diff.length - 1, i + CONTEXT); c++)
|
|
661
|
+
show[c] = 1;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
const renderLine = (line) => {
|
|
665
|
+
const num = String(line.lineNo).padStart(5, ' ');
|
|
666
|
+
if (line.kind === 'remove') {
|
|
667
|
+
const content = ` ${num} ${colors.error('-')} ${clip(line.text)}`;
|
|
668
|
+
writeLine(' ' + colors.error('▌') + chalk.bgHex('#1c0a0a')(content.padEnd(cols - 3)));
|
|
669
|
+
}
|
|
670
|
+
else if (line.kind === 'add') {
|
|
671
|
+
const content = ` ${num} ${colors.success('+')} ${clip(line.text)}`;
|
|
672
|
+
writeLine(' ' + colors.success('▌') + chalk.bgHex('#021a0e')(content.padEnd(cols - 3)));
|
|
673
|
+
}
|
|
674
|
+
else {
|
|
675
|
+
writeLine(colors.dim(` ${num} ${clip(line.text)}`));
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
const hunks = [];
|
|
679
|
+
let curHunk = [];
|
|
680
|
+
let lastIdx = -1;
|
|
681
|
+
for (let i = 0; i < diff.length; i++) {
|
|
682
|
+
if (!show[i])
|
|
683
|
+
continue;
|
|
684
|
+
if (lastIdx >= 0 && i > lastIdx + 1) {
|
|
685
|
+
hunks.push(curHunk);
|
|
686
|
+
curHunk = [];
|
|
687
|
+
}
|
|
688
|
+
lastIdx = i;
|
|
689
|
+
curHunk.push(diff[i]);
|
|
690
|
+
}
|
|
691
|
+
if (curHunk.length > 0)
|
|
692
|
+
hunks.push(curHunk);
|
|
693
|
+
let shown = 0;
|
|
694
|
+
const MAX_LINES = 60;
|
|
695
|
+
for (let h = 0; h < hunks.length; h++) {
|
|
696
|
+
if (shown >= MAX_LINES)
|
|
697
|
+
break;
|
|
698
|
+
if (h > 0) {
|
|
699
|
+
writeLine(colors.dim(' ╌╌╌'));
|
|
700
|
+
}
|
|
701
|
+
const hunk = hunks[h];
|
|
702
|
+
const before = [];
|
|
703
|
+
const hRem = [];
|
|
704
|
+
const hAdd = [];
|
|
705
|
+
let pendingCtx = [];
|
|
706
|
+
let seenChange = false;
|
|
707
|
+
for (const line of hunk) {
|
|
708
|
+
if (line.kind === 'context') {
|
|
709
|
+
if (!seenChange)
|
|
710
|
+
before.push(line);
|
|
711
|
+
else
|
|
712
|
+
pendingCtx.push(line);
|
|
713
|
+
}
|
|
714
|
+
else {
|
|
715
|
+
seenChange = true;
|
|
716
|
+
pendingCtx = [];
|
|
717
|
+
if (line.kind === 'remove')
|
|
718
|
+
hRem.push(line);
|
|
719
|
+
else
|
|
720
|
+
hAdd.push(line);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
for (const l of before)
|
|
724
|
+
renderLine(l);
|
|
725
|
+
for (const l of hRem) {
|
|
726
|
+
if (shown >= MAX_LINES)
|
|
727
|
+
break;
|
|
728
|
+
renderLine(l);
|
|
729
|
+
shown++;
|
|
730
|
+
}
|
|
731
|
+
for (const l of hAdd) {
|
|
732
|
+
if (shown >= MAX_LINES)
|
|
733
|
+
break;
|
|
734
|
+
renderLine(l);
|
|
735
|
+
shown++;
|
|
736
|
+
}
|
|
737
|
+
for (const l of pendingCtx)
|
|
738
|
+
renderLine(l);
|
|
739
|
+
}
|
|
740
|
+
const total = diff.filter(d => d.kind !== 'context').length;
|
|
741
|
+
if (total > MAX_LINES) {
|
|
742
|
+
writeLine(colors.muted(` … ${total - MAX_LINES} more lines`));
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
catch { /* ignore */ }
|
|
746
|
+
return printed;
|
|
747
|
+
}
|
|
748
|
+
async function askPermission(label, key, alwaysAllowed, noAlways, diffShown, previewLineCount = 0) {
|
|
749
|
+
if (!noAlways && alwaysAllowed.has(key))
|
|
750
|
+
return true;
|
|
751
|
+
return new Promise((resolve) => {
|
|
752
|
+
let sel = 0;
|
|
753
|
+
let drawn = false;
|
|
754
|
+
const ci = label.indexOf(': ');
|
|
755
|
+
const opType = ci !== -1 ? label.slice(0, ci) : label;
|
|
756
|
+
const opValue = ci !== -1 ? label.slice(ci + 2) : '';
|
|
757
|
+
const { icon, paint } = opStyle(label);
|
|
758
|
+
const optLabels = noAlways ? OPT_LABELS_RUN : OPT_LABELS_DEFAULT;
|
|
759
|
+
const optCount = optLabels.length;
|
|
760
|
+
// when diff already shown: just blank + options (no box)
|
|
761
|
+
const menuLines = diffShown ? (1 + optCount) : (noAlways ? 3 : 4) + 1 + optCount;
|
|
762
|
+
function printMenu() {
|
|
763
|
+
if (drawn)
|
|
764
|
+
clearMenu(menuLines);
|
|
765
|
+
drawn = true;
|
|
766
|
+
let lines;
|
|
767
|
+
if (diffShown) {
|
|
768
|
+
lines = [
|
|
769
|
+
'',
|
|
770
|
+
...optLabels.map((lbl, i) => i === sel
|
|
771
|
+
? ` ${colors.primary('›')} ${colors.primary.bold(lbl)}`
|
|
772
|
+
: ` ${colors.muted(lbl)}`),
|
|
773
|
+
];
|
|
774
|
+
}
|
|
775
|
+
else {
|
|
776
|
+
let boxLines;
|
|
777
|
+
if (noAlways) {
|
|
778
|
+
const dashes = SEP.length - 2 - 'run command'.length - 1;
|
|
779
|
+
boxLines = [
|
|
780
|
+
colors.dim(' ╭─ ') + colors.primary('run command') + colors.dim(' ' + '─'.repeat(Math.max(dashes, 1))),
|
|
781
|
+
` │ ${chalk.hex('#fbbf24')('$')} ${chalk.white(opValue)}`,
|
|
782
|
+
colors.dim(' ╰' + SEP),
|
|
783
|
+
];
|
|
784
|
+
}
|
|
785
|
+
else {
|
|
786
|
+
boxLines = [
|
|
787
|
+
colors.dim(' ╭' + SEP),
|
|
788
|
+
` │ ${paint(icon + ' ' + opType)}`,
|
|
789
|
+
` │ ${chalk.white(opValue)}`,
|
|
790
|
+
colors.dim(' ╰' + SEP),
|
|
791
|
+
];
|
|
792
|
+
}
|
|
793
|
+
lines = [
|
|
794
|
+
...boxLines,
|
|
795
|
+
'',
|
|
796
|
+
...optLabels.map((lbl, i) => i === sel
|
|
797
|
+
? ` ${colors.primary('›')} ${colors.primary.bold(lbl)}`
|
|
798
|
+
: ` ${colors.muted(lbl)}`),
|
|
799
|
+
];
|
|
800
|
+
}
|
|
801
|
+
process.stdout.write(lines.join('\n') + '\n');
|
|
802
|
+
}
|
|
803
|
+
printMenu();
|
|
804
|
+
function cleanup() {
|
|
805
|
+
process.stdin.removeListener('data', onData);
|
|
806
|
+
}
|
|
807
|
+
function confirm(idx) {
|
|
808
|
+
cleanup();
|
|
809
|
+
clearMenu(menuLines);
|
|
810
|
+
// Clear the diff preview lines (all except the first blank separator)
|
|
811
|
+
for (let i = 0; i < previewLineCount - 1; i++) {
|
|
812
|
+
process.stdout.write('\x1b[1A\x1b[2K');
|
|
813
|
+
}
|
|
814
|
+
const skipIdx = noAlways ? 1 : 2;
|
|
815
|
+
if (idx === skipIdx) {
|
|
816
|
+
process.stdout.write(` ${colors.muted('○')} ${colors.muted('Skipped: ' + label)}\n`);
|
|
817
|
+
resolve(false);
|
|
818
|
+
}
|
|
819
|
+
else {
|
|
820
|
+
if (!noAlways && idx === 1)
|
|
821
|
+
alwaysAllowed.add(key);
|
|
822
|
+
resolve(true);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
function onData(data) {
|
|
826
|
+
try {
|
|
827
|
+
switch (data) {
|
|
828
|
+
case '\x1b[A':
|
|
829
|
+
sel = (sel - 1 + optCount) % optCount;
|
|
830
|
+
printMenu();
|
|
831
|
+
break;
|
|
832
|
+
case '\x1b[B':
|
|
833
|
+
sel = (sel + 1) % optCount;
|
|
834
|
+
printMenu();
|
|
835
|
+
break;
|
|
836
|
+
case '\r':
|
|
837
|
+
case '\n':
|
|
838
|
+
confirm(sel);
|
|
839
|
+
break;
|
|
840
|
+
case 'y':
|
|
841
|
+
case 'Y':
|
|
842
|
+
confirm(0);
|
|
843
|
+
break;
|
|
844
|
+
case 'n':
|
|
845
|
+
case 'N':
|
|
846
|
+
confirm(noAlways ? 1 : 2);
|
|
847
|
+
break;
|
|
848
|
+
case 'a':
|
|
849
|
+
case 'A':
|
|
850
|
+
if (!noAlways)
|
|
851
|
+
confirm(1);
|
|
852
|
+
break;
|
|
853
|
+
case '\x03':
|
|
854
|
+
cleanup();
|
|
855
|
+
clearMenu(menuLines);
|
|
856
|
+
process.exit(0);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
catch (e) {
|
|
860
|
+
cleanup();
|
|
861
|
+
resolve(false);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
process.stdin.on('data', onData);
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
async function readLine(prompt, cwd) {
|
|
868
|
+
const rows = process.stdout.rows ?? 24;
|
|
869
|
+
const cols = process.stdout.columns ?? 80;
|
|
870
|
+
const sR = rows - 2;
|
|
871
|
+
const iR = rows - 1;
|
|
872
|
+
let SEP = colors.dim(' ' + '─'.repeat(Math.max(cols - 4, 40)));
|
|
873
|
+
// Ensure scroll region is active for chat history (top rows)
|
|
874
|
+
process.stdout.write(`\x1b[1;${rows - 3}r`);
|
|
875
|
+
// Render fixed bottom container (separator + input bar)
|
|
876
|
+
process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
|
|
877
|
+
process.stdout.write(`\x1b[${iR};1H\x1b[2K${prompt}`);
|
|
878
|
+
process.stdout.write(`\x1b[${iR};5H`);
|
|
879
|
+
return new Promise((resolve) => {
|
|
880
|
+
let prefix = '';
|
|
881
|
+
let pasteBlock = null;
|
|
882
|
+
let pasteCount = 0;
|
|
883
|
+
let suffix = '';
|
|
884
|
+
let ctrlCCount = 0;
|
|
885
|
+
let ctrlCTimer = null;
|
|
886
|
+
let atMode = false;
|
|
887
|
+
let atQuery = '';
|
|
888
|
+
let atSel = 0;
|
|
889
|
+
let atBoxLines = 0;
|
|
890
|
+
let allFiles = [];
|
|
891
|
+
let slashMode = false;
|
|
892
|
+
let slashQuery = '';
|
|
893
|
+
let slashSel = 0;
|
|
894
|
+
let slashBoxLines = 0;
|
|
895
|
+
let slashDrawn = false;
|
|
896
|
+
let tabMode = false;
|
|
897
|
+
let tabQuery = '';
|
|
898
|
+
let tabSel = 0;
|
|
899
|
+
let tabBoxLines = 0;
|
|
900
|
+
let tabDrawn = false;
|
|
901
|
+
let tabPreWord = '';
|
|
902
|
+
function onResize() {
|
|
903
|
+
const newCols = process.stdout.columns ?? 80;
|
|
904
|
+
const newRows = process.stdout.rows ?? 24;
|
|
905
|
+
process.stdout.write(`\x1b[1;${newRows - 3}r`);
|
|
906
|
+
SEP = colors.dim(' ' + '─'.repeat(Math.max(newCols - 4, 40)));
|
|
907
|
+
if (atMode) {
|
|
908
|
+
drawPicker();
|
|
909
|
+
}
|
|
910
|
+
else if (slashMode) {
|
|
911
|
+
drawSlashPicker();
|
|
912
|
+
}
|
|
913
|
+
else if (tabMode) {
|
|
914
|
+
drawTabPicker();
|
|
915
|
+
}
|
|
916
|
+
else {
|
|
917
|
+
redraw();
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
process.stdout.on('resize', onResize);
|
|
921
|
+
function cleanup() {
|
|
922
|
+
if (ctrlCTimer) {
|
|
923
|
+
clearTimeout(ctrlCTimer);
|
|
924
|
+
ctrlCTimer = null;
|
|
925
|
+
}
|
|
926
|
+
process.stdin.removeListener('data', onData);
|
|
927
|
+
process.stdout.removeListener('resize', onResize);
|
|
928
|
+
}
|
|
929
|
+
function loadFiles() {
|
|
930
|
+
if (allFiles.length > 0)
|
|
931
|
+
return;
|
|
932
|
+
const IGNORE = new Set([
|
|
933
|
+
'node_modules', '.git', 'dist', '.next', 'build',
|
|
934
|
+
'__pycache__', '.cache', '.svn', 'coverage',
|
|
935
|
+
]);
|
|
936
|
+
function walk(dir, depth, rel) {
|
|
937
|
+
if (depth > 4)
|
|
938
|
+
return;
|
|
939
|
+
let entries;
|
|
940
|
+
try {
|
|
941
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
942
|
+
}
|
|
943
|
+
catch {
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
for (const e of entries) {
|
|
947
|
+
if (IGNORE.has(e.name))
|
|
948
|
+
continue;
|
|
949
|
+
if (e.name.startsWith('.') && e.name !== '.env' && e.name !== '.gitignore')
|
|
950
|
+
continue;
|
|
951
|
+
const p = rel ? `${rel}/${e.name}` : e.name;
|
|
952
|
+
if (e.isDirectory()) {
|
|
953
|
+
allFiles.push(p + '/');
|
|
954
|
+
walk(path.join(dir, e.name), depth + 1, p);
|
|
955
|
+
}
|
|
956
|
+
else {
|
|
957
|
+
allFiles.push(p);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
walk(cwd, 0, '');
|
|
962
|
+
}
|
|
963
|
+
function filterFiles(q) {
|
|
964
|
+
const dirsFirst = (arr) => [
|
|
965
|
+
...arr.filter(f => f.endsWith('/')),
|
|
966
|
+
...arr.filter(f => !f.endsWith('/')),
|
|
967
|
+
];
|
|
968
|
+
if (!q)
|
|
969
|
+
return dirsFirst(allFiles).slice(0, 10);
|
|
970
|
+
const lq = q.toLowerCase();
|
|
971
|
+
const a = allFiles.filter(f => f.toLowerCase().startsWith(lq));
|
|
972
|
+
const b = allFiles.filter(f => !f.toLowerCase().startsWith(lq) && f.toLowerCase().includes(lq));
|
|
973
|
+
return dirsFirst([...a, ...b]).slice(0, 10);
|
|
974
|
+
}
|
|
975
|
+
function filterSlash(q) {
|
|
976
|
+
if (!q)
|
|
977
|
+
return SLASH_COMMANDS;
|
|
978
|
+
const lq = q.toLowerCase();
|
|
979
|
+
return SLASH_COMMANDS.filter(c => c.name.slice(1).toLowerCase().startsWith(lq));
|
|
980
|
+
}
|
|
981
|
+
let atDrawn = false;
|
|
982
|
+
function drawPicker() {
|
|
983
|
+
const cols = process.stdout.columns ?? 80;
|
|
984
|
+
const rows = process.stdout.rows ?? 24;
|
|
985
|
+
const sR = rows - 2;
|
|
986
|
+
const iR = rows - 1;
|
|
987
|
+
const filtered = filterFiles(atQuery);
|
|
988
|
+
if (atSel >= filtered.length && filtered.length > 0)
|
|
989
|
+
atSel = filtered.length - 1;
|
|
990
|
+
if (atSel < 0)
|
|
991
|
+
atSel = 0;
|
|
992
|
+
const maxVisible = Math.min(8, Math.max(3, rows - 6));
|
|
993
|
+
const shown = filtered.slice(0, maxVisible);
|
|
994
|
+
const DW = Math.min(Math.max(cols - 6, 44), 74);
|
|
995
|
+
const IW = DW - 6;
|
|
996
|
+
const boxLines = [];
|
|
997
|
+
const qLabel = atQuery ? `@${atQuery}` : 'files';
|
|
998
|
+
const hDashes = Math.max(DW - 4 - qLabel.length, 1);
|
|
999
|
+
boxLines.push(colors.dim(' ╭─ ') + colors.primary(qLabel) + colors.dim(' ' + '─'.repeat(hDashes) + '╮'));
|
|
1000
|
+
if (shown.length === 0) {
|
|
1001
|
+
const msg = 'no matches';
|
|
1002
|
+
const pad = ' '.repeat(Math.max(IW - msg.length, 0));
|
|
1003
|
+
boxLines.push(colors.dim(' │') + ' ' + colors.muted(msg) + pad + colors.dim('│'));
|
|
1004
|
+
}
|
|
1005
|
+
else {
|
|
1006
|
+
for (let i = 0; i < shown.length; i++) {
|
|
1007
|
+
const f = shown[i];
|
|
1008
|
+
const isDir = f.endsWith('/');
|
|
1009
|
+
const sel = i === atSel;
|
|
1010
|
+
const mark = sel ? colors.primary('›') : ' ';
|
|
1011
|
+
const clip = f.length > IW ? f.slice(0, IW - 1) + '…' : f;
|
|
1012
|
+
const pad = ' '.repeat(Math.max(IW - clip.length, 0));
|
|
1013
|
+
const name = sel && isDir ? colors.primary.bold(clip) + pad
|
|
1014
|
+
: sel ? colors.primary.bold(clip) + pad
|
|
1015
|
+
: isDir ? chalk.hex('#74b9ff')(clip) + pad
|
|
1016
|
+
: colors.subtext(clip + pad);
|
|
1017
|
+
boxLines.push(colors.dim(' │') + ` ${mark} ` + name + colors.dim('│'));
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
const hint = ' ↑↓ Navigate Enter Select Esc Close ';
|
|
1021
|
+
const fInner = DW - 2 - hint.length;
|
|
1022
|
+
const fLeft = Math.max(0, Math.floor(fInner / 2));
|
|
1023
|
+
const fRight = Math.max(0, fInner - fLeft);
|
|
1024
|
+
boxLines.push(colors.dim(' ╰' + '─'.repeat(fLeft)) + colors.muted(hint) + colors.dim('─'.repeat(fRight) + '╯'));
|
|
1025
|
+
const newLinesCount = boxLines.length;
|
|
1026
|
+
// Clear any leftover lines from previous taller popup
|
|
1027
|
+
if (atBoxLines > newLinesCount) {
|
|
1028
|
+
for (let r = sR - atBoxLines; r < sR - newLinesCount; r++) {
|
|
1029
|
+
if (r >= 1)
|
|
1030
|
+
process.stdout.write(`\x1b[${r};1H\x1b[2K`);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
// Render popup above separator
|
|
1034
|
+
for (let i = 0; i < newLinesCount; i++) {
|
|
1035
|
+
const targetRow = sR - newLinesCount + i;
|
|
1036
|
+
if (targetRow >= 1) {
|
|
1037
|
+
process.stdout.write(`\x1b[${targetRow};1H\x1b[2K${boxLines[i]}`);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
// Re-draw separator and input
|
|
1041
|
+
process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
|
|
1042
|
+
const inputLine = colors.primary(' › ') + colors.text(prefix) +
|
|
1043
|
+
(pasteBlock !== null ? colors.muted(`[paste: ${pasteCount} lines]`) + colors.text(suffix) : '') +
|
|
1044
|
+
colors.primary('@') + colors.text(atQuery);
|
|
1045
|
+
process.stdout.write(`\x1b[${iR};1H\x1b[2K${inputLine}`);
|
|
1046
|
+
const cursorCol = 5 + prefix.length + (pasteBlock !== null ? `[paste: ${pasteCount} lines]`.length + suffix.length : 0) + 1 + atQuery.length;
|
|
1047
|
+
process.stdout.write(`\x1b[${iR};${cursorCol}H`);
|
|
1048
|
+
atBoxLines = newLinesCount;
|
|
1049
|
+
atDrawn = true;
|
|
1050
|
+
}
|
|
1051
|
+
function closePicker() {
|
|
1052
|
+
const rows = process.stdout.rows ?? 24;
|
|
1053
|
+
const sR = rows - 2;
|
|
1054
|
+
if (atDrawn && atBoxLines > 0) {
|
|
1055
|
+
for (let r = sR - atBoxLines; r < sR; r++) {
|
|
1056
|
+
if (r >= 1)
|
|
1057
|
+
process.stdout.write(`\x1b[${r};1H\x1b[2K`);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
atBoxLines = 0;
|
|
1061
|
+
atMode = false;
|
|
1062
|
+
atQuery = '';
|
|
1063
|
+
atSel = 0;
|
|
1064
|
+
atDrawn = false;
|
|
1065
|
+
}
|
|
1066
|
+
function drawSlashPicker() {
|
|
1067
|
+
const cols = process.stdout.columns ?? 80;
|
|
1068
|
+
const rows = process.stdout.rows ?? 24;
|
|
1069
|
+
const sR = rows - 2;
|
|
1070
|
+
const iR = rows - 1;
|
|
1071
|
+
const filtered = filterSlash(slashQuery);
|
|
1072
|
+
if (slashSel >= filtered.length && filtered.length > 0)
|
|
1073
|
+
slashSel = filtered.length - 1;
|
|
1074
|
+
if (slashSel < 0)
|
|
1075
|
+
slashSel = 0;
|
|
1076
|
+
const maxVisible = Math.min(8, Math.max(3, rows - 6));
|
|
1077
|
+
const shown = filtered.slice(0, maxVisible);
|
|
1078
|
+
const DW = Math.min(Math.max(cols - 6, 44), 74);
|
|
1079
|
+
const nameW = 11;
|
|
1080
|
+
const descW = Math.max(DW - nameW - 9, 10);
|
|
1081
|
+
const boxLines = [];
|
|
1082
|
+
const qLabel = slashQuery ? `/${slashQuery}` : 'commands';
|
|
1083
|
+
const hDashes = Math.max(DW - 4 - qLabel.length, 1);
|
|
1084
|
+
boxLines.push(colors.dim(' ╭─ ') + colors.primary(qLabel) + colors.dim(' ' + '─'.repeat(hDashes) + '╮'));
|
|
1085
|
+
if (filtered.length === 0) {
|
|
1086
|
+
const msg = 'no matching commands';
|
|
1087
|
+
const pad = ' '.repeat(Math.max(DW - 4 - msg.length - 2, 0));
|
|
1088
|
+
boxLines.push(colors.dim(' │') + ' ' + colors.muted(msg) + pad + colors.dim('│'));
|
|
1089
|
+
}
|
|
1090
|
+
else {
|
|
1091
|
+
for (let i = 0; i < shown.length; i++) {
|
|
1092
|
+
const cmd = shown[i];
|
|
1093
|
+
const sel = i === slashSel;
|
|
1094
|
+
const mark = sel ? colors.primary('›') : ' ';
|
|
1095
|
+
const nameStr = cmd.name.padEnd(nameW);
|
|
1096
|
+
const descStr = cmd.desc.length > descW ? cmd.desc.slice(0, descW - 1) + '…' : cmd.desc;
|
|
1097
|
+
const descPad = ' '.repeat(Math.max(descW - descStr.length, 0));
|
|
1098
|
+
const namePaint = sel ? colors.primary.bold(nameStr) : colors.primary(nameStr);
|
|
1099
|
+
const descPaint = sel ? chalk.hex('#f1f5f9')(descStr) : colors.subtext(descStr);
|
|
1100
|
+
boxLines.push(colors.dim(' │') + ` ${mark} ` + namePaint + ' ' + descPaint + descPad + colors.dim('│'));
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
const hint = ' ↑↓ Navigate Tab Complete ↵ Run Esc Close ';
|
|
1104
|
+
const fInner = DW - 2 - hint.length;
|
|
1105
|
+
const fLeft = Math.max(0, Math.floor(fInner / 2));
|
|
1106
|
+
const fRight = Math.max(0, fInner - fLeft);
|
|
1107
|
+
boxLines.push(colors.dim(' ╰' + '─'.repeat(fLeft)) + colors.muted(hint) + colors.dim('─'.repeat(fRight) + '╯'));
|
|
1108
|
+
const newLinesCount = boxLines.length;
|
|
1109
|
+
// Clear any leftover lines from previous taller popup
|
|
1110
|
+
if (slashBoxLines > newLinesCount) {
|
|
1111
|
+
for (let r = sR - slashBoxLines; r < sR - newLinesCount; r++) {
|
|
1112
|
+
if (r >= 1)
|
|
1113
|
+
process.stdout.write(`\x1b[${r};1H\x1b[2K`);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
// Render popup above separator
|
|
1117
|
+
for (let i = 0; i < newLinesCount; i++) {
|
|
1118
|
+
const targetRow = sR - newLinesCount + i;
|
|
1119
|
+
if (targetRow >= 1) {
|
|
1120
|
+
process.stdout.write(`\x1b[${targetRow};1H\x1b[2K${boxLines[i]}`);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
// Re-draw separator and input line
|
|
1124
|
+
process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
|
|
1125
|
+
const inputLine = colors.primary(' › ') + colors.primary('/') + colors.text(slashQuery);
|
|
1126
|
+
process.stdout.write(`\x1b[${iR};1H\x1b[2K${inputLine}`);
|
|
1127
|
+
process.stdout.write(`\x1b[${iR};${5 + 1 + slashQuery.length}H`);
|
|
1128
|
+
slashBoxLines = newLinesCount;
|
|
1129
|
+
slashDrawn = true;
|
|
1130
|
+
}
|
|
1131
|
+
function closeSlashPicker() {
|
|
1132
|
+
const rows = process.stdout.rows ?? 24;
|
|
1133
|
+
const sR = rows - 2;
|
|
1134
|
+
if (slashDrawn && slashBoxLines > 0) {
|
|
1135
|
+
for (let r = sR - slashBoxLines; r < sR; r++) {
|
|
1136
|
+
if (r >= 1)
|
|
1137
|
+
process.stdout.write(`\x1b[${r};1H\x1b[2K`);
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
slashBoxLines = 0;
|
|
1141
|
+
slashMode = false;
|
|
1142
|
+
slashQuery = '';
|
|
1143
|
+
slashSel = 0;
|
|
1144
|
+
slashDrawn = false;
|
|
1145
|
+
}
|
|
1146
|
+
function drawTabPicker() {
|
|
1147
|
+
const cols = process.stdout.columns ?? 80;
|
|
1148
|
+
const rows = process.stdout.rows ?? 24;
|
|
1149
|
+
const sR = rows - 2;
|
|
1150
|
+
const iR = rows - 1;
|
|
1151
|
+
const TC = colors.success;
|
|
1152
|
+
const DW = Math.min(Math.max(cols - 6, 44), 74);
|
|
1153
|
+
const IW = DW - 6;
|
|
1154
|
+
const filtered = filterFiles(tabQuery);
|
|
1155
|
+
if (tabSel >= filtered.length && filtered.length > 0)
|
|
1156
|
+
tabSel = filtered.length - 1;
|
|
1157
|
+
if (tabSel < 0)
|
|
1158
|
+
tabSel = 0;
|
|
1159
|
+
const maxVisible = Math.min(8, Math.max(3, rows - 6));
|
|
1160
|
+
const shown = filtered.slice(0, maxVisible);
|
|
1161
|
+
const boxLines = [];
|
|
1162
|
+
const qLabel = tabQuery || 'tab complete';
|
|
1163
|
+
const hDashes = Math.max(DW - 4 - qLabel.length, 1);
|
|
1164
|
+
boxLines.push(colors.dim(' ╭─ ') + TC(qLabel) + colors.dim(' ' + '─'.repeat(hDashes) + '╮'));
|
|
1165
|
+
if (shown.length === 0) {
|
|
1166
|
+
const msg = 'no matches';
|
|
1167
|
+
const pad = ' '.repeat(Math.max(IW - msg.length, 0));
|
|
1168
|
+
boxLines.push(colors.dim(' │') + ' ' + colors.muted(msg) + pad + colors.dim('│'));
|
|
1169
|
+
}
|
|
1170
|
+
else {
|
|
1171
|
+
for (let i = 0; i < shown.length; i++) {
|
|
1172
|
+
const f = shown[i];
|
|
1173
|
+
const isDir = f.endsWith('/');
|
|
1174
|
+
const sel = i === tabSel;
|
|
1175
|
+
const mark = sel ? TC('›') : ' ';
|
|
1176
|
+
const clip = f.length > IW ? f.slice(0, IW - 1) + '…' : f;
|
|
1177
|
+
const pad = ' '.repeat(Math.max(IW - clip.length, 0));
|
|
1178
|
+
const name = sel ? TC.bold(clip) + pad
|
|
1179
|
+
: isDir ? chalk.hex('#74b9ff')(clip) + pad
|
|
1180
|
+
: colors.subtext(clip + pad);
|
|
1181
|
+
boxLines.push(colors.dim(' │') + ` ${mark} ` + name + colors.dim('│'));
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
const hint = ' Tab/↑↓ Navigate Enter Select Esc Close ';
|
|
1185
|
+
const fInner = DW - 2 - hint.length;
|
|
1186
|
+
const fLeft = Math.floor(fInner / 2);
|
|
1187
|
+
const fRight = fInner - fLeft;
|
|
1188
|
+
boxLines.push(colors.dim(' ╰' + '─'.repeat(Math.max(fLeft, 0))) + colors.muted(hint) + colors.dim('─'.repeat(Math.max(fRight, 0)) + '╯'));
|
|
1189
|
+
const newLinesCount = boxLines.length;
|
|
1190
|
+
// Clear any leftover lines from previous taller popup
|
|
1191
|
+
if (tabBoxLines > newLinesCount) {
|
|
1192
|
+
for (let r = sR - tabBoxLines; r < sR - newLinesCount; r++) {
|
|
1193
|
+
if (r >= 1)
|
|
1194
|
+
process.stdout.write(`\x1b[${r};1H\x1b[2K`);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
// Render popup above separator
|
|
1198
|
+
for (let i = 0; i < newLinesCount; i++) {
|
|
1199
|
+
const targetRow = sR - newLinesCount + i;
|
|
1200
|
+
if (targetRow >= 1) {
|
|
1201
|
+
process.stdout.write(`\x1b[${targetRow};1H\x1b[2K${boxLines[i]}`);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
// Re-draw separator and input line
|
|
1205
|
+
process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
|
|
1206
|
+
const inputLine = colors.primary(' › ') + colors.text(tabPreWord) + TC(tabQuery);
|
|
1207
|
+
process.stdout.write(`\x1b[${iR};1H\x1b[2K${inputLine}`);
|
|
1208
|
+
const cursorCol = 5 + tabPreWord.length + tabQuery.length;
|
|
1209
|
+
process.stdout.write(`\x1b[${iR};${cursorCol}H`);
|
|
1210
|
+
tabBoxLines = newLinesCount;
|
|
1211
|
+
tabDrawn = true;
|
|
1212
|
+
}
|
|
1213
|
+
function closeTabPicker() {
|
|
1214
|
+
const rows = process.stdout.rows ?? 24;
|
|
1215
|
+
const sR = rows - 2;
|
|
1216
|
+
if (tabDrawn && tabBoxLines > 0) {
|
|
1217
|
+
for (let r = sR - tabBoxLines; r < sR; r++) {
|
|
1218
|
+
if (r >= 1)
|
|
1219
|
+
process.stdout.write(`\x1b[${r};1H\x1b[2K`);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
tabBoxLines = 0;
|
|
1223
|
+
tabMode = false;
|
|
1224
|
+
tabQuery = '';
|
|
1225
|
+
tabSel = 0;
|
|
1226
|
+
tabPreWord = '';
|
|
1227
|
+
tabDrawn = false;
|
|
1228
|
+
}
|
|
1229
|
+
function redraw() {
|
|
1230
|
+
const cols = process.stdout.columns ?? 80;
|
|
1231
|
+
const rows = process.stdout.rows ?? 24;
|
|
1232
|
+
const sR = rows - 2;
|
|
1233
|
+
const iR = rows - 1;
|
|
1234
|
+
const maxLen = Math.max(cols - 8, 10);
|
|
1235
|
+
let displayPre = prefix;
|
|
1236
|
+
if (displayPre.length > maxLen)
|
|
1237
|
+
displayPre = '…' + displayPre.slice(-(maxLen - 1));
|
|
1238
|
+
let inp;
|
|
1239
|
+
let cursorCol = 5 + displayPre.length;
|
|
1240
|
+
if (pasteBlock !== null) {
|
|
1241
|
+
const pTag = `[paste: ${pasteCount} lines]`;
|
|
1242
|
+
inp = colors.primary(' › ') + colors.text(displayPre) +
|
|
1243
|
+
colors.muted(pTag) + colors.text(suffix);
|
|
1244
|
+
cursorCol = 5 + displayPre.length + pTag.length + suffix.length;
|
|
1245
|
+
}
|
|
1246
|
+
else {
|
|
1247
|
+
inp = colors.primary(' › ') + colors.text(displayPre) + colors.text(suffix);
|
|
1248
|
+
cursorCol = 5 + displayPre.length;
|
|
1249
|
+
}
|
|
1250
|
+
process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
|
|
1251
|
+
process.stdout.write(`\x1b[${iR};1H\x1b[2K${inp}`);
|
|
1252
|
+
process.stdout.write(`\x1b[${iR};${cursorCol}H`);
|
|
1253
|
+
}
|
|
1254
|
+
function submit() {
|
|
1255
|
+
if (atMode)
|
|
1256
|
+
closePicker();
|
|
1257
|
+
if (slashMode)
|
|
1258
|
+
closeSlashPicker();
|
|
1259
|
+
if (tabMode) {
|
|
1260
|
+
prefix = tabPreWord + tabQuery;
|
|
1261
|
+
closeTabPicker();
|
|
1262
|
+
}
|
|
1263
|
+
const parts = [];
|
|
1264
|
+
if (prefix.trim())
|
|
1265
|
+
parts.push(prefix.trim());
|
|
1266
|
+
if (pasteBlock)
|
|
1267
|
+
parts.push(...pasteBlock.split('\n').filter(Boolean));
|
|
1268
|
+
if (suffix.trim())
|
|
1269
|
+
parts.push(suffix.trim());
|
|
1270
|
+
const text = parts.join('\n');
|
|
1271
|
+
const lns = parts.length > 0 ? parts : (text ? [text] : []);
|
|
1272
|
+
cleanup();
|
|
1273
|
+
const rows = process.stdout.rows ?? 24;
|
|
1274
|
+
const cols = process.stdout.columns ?? 80;
|
|
1275
|
+
const sR = rows - 2;
|
|
1276
|
+
const iR = rows - 1;
|
|
1277
|
+
const scrBottom = rows - 3;
|
|
1278
|
+
// Clear fixed bottom input line
|
|
1279
|
+
process.stdout.write(`\x1b[${iR};1H\x1b[2K`);
|
|
1280
|
+
if (!text) {
|
|
1281
|
+
process.stdout.write(`\x1b[${sR};1H\x1b[2K${SEP}`);
|
|
1282
|
+
process.stdout.write(`\x1b[${iR};1H\x1b[2K${prompt}`);
|
|
1283
|
+
process.stdout.write(`\x1b[${iR};5H`);
|
|
1284
|
+
resolve(null);
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
const msgBg = chalk.bgHex('#334155').hex('#f1f5f9');
|
|
1288
|
+
const fillMsg = (raw) => (' > ' + raw + ' ').padEnd(cols);
|
|
1289
|
+
// Move to bottom of scroll region to append user message into chat
|
|
1290
|
+
process.stdout.write(`\x1b[${scrBottom};1H\n`);
|
|
1291
|
+
if (pasteBlock !== null) {
|
|
1292
|
+
const disp = [
|
|
1293
|
+
prefix ? prefix : '',
|
|
1294
|
+
`[${pasteCount} lines]`,
|
|
1295
|
+
suffix.trim() ? suffix.trim() : '',
|
|
1296
|
+
].filter(Boolean).join(' ');
|
|
1297
|
+
process.stdout.write(msgBg(fillMsg(disp)) + '\n');
|
|
1298
|
+
}
|
|
1299
|
+
else {
|
|
1300
|
+
process.stdout.write(msgBg(fillMsg(text)) + '\n');
|
|
1301
|
+
}
|
|
1302
|
+
process.stdout.write(`\x1b[${scrBottom};1H`);
|
|
1303
|
+
resolve({ text, lines: lns });
|
|
1304
|
+
}
|
|
1305
|
+
function onData(data) {
|
|
1306
|
+
try {
|
|
1307
|
+
if (data === '\x03') {
|
|
1308
|
+
// Close any active picker first
|
|
1309
|
+
if (atMode)
|
|
1310
|
+
closePicker();
|
|
1311
|
+
if (slashMode)
|
|
1312
|
+
closeSlashPicker();
|
|
1313
|
+
if (tabMode)
|
|
1314
|
+
closeTabPicker();
|
|
1315
|
+
// If there is typed input — clear it (safe copy behavior, like bash)
|
|
1316
|
+
if (prefix || pasteBlock !== null || suffix) {
|
|
1317
|
+
prefix = '';
|
|
1318
|
+
pasteBlock = null;
|
|
1319
|
+
pasteCount = 0;
|
|
1320
|
+
suffix = '';
|
|
1321
|
+
ctrlCCount = 0;
|
|
1322
|
+
if (ctrlCTimer) {
|
|
1323
|
+
clearTimeout(ctrlCTimer);
|
|
1324
|
+
ctrlCTimer = null;
|
|
1325
|
+
}
|
|
1326
|
+
redraw();
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
// No input: require double Ctrl+C to exit (prevents accidental exit from copy)
|
|
1330
|
+
ctrlCCount++;
|
|
1331
|
+
if (ctrlCTimer)
|
|
1332
|
+
clearTimeout(ctrlCTimer);
|
|
1333
|
+
if (ctrlCCount >= 2) {
|
|
1334
|
+
cleanup();
|
|
1335
|
+
process.stdout.write('\n\n ' + colors.muted('Goodbye!') + '\n\n');
|
|
1336
|
+
process.exit(0);
|
|
1337
|
+
}
|
|
1338
|
+
process.stdout.write('\r\x1b[K ' + colors.muted('(Ctrl+C again to exit — use /exit or close window)'));
|
|
1339
|
+
ctrlCTimer = setTimeout(() => { ctrlCCount = 0; redraw(); }, 1500);
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
if (ctrlCCount > 0) {
|
|
1343
|
+
ctrlCCount = 0;
|
|
1344
|
+
if (ctrlCTimer) {
|
|
1345
|
+
clearTimeout(ctrlCTimer);
|
|
1346
|
+
ctrlCTimer = null;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
if (data === '\x04') {
|
|
1350
|
+
cleanup();
|
|
1351
|
+
resolve(null);
|
|
1352
|
+
return;
|
|
1353
|
+
}
|
|
1354
|
+
// Ctrl+L — clear screen, redraw input
|
|
1355
|
+
if (data === '\x0c') {
|
|
1356
|
+
if (atMode)
|
|
1357
|
+
closePicker();
|
|
1358
|
+
if (slashMode)
|
|
1359
|
+
closeSlashPicker();
|
|
1360
|
+
if (tabMode)
|
|
1361
|
+
closeTabPicker();
|
|
1362
|
+
const curRows = process.stdout.rows ?? 24;
|
|
1363
|
+
const curSR = curRows - 2;
|
|
1364
|
+
const curIR = curRows - 1;
|
|
1365
|
+
console.clear();
|
|
1366
|
+
process.stdout.write(`\x1b[1;${curRows - 3}r`);
|
|
1367
|
+
process.stdout.write(`\x1b[${curSR};1H\x1b[2K${SEP}`);
|
|
1368
|
+
process.stdout.write(`\x1b[${curIR};1H\x1b[2K${prompt}`);
|
|
1369
|
+
process.stdout.write(`\x1b[${curIR};5H`);
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
// ── @ picker mode ─────────────────────────────────────────
|
|
1373
|
+
if (atMode) {
|
|
1374
|
+
if (data === '\x1b') { // Escape → cancel
|
|
1375
|
+
closePicker();
|
|
1376
|
+
redraw();
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
if (data === '\x1b[A') { // Arrow up
|
|
1380
|
+
const f = filterFiles(atQuery);
|
|
1381
|
+
if (f.length) {
|
|
1382
|
+
atSel = (atSel - 1 + f.length) % f.length;
|
|
1383
|
+
drawPicker();
|
|
1384
|
+
}
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
if (data === '\x1b[B') { // Arrow down
|
|
1388
|
+
const f = filterFiles(atQuery);
|
|
1389
|
+
if (f.length) {
|
|
1390
|
+
atSel = (atSel + 1) % f.length;
|
|
1391
|
+
drawPicker();
|
|
1392
|
+
}
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
if (data === '\x1b[C') { // Arrow right → enter folder
|
|
1396
|
+
const f = filterFiles(atQuery);
|
|
1397
|
+
if (f.length > 0) {
|
|
1398
|
+
const file = f[Math.min(atSel, f.length - 1)];
|
|
1399
|
+
if (file.endsWith('/')) {
|
|
1400
|
+
atQuery = file;
|
|
1401
|
+
atSel = 0;
|
|
1402
|
+
drawPicker();
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
if (data === '\x1b[D') { // Arrow left → go up one level
|
|
1408
|
+
const noTrail = atQuery.endsWith('/') ? atQuery.slice(0, -1) : atQuery;
|
|
1409
|
+
const lastSlash = noTrail.lastIndexOf('/');
|
|
1410
|
+
atQuery = lastSlash >= 0 ? noTrail.slice(0, lastSlash + 1) : '';
|
|
1411
|
+
atSel = 0;
|
|
1412
|
+
drawPicker();
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (data === '\r' || data === '\n' || data === '\t') { // Enter/Tab → drill into folder or insert file
|
|
1416
|
+
const filtered = filterFiles(atQuery);
|
|
1417
|
+
if (filtered.length > 0) {
|
|
1418
|
+
const file = filtered[Math.min(atSel, filtered.length - 1)];
|
|
1419
|
+
if (file.endsWith('/')) {
|
|
1420
|
+
atQuery = file;
|
|
1421
|
+
atSel = 0;
|
|
1422
|
+
drawPicker();
|
|
1423
|
+
}
|
|
1424
|
+
else {
|
|
1425
|
+
const mention = '@' + file;
|
|
1426
|
+
closePicker();
|
|
1427
|
+
if (pasteBlock !== null)
|
|
1428
|
+
suffix += mention;
|
|
1429
|
+
else
|
|
1430
|
+
prefix += mention;
|
|
1431
|
+
redraw();
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
else {
|
|
1435
|
+
closePicker();
|
|
1436
|
+
redraw();
|
|
1437
|
+
}
|
|
1438
|
+
return;
|
|
1439
|
+
}
|
|
1440
|
+
if (data === ' ') { // Space → select current item (file or folder)
|
|
1441
|
+
const filtered = filterFiles(atQuery);
|
|
1442
|
+
if (filtered.length > 0) {
|
|
1443
|
+
const file = filtered[Math.min(atSel, filtered.length - 1)];
|
|
1444
|
+
const mention = '@' + file;
|
|
1445
|
+
closePicker();
|
|
1446
|
+
if (pasteBlock !== null)
|
|
1447
|
+
suffix += mention;
|
|
1448
|
+
else
|
|
1449
|
+
prefix += mention;
|
|
1450
|
+
redraw();
|
|
1451
|
+
}
|
|
1452
|
+
else {
|
|
1453
|
+
closePicker();
|
|
1454
|
+
redraw();
|
|
1455
|
+
}
|
|
1456
|
+
return;
|
|
1457
|
+
}
|
|
1458
|
+
if (data === '\x7f' || data === '\b') { // Backspace
|
|
1459
|
+
if (atQuery.length > 0) {
|
|
1460
|
+
atQuery = atQuery.slice(0, -1);
|
|
1461
|
+
atSel = 0;
|
|
1462
|
+
drawPicker();
|
|
1463
|
+
}
|
|
1464
|
+
else {
|
|
1465
|
+
closePicker();
|
|
1466
|
+
redraw();
|
|
1467
|
+
}
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
if (data.length === 1 && data >= ' ') { // type to filter
|
|
1471
|
+
atQuery += data;
|
|
1472
|
+
atSel = 0;
|
|
1473
|
+
drawPicker();
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
// ── / slash picker mode ───────────────────────────────────
|
|
1479
|
+
if (slashMode) {
|
|
1480
|
+
if (data === '\x1b') {
|
|
1481
|
+
closeSlashPicker();
|
|
1482
|
+
redraw();
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
if (data === '\x1b[A') {
|
|
1486
|
+
const f = filterSlash(slashQuery);
|
|
1487
|
+
if (f.length) {
|
|
1488
|
+
slashSel = (slashSel - 1 + f.length) % f.length;
|
|
1489
|
+
drawSlashPicker();
|
|
1490
|
+
}
|
|
1491
|
+
return;
|
|
1492
|
+
}
|
|
1493
|
+
if (data === '\x1b[B') {
|
|
1494
|
+
const f = filterSlash(slashQuery);
|
|
1495
|
+
if (f.length) {
|
|
1496
|
+
slashSel = (slashSel + 1) % f.length;
|
|
1497
|
+
drawSlashPicker();
|
|
1498
|
+
}
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
if (data === '\r' || data === '\n') {
|
|
1502
|
+
const filtered = filterSlash(slashQuery);
|
|
1503
|
+
if (filtered.length > 0) {
|
|
1504
|
+
const cmd = filtered[Math.min(slashSel, filtered.length - 1)];
|
|
1505
|
+
prefix = cmd.name;
|
|
1506
|
+
closeSlashPicker();
|
|
1507
|
+
submit();
|
|
1508
|
+
}
|
|
1509
|
+
else {
|
|
1510
|
+
prefix = '/' + slashQuery;
|
|
1511
|
+
closeSlashPicker();
|
|
1512
|
+
submit();
|
|
1513
|
+
}
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
if (data === '\t') {
|
|
1517
|
+
const filtered = filterSlash(slashQuery);
|
|
1518
|
+
if (filtered.length > 0) {
|
|
1519
|
+
const cmd = filtered[Math.min(slashSel, filtered.length - 1)];
|
|
1520
|
+
prefix = cmd.name + ' ';
|
|
1521
|
+
closeSlashPicker();
|
|
1522
|
+
redraw();
|
|
1523
|
+
}
|
|
1524
|
+
else {
|
|
1525
|
+
closeSlashPicker();
|
|
1526
|
+
redraw();
|
|
1527
|
+
}
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
if (data === '\x7f' || data === '\b') {
|
|
1531
|
+
if (slashQuery.length > 0) {
|
|
1532
|
+
slashQuery = slashQuery.slice(0, -1);
|
|
1533
|
+
slashSel = 0;
|
|
1534
|
+
drawSlashPicker();
|
|
1535
|
+
}
|
|
1536
|
+
else {
|
|
1537
|
+
closeSlashPicker();
|
|
1538
|
+
redraw();
|
|
1539
|
+
}
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
if (data === ' ') {
|
|
1543
|
+
const filtered = filterSlash(slashQuery);
|
|
1544
|
+
if (filtered.length > 0) {
|
|
1545
|
+
const cmd = filtered[Math.min(slashSel, filtered.length - 1)];
|
|
1546
|
+
prefix = cmd.name + ' ';
|
|
1547
|
+
}
|
|
1548
|
+
else {
|
|
1549
|
+
prefix = '/' + slashQuery + ' ';
|
|
1550
|
+
}
|
|
1551
|
+
closeSlashPicker();
|
|
1552
|
+
redraw();
|
|
1553
|
+
return;
|
|
1554
|
+
}
|
|
1555
|
+
if (data.length === 1 && data >= ' ') {
|
|
1556
|
+
slashQuery += data;
|
|
1557
|
+
slashSel = 0;
|
|
1558
|
+
drawSlashPicker();
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
// ── Tab path-autocomplete mode ────────────────────────────
|
|
1564
|
+
if (tabMode) {
|
|
1565
|
+
if (data === '\x1b') { // Escape → cancel, restore text
|
|
1566
|
+
const saved = tabPreWord + tabQuery;
|
|
1567
|
+
closeTabPicker();
|
|
1568
|
+
prefix = saved;
|
|
1569
|
+
redraw();
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
if (data === '\x1b[A') { // Arrow up
|
|
1573
|
+
const f = filterFiles(tabQuery);
|
|
1574
|
+
if (f.length) {
|
|
1575
|
+
tabSel = (tabSel - 1 + f.length) % f.length;
|
|
1576
|
+
drawTabPicker();
|
|
1577
|
+
}
|
|
1578
|
+
return;
|
|
1579
|
+
}
|
|
1580
|
+
if (data === '\x1b[B' || data === '\t') { // Arrow down / Tab → next
|
|
1581
|
+
const f = filterFiles(tabQuery);
|
|
1582
|
+
if (f.length) {
|
|
1583
|
+
tabSel = (tabSel + 1) % f.length;
|
|
1584
|
+
drawTabPicker();
|
|
1585
|
+
}
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
if (data === '\x1b[C') { // Arrow right → enter folder
|
|
1589
|
+
const f = filterFiles(tabQuery);
|
|
1590
|
+
if (f.length > 0) {
|
|
1591
|
+
const file = f[Math.min(tabSel, f.length - 1)];
|
|
1592
|
+
if (file.endsWith('/')) {
|
|
1593
|
+
tabQuery = file;
|
|
1594
|
+
tabSel = 0;
|
|
1595
|
+
drawTabPicker();
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
return;
|
|
1599
|
+
}
|
|
1600
|
+
if (data === '\x1b[D') { // Arrow left → go up
|
|
1601
|
+
const noTrail = tabQuery.endsWith('/') ? tabQuery.slice(0, -1) : tabQuery;
|
|
1602
|
+
const lastSlash = noTrail.lastIndexOf('/');
|
|
1603
|
+
tabQuery = lastSlash >= 0 ? noTrail.slice(0, lastSlash + 1) : '';
|
|
1604
|
+
tabSel = 0;
|
|
1605
|
+
drawTabPicker();
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
if (data === '\r' || data === '\n') { // Enter → insert or drill
|
|
1609
|
+
const filtered = filterFiles(tabQuery);
|
|
1610
|
+
if (filtered.length > 0) {
|
|
1611
|
+
const file = filtered[Math.min(tabSel, filtered.length - 1)];
|
|
1612
|
+
if (file.endsWith('/')) {
|
|
1613
|
+
tabQuery = file;
|
|
1614
|
+
tabSel = 0;
|
|
1615
|
+
drawTabPicker();
|
|
1616
|
+
}
|
|
1617
|
+
else {
|
|
1618
|
+
prefix = tabPreWord + file;
|
|
1619
|
+
closeTabPicker();
|
|
1620
|
+
redraw();
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
else {
|
|
1624
|
+
prefix = tabPreWord + tabQuery;
|
|
1625
|
+
closeTabPicker();
|
|
1626
|
+
redraw();
|
|
1627
|
+
}
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
if (data === '\x7f' || data === '\b') { // Backspace
|
|
1631
|
+
if (tabQuery.length > 0) {
|
|
1632
|
+
tabQuery = tabQuery.slice(0, -1);
|
|
1633
|
+
tabSel = 0;
|
|
1634
|
+
drawTabPicker();
|
|
1635
|
+
}
|
|
1636
|
+
else {
|
|
1637
|
+
closeTabPicker();
|
|
1638
|
+
prefix = tabPreWord;
|
|
1639
|
+
redraw();
|
|
1640
|
+
}
|
|
1641
|
+
return;
|
|
1642
|
+
}
|
|
1643
|
+
if (data.length === 1 && data >= ' ') { // Type to filter
|
|
1644
|
+
tabQuery += data;
|
|
1645
|
+
tabSel = 0;
|
|
1646
|
+
drawTabPicker();
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1649
|
+
return;
|
|
1650
|
+
}
|
|
1651
|
+
// Enter
|
|
1652
|
+
if (data === '\r' || data === '\n' || data === '\r\n') {
|
|
1653
|
+
submit();
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1656
|
+
// ── Tab trigger ───────────────────────────────────────────
|
|
1657
|
+
if (data === '\t' && pasteBlock === null) {
|
|
1658
|
+
loadFiles();
|
|
1659
|
+
const spaceIdx = prefix.lastIndexOf(' ');
|
|
1660
|
+
tabPreWord = spaceIdx >= 0 ? prefix.slice(0, spaceIdx + 1) : '';
|
|
1661
|
+
tabQuery = spaceIdx >= 0 ? prefix.slice(spaceIdx + 1) : prefix;
|
|
1662
|
+
tabSel = 0;
|
|
1663
|
+
tabMode = true;
|
|
1664
|
+
drawTabPicker();
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
// ── @ trigger ─────────────────────────────────────────────
|
|
1668
|
+
if (data === '@') {
|
|
1669
|
+
loadFiles();
|
|
1670
|
+
atMode = true;
|
|
1671
|
+
atQuery = '';
|
|
1672
|
+
atSel = 0;
|
|
1673
|
+
drawPicker();
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
// ── / trigger ─────────────────────────────────────────────
|
|
1677
|
+
if (data === '/' && prefix === '' && pasteBlock === null) {
|
|
1678
|
+
slashMode = true;
|
|
1679
|
+
slashQuery = '';
|
|
1680
|
+
slashSel = 0;
|
|
1681
|
+
drawSlashPicker();
|
|
1682
|
+
return;
|
|
1683
|
+
}
|
|
1684
|
+
// ── Paste detection ───────────────────────────────────────
|
|
1685
|
+
const normalized = data.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
1686
|
+
if (normalized.includes('\n')) {
|
|
1687
|
+
prefix += suffix;
|
|
1688
|
+
suffix = '';
|
|
1689
|
+
const pasted = normalized.replace(/\n$/, '');
|
|
1690
|
+
pasteBlock = pasted;
|
|
1691
|
+
pasteCount = pasted.split('\n').filter(l => l.length > 0).length || 1;
|
|
1692
|
+
redraw();
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
// Backspace
|
|
1696
|
+
if (data === '\x7f' || data === '\b') {
|
|
1697
|
+
if (suffix.length > 0) {
|
|
1698
|
+
suffix = suffix.slice(0, -1);
|
|
1699
|
+
process.stdout.write('\b \b');
|
|
1700
|
+
}
|
|
1701
|
+
else if (pasteBlock !== null) {
|
|
1702
|
+
pasteBlock = null;
|
|
1703
|
+
pasteCount = 0;
|
|
1704
|
+
redraw();
|
|
1705
|
+
}
|
|
1706
|
+
else if (prefix.length > 0) {
|
|
1707
|
+
prefix = prefix.slice(0, -1);
|
|
1708
|
+
process.stdout.write('\b \b');
|
|
1709
|
+
}
|
|
1710
|
+
return;
|
|
1711
|
+
}
|
|
1712
|
+
// Ignore unrecognised escape sequences (arrow keys, Fn keys, etc.)
|
|
1713
|
+
if (data.startsWith('\x1b'))
|
|
1714
|
+
return;
|
|
1715
|
+
// Single-line paste (multiple printable chars arriving at once — no newline)
|
|
1716
|
+
if (data.length > 1) {
|
|
1717
|
+
const printable = data.split('').filter(c => c >= ' ').join('');
|
|
1718
|
+
if (printable) {
|
|
1719
|
+
if (pasteBlock !== null)
|
|
1720
|
+
suffix += printable;
|
|
1721
|
+
else
|
|
1722
|
+
prefix += printable;
|
|
1723
|
+
process.stdout.write(printable);
|
|
1724
|
+
}
|
|
1725
|
+
return;
|
|
1726
|
+
}
|
|
1727
|
+
// Regular single printable char
|
|
1728
|
+
if (data.length === 1 && data >= ' ') {
|
|
1729
|
+
if (pasteBlock !== null)
|
|
1730
|
+
suffix += data;
|
|
1731
|
+
else
|
|
1732
|
+
prefix += data;
|
|
1733
|
+
process.stdout.write(data);
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
catch (e) {
|
|
1737
|
+
// If any keypress handler throws, restore terminal so keys don't get stuck
|
|
1738
|
+
cleanup();
|
|
1739
|
+
resolve(null);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
process.stdin.on('data', onData);
|
|
1743
|
+
});
|
|
1744
|
+
}
|
|
1745
|
+
// ── Main REPL ───────────────────────────────────────────────────
|
|
1746
|
+
function fmtDate(iso) {
|
|
1747
|
+
const d = new Date(iso);
|
|
1748
|
+
const mo = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
|
|
1749
|
+
return `${mo} ${String(d.getDate()).padStart(2, ' ')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
|
1750
|
+
}
|
|
1751
|
+
function timeAgoShort(iso) {
|
|
1752
|
+
const diff = Date.now() - new Date(iso).getTime();
|
|
1753
|
+
const m = Math.floor(diff / 60000);
|
|
1754
|
+
if (m < 1)
|
|
1755
|
+
return 'now';
|
|
1756
|
+
if (m < 60)
|
|
1757
|
+
return `${m}m`;
|
|
1758
|
+
const h = Math.floor(m / 60);
|
|
1759
|
+
if (h < 24)
|
|
1760
|
+
return `${h}h`;
|
|
1761
|
+
const d = Math.floor(h / 24);
|
|
1762
|
+
if (d < 30)
|
|
1763
|
+
return `${d}d`;
|
|
1764
|
+
return `${Math.floor(d / 30)}mo`;
|
|
1765
|
+
}
|
|
1766
|
+
async function showConversationPicker(cwd) {
|
|
1767
|
+
const allConvs = listConversations(cwd, 100);
|
|
1768
|
+
if (allConvs.length === 0) {
|
|
1769
|
+
printInfo('No saved conversations yet.');
|
|
1770
|
+
return null;
|
|
1771
|
+
}
|
|
1772
|
+
return new Promise((resolve) => {
|
|
1773
|
+
let sel = 0;
|
|
1774
|
+
let query = '';
|
|
1775
|
+
let drawnLines = 0;
|
|
1776
|
+
let lastDW = 0;
|
|
1777
|
+
const MAX_SHOWN = 10;
|
|
1778
|
+
let scroll = 0; // first visible index within filtered list
|
|
1779
|
+
function getAllFiltered() {
|
|
1780
|
+
if (!query)
|
|
1781
|
+
return allConvs;
|
|
1782
|
+
const lq = query.toLowerCase();
|
|
1783
|
+
return allConvs.filter(c => c.title.toLowerCase().includes(lq));
|
|
1784
|
+
}
|
|
1785
|
+
function draw() {
|
|
1786
|
+
const cols = process.stdout.columns ?? 80;
|
|
1787
|
+
const DW = Math.min(Math.max(cols - 6, 50), 84);
|
|
1788
|
+
lastDW = DW;
|
|
1789
|
+
const all = getAllFiltered();
|
|
1790
|
+
const total = all.length;
|
|
1791
|
+
if (total > 0 && sel >= total)
|
|
1792
|
+
sel = total - 1;
|
|
1793
|
+
if (sel < 0)
|
|
1794
|
+
sel = 0;
|
|
1795
|
+
// Keep sel in visible window
|
|
1796
|
+
if (sel < scroll)
|
|
1797
|
+
scroll = sel;
|
|
1798
|
+
if (sel >= scroll + MAX_SHOWN)
|
|
1799
|
+
scroll = sel - MAX_SHOWN + 1;
|
|
1800
|
+
scroll = Math.max(0, Math.min(scroll, Math.max(0, total - MAX_SHOWN)));
|
|
1801
|
+
const shown = all.slice(scroll, scroll + MAX_SHOWN);
|
|
1802
|
+
const N = shown.length;
|
|
1803
|
+
// Clear previous draw
|
|
1804
|
+
if (drawnLines > 0) {
|
|
1805
|
+
for (let i = 0; i < drawnLines; i++)
|
|
1806
|
+
process.stdout.write('\x1b[1A\x1b[2K');
|
|
1807
|
+
}
|
|
1808
|
+
drawnLines = 0;
|
|
1809
|
+
const BC = chalk.hex('#4338ca');
|
|
1810
|
+
const PC = chalk.hex('#818cf8');
|
|
1811
|
+
const DIM = chalk.hex('#4b5563');
|
|
1812
|
+
// ── Header ─────────────────────────────────────────────────
|
|
1813
|
+
// Visible: " ╭─" (4) + hLabel + " " + "─"*hDashes + "╮" (1) = DW+2
|
|
1814
|
+
const hLabel = query
|
|
1815
|
+
? ` / ${query} ` + DIM(`${total} found`)
|
|
1816
|
+
: ` ${allConvs.length} conversation${allConvs.length !== 1 ? 's' : ''}`;
|
|
1817
|
+
const hLabelVis = stripAnsi(hLabel).length;
|
|
1818
|
+
const hDashes = Math.max(DW - 4 - hLabelVis, 1);
|
|
1819
|
+
process.stdout.write(BC(' ╭─') + PC(hLabel) + BC(' ' + '─'.repeat(hDashes) + '╮') + '\n');
|
|
1820
|
+
drawnLines++;
|
|
1821
|
+
// ── Search input ────────────────────────────────────────────
|
|
1822
|
+
// Visible: " │" (3) + " / " (5) + query + cursor(1) + pad + "│" (1) = DW+2
|
|
1823
|
+
// → pad = DW - 8 - query.length
|
|
1824
|
+
const sCursor = colors.primary('│');
|
|
1825
|
+
const sPad = ' '.repeat(Math.max(DW - 8 - query.length, 0));
|
|
1826
|
+
process.stdout.write(BC(' │') + colors.muted(' / ') + chalk.white(query) + sCursor + sPad + BC('│') + '\n');
|
|
1827
|
+
drawnLines++;
|
|
1828
|
+
// ── Separator ──────────────────────────────────────────────
|
|
1829
|
+
process.stdout.write(BC(' ├' + '─'.repeat(DW - 2) + '┤') + '\n');
|
|
1830
|
+
drawnLines++;
|
|
1831
|
+
// ── Items ──────────────────────────────────────────────────
|
|
1832
|
+
// Row visible: " │" (3) + " > " (4) + TITLE_W + " " (2) + msgs(7) + " " (2) + ago(3) + " │" (2) = DW+2
|
|
1833
|
+
// → 3+4+TITLE_W+2+7+2+3+2 = 23+TITLE_W = DW+2 → TITLE_W = DW-21
|
|
1834
|
+
const TITLE_W = Math.max(DW - 21, 12);
|
|
1835
|
+
if (N === 0) {
|
|
1836
|
+
const msg = query ? 'no matching conversations' : 'no conversations yet';
|
|
1837
|
+
const ipad = ' '.repeat(Math.max(DW - 6 - msg.length, 0));
|
|
1838
|
+
process.stdout.write(BC(' │') + ' ' + colors.muted(msg) + ipad + BC('│') + '\n');
|
|
1839
|
+
drawnLines++;
|
|
1840
|
+
}
|
|
1841
|
+
else {
|
|
1842
|
+
for (let i = 0; i < N; i++) {
|
|
1843
|
+
const c = shown[i];
|
|
1844
|
+
const isSel = (scroll + i) === sel;
|
|
1845
|
+
const mark = isSel ? PC('>') : ' ';
|
|
1846
|
+
const title = c.title.replace(/\s+/g, ' ');
|
|
1847
|
+
const disp = title.length > TITLE_W ? title.slice(0, TITLE_W - 1) + '…' : title;
|
|
1848
|
+
const gap = ' '.repeat(Math.max(TITLE_W - disp.length, 0));
|
|
1849
|
+
// msgs: always 7 chars — e.g. " 2 msgs" or "20 msgs"
|
|
1850
|
+
const msgs = String(c.messageCount).padStart(2) + ' msgs';
|
|
1851
|
+
// ago: always 3 chars
|
|
1852
|
+
const ago = timeAgoShort(c.updatedAt).padStart(3);
|
|
1853
|
+
const titleC = isSel ? PC.bold(disp) : chalk.hex('#94a3b8')(disp);
|
|
1854
|
+
const msgsC = isSel ? chalk.hex('#818cf8')(msgs) : DIM(msgs);
|
|
1855
|
+
const agoC = isSel ? PC(ago) : DIM(ago);
|
|
1856
|
+
process.stdout.write(BC(' │') + ` ${mark} ` + titleC + gap + ` ` + msgsC + ` ` + agoC + ` ` + BC('│') + '\n');
|
|
1857
|
+
drawnLines++;
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
// ── Scroll indicator row (if needed) ───────────────────────
|
|
1861
|
+
if (total > MAX_SHOWN) {
|
|
1862
|
+
const above = scroll > 0;
|
|
1863
|
+
const below = scroll + MAX_SHOWN < total;
|
|
1864
|
+
const pos = `${sel + 1} / ${total}`;
|
|
1865
|
+
const arrows = (above ? '↑ ' : ' ') + pos + (below ? ' ↓' : ' ');
|
|
1866
|
+
const ipad = ' '.repeat(Math.max(DW - 4 - arrows.length, 0));
|
|
1867
|
+
process.stdout.write(BC(' │') + ipad + colors.muted(arrows) + ` ` + BC('│') + '\n');
|
|
1868
|
+
drawnLines++;
|
|
1869
|
+
}
|
|
1870
|
+
// ── Footer ─────────────────────────────────────────────────
|
|
1871
|
+
const hint = ' ↑↓ navigate Enter open Esc cancel ';
|
|
1872
|
+
const fInner = DW - 2 - hint.length;
|
|
1873
|
+
const fLeft = Math.max(Math.floor(fInner / 2), 0);
|
|
1874
|
+
const fRight = Math.max(fInner - fLeft, 0);
|
|
1875
|
+
process.stdout.write(BC(' ╰' + '─'.repeat(fLeft)) + colors.muted(hint) + BC('─'.repeat(fRight) + '╯') + '\n');
|
|
1876
|
+
drawnLines++;
|
|
1877
|
+
}
|
|
1878
|
+
draw();
|
|
1879
|
+
function onResize() {
|
|
1880
|
+
const newCols = process.stdout.columns ?? 80;
|
|
1881
|
+
const rowsPerLine = Math.max(1, Math.ceil((lastDW + 2) / newCols));
|
|
1882
|
+
const physRows = drawnLines * rowsPerLine;
|
|
1883
|
+
for (let i = 0; i < physRows; i++)
|
|
1884
|
+
process.stdout.write('\x1b[1A');
|
|
1885
|
+
process.stdout.write('\r\x1b[0J');
|
|
1886
|
+
drawnLines = 0;
|
|
1887
|
+
draw();
|
|
1888
|
+
}
|
|
1889
|
+
process.stdout.on('resize', onResize);
|
|
1890
|
+
function cleanup() {
|
|
1891
|
+
process.stdin.removeListener('data', onKey);
|
|
1892
|
+
process.stdout.removeListener('resize', onResize);
|
|
1893
|
+
}
|
|
1894
|
+
function close(id) {
|
|
1895
|
+
cleanup();
|
|
1896
|
+
for (let i = 0; i < drawnLines; i++)
|
|
1897
|
+
process.stdout.write('\x1b[1A\x1b[2K');
|
|
1898
|
+
resolve(id);
|
|
1899
|
+
}
|
|
1900
|
+
function onKey(data) {
|
|
1901
|
+
const all = getAllFiltered();
|
|
1902
|
+
const N = all.length;
|
|
1903
|
+
switch (data) {
|
|
1904
|
+
case '\x1b[A': // Arrow up
|
|
1905
|
+
if (N > 0) {
|
|
1906
|
+
sel = Math.max(sel - 1, 0);
|
|
1907
|
+
draw();
|
|
1908
|
+
}
|
|
1909
|
+
break;
|
|
1910
|
+
case '\x1b[B': // Arrow down
|
|
1911
|
+
if (N > 0) {
|
|
1912
|
+
sel = Math.min(sel + 1, N - 1);
|
|
1913
|
+
draw();
|
|
1914
|
+
}
|
|
1915
|
+
break;
|
|
1916
|
+
case '\r':
|
|
1917
|
+
case '\n':
|
|
1918
|
+
close(all[sel]?.id ?? null);
|
|
1919
|
+
break;
|
|
1920
|
+
case '\x1b':
|
|
1921
|
+
close(null);
|
|
1922
|
+
break;
|
|
1923
|
+
case '\x03':
|
|
1924
|
+
cleanup();
|
|
1925
|
+
process.exit(0);
|
|
1926
|
+
break;
|
|
1927
|
+
case '\x7f':
|
|
1928
|
+
case '\b':
|
|
1929
|
+
if (query.length > 0) {
|
|
1930
|
+
query = query.slice(0, -1);
|
|
1931
|
+
sel = 0;
|
|
1932
|
+
scroll = 0;
|
|
1933
|
+
draw();
|
|
1934
|
+
}
|
|
1935
|
+
break;
|
|
1936
|
+
default:
|
|
1937
|
+
if (data.length === 1 && data >= ' ') {
|
|
1938
|
+
query += data;
|
|
1939
|
+
sel = 0;
|
|
1940
|
+
scroll = 0;
|
|
1941
|
+
draw();
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
process.stdin.on('data', onKey);
|
|
1946
|
+
});
|
|
1947
|
+
}
|
|
1948
|
+
function printConversationHistory(messages) {
|
|
1949
|
+
const cols = process.stdout.columns ?? 80;
|
|
1950
|
+
const chatMsgs = messages.filter(m => m.role === 'user' || m.role === 'assistant');
|
|
1951
|
+
if (chatMsgs.length === 0)
|
|
1952
|
+
return;
|
|
1953
|
+
// Build map: filepath → last known content (from system read_file messages)
|
|
1954
|
+
const fileSnapshot = new Map();
|
|
1955
|
+
for (const msg of messages) {
|
|
1956
|
+
if (msg.role === 'system') {
|
|
1957
|
+
const text = String(msg.content);
|
|
1958
|
+
const match = text.match(/^\[File content — ([^\]]+)\]:\n([\s\S]*)$/);
|
|
1959
|
+
if (match)
|
|
1960
|
+
fileSnapshot.set(match[1], match[2]);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
const toShow = chatMsgs.length > 20 ? chatMsgs.slice(-20) : chatMsgs;
|
|
1964
|
+
if (chatMsgs.length > 20) {
|
|
1965
|
+
process.stdout.write(colors.muted(`\n … ${chatMsgs.length - 20} earlier messages …\n`));
|
|
1966
|
+
}
|
|
1967
|
+
const msgBg = chalk.bgHex('#334155').hex('#f1f5f9');
|
|
1968
|
+
const BC = chalk.hex('#4338ca');
|
|
1969
|
+
const FC = chalk.hex('#e2e8f0');
|
|
1970
|
+
for (const msg of toShow) {
|
|
1971
|
+
if (msg.role === 'user') {
|
|
1972
|
+
const raw = String(msg.content).replace(/\s+/g, ' ').trim();
|
|
1973
|
+
const display = raw.length > cols - 8 ? raw.slice(0, cols - 11) + '...' : raw;
|
|
1974
|
+
process.stdout.write('\n' + msgBg((' > ' + display + ' ').padEnd(cols)) + '\n');
|
|
1975
|
+
}
|
|
1976
|
+
else {
|
|
1977
|
+
const raw = String(msg.content);
|
|
1978
|
+
const stripper = new TagStripper();
|
|
1979
|
+
const renderer = new MarkdownRenderer();
|
|
1980
|
+
const stripped = stripper.feed(raw) + stripper.flush();
|
|
1981
|
+
const rendered = (renderer.format(stripped) + renderer.flush()).replace(/^\n+/, '');
|
|
1982
|
+
if (rendered.trim())
|
|
1983
|
+
process.stdout.write('\n' + rendered);
|
|
1984
|
+
const allOps = parseOps(normalizeResponse(raw));
|
|
1985
|
+
const readOps = allOps.filter(op => (op.type === 'read_file' && op.path) ||
|
|
1986
|
+
(op.type === 'read_folder' && op.path) ||
|
|
1987
|
+
(op.type === 'search_code' && op.pattern));
|
|
1988
|
+
const fileOps = allOps.filter(op => op.type !== 'read_file' && op.type !== 'read_folder' && op.type !== 'search_code');
|
|
1989
|
+
// ── File operation summaries ─────────────────────────────
|
|
1990
|
+
if (fileOps.length > 0) {
|
|
1991
|
+
const maxW = Math.min(cols - 12, 120);
|
|
1992
|
+
const clip = (t) => t.length > maxW ? t.slice(0, maxW - 1) + '…' : t;
|
|
1993
|
+
const renderDiffLines = (diff, maxLines = 60) => {
|
|
1994
|
+
const CONTEXT = 2;
|
|
1995
|
+
const show = new Uint8Array(diff.length);
|
|
1996
|
+
for (let i = 0; i < diff.length; i++) {
|
|
1997
|
+
if (diff[i].kind !== 'context') {
|
|
1998
|
+
for (let c = Math.max(0, i - CONTEXT); c <= Math.min(diff.length - 1, i + CONTEXT); c++)
|
|
1999
|
+
show[c] = 1;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
const renderLine = (line) => {
|
|
2003
|
+
const num = String(line.lineNo).padStart(5, ' ');
|
|
2004
|
+
if (line.kind === 'remove') {
|
|
2005
|
+
const content = ` ${num} ${chalk.hex('#f87171')('-')} ${clip(line.text)}`;
|
|
2006
|
+
process.stdout.write(' ' + chalk.hex('#7f1d1d')('▌') + chalk.bgHex('#1c0a0a')(content.padEnd(cols - 3)) + '\n');
|
|
2007
|
+
}
|
|
2008
|
+
else if (line.kind === 'add') {
|
|
2009
|
+
const content = ` ${num} ${chalk.hex('#34d399')('+')} ${clip(line.text)}`;
|
|
2010
|
+
process.stdout.write(' ' + chalk.hex('#065f46')('▌') + chalk.bgHex('#021a0e')(content.padEnd(cols - 3)) + '\n');
|
|
2011
|
+
}
|
|
2012
|
+
else {
|
|
2013
|
+
process.stdout.write(chalk.hex('#374151')(` ${num} ${clip(line.text)}\n`));
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
// Build hunks
|
|
2017
|
+
const hunks = [];
|
|
2018
|
+
let curHunk = [];
|
|
2019
|
+
let lastIdx = -1;
|
|
2020
|
+
for (let i = 0; i < diff.length; i++) {
|
|
2021
|
+
if (!show[i])
|
|
2022
|
+
continue;
|
|
2023
|
+
if (lastIdx >= 0 && i > lastIdx + 1) {
|
|
2024
|
+
hunks.push(curHunk);
|
|
2025
|
+
curHunk = [];
|
|
2026
|
+
}
|
|
2027
|
+
lastIdx = i;
|
|
2028
|
+
curHunk.push(diff[i]);
|
|
2029
|
+
}
|
|
2030
|
+
if (curHunk.length > 0)
|
|
2031
|
+
hunks.push(curHunk);
|
|
2032
|
+
// Per-hunk: leading context, all removes, all adds, trailing context
|
|
2033
|
+
let shown = 0;
|
|
2034
|
+
for (let h = 0; h < hunks.length; h++) {
|
|
2035
|
+
if (shown >= maxLines)
|
|
2036
|
+
break;
|
|
2037
|
+
if (h > 0)
|
|
2038
|
+
process.stdout.write(chalk.hex('#374151')(' ╌╌╌\n'));
|
|
2039
|
+
const hunk = hunks[h];
|
|
2040
|
+
const before = [];
|
|
2041
|
+
const hRemoves = [];
|
|
2042
|
+
const hAdds = [];
|
|
2043
|
+
let pendingCtx = [];
|
|
2044
|
+
let seenChange = false;
|
|
2045
|
+
for (const line of hunk) {
|
|
2046
|
+
if (line.kind === 'context') {
|
|
2047
|
+
if (!seenChange)
|
|
2048
|
+
before.push(line);
|
|
2049
|
+
else
|
|
2050
|
+
pendingCtx.push(line);
|
|
2051
|
+
}
|
|
2052
|
+
else {
|
|
2053
|
+
seenChange = true;
|
|
2054
|
+
pendingCtx = [];
|
|
2055
|
+
if (line.kind === 'remove')
|
|
2056
|
+
hRemoves.push(line);
|
|
2057
|
+
else
|
|
2058
|
+
hAdds.push(line);
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
for (const l of before)
|
|
2062
|
+
renderLine(l);
|
|
2063
|
+
for (const l of hRemoves) {
|
|
2064
|
+
if (shown >= maxLines)
|
|
2065
|
+
break;
|
|
2066
|
+
renderLine(l);
|
|
2067
|
+
shown++;
|
|
2068
|
+
}
|
|
2069
|
+
for (const l of hAdds) {
|
|
2070
|
+
if (shown >= maxLines)
|
|
2071
|
+
break;
|
|
2072
|
+
renderLine(l);
|
|
2073
|
+
shown++;
|
|
2074
|
+
}
|
|
2075
|
+
for (const l of pendingCtx)
|
|
2076
|
+
renderLine(l);
|
|
2077
|
+
}
|
|
2078
|
+
const total = diff.filter(d => d.kind !== 'context').length;
|
|
2079
|
+
if (total > maxLines) {
|
|
2080
|
+
process.stdout.write(chalk.hex('#4b5563')(` … ${total - maxLines} more lines\n`));
|
|
2081
|
+
}
|
|
2082
|
+
};
|
|
2083
|
+
process.stdout.write('\n');
|
|
2084
|
+
for (const op of fileOps) {
|
|
2085
|
+
if (op.type === 'write' && op.path && op.content !== undefined) {
|
|
2086
|
+
const oldContent = fileSnapshot.get(op.path) ?? fileSnapshot.get(op.path.replace(/\\/g, '/')) ?? '';
|
|
2087
|
+
const diff = computeDiff(oldContent, op.content);
|
|
2088
|
+
const adds = diff.filter(d => d.kind === 'add').length;
|
|
2089
|
+
const removes = diff.filter(d => d.kind === 'remove').length;
|
|
2090
|
+
const statStr = [
|
|
2091
|
+
removes > 0 ? chalk.hex('#f87171').bold(`-${removes}`) : '',
|
|
2092
|
+
adds > 0 ? chalk.hex('#34d399').bold(`+${adds}`) : '',
|
|
2093
|
+
].filter(Boolean).join(' ');
|
|
2094
|
+
process.stdout.write(chalk.hex('#fbbf24')(' ~') + chalk.hex('#94a3b8')(' Updated ') +
|
|
2095
|
+
chalk.hex('#e2e8f0')(op.path) + (statStr ? ' ' + statStr : '') + '\n');
|
|
2096
|
+
renderDiffLines(diff);
|
|
2097
|
+
// Update snapshot so subsequent ops see the new content
|
|
2098
|
+
fileSnapshot.set(op.path, op.content);
|
|
2099
|
+
}
|
|
2100
|
+
else if (op.type === 'edit' && op.path && op.find !== undefined && op.replace !== undefined) {
|
|
2101
|
+
const diff = computeDiff(op.find, op.replace);
|
|
2102
|
+
const adds = diff.filter(d => d.kind === 'add').length;
|
|
2103
|
+
const removes = diff.filter(d => d.kind === 'remove').length;
|
|
2104
|
+
const statStr = [
|
|
2105
|
+
removes > 0 ? chalk.hex('#f87171').bold(`-${removes}`) : '',
|
|
2106
|
+
adds > 0 ? chalk.hex('#34d399').bold(`+${adds}`) : '',
|
|
2107
|
+
].filter(Boolean).join(' ');
|
|
2108
|
+
process.stdout.write(chalk.hex('#fbbf24')(' ~') + chalk.hex('#94a3b8')(' Updated ') +
|
|
2109
|
+
chalk.hex('#e2e8f0')(op.path) + (statStr ? ' ' + statStr : '') + '\n');
|
|
2110
|
+
renderDiffLines(diff);
|
|
2111
|
+
}
|
|
2112
|
+
else if (op.type === 'run' && op.command) {
|
|
2113
|
+
process.stdout.write(colors.primary(' $') + ' ' + chalk.white(op.command) + '\n');
|
|
2114
|
+
}
|
|
2115
|
+
else if (op.type === 'delete' && op.path) {
|
|
2116
|
+
process.stdout.write(colors.error(' ✗') + chalk.hex('#94a3b8')(' Deleted ') + colors.muted(op.path) + '\n');
|
|
2117
|
+
}
|
|
2118
|
+
else if (op.type === 'mkdir' && op.path) {
|
|
2119
|
+
process.stdout.write(colors.success(' ✓') + chalk.hex('#94a3b8')(' Created ') + colors.muted(op.path) + '\n');
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
// ── Read / search / folder summary (compact box) ────────
|
|
2124
|
+
if (readOps.length > 0) {
|
|
2125
|
+
const total = readOps.length;
|
|
2126
|
+
const boxW = Math.min(Math.max(cols - 2, 52), 100);
|
|
2127
|
+
const maxFnameW = Math.max(boxW - 10, 8);
|
|
2128
|
+
const titleText = ` ${total} operation${total === 1 ? '' : 's'} `;
|
|
2129
|
+
const dashCount = Math.max(boxW - 3 - titleText.length, 2);
|
|
2130
|
+
process.stdout.write('\n ' + BC('╭─') + colors.muted(titleText) + BC('─'.repeat(dashCount) + '╮') + '\n');
|
|
2131
|
+
for (const op of readOps) {
|
|
2132
|
+
let label;
|
|
2133
|
+
if (op.type === 'search_code') {
|
|
2134
|
+
label = `search: "${op.pattern}"`;
|
|
2135
|
+
}
|
|
2136
|
+
else if (op.type === 'read_folder') {
|
|
2137
|
+
label = `folder: ${op.path}`;
|
|
2138
|
+
}
|
|
2139
|
+
else {
|
|
2140
|
+
label = op.path;
|
|
2141
|
+
}
|
|
2142
|
+
const disp = label.length > maxFnameW ? '…' + label.slice(-(maxFnameW - 1)) : label;
|
|
2143
|
+
const pad = ' '.repeat(Math.max(boxW - 7 - disp.length, 2));
|
|
2144
|
+
process.stdout.write(' ' + BC('│') + ' ' + colors.muted('✓') + ' ' + FC(disp) + pad + BC('│') + '\n');
|
|
2145
|
+
}
|
|
2146
|
+
process.stdout.write(' ' + BC('╰' + '─'.repeat(boxW - 2) + '╯') + '\n');
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
async function generateAITitle(userMsg, aiMsg, token) {
|
|
2152
|
+
const msgs = [
|
|
2153
|
+
{ role: 'system', content: 'Generate a short 2-5 word English title for this conversation. Reply with ONLY the title words. No punctuation, no quotes.' },
|
|
2154
|
+
{ role: 'user', content: userMsg.slice(0, 400) },
|
|
2155
|
+
{ role: 'assistant', content: aiMsg.slice(0, 400) },
|
|
2156
|
+
{ role: 'user', content: 'Title:' },
|
|
2157
|
+
];
|
|
2158
|
+
return new Promise((resolve) => {
|
|
2159
|
+
let out = '';
|
|
2160
|
+
streamChat(msgs, token, (chunk) => { out += chunk; }, () => {
|
|
2161
|
+
const title = out.replace(/['"]/g, '').replace(/\s+/g, ' ').trim().slice(0, 50);
|
|
2162
|
+
resolve(title || 'New Conversation');
|
|
2163
|
+
}, () => resolve('New Conversation'));
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
async function showDesignModeLoader(skills) {
|
|
2167
|
+
const P = chalk.hex('#a78bfa');
|
|
2168
|
+
const G = chalk.hex('#34d399');
|
|
2169
|
+
const D = chalk.hex('#6b7280');
|
|
2170
|
+
const W = chalk.hex('#e2e8f0');
|
|
2171
|
+
const FR = SPINNER_FRAMES;
|
|
2172
|
+
const items = skills.length > 0 ? skills.slice(0, 8) : ['Preparing design system...'];
|
|
2173
|
+
process.stdout.write('\n');
|
|
2174
|
+
// ── Spinner ───────────────────────────────────────────────────
|
|
2175
|
+
let fi = 0;
|
|
2176
|
+
const spin = setInterval(() => {
|
|
2177
|
+
process.stdout.write(`\r ${P(FR[fi++ % FR.length])} ${D('Loading Web Designer skill...')}`);
|
|
2178
|
+
}, 60);
|
|
2179
|
+
await new Promise(r => setTimeout(r, 500));
|
|
2180
|
+
clearInterval(spin);
|
|
2181
|
+
process.stdout.write('\r\x1b[K');
|
|
2182
|
+
// ── Box with dynamic skill lines ─────────────────────────────
|
|
2183
|
+
const cols = process.stdout.columns ?? 80;
|
|
2184
|
+
const maxW = Math.max(...items.map(s => s.length), 30);
|
|
2185
|
+
const lineW = Math.min(maxW + 8, cols - 6);
|
|
2186
|
+
process.stdout.write(' ' + P('╭' + '─'.repeat(lineW)) + '\n');
|
|
2187
|
+
for (const skill of items) {
|
|
2188
|
+
let fi2 = 0;
|
|
2189
|
+
const sp2 = setInterval(() => {
|
|
2190
|
+
process.stdout.write(`\r ${P('│')} ${D(FR[fi2++ % FR.length])} ${D(skill)}`);
|
|
2191
|
+
}, 60);
|
|
2192
|
+
await new Promise(r => setTimeout(r, 200));
|
|
2193
|
+
clearInterval(sp2);
|
|
2194
|
+
process.stdout.write(`\r ${P('│')} ${G('✓')} ${W(skill)}\n`);
|
|
2195
|
+
}
|
|
2196
|
+
process.stdout.write(' ' + P('╰' + '─'.repeat(lineW)) + '\n');
|
|
2197
|
+
// ── Final badge ───────────────────────────────────────────────
|
|
2198
|
+
await new Promise(r => setTimeout(r, 100));
|
|
2199
|
+
process.stdout.write('\n ' + G('✓') + ' ' + chalk.hex('#c4b5fd').bold('Design') +
|
|
2200
|
+
W(' mode activated') + '\n\n');
|
|
2201
|
+
}
|
|
2202
|
+
export async function startRepl(cwd) {
|
|
2203
|
+
const alwaysAllowed = new Set();
|
|
2204
|
+
const token = getToken() ?? '';
|
|
2205
|
+
let SYSTEM_PROMPT = 'You are Dravix Code — an elite AI coding assistant. The server is temporarily unreachable. Use your best judgment to help the user.';
|
|
2206
|
+
if (token) {
|
|
2207
|
+
const { prompt, webDesignerSkill } = await fetchSystemPrompt(token);
|
|
2208
|
+
if (prompt) {
|
|
2209
|
+
SYSTEM_PROMPT = prompt;
|
|
2210
|
+
_serverWebDesignerSkill = webDesignerSkill;
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
// activeCwd can change when /resume loads a conversation from a different directory
|
|
2214
|
+
let activeCwd = cwd;
|
|
2215
|
+
// Rules appended to every system prompt to enforce safe file-operation behavior
|
|
2216
|
+
const SAFE_FILE_RULES = `
|
|
2217
|
+
|
|
2218
|
+
## CORE RULES
|
|
2219
|
+
|
|
2220
|
+
### READ FIRST, THEN ANSWER
|
|
2221
|
+
When the user asks about their code:
|
|
2222
|
+
1. Find the relevant file(s)
|
|
2223
|
+
2. Read them silently
|
|
2224
|
+
3. Give a direct, accurate answer based on what you found
|
|
2225
|
+
Never guess or fabricate information.
|
|
2226
|
+
|
|
2227
|
+
### BE ACCURATE
|
|
2228
|
+
- Only report what you actually see in the code
|
|
2229
|
+
- If you are unsure, say so — do not fabricate answers
|
|
2230
|
+
- Never add features or items that do not exist in the code
|
|
2231
|
+
|
|
2232
|
+
### RESPOND IN THE SAME LANGUAGE
|
|
2233
|
+
- Respond in the same language the user writes in
|
|
2234
|
+
- If user writes in English → respond in English
|
|
2235
|
+
- If user writes in Russian → respond in Russian
|
|
2236
|
+
- And so on for any language
|
|
2237
|
+
|
|
2238
|
+
### FORMAT ANSWERS CLEARLY
|
|
2239
|
+
- Use bullet points or numbered lists for multiple items
|
|
2240
|
+
- Put each item on its own line
|
|
2241
|
+
- Keep answers concise — 3-10 lines maximum
|
|
2242
|
+
- Do not dump entire file contents unless asked
|
|
2243
|
+
- Do not add unnecessary commentary
|
|
2244
|
+
|
|
2245
|
+
### WORK SILENTLY
|
|
2246
|
+
- Do not say "I will read the file" — just read it and answer
|
|
2247
|
+
- Do not narrate your thought process
|
|
2248
|
+
- Do not say "I already answered your question"
|
|
2249
|
+
- Give your answer ONCE and STOP
|
|
2250
|
+
|
|
2251
|
+
### WHEN CREATING/EDITING FILES
|
|
2252
|
+
- write_file = CREATE new files only
|
|
2253
|
+
- edit_file = MODIFY existing (read first, then find/replace)
|
|
2254
|
+
- Before editing: ALWAYS read_file first
|
|
2255
|
+
- Complete the ENTIRE task in ONE response
|
|
2256
|
+
- Use tags, NOT code blocks
|
|
2257
|
+
|
|
2258
|
+
### WHEN CREATING/EDITING FILES
|
|
2259
|
+
- write_file = CREATE new files only
|
|
2260
|
+
- edit_file = MODIFY existing (read first, then find/replace)
|
|
2261
|
+
- Before editing: ALWAYS read_file first
|
|
2262
|
+
- Multiple edits: order from BOTTOM to TOP
|
|
2263
|
+
- Complete the ENTIRE task in ONE response
|
|
2264
|
+
- Use tags, NOT code blocks
|
|
2265
|
+
|
|
2266
|
+
### When the user asks you to do something:
|
|
2267
|
+
1. Read the relevant files first
|
|
2268
|
+
2. Do the work using <write_file> / <edit_file> tags
|
|
2269
|
+
3. Summarize what you did in 1-2 sentences
|
|
2270
|
+
|
|
2271
|
+
### Act decisively
|
|
2272
|
+
- Use judgment and execute immediately when intent is clear.
|
|
2273
|
+
- Do NOT ask unnecessary clarifying questions — just do the task.
|
|
2274
|
+
- Make reasonable assumptions and proceed.
|
|
2275
|
+
|
|
2276
|
+
### Creating files
|
|
2277
|
+
- NEVER show code in code blocks when the user asks to create files or a project.
|
|
2278
|
+
- ALWAYS use <write_file path="filename"> tags to create actual files.
|
|
2279
|
+
- Code blocks are for short inline explanations only — they do NOT create files.
|
|
2280
|
+
- Output ALL required files in ONE response using <write_file> tags.
|
|
2281
|
+
|
|
2282
|
+
### File operations
|
|
2283
|
+
- **write_file** = CREATE only. Use it ONLY when a file does NOT exist yet.
|
|
2284
|
+
- **edit_file** = MODIFY existing files. For ANY change to an existing file, always use edit_file with <find>/<replace>.
|
|
2285
|
+
- Before editing any file: use <read_file> to see its current content first.
|
|
2286
|
+
- NEVER overwrite an existing file with write_file — it destroys user code.
|
|
2287
|
+
|
|
2288
|
+
### How to use edit_file correctly
|
|
2289
|
+
1. ALWAYS read_file first to see the current content
|
|
2290
|
+
2. Copy the EXACT text from the file into <find> — character by character
|
|
2291
|
+
3. The <find> text must match EXACTLY (including whitespace, indentation)
|
|
2292
|
+
4. If edit fails, the system will show you the actual content — use it to retry
|
|
2293
|
+
5. Do NOT put line numbers in <find> (e.g., "42 │ code" is WRONG)
|
|
2294
|
+
6. Do NOT modify the text in <find> — copy it EXACTLY from the file
|
|
2295
|
+
|
|
2296
|
+
### Searching and navigating
|
|
2297
|
+
- Use <glob_files pattern="**/*.ts" /> to find files by extension
|
|
2298
|
+
- Use <search_code pattern="functionName" /> to find code
|
|
2299
|
+
- Use <search_code pattern="regex.*pattern" regex="true" /> for regex search
|
|
2300
|
+
- Use <search_code pattern="error" include="*.ts" /> to search specific file types
|
|
2301
|
+
- Use <search_code pattern="TODO" context="2" /> to show context around matches
|
|
2302
|
+
- Read files before editing them — always!
|
|
2303
|
+
|
|
2304
|
+
### Multi-file tasks
|
|
2305
|
+
- Plan all files FIRST (list them in your response)
|
|
2306
|
+
- Create/edit files in LOGICAL ORDER (dependencies first)
|
|
2307
|
+
- Use write_file for ALL new files
|
|
2308
|
+
- Use edit_file for ALL modifications
|
|
2309
|
+
- Run commands LAST (after all files are created)
|
|
2310
|
+
|
|
2311
|
+
### Error recovery
|
|
2312
|
+
- If an edit_file fails, read the file again and retry with the actual content
|
|
2313
|
+
- If a run_command fails, read the error message and fix the issue
|
|
2314
|
+
- Never give up — keep trying until the task is complete
|
|
2315
|
+
|
|
2316
|
+
### Scope
|
|
2317
|
+
- Only touch files the user explicitly mentioned or that are clearly required by the task.
|
|
2318
|
+
- Do NOT restructure, rename, or "improve" anything that wasn't asked.
|
|
2319
|
+
- When creating a new project, create ALL necessary files (not just some).
|
|
2320
|
+
- When fixing a bug, fix the ROOT CAUSE, not just the symptom.`;
|
|
2321
|
+
const buildSystemMsg = (dir) => ({
|
|
2322
|
+
role: 'system',
|
|
2323
|
+
content: SYSTEM_PROMPT + SAFE_FILE_RULES + '\n\nProject context:\n' + buildContext(dir),
|
|
2324
|
+
});
|
|
2325
|
+
const history = [buildSystemMsg(activeCwd)];
|
|
2326
|
+
let sessionId = generateId();
|
|
2327
|
+
const PROMPT = colors.primary(' › ');
|
|
2328
|
+
let queuedResult = null;
|
|
2329
|
+
let lastUserLine = '';
|
|
2330
|
+
let lastAIResponse = '';
|
|
2331
|
+
let readFileContinue = false;
|
|
2332
|
+
let readFileTurnCount = 0; // resets each user message; caps read loops
|
|
2333
|
+
let forcedEditMode = false; // blocks further read ops after limit
|
|
2334
|
+
let conversationTitle = null;
|
|
2335
|
+
let webDesignerActive = false;
|
|
2336
|
+
let pendingOutputTokens = 0;
|
|
2337
|
+
let pendingUserTokens = 0;
|
|
2338
|
+
let hasPendingReport = false;
|
|
2339
|
+
// Auto-retry state
|
|
2340
|
+
const MAX_AUTO_RETRIES = 3;
|
|
2341
|
+
let autoRetryCount = 0;
|
|
2342
|
+
let lastFailedOp = null;
|
|
2343
|
+
process.stdin.once('end', () => {
|
|
2344
|
+
console.log(colors.muted('\n Goodbye!\n'));
|
|
2345
|
+
process.exit(0);
|
|
2346
|
+
});
|
|
2347
|
+
// Prevent any unhandled rejection from crashing the process — log to file for debugging
|
|
2348
|
+
const ERROR_LOG = path.join(os.homedir(), '.dravix-code', 'error.log');
|
|
2349
|
+
const logError = (label, err) => {
|
|
2350
|
+
try {
|
|
2351
|
+
const line = `[${new Date().toISOString()}] ${label}: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`;
|
|
2352
|
+
fs.appendFileSync(ERROR_LOG, line);
|
|
2353
|
+
}
|
|
2354
|
+
catch { }
|
|
2355
|
+
};
|
|
2356
|
+
// Always restore terminal on any error — prevents keyboard from getting stuck
|
|
2357
|
+
const resetTerminal = () => {
|
|
2358
|
+
try {
|
|
2359
|
+
process.stdin.setRawMode(false);
|
|
2360
|
+
}
|
|
2361
|
+
catch { }
|
|
2362
|
+
try {
|
|
2363
|
+
process.stdin.pause();
|
|
2364
|
+
}
|
|
2365
|
+
catch { }
|
|
2366
|
+
};
|
|
2367
|
+
process.on('exit', resetTerminal);
|
|
2368
|
+
process.on('SIGINT', () => { resetTerminal(); process.exit(0); });
|
|
2369
|
+
process.on('SIGTERM', () => { resetTerminal(); process.exit(0); });
|
|
2370
|
+
process.on('unhandledRejection', (reason) => { logError('unhandledRejection', reason); resetTerminal(); });
|
|
2371
|
+
process.on('uncaughtException', (err) => { logError('uncaughtException', err); resetTerminal(); });
|
|
2372
|
+
// Set raw mode ONCE — never toggle it during the session to avoid CMD getting stuck
|
|
2373
|
+
process.stdin.setRawMode(true);
|
|
2374
|
+
process.stdin.resume();
|
|
2375
|
+
process.stdin.setEncoding('utf8');
|
|
2376
|
+
// Sequential loop — queued input lets user type during AI stream
|
|
2377
|
+
while (true) {
|
|
2378
|
+
try {
|
|
2379
|
+
const cliTok = getToken() ?? '';
|
|
2380
|
+
// Flush pending usage when starting a new user turn (all auto-continues are done)
|
|
2381
|
+
if (!readFileContinue && hasPendingReport && cliTok) {
|
|
2382
|
+
reportUsage(cliTok, Math.min(pendingUserTokens + pendingOutputTokens, 16000)).catch(() => { });
|
|
2383
|
+
hasPendingReport = false;
|
|
2384
|
+
pendingOutputTokens = 0;
|
|
2385
|
+
pendingUserTokens = 0;
|
|
2386
|
+
}
|
|
2387
|
+
let result;
|
|
2388
|
+
let skipInput = false;
|
|
2389
|
+
if (readFileContinue) {
|
|
2390
|
+
readFileContinue = false;
|
|
2391
|
+
readFileTurnCount++;
|
|
2392
|
+
// Remind AI of the original user request — show first + last line so pasted code
|
|
2393
|
+
// doesn't eclipse the actual instruction written at the end.
|
|
2394
|
+
const rawUserMsg = lastUserLine.trim();
|
|
2395
|
+
const msgLines = rawUserMsg.split('\n').map(l => l.trim()).filter(Boolean);
|
|
2396
|
+
let userReminder = '';
|
|
2397
|
+
if (msgLines.length > 0) {
|
|
2398
|
+
const first = msgLines[0].slice(0, 100);
|
|
2399
|
+
const last = msgLines[msgLines.length - 1].slice(0, 150);
|
|
2400
|
+
const display = msgLines.length <= 2 ? msgLines.join(' / ').slice(0, 200) : `${first} [...] ${last}`;
|
|
2401
|
+
userReminder = `The user's request: "${display}". `;
|
|
2402
|
+
}
|
|
2403
|
+
const taskInstruction = userReminder
|
|
2404
|
+
? `The user's exact request was: "${rawUserMsg.slice(0, 300)}"\nNow execute THIS request and ONLY this request — nothing else. Do not invent, add, or change anything the user did not ask for. Use <edit_file> with targeted <find>/<replace> — never use <write_file> on existing files. Use the file content above to find the exact text and apply the change.`
|
|
2405
|
+
: `Execute the user's request using the file content above. Use <edit_file> for existing files, <write_file> only for new files.`;
|
|
2406
|
+
// Keep using FLASH_MODEL after file reads
|
|
2407
|
+
if (readFileTurnCount > 5 && !forcedEditMode) {
|
|
2408
|
+
forcedEditMode = true;
|
|
2409
|
+
history.push({
|
|
2410
|
+
role: 'system',
|
|
2411
|
+
content: `[CONTEXT READY] ${taskInstruction}\nDo not read any more files — use what is already in context.`,
|
|
2412
|
+
});
|
|
2413
|
+
process.stdout.write('\n' + colors.muted(' ⚠ Too many read operations — forced edit mode') + '\n');
|
|
2414
|
+
}
|
|
2415
|
+
else if (readFileTurnCount >= 3) {
|
|
2416
|
+
history.push({
|
|
2417
|
+
role: 'system',
|
|
2418
|
+
content: `[CONTEXT READY] ${taskInstruction}`,
|
|
2419
|
+
});
|
|
2420
|
+
}
|
|
2421
|
+
else {
|
|
2422
|
+
history.push({
|
|
2423
|
+
role: 'system',
|
|
2424
|
+
content: `[FILE CONTENT READY] ${taskInstruction}`,
|
|
2425
|
+
});
|
|
2426
|
+
}
|
|
2427
|
+
skipInput = true;
|
|
2428
|
+
result = { text: '', lines: [] };
|
|
2429
|
+
}
|
|
2430
|
+
else if (queuedResult) {
|
|
2431
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2432
|
+
const q = queuedResult;
|
|
2433
|
+
queuedResult = null;
|
|
2434
|
+
result = q;
|
|
2435
|
+
// Show queued message as if just submitted
|
|
2436
|
+
const cols = process.stdout.columns ?? 80;
|
|
2437
|
+
const msgBgQ = chalk.bgHex('#334155').hex('#f1f5f9');
|
|
2438
|
+
process.stdout.write(msgBgQ((' > ' + q.text + ' ').padEnd(cols)) + '\n');
|
|
2439
|
+
}
|
|
2440
|
+
else {
|
|
2441
|
+
result = await readLine(PROMPT, activeCwd);
|
|
2442
|
+
}
|
|
2443
|
+
if (!result)
|
|
2444
|
+
continue;
|
|
2445
|
+
const { text: line } = result;
|
|
2446
|
+
if (!skipInput)
|
|
2447
|
+
lastUserLine = line;
|
|
2448
|
+
// ── Slash commands ──────────────────────────────────────────
|
|
2449
|
+
if (!skipInput && line.trim() === '/resume') {
|
|
2450
|
+
const convId = await showConversationPicker(activeCwd);
|
|
2451
|
+
if (convId) {
|
|
2452
|
+
const conv = loadConversation(convId, activeCwd);
|
|
2453
|
+
if (conv) {
|
|
2454
|
+
// Restore the original working directory so file ops work correctly
|
|
2455
|
+
activeCwd = conv.cwd;
|
|
2456
|
+
// Rebuild system message with the correct directory
|
|
2457
|
+
history[0] = buildSystemMsg(activeCwd);
|
|
2458
|
+
history.splice(1);
|
|
2459
|
+
history.push(...conv.messages);
|
|
2460
|
+
// Warn AI that file states may have changed since the saved session
|
|
2461
|
+
history.push({
|
|
2462
|
+
role: 'system',
|
|
2463
|
+
content: `[Resumed session] Working directory: ${activeCwd}\nFile contents may have changed since the last session. ALWAYS use <read_file> or <search_code> to get the CURRENT file content before editing. Never assume files match the conversation history.`,
|
|
2464
|
+
});
|
|
2465
|
+
sessionId = convId;
|
|
2466
|
+
conversationTitle = conv.title;
|
|
2467
|
+
printConversationHistory(conv.messages);
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
continue;
|
|
2471
|
+
}
|
|
2472
|
+
if (!skipInput && line.startsWith('/')) {
|
|
2473
|
+
await handleCommand(line, activeCwd, () => {
|
|
2474
|
+
activeCwd = cwd;
|
|
2475
|
+
history.splice(1);
|
|
2476
|
+
history[0] = buildSystemMsg(activeCwd);
|
|
2477
|
+
conversationTitle = null;
|
|
2478
|
+
sessionId = generateId();
|
|
2479
|
+
}, (filePath, content) => {
|
|
2480
|
+
const existing = history.findIndex(m => m.role === 'system' && m.content.startsWith(`[Added file: ${filePath}]`));
|
|
2481
|
+
const msg = { role: 'system', content: `[Added file: ${filePath}]\n${content}` };
|
|
2482
|
+
if (existing !== -1)
|
|
2483
|
+
history[existing] = msg;
|
|
2484
|
+
else
|
|
2485
|
+
history.push(msg);
|
|
2486
|
+
}, () => lastAIResponse || null, () => {
|
|
2487
|
+
if (lastUserLine)
|
|
2488
|
+
queuedResult = { text: lastUserLine, lines: [lastUserLine] };
|
|
2489
|
+
});
|
|
2490
|
+
continue;
|
|
2491
|
+
}
|
|
2492
|
+
if (!skipInput) {
|
|
2493
|
+
readFileTurnCount = 0; // reset loop counter for each new user message
|
|
2494
|
+
forcedEditMode = false; // reset forced edit mode for each new user message
|
|
2495
|
+
autoRetryCount = 0; // reset auto-retry counter for each new user message
|
|
2496
|
+
lastFailedOp = null;
|
|
2497
|
+
// ── Refresh project context (files may have changed since last turn) ──
|
|
2498
|
+
history[0] = buildSystemMsg(activeCwd);
|
|
2499
|
+
// ── Clear stale operational messages left from previous auto-continue turns ──
|
|
2500
|
+
// They pollute future user messages when prepareMessages merges consecutive roles.
|
|
2501
|
+
const STALE_PREFIXES = [
|
|
2502
|
+
'[File updated]', '[SYSTEM LIMIT]', '[BLOCKED]', 'Please proceed with the task',
|
|
2503
|
+
'[FORCED EDIT MODE]', '[ACTION REQUIRED]', '[Auto-reading',
|
|
2504
|
+
'[Web Designer mode', 'You have done ', 'You now have the file content',
|
|
2505
|
+
'You described the steps but', 'Your previous response was cut off',
|
|
2506
|
+
'[CONTEXT READY]', '[TARGET SECTION', '[FILE CONTENT READY]',
|
|
2507
|
+
'The user\'s exact request was:',
|
|
2508
|
+
];
|
|
2509
|
+
for (let i = history.length - 1; i > 0; i--) {
|
|
2510
|
+
if (history[i].role === 'system' &&
|
|
2511
|
+
STALE_PREFIXES.some(p => history[i].content.startsWith(p))) {
|
|
2512
|
+
history.splice(i, 1);
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
// ── Trim history: keep system[0] + last 20 messages ──
|
|
2516
|
+
if (history.length > 22) {
|
|
2517
|
+
history.splice(1, history.length - 22);
|
|
2518
|
+
}
|
|
2519
|
+
// ── Auto-inject mentioned file contents ──────────────────────
|
|
2520
|
+
// Files ≤ 3000 lines: full raw content injected — AI has exact text for <find>, no reads needed.
|
|
2521
|
+
const FILE_PATTERN = /[\w\-.\/\\]+\.\w{2,5}/g;
|
|
2522
|
+
const mentioned = [...new Set(line.match(FILE_PATTERN) ?? [])];
|
|
2523
|
+
let fileContext = '';
|
|
2524
|
+
const FULL_INJECT_LINES = 3000;
|
|
2525
|
+
for (const fname of mentioned) {
|
|
2526
|
+
const fullPath = path.resolve(activeCwd, fname);
|
|
2527
|
+
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
|
|
2528
|
+
try {
|
|
2529
|
+
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
2530
|
+
const fileLines = content.split('\n');
|
|
2531
|
+
const lineCount = fileLines.length;
|
|
2532
|
+
if (lineCount <= FULL_INJECT_LINES) {
|
|
2533
|
+
fileContext += `\n\n[File: ${fname} — ${lineCount} lines — FULL]\n` + content;
|
|
2534
|
+
}
|
|
2535
|
+
else {
|
|
2536
|
+
fileContext += `\n\n[File: ${fname} — ${lineCount} lines]\n` +
|
|
2537
|
+
`Use: <search_code pattern="TERM" path="${fname}"/> → <read_file path="${fname}"/> → <edit_file>\n`;
|
|
2538
|
+
}
|
|
2539
|
+
}
|
|
2540
|
+
catch { /* skip unreadable */ }
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
history.push({ role: 'user', content: fileContext ? line + fileContext : line });
|
|
2544
|
+
}
|
|
2545
|
+
// ── Token limit check ────────────────────────────────────────
|
|
2546
|
+
if (cliTok && !skipInput) {
|
|
2547
|
+
const usage = await checkUsage(cliTok);
|
|
2548
|
+
if (usage && !usage.allowed) {
|
|
2549
|
+
const resetStr = formatResetTime(usage);
|
|
2550
|
+
process.stdout.write('\n');
|
|
2551
|
+
process.stdout.write(' ' + colors.error('✗') + ' ' + chalk.hex('#e2e8f0').bold('Daily token limit reached') + '\n' +
|
|
2552
|
+
' ' + colors.muted(` ${fmtNum(usage.tokens_used)} / ${fmtNum(usage.limit)} tokens used`) + '\n' +
|
|
2553
|
+
' ' + colors.muted(` Resets in ${resetStr}`) +
|
|
2554
|
+
(usage.is_plus ? '' : ' ' + chalk.hex('#fcd34d')('· Upgrade to Plus for 100k tokens/day')) + '\n\n');
|
|
2555
|
+
continue;
|
|
2556
|
+
}
|
|
2557
|
+
// Warning when >80% used
|
|
2558
|
+
if (usage && usage.tokens_used / usage.limit >= 0.8) {
|
|
2559
|
+
const { bar, pct } = usageBar(usage.tokens_used, usage.limit, 14);
|
|
2560
|
+
process.stdout.write('\n ' + colors.warn('⚠') + ' ' + chalk.hex('#fbbf24')(`Token limit: ${pct}% used`) + ' ' +
|
|
2561
|
+
chalk.hex('#f87171')(bar) + ' ' +
|
|
2562
|
+
colors.muted(`${fmtNum(usage.remaining)} remaining · resets in ${formatResetTime(usage)}`) + '\n');
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
2565
|
+
// ── Ctrl+C cancel during streaming ──────────────────────────
|
|
2566
|
+
let streamCancelled = false;
|
|
2567
|
+
const streamAbort = new AbortController();
|
|
2568
|
+
const onStreamKey = (data) => {
|
|
2569
|
+
try {
|
|
2570
|
+
if (data === '\x03') {
|
|
2571
|
+
streamCancelled = true;
|
|
2572
|
+
streamAbort.abort();
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
catch { /* ignore */ }
|
|
2576
|
+
};
|
|
2577
|
+
process.stdin.on('data', onStreamKey);
|
|
2578
|
+
// ── Spinner ──────────────────────────────────────────────────
|
|
2579
|
+
if (!skipInput)
|
|
2580
|
+
process.stdout.write('\n');
|
|
2581
|
+
let frameIdx = 0;
|
|
2582
|
+
const aiStart = Date.now();
|
|
2583
|
+
const spinnerInterval = setInterval(() => {
|
|
2584
|
+
process.stdout.write(`\r\x1b[K ${colors.muted(SPINNER_FRAMES[frameIdx++ % SPINNER_FRAMES.length])} ${colors.muted('Thinking...')}`);
|
|
2585
|
+
}, 80);
|
|
2586
|
+
// ── Stream AI response ──────────────────────────────────────
|
|
2587
|
+
let fullResponse = '';
|
|
2588
|
+
let streamStarted = false;
|
|
2589
|
+
let inStreamingOp = false;
|
|
2590
|
+
let streamOpLabel = '';
|
|
2591
|
+
let streamOpFrame = 0;
|
|
2592
|
+
let streamOpInterval = null;
|
|
2593
|
+
let showingMidLoader = false;
|
|
2594
|
+
let midStreamFrame = 0;
|
|
2595
|
+
let midStreamInterval = null;
|
|
2596
|
+
// ── Inline op execution (write/edit/delete run inline as tags complete) ──
|
|
2597
|
+
const executedInlineOps = new Set();
|
|
2598
|
+
let inlineOpRunning = false;
|
|
2599
|
+
let inlineTextQueue = ''; // AI text buffered while inline op runs
|
|
2600
|
+
const inlineFileOpErrors = [];
|
|
2601
|
+
const inlineSkippedPaths = new Set();
|
|
2602
|
+
const inlineOpFingerprint = (op) => JSON.stringify({
|
|
2603
|
+
t: op.type, p: op.path ?? null,
|
|
2604
|
+
f: op.find ? op.find.slice(0, 200) : null,
|
|
2605
|
+
r: op.replace ? op.replace.slice(0, 200) : null,
|
|
2606
|
+
c: op.content ? op.content.length + ':' + op.content.slice(0, 100) : null,
|
|
2607
|
+
cmd: op.command ?? null,
|
|
2608
|
+
});
|
|
2609
|
+
const runInlineOp = async (op) => {
|
|
2610
|
+
inlineOpRunning = true;
|
|
2611
|
+
try {
|
|
2612
|
+
// Clear any active streaming spinner before showing the permission dialog
|
|
2613
|
+
if (streamOpInterval) {
|
|
2614
|
+
clearInterval(streamOpInterval);
|
|
2615
|
+
streamOpInterval = null;
|
|
2616
|
+
}
|
|
2617
|
+
if (inStreamingOp) {
|
|
2618
|
+
process.stdout.write('\r\x1b[K');
|
|
2619
|
+
inStreamingOp = false;
|
|
2620
|
+
streamOpLabel = '';
|
|
2621
|
+
streamOpFrame = 0;
|
|
2622
|
+
}
|
|
2623
|
+
if (midStreamTimer)
|
|
2624
|
+
clearTimeout(midStreamTimer);
|
|
2625
|
+
if (midStreamInterval) {
|
|
2626
|
+
clearInterval(midStreamInterval);
|
|
2627
|
+
midStreamInterval = null;
|
|
2628
|
+
showingMidLoader = false;
|
|
2629
|
+
}
|
|
2630
|
+
if (showingMidLoader) {
|
|
2631
|
+
process.stdout.write('\r\x1b[K');
|
|
2632
|
+
showingMidLoader = false;
|
|
2633
|
+
}
|
|
2634
|
+
if (hasRenderedContent && trailingNLs === 0)
|
|
2635
|
+
process.stdout.write('\n');
|
|
2636
|
+
const label = opLabel(op, activeCwd);
|
|
2637
|
+
const key = opKey(op, activeCwd);
|
|
2638
|
+
const depSkipped = op.type === 'run' && op.command &&
|
|
2639
|
+
[...inlineSkippedPaths].some(p => op.command.includes(path.basename(p)));
|
|
2640
|
+
if (depSkipped) {
|
|
2641
|
+
process.stdout.write(` ${colors.muted('○')} ${colors.muted('Skipped: ' + label + ' (dependency missing)')}\n`);
|
|
2642
|
+
executedInlineOps.add(inlineOpFingerprint(op));
|
|
2643
|
+
}
|
|
2644
|
+
else {
|
|
2645
|
+
// Track existing file size to detect write_file overwrites of existing code
|
|
2646
|
+
let existingLineCount = 0;
|
|
2647
|
+
if (op.type === 'write' && op.path) {
|
|
2648
|
+
try {
|
|
2649
|
+
const fp = path.resolve(activeCwd, op.path);
|
|
2650
|
+
if (fs.existsSync(fp))
|
|
2651
|
+
existingLineCount = fs.readFileSync(fp, 'utf-8').split('\n').length;
|
|
2652
|
+
}
|
|
2653
|
+
catch { /* ignore */ }
|
|
2654
|
+
}
|
|
2655
|
+
const previewLines = (!alwaysAllowed.has(key) && (op.type === 'write' || op.type === 'edit')) ? printDiffPreview(op, activeCwd) : 0;
|
|
2656
|
+
const allowed = await askPermission(label, key, alwaysAllowed, op.type === 'run', previewLines > 0, previewLines);
|
|
2657
|
+
executedInlineOps.add(inlineOpFingerprint(op));
|
|
2658
|
+
if (!allowed) {
|
|
2659
|
+
if (op.path)
|
|
2660
|
+
inlineSkippedPaths.add(op.path);
|
|
2661
|
+
}
|
|
2662
|
+
else {
|
|
2663
|
+
let stageSpinInterval2 = null;
|
|
2664
|
+
let stageSpinFrame2 = 0;
|
|
2665
|
+
let stageSpinMsg2 = '';
|
|
2666
|
+
const opResult = await executeSingleOp(op, activeCwd, (msg) => {
|
|
2667
|
+
stageSpinMsg2 = msg;
|
|
2668
|
+
if (!stageSpinInterval2) {
|
|
2669
|
+
stageSpinFrame2 = 0;
|
|
2670
|
+
stageSpinInterval2 = setInterval(() => {
|
|
2671
|
+
const f = SPINNER_FRAMES[stageSpinFrame2++ % SPINNER_FRAMES.length];
|
|
2672
|
+
process.stdout.write(`\r\x1b[K ${colors.muted(f)} ${chalk.hex('#94a3b8')(stageSpinMsg2)}`);
|
|
2673
|
+
}, 80);
|
|
2674
|
+
}
|
|
2675
|
+
});
|
|
2676
|
+
if (stageSpinInterval2) {
|
|
2677
|
+
clearInterval(stageSpinInterval2);
|
|
2678
|
+
stageSpinInterval2 = null;
|
|
2679
|
+
}
|
|
2680
|
+
process.stdout.write('\r\x1b[K');
|
|
2681
|
+
printOpResult(opResult);
|
|
2682
|
+
if (opResult.type === 'error' && op.type !== 'run') {
|
|
2683
|
+
let errMsg = `[Operation failed — ${label}]: ${opResult.message ?? 'Unknown error'}`;
|
|
2684
|
+
if (opResult.message?.includes('not found') && op.path) {
|
|
2685
|
+
try {
|
|
2686
|
+
const fp = path.resolve(activeCwd, op.path);
|
|
2687
|
+
if (fs.existsSync(fp)) {
|
|
2688
|
+
const cur = fs.readFileSync(fp, 'utf-8');
|
|
2689
|
+
const curLines = cur.split('\n');
|
|
2690
|
+
const nLines = curLines.length;
|
|
2691
|
+
// Smart error recovery: find approximate location and provide fix instructions
|
|
2692
|
+
const findLines = (op.find ?? '').split('\n').map(l => l.replace(/^\s*\d+\s*[│|:]\s?/, '').trim()).filter(Boolean);
|
|
2693
|
+
const searchTerm = findLines[0]?.slice(0, 60) ?? '';
|
|
2694
|
+
let foundAt = -1;
|
|
2695
|
+
if (searchTerm.length > 4) {
|
|
2696
|
+
for (let si = 0; si < curLines.length; si++) {
|
|
2697
|
+
if (curLines[si].toLowerCase().includes(searchTerm.toLowerCase())) {
|
|
2698
|
+
foundAt = si;
|
|
2699
|
+
break;
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
if (foundAt >= 0) {
|
|
2704
|
+
// Found approximate location — show surrounding context
|
|
2705
|
+
const start = Math.max(0, foundAt - 3);
|
|
2706
|
+
const end = Math.min(curLines.length - 1, foundAt + 50);
|
|
2707
|
+
const block = curLines.slice(start, end + 1).join('\n');
|
|
2708
|
+
errMsg += `\n\n[FILE CONTENT — ${op.path} lines ${start + 1}-${end + 1}]:\n${block}`;
|
|
2709
|
+
errMsg += `\n\nFIX: The edit failed. Copy the EXACT text from the file above into <find>. Do NOT include line numbers.`;
|
|
2710
|
+
}
|
|
2711
|
+
else if (nLines <= 400) {
|
|
2712
|
+
// File is small — show full content
|
|
2713
|
+
errMsg += `\n\n[FILE CONTENT — ${op.path} (${nLines} lines)]:\n${cur}`;
|
|
2714
|
+
errMsg += `\n\nFIX: Copy the EXACT text from the file above into <find>.`;
|
|
2715
|
+
}
|
|
2716
|
+
else {
|
|
2717
|
+
// File is large — show first 100 lines and instruct to search
|
|
2718
|
+
const preview = curLines.slice(0, 100).join('\n');
|
|
2719
|
+
errMsg += `\n\n[FILE CONTENT — ${op.path} (first 100 of ${nLines} lines)]:\n${preview}`;
|
|
2720
|
+
errMsg += `\n\nFIX: Use <read_file path="${op.path}" lines="N-M"/> to read the correct section, then copy EXACT text into <find>.`;
|
|
2721
|
+
}
|
|
2722
|
+
// Auto-retry: inject file content and force continuation
|
|
2723
|
+
history.push({
|
|
2724
|
+
role: 'system',
|
|
2725
|
+
content: `[AUTO-RETRY] The edit failed. Here is the current file content:\n\n${nLines <= 200 ? cur : curLines.slice(0, 200).join('\n')}\n\nRetry the edit using the EXACT content above. Copy text CHARACTER FOR CHARACTER into <find>.`,
|
|
2726
|
+
});
|
|
2727
|
+
readFileContinue = true;
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
catch { /* ignore */ }
|
|
2731
|
+
}
|
|
2732
|
+
inlineFileOpErrors.push(errMsg);
|
|
2733
|
+
// Auto-retry logic: if edit_file fails, automatically retry with updated context
|
|
2734
|
+
if (op.type === 'edit' && autoRetryCount < MAX_AUTO_RETRIES) {
|
|
2735
|
+
autoRetryCount++;
|
|
2736
|
+
lastFailedOp = op.path ?? null;
|
|
2737
|
+
}
|
|
2738
|
+
else if (autoRetryCount >= MAX_AUTO_RETRIES) {
|
|
2739
|
+
// Reset retry counter after max retries — prevent infinite loop
|
|
2740
|
+
autoRetryCount = 0;
|
|
2741
|
+
lastFailedOp = null;
|
|
2742
|
+
// Tell AI to stop retrying this specific edit
|
|
2743
|
+
history.push({
|
|
2744
|
+
role: 'system',
|
|
2745
|
+
content: `[STOP] Edit failed ${MAX_AUTO_RETRIES} times. Do NOT retry this specific edit. Move on to other tasks or ask the user for help.`,
|
|
2746
|
+
});
|
|
2747
|
+
readFileContinue = true;
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
else if ((opResult.type === 'modified' || opResult.type === 'created') && op.path &&
|
|
2751
|
+
(op.type === 'edit' || op.type === 'write')) {
|
|
2752
|
+
// After a successful edit, inject a note so AI knows the file changed
|
|
2753
|
+
history.push({
|
|
2754
|
+
role: 'system',
|
|
2755
|
+
content: `[File updated] ${op.path} was just modified. For further edits to this file, use <read_file path="${op.path}"/> first to get the current content, then <edit_file> with targeted changes.`,
|
|
2756
|
+
});
|
|
2757
|
+
// Educate AI when it used write_file to overwrite a non-trivial existing file
|
|
2758
|
+
if (op.type === 'write' && opResult.type === 'modified' && existingLineCount > 20) {
|
|
2759
|
+
history.push({
|
|
2760
|
+
role: 'system',
|
|
2761
|
+
content: `[Rule] You used <write_file> to completely replace ${op.path} (${existingLineCount} lines of existing code). This is wrong. RULE: write_file is ONLY for creating new files. For existing files, always use <edit_file> with <find>/<replace> to make targeted changes. Never overwrite existing code with write_file.`,
|
|
2762
|
+
});
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
catch { /* ignore */ }
|
|
2769
|
+
inlineOpRunning = false;
|
|
2770
|
+
trailingNLs = 1;
|
|
2771
|
+
// Flush buffered AI text that arrived while op was running
|
|
2772
|
+
if (inlineTextQueue) {
|
|
2773
|
+
const vis = renderer.format(inlineTextQueue);
|
|
2774
|
+
inlineTextQueue = '';
|
|
2775
|
+
if (vis) {
|
|
2776
|
+
process.stdout.write(vis);
|
|
2777
|
+
hasRenderedContent = true;
|
|
2778
|
+
const trail = vis.match(/(\n+)$/);
|
|
2779
|
+
trailingNLs = trail ? trail[1].length : 0;
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
// Check if more ops became complete while this op was running
|
|
2783
|
+
checkForNextInlineOp();
|
|
2784
|
+
};
|
|
2785
|
+
const checkForNextInlineOp = () => {
|
|
2786
|
+
if (inlineOpRunning)
|
|
2787
|
+
return;
|
|
2788
|
+
// Don't run inline ops in design_mode — let the post-stream flow handle them
|
|
2789
|
+
if (fullResponse.includes('<design_mode>'))
|
|
2790
|
+
return;
|
|
2791
|
+
const allParsed = parseOps(normalizeResponse(fullResponse));
|
|
2792
|
+
// Only write/edit/delete/mkdir ops are executed inline — run/read ops stay post-stream
|
|
2793
|
+
const writeOps = allParsed.filter(op => op.type === 'write' || op.type === 'edit' || op.type === 'delete' || op.type === 'mkdir');
|
|
2794
|
+
const nextOp = writeOps.find(op => !executedInlineOps.has(inlineOpFingerprint(op)));
|
|
2795
|
+
if (nextOp)
|
|
2796
|
+
runInlineOp(nextOp);
|
|
2797
|
+
};
|
|
2798
|
+
let midStreamTimer = null;
|
|
2799
|
+
let hasRenderedContent = false;
|
|
2800
|
+
let trailingNLs = 0; // trailing newlines written by AI text renders
|
|
2801
|
+
const stripper = new TagStripper();
|
|
2802
|
+
const renderer = new MarkdownRenderer();
|
|
2803
|
+
const token = getToken() ?? '';
|
|
2804
|
+
await new Promise((resolve) => {
|
|
2805
|
+
streamChat(history, token, (chunk) => {
|
|
2806
|
+
fullResponse += chunk;
|
|
2807
|
+
if (!streamStarted) {
|
|
2808
|
+
streamStarted = true;
|
|
2809
|
+
clearInterval(spinnerInterval);
|
|
2810
|
+
process.stdout.write('\r\x1b[K');
|
|
2811
|
+
trailingNLs = 1; // cursor on cleared line = effectively blank line start
|
|
2812
|
+
}
|
|
2813
|
+
// ── Clear mid-stream loader ────────────────────────────
|
|
2814
|
+
if (showingMidLoader) {
|
|
2815
|
+
if (midStreamInterval) {
|
|
2816
|
+
clearInterval(midStreamInterval);
|
|
2817
|
+
midStreamInterval = null;
|
|
2818
|
+
}
|
|
2819
|
+
process.stdout.write('\r\x1b[K');
|
|
2820
|
+
showingMidLoader = false;
|
|
2821
|
+
trailingNLs = 1;
|
|
2822
|
+
}
|
|
2823
|
+
// Reset mid-stream pause timer
|
|
2824
|
+
if (midStreamTimer)
|
|
2825
|
+
clearTimeout(midStreamTimer);
|
|
2826
|
+
midStreamTimer = setTimeout(() => {
|
|
2827
|
+
if (!inStreamingOp && !inlineOpRunning) {
|
|
2828
|
+
showingMidLoader = true;
|
|
2829
|
+
midStreamFrame = 0;
|
|
2830
|
+
midStreamInterval = setInterval(() => {
|
|
2831
|
+
const f = SPINNER_FRAMES[midStreamFrame++ % SPINNER_FRAMES.length];
|
|
2832
|
+
process.stdout.write(`\r\x1b[K ${colors.muted(f)} ${colors.muted('Processing...')}`);
|
|
2833
|
+
}, 80);
|
|
2834
|
+
}
|
|
2835
|
+
}, 900);
|
|
2836
|
+
// ── Visible text ────────────────────────────────────────
|
|
2837
|
+
const stripped = stripper.feed(chunk);
|
|
2838
|
+
const visible = stripped ? renderer.format(stripped) : '';
|
|
2839
|
+
if (visible) {
|
|
2840
|
+
if (inStreamingOp && !inlineOpRunning) {
|
|
2841
|
+
if (streamOpInterval) {
|
|
2842
|
+
clearInterval(streamOpInterval);
|
|
2843
|
+
streamOpInterval = null;
|
|
2844
|
+
}
|
|
2845
|
+
process.stdout.write('\r\x1b[K');
|
|
2846
|
+
inStreamingOp = false;
|
|
2847
|
+
streamOpLabel = '';
|
|
2848
|
+
streamOpFrame = 0;
|
|
2849
|
+
}
|
|
2850
|
+
const toPrint = hasRenderedContent ? visible : visible.replace(/^\n+/, '');
|
|
2851
|
+
if (toPrint) {
|
|
2852
|
+
if (toPrint.trim())
|
|
2853
|
+
hasRenderedContent = true;
|
|
2854
|
+
if (hasRenderedContent) {
|
|
2855
|
+
if (inlineOpRunning) {
|
|
2856
|
+
inlineTextQueue += toPrint; // buffer while op runs
|
|
2857
|
+
}
|
|
2858
|
+
else {
|
|
2859
|
+
process.stdout.write(toPrint);
|
|
2860
|
+
const trail = toPrint.match(/(\n+)$/);
|
|
2861
|
+
trailingNLs = trail ? trail[1].length : 0;
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
// ── Check for newly complete inline ops (write/edit/delete) ──
|
|
2867
|
+
if (!inlineOpRunning)
|
|
2868
|
+
checkForNextInlineOp();
|
|
2869
|
+
// ── Animate spinner while tag is still being generated ──────
|
|
2870
|
+
if (!inlineOpRunning) {
|
|
2871
|
+
const currentOp = detectActiveStreamingOp(fullResponse);
|
|
2872
|
+
if (currentOp && !inStreamingOp) {
|
|
2873
|
+
inStreamingOp = true;
|
|
2874
|
+
streamOpLabel = currentOp;
|
|
2875
|
+
streamOpFrame = 0;
|
|
2876
|
+
if (hasRenderedContent && trailingNLs === 0)
|
|
2877
|
+
process.stdout.write('\n');
|
|
2878
|
+
process.stdout.write(`\r\x1b[K ${colors.muted(SPINNER_FRAMES[0])} ${chalk.hex('#94a3b8')(streamOpLabel)}`);
|
|
2879
|
+
streamOpInterval = setInterval(() => {
|
|
2880
|
+
streamOpFrame = (streamOpFrame + 1) % SPINNER_FRAMES.length;
|
|
2881
|
+
process.stdout.write(`\r\x1b[K ${colors.muted(SPINNER_FRAMES[streamOpFrame])} ${chalk.hex('#94a3b8')(streamOpLabel)}`);
|
|
2882
|
+
}, 80);
|
|
2883
|
+
}
|
|
2884
|
+
else if (currentOp && inStreamingOp && currentOp !== streamOpLabel) {
|
|
2885
|
+
streamOpLabel = currentOp;
|
|
2886
|
+
}
|
|
2887
|
+
else if (!currentOp && inStreamingOp) {
|
|
2888
|
+
if (streamOpInterval) {
|
|
2889
|
+
clearInterval(streamOpInterval);
|
|
2890
|
+
streamOpInterval = null;
|
|
2891
|
+
}
|
|
2892
|
+
process.stdout.write('\r\x1b[K');
|
|
2893
|
+
inStreamingOp = false;
|
|
2894
|
+
streamOpLabel = '';
|
|
2895
|
+
streamOpFrame = 0;
|
|
2896
|
+
trailingNLs = 1;
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
}, async () => {
|
|
2900
|
+
clearInterval(spinnerInterval);
|
|
2901
|
+
if (midStreamTimer)
|
|
2902
|
+
clearTimeout(midStreamTimer);
|
|
2903
|
+
if (midStreamInterval) {
|
|
2904
|
+
clearInterval(midStreamInterval);
|
|
2905
|
+
midStreamInterval = null;
|
|
2906
|
+
}
|
|
2907
|
+
if (streamOpInterval) {
|
|
2908
|
+
clearInterval(streamOpInterval);
|
|
2909
|
+
streamOpInterval = null;
|
|
2910
|
+
}
|
|
2911
|
+
if (showingMidLoader || inStreamingOp)
|
|
2912
|
+
process.stdout.write('\r\x1b[K');
|
|
2913
|
+
showingMidLoader = false;
|
|
2914
|
+
inStreamingOp = false;
|
|
2915
|
+
const tail = stripper.flush();
|
|
2916
|
+
if (tail) {
|
|
2917
|
+
const tV = renderer.format(tail);
|
|
2918
|
+
if (tV) {
|
|
2919
|
+
hasRenderedContent = true;
|
|
2920
|
+
process.stdout.write(tV);
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
const rest = renderer.flush();
|
|
2924
|
+
if (rest) {
|
|
2925
|
+
hasRenderedContent = true;
|
|
2926
|
+
process.stdout.write(rest);
|
|
2927
|
+
}
|
|
2928
|
+
if (!streamStarted) {
|
|
2929
|
+
clearInterval(spinnerInterval);
|
|
2930
|
+
process.stdout.write('\r\x1b[K\n');
|
|
2931
|
+
}
|
|
2932
|
+
// ── Cancelled by user (Ctrl+C) ────────────────────────
|
|
2933
|
+
if (streamCancelled) {
|
|
2934
|
+
process.stdout.write('\r\x1b[K');
|
|
2935
|
+
if (hasRenderedContent && trailingNLs === 0)
|
|
2936
|
+
process.stdout.write('\n');
|
|
2937
|
+
process.stdout.write('\n ' + colors.muted('◼ Cancelled\n'));
|
|
2938
|
+
if (fullResponse.trim()) {
|
|
2939
|
+
history.push({ role: 'assistant', content: normalizeResponse(fullResponse) });
|
|
2940
|
+
}
|
|
2941
|
+
resolve();
|
|
2942
|
+
return;
|
|
2943
|
+
}
|
|
2944
|
+
const normalized = normalizeResponse(fullResponse);
|
|
2945
|
+
// Clean up the response — remove trailing newlines
|
|
2946
|
+
const stripped = normalized.replace(/\n+$/, '').trim();
|
|
2947
|
+
lastAIResponse = stripped;
|
|
2948
|
+
if (stripped.trim()) {
|
|
2949
|
+
history.push({ role: 'assistant', content: stripped });
|
|
2950
|
+
}
|
|
2951
|
+
if (conversationTitle === null) {
|
|
2952
|
+
const _msgs = history.slice(1).filter(m => m.role === 'user' || m.role === 'assistant');
|
|
2953
|
+
const _u = _msgs.find(m => m.role === 'user');
|
|
2954
|
+
const _a = _msgs.find(m => m.role === 'assistant');
|
|
2955
|
+
if (_u && _a) {
|
|
2956
|
+
generateAITitle(String(_u.content), String(_a.content), token).then(t => {
|
|
2957
|
+
conversationTitle = t;
|
|
2958
|
+
saveConversation(sessionId, t, activeCwd, history.slice(1));
|
|
2959
|
+
}).catch(() => { });
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
// Wait for any inline op still executing before touching stdout
|
|
2963
|
+
while (inlineOpRunning)
|
|
2964
|
+
await new Promise(r => setTimeout(r, 20));
|
|
2965
|
+
// ── design_mode tag → activate Web Designer skill ────────
|
|
2966
|
+
const designMatch = fullResponse.match(/<design_mode>([\s\S]*?)<\/design_mode>/);
|
|
2967
|
+
if (!webDesignerActive && designMatch) {
|
|
2968
|
+
webDesignerActive = true;
|
|
2969
|
+
history[0] = { role: 'system', content: history[0].content + _serverWebDesignerSkill };
|
|
2970
|
+
const skills = designMatch[1]
|
|
2971
|
+
.split('\n')
|
|
2972
|
+
.map(l => l.trim())
|
|
2973
|
+
.filter(Boolean);
|
|
2974
|
+
await showDesignModeLoader(skills);
|
|
2975
|
+
history.push({ role: 'system', content: '[Web Designer mode is now active. Apply all design guidelines from your system prompt. Proceed to build the website now.]' });
|
|
2976
|
+
readFileContinue = true;
|
|
2977
|
+
}
|
|
2978
|
+
// Run any ops that became complete just as stream ended
|
|
2979
|
+
checkForNextInlineOp();
|
|
2980
|
+
while (inlineOpRunning)
|
|
2981
|
+
await new Promise(r => setTimeout(r, 20));
|
|
2982
|
+
// Add inline op errors to history so AI can retry
|
|
2983
|
+
if (inlineFileOpErrors.length > 0) {
|
|
2984
|
+
history.push({ role: 'system', content: inlineFileOpErrors.join('\n\n') + '\n\nFix the above errors and retry the failed operations.' });
|
|
2985
|
+
readFileContinue = true;
|
|
2986
|
+
}
|
|
2987
|
+
const allOps = parseOps(fullResponse);
|
|
2988
|
+
// ── Detect incomplete plan: AI described steps but didn't output tags ──
|
|
2989
|
+
if (!readFileContinue && !streamCancelled) {
|
|
2990
|
+
const hasAnyReadOp = allOps.some(op => op.type === 'read_file' || op.type === 'read_folder' || op.type === 'search_code');
|
|
2991
|
+
const hasAnyWriteOp = allOps.some(op => op.type === 'write' || op.type === 'edit' || op.type === 'delete' || op.type === 'mkdir' || op.type === 'run');
|
|
2992
|
+
const writeOps = allOps.filter(op => op.type !== 'read_file' && op.type !== 'read_folder' && op.type !== 'search_code').length;
|
|
2993
|
+
const plannedSteps = (stripped.match(/^\s*[2-9]\.\s+\S/mg) ?? []).length;
|
|
2994
|
+
const hasCodeFence = stripped.includes('```');
|
|
2995
|
+
const hasStepList = (stripped.match(/^\s*\d+[.)]\s+\S/mg) ?? []).length >= 2;
|
|
2996
|
+
// Case 0: AI only output read/search ops with NO substantial text answer — force continuation
|
|
2997
|
+
// BUT: if AI wrote a substantial answer along with read ops, it already answered
|
|
2998
|
+
const textLength = stripped.replace(/<[^>]+>/g, '').trim().length;
|
|
2999
|
+
// Also check if the answer contains useful content (bullet points, lists, specific info)
|
|
3000
|
+
const hasUsefulContent = /[•\-\*]\s|^\d+\.\s|\b\d+\s+(забон|function|file|language|item)/m.test(stripped);
|
|
3001
|
+
// Check for loop: if same answer was given before, STOP
|
|
3002
|
+
const isDuplicate = lastAIResponse && stripped === lastAIResponse;
|
|
3003
|
+
// Check if answer contains specific info (numbers, names, etc.)
|
|
3004
|
+
const hasSpecificInfo = /\d+\s+(забон|function|file|language|item|line|row)|`\w+`/i.test(stripped);
|
|
3005
|
+
// Check if AI already gave a complete answer (more than 3 lines or contains list items)
|
|
3006
|
+
const hasCompleteAnswer = stripped.split('\n').length > 3 || /\n\s*[-•*]\s/.test(stripped) || /\n\s*\d+\.\s/.test(stripped);
|
|
3007
|
+
// Check if this is a repeat of recent answers (compare first 50 chars)
|
|
3008
|
+
const recentAnswerPrefix = lastAIResponse.slice(0, 50);
|
|
3009
|
+
const currentPrefix = stripped.slice(0, 50);
|
|
3010
|
+
const isSimilarToRecent = recentAnswerPrefix.length > 10 && currentPrefix === recentAnswerPrefix;
|
|
3011
|
+
if (hasAnyReadOp && !hasAnyWriteOp && readFileTurnCount < 3 && textLength < 20 && !hasUsefulContent && !isDuplicate && !hasSpecificInfo && !hasCompleteAnswer && !isSimilarToRecent) {
|
|
3012
|
+
// AI read files but didn't produce any answer — force it to answer
|
|
3013
|
+
const readPrompt = `[FILE CONTENTS LOADED] The files have been read and their contents are now in your context above.\n\nThe user's question was: "${lastUserLine.slice(0, 300)}"\n\nANSWER THE QUESTION NOW based on what you read. Do NOT say "let me read" — you already read the files. Give a DIRECT, SPECIFIC answer. Do NOT repeat yourself.`;
|
|
3014
|
+
history.push({ role: 'system', content: readPrompt });
|
|
3015
|
+
readFileContinue = true;
|
|
3016
|
+
}
|
|
3017
|
+
// Case 1: AI listed numbered steps (2+) but produced zero file ops
|
|
3018
|
+
else if (plannedSteps >= 1 && writeOps === 0 && !hasAnyReadOp) {
|
|
3019
|
+
history.push({ role: 'system', content: 'CRITICAL ERROR: You described steps but produced NO file operation tags. You MUST output <write_file> or <edit_file> tags to create/modify actual files. Do NOT show code in ``` blocks — use <write_file path="filename"> tags instead. Output all the tags NOW. No explanation.' });
|
|
3020
|
+
readFileContinue = true;
|
|
3021
|
+
// Case 2: AI showed code blocks + numbered list but no tags — regardless of language
|
|
3022
|
+
}
|
|
3023
|
+
else if (hasCodeFence && hasStepList && writeOps === 0 && allOps.length === 0) {
|
|
3024
|
+
history.push({ role: 'system', content: 'CRITICAL ERROR: You are showing code in ``` blocks instead of using <write_file> tags. This is wrong. ``` blocks do NOT create files — only <write_file> tags create files. Replace every ``` code block with a <write_file path="filename"> tag and output ALL files now.' });
|
|
3025
|
+
readFileContinue = true;
|
|
3026
|
+
// Case 3: Long response with code blocks but zero file ops — catch any language
|
|
3027
|
+
}
|
|
3028
|
+
else if (hasCodeFence && writeOps === 0 && allOps.length === 0 && normalized.trim().length > 400) {
|
|
3029
|
+
const hasWouldNeed = /(?:should|would need to|need to|you(?:'d)? need to|we(?:'d)? need to)\s+(?:edit|modify|update|change|create|add|remove)/i.test(normalized);
|
|
3030
|
+
const looksLikeFileDump = normalized.split('```').length > 3; // 2+ code blocks
|
|
3031
|
+
if (hasWouldNeed || looksLikeFileDump) {
|
|
3032
|
+
history.push({ role: 'system', content: 'CRITICAL ERROR: You showed code in ``` blocks instead of using <write_file> tags. ``` blocks are for explanations only — they do NOT create actual files. Output all files using <write_file path="..."> tags RIGHT NOW. No text, no explanation — only tags.' });
|
|
3033
|
+
readFileContinue = true;
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
const readOps = allOps.filter(op => op.type === 'read_file' || op.type === 'read_folder' || op.type === 'search_code');
|
|
3038
|
+
// Skip ops already executed inline (write/edit/delete/mkdir)
|
|
3039
|
+
const ops = allOps.filter(op => op.type !== 'read_file' && op.type !== 'read_folder' && op.type !== 'search_code' &&
|
|
3040
|
+
!executedInlineOps.has(inlineOpFingerprint(op)));
|
|
3041
|
+
// Trailing newline — skip when read ops follow (they start on current line)
|
|
3042
|
+
if (hasRenderedContent && readOps.length === 0)
|
|
3043
|
+
process.stdout.write('\n');
|
|
3044
|
+
// ── Handle read_file ops ──────────────────────────────
|
|
3045
|
+
// forcedEditMode: block further reads — AI must use existing context
|
|
3046
|
+
if (readOps.length > 0 && forcedEditMode) {
|
|
3047
|
+
history.push({
|
|
3048
|
+
role: 'system',
|
|
3049
|
+
content: `[BLOCKED] Read/search ops are blocked (limit reached). Use the file content already in context to make edits. Do NOT request more reads.`,
|
|
3050
|
+
});
|
|
3051
|
+
readFileContinue = true;
|
|
3052
|
+
}
|
|
3053
|
+
else if (readOps.length > 0) {
|
|
3054
|
+
// Absorb blank lines so reading block starts immediately after user message
|
|
3055
|
+
if (hasRenderedContent) {
|
|
3056
|
+
// Ensure cursor is on a new line, then absorb excess trailing blank lines
|
|
3057
|
+
if (trailingNLs === 0)
|
|
3058
|
+
process.stdout.write('\n');
|
|
3059
|
+
const excess = Math.max((trailingNLs || 1) - 1, 0);
|
|
3060
|
+
for (let i = 0; i < excess; i++)
|
|
3061
|
+
process.stdout.write('\x1b[1A\x1b[2K');
|
|
3062
|
+
}
|
|
3063
|
+
else if (!skipInput) {
|
|
3064
|
+
// No AI text — absorb the blank line from main loop's \n
|
|
3065
|
+
const lines = streamStarted ? 1 : 2;
|
|
3066
|
+
for (let i = 0; i < lines; i++)
|
|
3067
|
+
process.stdout.write('\x1b[1A\x1b[2K');
|
|
3068
|
+
}
|
|
3069
|
+
(async () => {
|
|
3070
|
+
try {
|
|
3071
|
+
const validOps = readOps.filter(op => (op.type === 'read_file' && op.path) ||
|
|
3072
|
+
(op.type === 'read_folder' && op.path) ||
|
|
3073
|
+
(op.type === 'search_code' && op.pattern));
|
|
3074
|
+
const total = validOps.length;
|
|
3075
|
+
if (total === 0) {
|
|
3076
|
+
readFileContinue = true;
|
|
3077
|
+
resolve();
|
|
3078
|
+
return;
|
|
3079
|
+
}
|
|
3080
|
+
const cols = process.stdout.columns ?? 80;
|
|
3081
|
+
const boxW = Math.min(Math.max(cols - 6, 40), 60);
|
|
3082
|
+
const BC = colors.dim;
|
|
3083
|
+
const FC = colors.text;
|
|
3084
|
+
const RIGHT_W = 8;
|
|
3085
|
+
const LABEL_W = Math.max(boxW - 11 - RIGHT_W, 10);
|
|
3086
|
+
// Helper: shorten file path (remove common prefixes)
|
|
3087
|
+
const shortenPath = (p) => {
|
|
3088
|
+
// Remove drive letter and common prefixes
|
|
3089
|
+
let short = p.replace(/^[A-Z]:\\[^\\]+\\[^\\]+\\/i, '');
|
|
3090
|
+
// If still too long, show only last 2 parts
|
|
3091
|
+
if (short.length > 30) {
|
|
3092
|
+
const parts = short.split(/[/\\]/);
|
|
3093
|
+
short = '...' + parts.slice(-2).join('/');
|
|
3094
|
+
}
|
|
3095
|
+
return short;
|
|
3096
|
+
};
|
|
3097
|
+
// Helper: truncate long file names
|
|
3098
|
+
const truncateName = (name, maxLen) => {
|
|
3099
|
+
if (name.length <= maxLen)
|
|
3100
|
+
return name;
|
|
3101
|
+
const ext = name.lastIndexOf('.');
|
|
3102
|
+
if (ext > 0) {
|
|
3103
|
+
const base = name.slice(0, ext);
|
|
3104
|
+
const fileExt = name.slice(ext);
|
|
3105
|
+
return base.slice(0, maxLen - fileExt.length - 3) + '...' + fileExt;
|
|
3106
|
+
}
|
|
3107
|
+
return name.slice(0, maxLen - 3) + '...';
|
|
3108
|
+
};
|
|
3109
|
+
const results = [];
|
|
3110
|
+
for (const op of validOps) {
|
|
3111
|
+
let spinLabel = '';
|
|
3112
|
+
let spinColor = chalk.hex('#818cf8');
|
|
3113
|
+
if (op.type === 'search_code') {
|
|
3114
|
+
spinLabel = `Searching ${chalk.white('"' + (op.pattern ?? '') + '"')}`;
|
|
3115
|
+
spinColor = chalk.hex('#f59e0b');
|
|
3116
|
+
}
|
|
3117
|
+
else if (op.type === 'read_folder') {
|
|
3118
|
+
spinLabel = `Reading ${chalk.white(op.path ?? '')}`;
|
|
3119
|
+
spinColor = chalk.hex('#818cf8');
|
|
3120
|
+
}
|
|
3121
|
+
else {
|
|
3122
|
+
spinLabel = `Reading ${chalk.white(op.path ?? '')}`;
|
|
3123
|
+
spinColor = chalk.hex('#818cf8');
|
|
3124
|
+
}
|
|
3125
|
+
let rfFrame = 0;
|
|
3126
|
+
const spinLine = () => `\r\x1b[K ${colors.muted(SPINNER_FRAMES[rfFrame])} ${spinColor(spinLabel)}`;
|
|
3127
|
+
process.stdout.write(spinLine());
|
|
3128
|
+
const rfInterval = setInterval(() => {
|
|
3129
|
+
rfFrame = (rfFrame + 1) % SPINNER_FRAMES.length;
|
|
3130
|
+
process.stdout.write(spinLine());
|
|
3131
|
+
}, 80);
|
|
3132
|
+
const t0 = Date.now();
|
|
3133
|
+
const res = await executeSingleOp(op, activeCwd);
|
|
3134
|
+
const ms = Date.now() - t0;
|
|
3135
|
+
clearInterval(rfInterval);
|
|
3136
|
+
if (res.type === 'run') {
|
|
3137
|
+
let ctxLabel = '';
|
|
3138
|
+
let displayLabel = '';
|
|
3139
|
+
let rightCol = '';
|
|
3140
|
+
if (op.type === 'search_code') {
|
|
3141
|
+
ctxLabel = `[Search results — "${op.pattern}"${op.path ? ` in "${op.path}"` : ''}]:\n${res.output ?? ''}`;
|
|
3142
|
+
const lastLine = (res.output ?? '').split('\n').filter(Boolean).pop() ?? '';
|
|
3143
|
+
rightCol = chalk.hex('#6b7280')(lastLine.startsWith('Total:') ? lastLine.slice(7).trim() : `${ms}ms`);
|
|
3144
|
+
displayLabel = `"${op.pattern}"`;
|
|
3145
|
+
const firstMatchLine = (res.output ?? '').match(/^([^\n:]+):(\d+):/m);
|
|
3146
|
+
if (firstMatchLine) {
|
|
3147
|
+
const matchFile = firstMatchLine[1].trim();
|
|
3148
|
+
const matchLineNum = parseInt(firstMatchLine[2]);
|
|
3149
|
+
if (!isNaN(matchLineNum) && matchFile) {
|
|
3150
|
+
const readStart = Math.max(1, matchLineNum - 3);
|
|
3151
|
+
const readEnd = matchLineNum + 280;
|
|
3152
|
+
const autoKey = `[File content — ${matchFile}][lines=${readStart}-${readEnd}]`;
|
|
3153
|
+
const alreadyHaveIt = history.slice(-10).some(m => m.role === 'system' && m.content.includes(`[File content — ${matchFile}]`));
|
|
3154
|
+
if (!alreadyHaveIt) {
|
|
3155
|
+
validOps.push({ type: 'read_file', path: matchFile, lines: `${readStart}-${readEnd}` });
|
|
3156
|
+
void autoKey;
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
}
|
|
3161
|
+
else if (op.type === 'read_folder') {
|
|
3162
|
+
ctxLabel = `[Folder contents — "${op.path}"]:\n${res.output ?? ''}`;
|
|
3163
|
+
const firstLine = (res.output ?? '').split('\n')[0] ?? '';
|
|
3164
|
+
const counts = firstLine.match(/\((.+)\)/);
|
|
3165
|
+
rightCol = chalk.hex('#6b7280')(counts ? counts[1] : `${ms}ms`);
|
|
3166
|
+
displayLabel = op.path ?? '';
|
|
3167
|
+
}
|
|
3168
|
+
else {
|
|
3169
|
+
const lineTag = op.lines ? `[lines=${op.lines}]` : '[full]';
|
|
3170
|
+
ctxLabel = `[File content — ${res.message ?? op.path}]${lineTag}:\n${res.output ?? ''}`;
|
|
3171
|
+
rightCol = chalk.hex('#6b7280')(op.lines ? `lines ${op.lines}` : `${ms}ms`);
|
|
3172
|
+
displayLabel = op.lines ? `${op.path ?? ''} :${op.lines}` : (op.path ?? '');
|
|
3173
|
+
const pageMatch = (res.output ?? '').match(/\.\.\. \((\d+) more lines — next page: lines (\d+)-(\d+)\)/);
|
|
3174
|
+
if (pageMatch && op.path) {
|
|
3175
|
+
const [, , nextStart, nextEnd] = pageMatch;
|
|
3176
|
+
history.push({
|
|
3177
|
+
role: 'system',
|
|
3178
|
+
content: `[Auto-reading next page of ${op.path}...]`,
|
|
3179
|
+
});
|
|
3180
|
+
validOps.push({ type: 'read_file', path: op.path, lines: `${nextStart}-${nextEnd}` });
|
|
3181
|
+
}
|
|
3182
|
+
}
|
|
3183
|
+
// Deduplicate: don't push the exact same read twice in recent history
|
|
3184
|
+
// For read_file with lines=, include the range so different sections are NOT deduped
|
|
3185
|
+
const dupKey = op.type === 'read_file'
|
|
3186
|
+
? `[File content — ${res.message ?? op.path}]${op.lines ? `[lines=${op.lines}]` : '[full]'}`
|
|
3187
|
+
: op.type === 'read_folder'
|
|
3188
|
+
? `[Folder contents — "${op.path}"]`
|
|
3189
|
+
: null;
|
|
3190
|
+
const alreadyInHistory = dupKey
|
|
3191
|
+
? history.slice(-8).some(m => m.role === 'system' && m.content.includes(dupKey))
|
|
3192
|
+
: false;
|
|
3193
|
+
if (!alreadyInHistory) {
|
|
3194
|
+
history.push({ role: 'system', content: ctxLabel });
|
|
3195
|
+
}
|
|
3196
|
+
results.push({ label: displayLabel, right: rightCol, ok: true, contextMsg: ctxLabel });
|
|
3197
|
+
}
|
|
3198
|
+
else {
|
|
3199
|
+
const displayLabel = op.type === 'search_code'
|
|
3200
|
+
? `"${op.pattern ?? ''}"`
|
|
3201
|
+
: (op.path ?? '');
|
|
3202
|
+
results.push({ label: displayLabel, right: chalk.hex('#f87171')('err'), ok: false, contextMsg: '' });
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
// ── Phase 2: summary box ────────────────────────────────
|
|
3206
|
+
process.stdout.write('\r\x1b[K');
|
|
3207
|
+
const hasSearch = validOps.some(o => o.type === 'search_code');
|
|
3208
|
+
const hasFolder = validOps.some(o => o.type === 'read_folder');
|
|
3209
|
+
const hasFiles = validOps.some(o => o.type === 'read_file');
|
|
3210
|
+
const titleParts = [];
|
|
3211
|
+
if (hasSearch)
|
|
3212
|
+
titleParts.push(`Search`);
|
|
3213
|
+
if (hasFolder)
|
|
3214
|
+
titleParts.push(`Folder`);
|
|
3215
|
+
if (hasFiles)
|
|
3216
|
+
titleParts.push(total === 1 ? '1 file' : `${total} files`);
|
|
3217
|
+
const titleText = ` ${titleParts.join(' · ')} `;
|
|
3218
|
+
const dashCount = Math.max(boxW - 3 - titleText.length, 2);
|
|
3219
|
+
process.stdout.write(` ` + BC('╭─') + colors.primary.bold(titleText) + BC('─'.repeat(dashCount) + '╮') + `\n`);
|
|
3220
|
+
for (const r of results) {
|
|
3221
|
+
const icon = r.ok ? colors.success('✓') : colors.error('✗');
|
|
3222
|
+
const shortLabel = shortenPath(r.label);
|
|
3223
|
+
const disp = truncateName(shortLabel, LABEL_W);
|
|
3224
|
+
const labelPad = ' '.repeat(Math.max(LABEL_W - disp.length, 0));
|
|
3225
|
+
const rightVis = stripAnsi(r.right);
|
|
3226
|
+
const rightPad = ' '.repeat(Math.max(RIGHT_W - rightVis.length, 0));
|
|
3227
|
+
process.stdout.write(` ` + BC('│') + ` ` + icon + ` ` + FC(disp) + labelPad + ` ` + r.right + rightPad + ` ` + BC('│') + `\n`);
|
|
3228
|
+
}
|
|
3229
|
+
process.stdout.write(` ` + BC('╰' + '─'.repeat(boxW - 2) + '╯') + `\n`);
|
|
3230
|
+
readFileContinue = true;
|
|
3231
|
+
resolve();
|
|
3232
|
+
}
|
|
3233
|
+
catch (e) {
|
|
3234
|
+
logError('readOps', e);
|
|
3235
|
+
resolve();
|
|
3236
|
+
}
|
|
3237
|
+
})();
|
|
3238
|
+
return;
|
|
3239
|
+
} // end else if (readOps.length > 0)
|
|
3240
|
+
if (ops.length > 0) {
|
|
3241
|
+
(async () => {
|
|
3242
|
+
try {
|
|
3243
|
+
const skippedPaths = new Set();
|
|
3244
|
+
const runOutputs = [];
|
|
3245
|
+
const fileOpErrors = [];
|
|
3246
|
+
const declinedCmds = [];
|
|
3247
|
+
for (const op of ops) {
|
|
3248
|
+
const label = opLabel(op, activeCwd);
|
|
3249
|
+
const key = opKey(op, activeCwd);
|
|
3250
|
+
if (op.type === 'run' && op.command) {
|
|
3251
|
+
const depSkipped = [...skippedPaths].some(p => op.command.includes(path.basename(p)));
|
|
3252
|
+
if (depSkipped) {
|
|
3253
|
+
process.stdout.write(` ${colors.muted('○')} ${colors.muted('Skipped: ' + label)} ${colors.muted('(dependency missing)')}\n`);
|
|
3254
|
+
continue;
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
const previewLines2 = (!alwaysAllowed.has(key) && (op.type === 'write' || op.type === 'edit')) ? printDiffPreview(op, activeCwd) : 0;
|
|
3258
|
+
const allowed = await askPermission(label, key, alwaysAllowed, op.type === 'run', previewLines2 > 0, previewLines2);
|
|
3259
|
+
if (!allowed) {
|
|
3260
|
+
if (op.path)
|
|
3261
|
+
skippedPaths.add(op.path);
|
|
3262
|
+
if (op.type === 'run' && op.command)
|
|
3263
|
+
declinedCmds.push(op.command);
|
|
3264
|
+
continue;
|
|
3265
|
+
}
|
|
3266
|
+
let stageSpinInterval = null;
|
|
3267
|
+
let stageSpinFrame = 0;
|
|
3268
|
+
let stageSpinMsg = '';
|
|
3269
|
+
const opResult = await executeSingleOp(op, activeCwd, (stageMsg) => {
|
|
3270
|
+
stageSpinMsg = stageMsg;
|
|
3271
|
+
if (!stageSpinInterval) {
|
|
3272
|
+
stageSpinFrame = 0;
|
|
3273
|
+
stageSpinInterval = setInterval(() => {
|
|
3274
|
+
const f = SPINNER_FRAMES[stageSpinFrame++ % SPINNER_FRAMES.length];
|
|
3275
|
+
process.stdout.write(`\r\x1b[K ${colors.muted(f)} ${colors.subtext(stageSpinMsg)}`);
|
|
3276
|
+
}, 80);
|
|
3277
|
+
}
|
|
3278
|
+
});
|
|
3279
|
+
if (stageSpinInterval) {
|
|
3280
|
+
clearInterval(stageSpinInterval);
|
|
3281
|
+
stageSpinInterval = null;
|
|
3282
|
+
}
|
|
3283
|
+
process.stdout.write('\r\x1b[K');
|
|
3284
|
+
printOpResult(opResult);
|
|
3285
|
+
// Collect file operation errors for AI feedback
|
|
3286
|
+
if (opResult.type === 'error' && op.type !== 'run') {
|
|
3287
|
+
let errMsg = `[Operation failed — ${label}]: ${opResult.message ?? 'Unknown error'}`;
|
|
3288
|
+
if (opResult.message?.includes('not found') && op.path) {
|
|
3289
|
+
try {
|
|
3290
|
+
const fp = path.resolve(activeCwd, op.path);
|
|
3291
|
+
if (fs.existsSync(fp)) {
|
|
3292
|
+
const cur = fs.readFileSync(fp, 'utf-8');
|
|
3293
|
+
const curLines = cur.split('\n');
|
|
3294
|
+
const nLines = curLines.length;
|
|
3295
|
+
const isDeleteOp = !op.replace || op.replace.trim() === '';
|
|
3296
|
+
// Auto-search for approximate location of what AI tried to find
|
|
3297
|
+
const findLines = (op.find ?? '').split('\n').map(l => l.replace(/^\s*\d+\s*[│|:]\s?/, '').trim()).filter(Boolean);
|
|
3298
|
+
const searchTerm = findLines[0]?.slice(0, 60) ?? '';
|
|
3299
|
+
let foundAt = -1;
|
|
3300
|
+
if (searchTerm.length > 4) {
|
|
3301
|
+
for (let si = 0; si < curLines.length; si++) {
|
|
3302
|
+
if (curLines[si].toLowerCase().includes(searchTerm.toLowerCase())) {
|
|
3303
|
+
foundAt = si;
|
|
3304
|
+
break;
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
}
|
|
3308
|
+
if (foundAt >= 0) {
|
|
3309
|
+
const start = Math.max(0, foundAt - 2);
|
|
3310
|
+
const end = Math.min(curLines.length - 1, foundAt + 100);
|
|
3311
|
+
errMsg += `\n\n[FOUND near line ${foundAt + 1}]:\n${curLines.slice(start, end + 1).join('\n')}\n`;
|
|
3312
|
+
errMsg += isDeleteOp
|
|
3313
|
+
? `\nDELETE FIX: Copy the EXACT full container from above into <edit_file><find>EXACT</find><replace></replace>.`
|
|
3314
|
+
: `\nEDIT FIX: Copy EXACT text from above into <edit_file><find>EXACT</find><replace>NEW</replace>.`;
|
|
3315
|
+
}
|
|
3316
|
+
else if (nLines <= 400) {
|
|
3317
|
+
errMsg += `\n\nFull file (${nLines} lines):\n${cur}\n\nFIX: Copy EXACT text from above into <find>.`;
|
|
3318
|
+
}
|
|
3319
|
+
else {
|
|
3320
|
+
const safe = searchTerm.replace(/['"<>{}()\[\]]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 35);
|
|
3321
|
+
errMsg += `\n\nFIX: <search_code pattern="${safe}" path="${op.path}"/> → <read_file lines="N-M"/> → copy EXACT text into <find>.`;
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
catch { /* ignore */ }
|
|
3326
|
+
}
|
|
3327
|
+
fileOpErrors.push(errMsg);
|
|
3328
|
+
}
|
|
3329
|
+
if (op.type === 'run' && op.command) {
|
|
3330
|
+
if (opResult.type === 'run') {
|
|
3331
|
+
runOutputs.push({ cmd: op.command, output: opResult.output || '(command executed successfully — no terminal output)', isError: false });
|
|
3332
|
+
}
|
|
3333
|
+
else if (opResult.type === 'error') {
|
|
3334
|
+
runOutputs.push({ cmd: op.command, output: opResult.message ?? 'Unknown error', isError: true });
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
3338
|
+
if (runOutputs.length > 0) {
|
|
3339
|
+
const NO_OUTPUT_MARKER = '(command executed successfully — no terminal output)';
|
|
3340
|
+
const content = runOutputs.map(r => r.isError
|
|
3341
|
+
? `[Command failed — ${r.cmd}]:\n${r.output}`
|
|
3342
|
+
: `[Command output — ${r.cmd}]:\n${r.output}`).join('\n\n');
|
|
3343
|
+
history.push({ role: 'system', content });
|
|
3344
|
+
// Auto-retry for failed commands
|
|
3345
|
+
const failedCmds = runOutputs.filter(r => r.isError);
|
|
3346
|
+
if (failedCmds.length > 0 && autoRetryCount < MAX_AUTO_RETRIES) {
|
|
3347
|
+
autoRetryCount++;
|
|
3348
|
+
const retryHint = `[Auto-retry ${autoRetryCount}/${MAX_AUTO_RETRIES}] ` +
|
|
3349
|
+
`Previous command(s) failed. Analyze the error and try again with a fix. ` +
|
|
3350
|
+
`Common fixes: check file paths, install missing dependencies, verify syntax.`;
|
|
3351
|
+
history.push({ role: 'system', content: retryHint });
|
|
3352
|
+
readFileContinue = true;
|
|
3353
|
+
}
|
|
3354
|
+
else if (autoRetryCount >= MAX_AUTO_RETRIES) {
|
|
3355
|
+
autoRetryCount = 0;
|
|
3356
|
+
}
|
|
3357
|
+
// Only auto-continue if there is real output to react to, or an error to explain
|
|
3358
|
+
const needsReaction = runOutputs.some(r => r.isError || r.output !== NO_OUTPUT_MARKER);
|
|
3359
|
+
if (needsReaction)
|
|
3360
|
+
readFileContinue = true;
|
|
3361
|
+
}
|
|
3362
|
+
// ── Feed file operation errors back to AI so it can retry ──
|
|
3363
|
+
if (fileOpErrors.length > 0) {
|
|
3364
|
+
history.push({ role: 'system', content: fileOpErrors.join('\n\n') + '\n\nFix the above errors and retry the failed operations.' });
|
|
3365
|
+
readFileContinue = true;
|
|
3366
|
+
}
|
|
3367
|
+
if (declinedCmds.length > 0) {
|
|
3368
|
+
const content = declinedCmds.map(cmd => `[User declined to run — ${cmd}]: User pressed No. Do not retry or ask about this command.`).join('\n\n');
|
|
3369
|
+
history.push({ role: 'system', content });
|
|
3370
|
+
// No readFileContinue — AI already responded; wait for user's next message
|
|
3371
|
+
}
|
|
3372
|
+
resolve();
|
|
3373
|
+
}
|
|
3374
|
+
catch (e) {
|
|
3375
|
+
logError('ops', e);
|
|
3376
|
+
resolve();
|
|
3377
|
+
}
|
|
3378
|
+
})();
|
|
3379
|
+
}
|
|
3380
|
+
else {
|
|
3381
|
+
resolve();
|
|
3382
|
+
}
|
|
3383
|
+
}, (err) => {
|
|
3384
|
+
clearInterval(spinnerInterval);
|
|
3385
|
+
if (midStreamTimer)
|
|
3386
|
+
clearTimeout(midStreamTimer);
|
|
3387
|
+
if (midStreamInterval) {
|
|
3388
|
+
clearInterval(midStreamInterval);
|
|
3389
|
+
midStreamInterval = null;
|
|
3390
|
+
}
|
|
3391
|
+
if (streamOpInterval) {
|
|
3392
|
+
clearInterval(streamOpInterval);
|
|
3393
|
+
streamOpInterval = null;
|
|
3394
|
+
}
|
|
3395
|
+
process.stdout.write('\r\x1b[K');
|
|
3396
|
+
const raw = err.message;
|
|
3397
|
+
const msg = raw.includes('timed out')
|
|
3398
|
+
? 'Connection timed out — check your internet and try again'
|
|
3399
|
+
: raw.includes('401') || raw.includes('403') || raw.includes('Unauthorized')
|
|
3400
|
+
? 'Authentication error — run dravix --login to sign in again'
|
|
3401
|
+
: raw.includes('429') || raw.includes('rate')
|
|
3402
|
+
? 'Rate limit reached — please wait a moment and try again'
|
|
3403
|
+
: raw.includes('500') || raw.includes('502') || raw.includes('503')
|
|
3404
|
+
? 'Server error — the AI service is temporarily unavailable'
|
|
3405
|
+
: raw;
|
|
3406
|
+
printError(msg);
|
|
3407
|
+
resolve();
|
|
3408
|
+
}, streamAbort.signal, FLASH_MODEL);
|
|
3409
|
+
});
|
|
3410
|
+
// ── Remove streaming key listener ─────────────────────────
|
|
3411
|
+
process.stdin.removeListener('data', onStreamKey);
|
|
3412
|
+
// ── Accumulate token usage (deferred — report on next user turn) ──
|
|
3413
|
+
if (cliTok && fullResponse) {
|
|
3414
|
+
pendingOutputTokens += estimateTokens(normalizeResponse(fullResponse));
|
|
3415
|
+
if (!skipInput && lastUserLine) {
|
|
3416
|
+
pendingUserTokens = estimateTokens(lastUserLine);
|
|
3417
|
+
hasPendingReport = true;
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
// ── Auto-save conversation ────────────────────────────────
|
|
3421
|
+
const chatMsgs = history.slice(1).filter(m => m.role === 'user' || m.role === 'assistant');
|
|
3422
|
+
if (chatMsgs.length > 0) {
|
|
3423
|
+
saveConversation(sessionId, conversationTitle ?? generateTitle(chatMsgs), activeCwd, history.slice(1));
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
catch (loopErr) {
|
|
3427
|
+
// Never let an internal error crash the session — show it and continue
|
|
3428
|
+
const msg = loopErr instanceof Error ? loopErr.message : String(loopErr);
|
|
3429
|
+
printError(`Internal error: ${msg}`);
|
|
3430
|
+
readFileContinue = false;
|
|
3431
|
+
}
|
|
3432
|
+
}
|
|
3433
|
+
}
|