@tensorspark/dravix-code 0.0.0-stage → 1.5.1

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