@tensorspark/dravix-code 1.5.0 → 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.
@@ -1,201 +1,650 @@
1
1
  import chalk from 'chalk';
2
2
  import { readFileSync } from 'fs';
3
3
  import { fileURLToPath } from 'url';
4
- import { dirname, join } from 'path';
4
+ import { dirname, join, basename } from 'path';
5
+ import { usageBar, fmtNum, formatResetTime } from '../services/usage.js';
5
6
  const _dir = dirname(fileURLToPath(import.meta.url));
6
7
  const _pkg = JSON.parse(readFileSync(join(_dir, '../../package.json'), 'utf-8'));
7
8
  export const VERSION = _pkg.version;
8
9
  export const colors = {
9
- primary: chalk.hex('#6366f1'),
10
- accent: chalk.hex('#818cf8'),
10
+ primary: chalk.hex('#818cf8'),
11
+ brand: chalk.hex('#6366f1'),
12
+ accent: chalk.hex('#a78bfa'),
11
13
  success: chalk.hex('#34d399'),
12
14
  error: chalk.hex('#f87171'),
13
15
  warn: chalk.hex('#fbbf24'),
14
- muted: chalk.hex('#6b7280'),
15
- ai: chalk.hex('#c4b5fd'),
16
- dim: chalk.hex('#374151'),
16
+ info: chalk.hex('#38bdf8'),
17
+ muted: chalk.hex('#64748b'),
18
+ ai: chalk.hex('#e5e7eb'),
19
+ dim: chalk.hex('#334155'),
20
+ border: chalk.hex('#434c6e'),
17
21
  bg: chalk.hex('#0d1117'),
18
22
  surface: chalk.hex('#161b22'),
19
- border: chalk.hex('#30363d'),
20
- text: chalk.hex('#e2e8f0'),
23
+ text: chalk.hex('#f1f5f9'),
21
24
  subtext: chalk.hex('#94a3b8'),
22
25
  };
26
+ // ── ANSI & Unicode display-width utilities ──────────────────────
27
+ const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
28
+ export function stripAnsi(s) {
29
+ return s.replace(ANSI_RE, '');
30
+ }
31
+ export function charWidth(cp) {
32
+ if (cp === 0 || cp < 0x20 || (cp >= 0x7f && cp < 0xa0))
33
+ return 0;
34
+ // Combining diacritical & variation selectors
35
+ if ((cp >= 0x0300 && cp <= 0x036f) ||
36
+ (cp >= 0x1ab0 && cp <= 0x1aff) ||
37
+ (cp >= 0x1dc0 && cp <= 0x1dff) ||
38
+ (cp >= 0x20d0 && cp <= 0x20ff) ||
39
+ (cp >= 0xfe00 && cp <= 0xfe0f) ||
40
+ (cp >= 0xfe20 && cp <= 0xfe2f) ||
41
+ cp === 0x200d)
42
+ return 0;
43
+ // East Asian Wide / Fullwidth / Emoji ranges
44
+ if ((cp >= 0x1100 && cp <= 0x115f) ||
45
+ cp === 0x2329 || cp === 0x232a ||
46
+ (cp >= 0x2e80 && cp <= 0x303e) ||
47
+ (cp >= 0x3040 && cp <= 0xa4cf) ||
48
+ (cp >= 0xac00 && cp <= 0xd7a3) ||
49
+ (cp >= 0xf900 && cp <= 0xfaff) ||
50
+ (cp >= 0xfe10 && cp <= 0xfe19) ||
51
+ (cp >= 0xfe30 && cp <= 0xfe6f) ||
52
+ (cp >= 0xff00 && cp <= 0xff60) ||
53
+ (cp >= 0xffe0 && cp <= 0xffe6) ||
54
+ (cp >= 0x1f300 && cp <= 0x1faff) ||
55
+ (cp >= 0x20000 && cp <= 0x3fffd))
56
+ return 2;
57
+ return 1;
58
+ }
59
+ export function visWidth(s) {
60
+ const plain = stripAnsi(s);
61
+ let w = 0;
62
+ for (const ch of plain) {
63
+ w += charWidth(ch.codePointAt(0) ?? 0);
64
+ }
65
+ return w;
66
+ }
67
+ export function clipVis(s, maxW) {
68
+ if (maxW <= 0)
69
+ return '';
70
+ if (visWidth(s) <= maxW)
71
+ return s;
72
+ if (maxW === 1)
73
+ return '…';
74
+ let w = 0;
75
+ let out = '';
76
+ for (const ch of s) {
77
+ const cw = charWidth(ch.codePointAt(0) ?? 0);
78
+ if (w + cw > maxW - 1)
79
+ break;
80
+ out += ch;
81
+ w += cw;
82
+ }
83
+ return out + '…';
84
+ }
85
+ export function clipStartVis(s, maxW) {
86
+ if (maxW <= 0)
87
+ return '';
88
+ if (visWidth(s) <= maxW)
89
+ return s;
90
+ if (maxW === 1)
91
+ return '…';
92
+ const chars = [...s];
93
+ let w = 0;
94
+ const kept = [];
95
+ for (let i = chars.length - 1; i >= 0; i--) {
96
+ const cw = charWidth(chars[i].codePointAt(0) ?? 0);
97
+ if (w + cw > maxW - 1)
98
+ break;
99
+ kept.push(chars[i]);
100
+ w += cw;
101
+ }
102
+ return '…' + kept.reverse().join('');
103
+ }
104
+ export function clipAnsi(s, maxW) {
105
+ if (maxW <= 0)
106
+ return '';
107
+ if (visWidth(s) <= maxW)
108
+ return s;
109
+ if (maxW === 1)
110
+ return '…';
111
+ let w = 0;
112
+ let out = '';
113
+ let hadAnsi = false;
114
+ const parts = s.split(/(\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\))/);
115
+ for (const part of parts) {
116
+ if (!part)
117
+ continue;
118
+ if (part.startsWith('\x1b')) {
119
+ hadAnsi = true;
120
+ out += part;
121
+ continue;
122
+ }
123
+ for (const ch of part) {
124
+ const cw = charWidth(ch.codePointAt(0) ?? 0);
125
+ if (w + cw > maxW - 1) {
126
+ return out + '…' + (hadAnsi ? '\x1b[0m' : '');
127
+ }
128
+ out += ch;
129
+ w += cw;
130
+ }
131
+ }
132
+ return out + (hadAnsi ? '\x1b[0m' : '');
133
+ }
134
+ export function padVis(s, targetW) {
135
+ const diff = targetW - visWidth(s);
136
+ return diff > 0 ? s + ' '.repeat(diff) : s;
137
+ }
138
+ export function physRowsOf(line, termCols) {
139
+ const w = visWidth(line);
140
+ if (w === 0)
141
+ return 1;
142
+ return Math.max(1, Math.ceil(w / Math.max(termCols, 1)));
143
+ }
144
+ /**
145
+ * Word-wraps ANSI-styled text cleanly while preserving active SGR styles
146
+ * across line breaks so bold/italic/inline-code styling never bleeds or breaks.
147
+ */
148
+ export function wrapAnsi(text, maxW, firstPrefix = '', nextPrefix = '') {
149
+ const width = Math.max(maxW, 12);
150
+ const firstPrefW = visWidth(firstPrefix);
151
+ const nextPrefW = visWidth(nextPrefix);
152
+ const firstLim = Math.max(width - firstPrefW, 8);
153
+ const nextLim = Math.max(width - nextPrefW, 8);
154
+ const state = {};
155
+ const emitState = () => (state.bold ?? '') +
156
+ (state.dim ?? '') +
157
+ (state.italic ?? '') +
158
+ (state.underline ?? '') +
159
+ (state.strike ?? '') +
160
+ (state.fg ?? '') +
161
+ (state.bg ?? '');
162
+ const hasState = () => Boolean(state.bold || state.dim || state.italic || state.underline || state.strike || state.fg || state.bg);
163
+ const applySgr = (seq) => {
164
+ const m = seq.match(/^\x1b\[([0-9;]*)m$/);
165
+ if (!m)
166
+ return;
167
+ const nums = (m[1] || '0').split(';').map(n => parseInt(n || '0', 10));
168
+ let i = 0;
169
+ while (i < nums.length) {
170
+ const code = nums[i];
171
+ if (code === 0) {
172
+ delete state.bold;
173
+ delete state.dim;
174
+ delete state.italic;
175
+ delete state.underline;
176
+ delete state.strike;
177
+ delete state.fg;
178
+ delete state.bg;
179
+ }
180
+ else if (code === 1)
181
+ state.bold = '\x1b[1m';
182
+ else if (code === 2)
183
+ state.dim = '\x1b[2m';
184
+ else if (code === 3)
185
+ state.italic = '\x1b[3m';
186
+ else if (code === 4)
187
+ state.underline = '\x1b[4m';
188
+ else if (code === 9)
189
+ state.strike = '\x1b[9m';
190
+ else if (code === 22) {
191
+ delete state.bold;
192
+ delete state.dim;
193
+ }
194
+ else if (code === 23)
195
+ delete state.italic;
196
+ else if (code === 24)
197
+ delete state.underline;
198
+ else if (code === 29)
199
+ delete state.strike;
200
+ else if (code === 39)
201
+ delete state.fg;
202
+ else if (code === 49)
203
+ delete state.bg;
204
+ else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
205
+ state.fg = `\x1b[${code}m`;
206
+ }
207
+ else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
208
+ state.bg = `\x1b[${code}m`;
209
+ }
210
+ else if (code === 38) {
211
+ if (nums[i + 1] === 5 && i + 2 < nums.length) {
212
+ state.fg = `\x1b[38;5;${nums[i + 2]}m`;
213
+ i += 2;
214
+ }
215
+ else if (nums[i + 1] === 2 && i + 4 < nums.length) {
216
+ state.fg = `\x1b[38;2;${nums[i + 2]};${nums[i + 3]};${nums[i + 4]}m`;
217
+ i += 4;
218
+ }
219
+ }
220
+ else if (code === 48) {
221
+ if (nums[i + 1] === 5 && i + 2 < nums.length) {
222
+ state.bg = `\x1b[48;5;${nums[i + 2]}m`;
223
+ i += 2;
224
+ }
225
+ else if (nums[i + 1] === 2 && i + 4 < nums.length) {
226
+ state.bg = `\x1b[48;2;${nums[i + 2]};${nums[i + 3]};${nums[i + 4]}m`;
227
+ i += 4;
228
+ }
229
+ }
230
+ i++;
231
+ }
232
+ };
233
+ // Tokenize into ANSI tags, whitespace runs, and non-space chunks
234
+ const tokens = [];
235
+ const tokenRe = /(\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[ \t]+|[^\x1b \t]+)/g;
236
+ let match;
237
+ while ((match = tokenRe.exec(text)) !== null) {
238
+ const val = match[0];
239
+ if (val.startsWith('\x1b'))
240
+ tokens.push({ kind: 'ansi', val });
241
+ else if (/^[ \t]+$/.test(val))
242
+ tokens.push({ kind: 'space', val });
243
+ else
244
+ tokens.push({ kind: 'word', val });
245
+ }
246
+ const lines = [];
247
+ let curLine = '';
248
+ let curW = 0;
249
+ let isFirst = true;
250
+ const lim = () => (isFirst ? firstLim : nextLim);
251
+ const pref = () => (isFirst ? firstPrefix : nextPrefix);
252
+ const pushLine = () => {
253
+ const endReset = hasState() ? '\x1b[0m' : '';
254
+ lines.push(pref() + curLine.replace(/[ \t]+$/, '') + endReset);
255
+ isFirst = false;
256
+ curLine = emitState();
257
+ curW = 0;
258
+ };
259
+ for (const tok of tokens) {
260
+ if (tok.kind === 'ansi') {
261
+ curLine += tok.val;
262
+ applySgr(tok.val);
263
+ continue;
264
+ }
265
+ if (tok.kind === 'space') {
266
+ if (curW === 0)
267
+ continue; // skip leading whitespace at start of wrapped line
268
+ const sw = tok.val.length;
269
+ if (curW + sw <= lim()) {
270
+ curLine += tok.val;
271
+ curW += sw;
272
+ }
273
+ else {
274
+ pushLine();
275
+ }
276
+ continue;
277
+ }
278
+ // tok.kind === 'word'
279
+ const ww = visWidth(tok.val);
280
+ if (curW + ww <= lim()) {
281
+ curLine += tok.val;
282
+ curW += ww;
283
+ continue;
284
+ }
285
+ // Wrap onto new line if current line already has content
286
+ if (curW > 0) {
287
+ pushLine();
288
+ }
289
+ // If word itself fits on an empty line, place it directly
290
+ if (ww <= lim()) {
291
+ curLine += tok.val;
292
+ curW += ww;
293
+ }
294
+ else {
295
+ // Break ultra-long unspaced token (URL/path) character-by-character
296
+ for (const ch of tok.val) {
297
+ const cw = charWidth(ch.codePointAt(0) ?? 0);
298
+ if (curW + cw > lim() && curW > 0) {
299
+ pushLine();
300
+ }
301
+ curLine += ch;
302
+ curW += cw;
303
+ }
304
+ }
305
+ }
306
+ if (curW > 0 || lines.length === 0) {
307
+ const endReset = hasState() ? '\x1b[0m' : '';
308
+ lines.push(pref() + curLine + endReset);
309
+ }
310
+ return lines;
311
+ }
312
+ // ── Reusable terminal spinner ───────────────────────────────────
313
+ export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
314
+ export class Spinner {
315
+ timer = null;
316
+ frame = 0;
317
+ label = '';
318
+ startedAt = 0;
319
+ showElapsed = false;
320
+ accentHex = '#818cf8';
321
+ start(label, opts) {
322
+ this.stop(false);
323
+ this.label = label;
324
+ this.frame = 0;
325
+ this.startedAt = Date.now();
326
+ this.showElapsed = opts?.showElapsed ?? false;
327
+ this.accentHex = opts?.colorHex ?? '#818cf8';
328
+ this.render();
329
+ this.timer = setInterval(() => {
330
+ this.frame = (this.frame + 1) % SPINNER_FRAMES.length;
331
+ this.render();
332
+ }, 80);
333
+ }
334
+ update(label) {
335
+ this.label = label;
336
+ if (this.timer)
337
+ this.render();
338
+ }
339
+ isActive() {
340
+ return this.timer !== null;
341
+ }
342
+ render() {
343
+ const cols = process.stdout.columns ?? 80;
344
+ const f = SPINNER_FRAMES[this.frame];
345
+ let suffix = '';
346
+ if (this.showElapsed) {
347
+ const secs = ((Date.now() - this.startedAt) / 1000).toFixed(1);
348
+ suffix = chalk.hex('#475569')(` ${secs}s`);
349
+ }
350
+ const maxLabel = Math.max(cols - 12 - (this.showElapsed ? 7 : 0), 10);
351
+ const clipped = clipVis(stripAnsi(this.label), maxLabel);
352
+ const line = ` ${chalk.hex(this.accentHex)(f)} ${colors.subtext(clipped)}${suffix}`;
353
+ process.stdout.write(`\r\x1b[K${line}`);
354
+ }
355
+ stop(clearLine = true) {
356
+ if (this.timer) {
357
+ clearInterval(this.timer);
358
+ this.timer = null;
359
+ }
360
+ if (clearLine) {
361
+ process.stdout.write('\r\x1b[K');
362
+ }
363
+ }
364
+ }
365
+ // ── Brand banner & welcome cards ────────────────────────────────
23
366
  export function banner() {
24
- console.log(colors.primary.bold(`
25
- ██████╗ ██████╗ █████╗ ██╗ ██╗██╗██╗ ██╗
26
- ██╔══██╗██╔══██╗██╔══██╗██║ ██║██║╚██╗██╔╝
27
- ██║ ██║██████╔╝███████║██║ ██║██║ ╚███╔╝
28
- ██║ ██║██╔══██╗██╔══██║╚██╗ ██╔╝██║ ██╔██╗
29
- ██████╔╝██║ ██║██║ ██║ ╚████╔╝ ██║██╔╝ ██╗
30
- ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═══╝ ╚═╝╚═╝ ╚═╝`));
31
- console.log(colors.primary.bold(' Code') + colors.muted(` v${VERSION} · `) + colors.accent('AI-powered coding assistant'));
32
- console.log(colors.dim(' ─────────────────────────────────────────────\n'));
367
+ const g1 = chalk.hex('#6366f1').bold;
368
+ const g2 = chalk.hex('#7c7ff5').bold;
369
+ const g3 = chalk.hex('#818cf8').bold;
370
+ const g4 = chalk.hex('#a78bfa').bold;
371
+ console.log('');
372
+ console.log(' ' + g1('██████╗ ██████╗ █████╗ ██╗ ██╗██╗██╗ ██╗'));
373
+ console.log(' ' + g2('██╔══██╗██╔══██╗██╔══██╗██║ ██║██║╚██╗██╔╝'));
374
+ console.log(' ' + g3('██║ ██║██████╔╝███████║██║ ██║██║ ╚███╔╝ '));
375
+ console.log(' ' + g3('██║ ██║██╔══██╗██╔══██║╚██╗ ██╔╝██║ ██╔██╗ '));
376
+ console.log(' ' + g4('██████╔╝██║ ██║██║ ██║ ╚████╔╝ ██║██╔╝ ██╗'));
377
+ console.log(' ' + g4('╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═══╝ ╚═╝╚═╝ ╚═╝'));
378
+ console.log(' ' + colors.primary.bold('Code') + colors.muted(` v${VERSION} · `) + colors.subtext('AI coding assistant by TensorSpark'));
379
+ console.log(' ' + colors.dim('─'.repeat(52)) + '\n');
380
+ }
381
+ export function renderWelcomeCard(cwd, meta) {
382
+ const cols = process.stdout.columns ?? 80;
383
+ const B = colors.border;
384
+ const P = colors.primary;
385
+ const A = colors.accent;
386
+ const W = colors.text;
387
+ const S = colors.subtext;
388
+ const M = colors.muted;
389
+ const project = basename(cwd) || cwd;
390
+ const planStr = meta?.plan === 'Plus'
391
+ ? chalk.bgHex('#312e81').hex('#c7d2fe').bold(' PLUS ')
392
+ : chalk.bgHex('#1e293b').hex('#94a3b8')(' FREE ');
393
+ const userStr = meta?.name
394
+ ? `${W(meta.name)}${meta.email ? M(' · ') + S(meta.email) : ''}`
395
+ : M('Not signed in');
396
+ let tokensStr = '';
397
+ if (meta?.usage) {
398
+ const u = meta.usage;
399
+ const { bar, pct } = usageBar(u.tokens_used, u.limit, 14);
400
+ const barPaint = pct >= 80 ? colors.error : pct >= 50 ? colors.warn : colors.success;
401
+ tokensStr = `${barPaint(bar)} ${S(`${fmtNum(u.tokens_used)}/${fmtNum(u.limit)}`)} ${M(`(${formatResetTime(u)})`)}`;
402
+ }
403
+ const cardW = Math.min(Math.max(cols - 4, 44), 96);
404
+ const titleTag = ` ◆ Dravix Code v${VERSION} `;
405
+ const topDashes = Math.max(cardW - 3 - visWidth(titleTag), 2);
406
+ let linesPrinted = 0;
407
+ const out = (s) => { console.log(s); linesPrinted++; };
408
+ out('');
409
+ out(' ' + B('╭─') + P.bold(titleTag) + B('─'.repeat(topDashes) + '╮'));
410
+ if (cardW >= 78) {
411
+ // Two-column hero card
412
+ const leftW = 30;
413
+ const rightW = cardW - leftW - 3; // 3 borders (│ ... │ ... │)
414
+ const g1 = chalk.hex('#6366f1').bold;
415
+ const g2 = chalk.hex('#818cf8').bold;
416
+ const g3 = chalk.hex('#a78bfa').bold;
417
+ const leftLines = [
418
+ ' ' + g1('▛▀▄ ▛▀▖ ▞▀▖ ▌ ▌ ▀ ▀▄▀'),
419
+ ' ' + g2('▌ ▌ ▙▄▘ ▛▀▌ ▐▐ █ █ '),
420
+ ' ' + g3('▀▀ ▌ ▌ ▌ ▌ ▀ ▀ ▀ ▀'),
421
+ '',
422
+ ' ' + S('AI coding assistant'),
423
+ ' ' + M('by TensorSpark'),
424
+ ];
425
+ const rightLines = [
426
+ `${M('User ')} ${clipAnsi(userStr, Math.max(rightW - 9, 10))}`,
427
+ `${M('Plan ')} ${planStr}`,
428
+ ...(tokensStr ? [`${M('Tokens ')} ${clipAnsi(tokensStr, Math.max(rightW - 9, 10))}`] : []),
429
+ `${M('Project')} ${colors.text.bold(clipVis(project, Math.max(rightW - 9, 10)))}`,
430
+ `${M('Path ')} ${M(clipStartVis(cwd, Math.max(rightW - 9, 10)))}`,
431
+ ];
432
+ const rowCount = Math.max(leftLines.length, rightLines.length);
433
+ for (let i = 0; i < rowCount; i++) {
434
+ const l = padVis(leftLines[i] ?? '', leftW);
435
+ const r = padVis(' ' + (rightLines[i] ?? ''), rightW);
436
+ out(' ' + B('│') + l + colors.dim('│') + r + B('│'));
437
+ }
438
+ }
439
+ else {
440
+ // Compact single-column card for narrow terminals
441
+ const innerW = cardW - 4;
442
+ const rows = [
443
+ `${P.bold('Dravix Code')} ${M('· AI coding assistant')}`,
444
+ `${M('User ')} ${clipAnsi(userStr, Math.max(innerW - 8, 8))}`,
445
+ `${M('Plan ')} ${planStr}`,
446
+ ...(tokensStr ? [`${M('Tokens ')} ${clipAnsi(tokensStr, Math.max(innerW - 8, 8))}`] : []),
447
+ `${M('Project')} ${W(clipVis(project, Math.max(innerW - 8, 8)))}`,
448
+ `${M('Path ')} ${M(clipStartVis(cwd, Math.max(innerW - 8, 8)))}`,
449
+ ];
450
+ for (const r of rows) {
451
+ out(' ' + B('│') + ' ' + padVis(r, innerW) + ' ' + B('│'));
452
+ }
453
+ }
454
+ out(' ' + B('╰' + '─'.repeat(cardW - 2) + '╯'));
455
+ const hintLine = A('@') + M(' file ') +
456
+ P('/') + M(' commands ') +
457
+ P('Tab') + M(' path ') +
458
+ P('↑↓') + M(' history ') +
459
+ P('Ctrl+C') + M(' cancel ') +
460
+ P('/help') + M(' help');
461
+ for (const hl of wrapAnsi(hintLine, Math.max(cols - 4, 24), ' ', ' ')) {
462
+ out(hl);
463
+ }
464
+ return linesPrinted;
465
+ }
466
+ export function renderCompactHeader(cwd, meta) {
467
+ const project = basename(cwd) || cwd;
468
+ const cols = process.stdout.columns ?? 80;
469
+ const planBadge = meta?.plan === 'Plus'
470
+ ? chalk.hex('#a78bfa').bold('Plus')
471
+ : colors.muted('Free');
472
+ console.log('');
473
+ console.log(' ' + colors.primary.bold('◆ Dravix Code') + colors.muted(` v${VERSION}`) +
474
+ colors.dim(' │ ') + colors.text(project) +
475
+ colors.dim(' · ') + planBadge);
476
+ console.log(' ' + colors.dim('─'.repeat(Math.min(Math.max(cols - 4, 30), 76))) + '\n');
477
+ }
478
+ export function renderUnifiedDiff(diff, opts) {
479
+ const cols = opts?.cols ?? (process.stdout.columns ?? 80);
480
+ const maxLines = opts?.maxLines ?? 40;
481
+ const maxTextW = Math.max(cols - 14, 20);
482
+ const emit = opts?.writeLine ?? ((s) => {
483
+ process.stdout.write(s + '\n');
484
+ return physRowsOf(s, cols);
485
+ });
486
+ const adds = diff.filter(d => d.kind === 'add').length;
487
+ const removes = diff.filter(d => d.kind === 'remove').length;
488
+ if (adds === 0 && removes === 0)
489
+ return 0;
490
+ let totalRows = 0;
491
+ // Compact summary when change is massive
492
+ if (adds + removes > 45 && !opts?.maxLines) {
493
+ const delta = adds - removes;
494
+ const deltaStr = delta > 0 ? colors.success(`+${delta}`) : delta < 0 ? colors.error(`${delta}`) : '±0';
495
+ totalRows += emit(colors.muted(` ${colors.success(`+${adds}`)} added, ${colors.error(`-${removes}`)} removed (${deltaStr} net)`));
496
+ return totalRows;
497
+ }
498
+ const CONTEXT = 2;
499
+ const show = new Uint8Array(diff.length);
500
+ for (let i = 0; i < diff.length; i++) {
501
+ if (diff[i].kind !== 'context') {
502
+ for (let c = Math.max(0, i - CONTEXT); c <= Math.min(diff.length - 1, i + CONTEXT); c++) {
503
+ show[c] = 1;
504
+ }
505
+ }
506
+ }
507
+ const hunks = [];
508
+ let curHunk = [];
509
+ let lastIdx = -1;
510
+ for (let i = 0; i < diff.length; i++) {
511
+ if (!show[i])
512
+ continue;
513
+ if (lastIdx >= 0 && i > lastIdx + 1) {
514
+ hunks.push(curHunk);
515
+ curHunk = [];
516
+ }
517
+ lastIdx = i;
518
+ curHunk.push(diff[i]);
519
+ }
520
+ if (curHunk.length > 0)
521
+ hunks.push(curHunk);
522
+ const barW = Math.max(cols - 3, 24);
523
+ const renderLine = (line) => {
524
+ const num = String(line.lineNo).padStart(5, ' ');
525
+ const clipped = clipVis(line.text.replace(/\t/g, ' '), maxTextW);
526
+ if (line.kind === 'remove') {
527
+ const inner = padVis(` ${num} - ${clipped}`, barW);
528
+ totalRows += emit(' ' + chalk.hex('#ef4444')('▌') + chalk.bgHex('#271014').hex('#fecaca')(inner));
529
+ }
530
+ else if (line.kind === 'add') {
531
+ const inner = padVis(` ${num} + ${clipped}`, barW);
532
+ totalRows += emit(' ' + chalk.hex('#10b981')('▌') + chalk.bgHex('#072318').hex('#bbf7d0')(inner));
533
+ }
534
+ else {
535
+ totalRows += emit(colors.muted(` ${num} `) + colors.dim(clipped));
536
+ }
537
+ };
538
+ let shownChanges = 0;
539
+ for (let h = 0; h < hunks.length; h++) {
540
+ if (shownChanges >= maxLines)
541
+ break;
542
+ if (h > 0) {
543
+ totalRows += emit(colors.dim(' ···'));
544
+ }
545
+ const hunk = hunks[h];
546
+ const before = [];
547
+ const hRemoves = [];
548
+ const hAdds = [];
549
+ let pendingCtx = [];
550
+ let seenChange = false;
551
+ for (const line of hunk) {
552
+ if (line.kind === 'context') {
553
+ if (!seenChange)
554
+ before.push(line);
555
+ else
556
+ pendingCtx.push(line);
557
+ }
558
+ else {
559
+ seenChange = true;
560
+ pendingCtx = [];
561
+ if (line.kind === 'remove')
562
+ hRemoves.push(line);
563
+ else
564
+ hAdds.push(line);
565
+ }
566
+ }
567
+ for (const l of before)
568
+ renderLine(l);
569
+ for (const l of hRemoves) {
570
+ if (shownChanges >= maxLines)
571
+ break;
572
+ renderLine(l);
573
+ shownChanges++;
574
+ }
575
+ for (const l of hAdds) {
576
+ if (shownChanges >= maxLines)
577
+ break;
578
+ renderLine(l);
579
+ shownChanges++;
580
+ }
581
+ for (const l of pendingCtx)
582
+ renderLine(l);
583
+ }
584
+ const totalChanges = adds + removes;
585
+ if (totalChanges > shownChanges) {
586
+ totalRows += emit(colors.muted(` … ${totalChanges - shownChanges} more changed line(s)`));
587
+ }
588
+ return totalRows;
33
589
  }
34
590
  export function printAI(chunk) {
35
591
  process.stdout.write(colors.ai(chunk));
36
592
  }
37
593
  export function printOpResult(result) {
38
594
  if (result.type === 'created') {
39
- console.log(colors.success(' ✓') + colors.text(' Created ') + colors.muted(result.path ?? ''));
595
+ console.log(' ' + colors.success('✓') + colors.subtext(' Created ') + colors.text(result.path ?? ''));
40
596
  }
41
597
  else if (result.type === 'skipped') {
42
- console.log(colors.muted(' ·') + colors.text(' Unchanged ') + colors.muted(result.path ?? ''));
598
+ console.log(' ' + colors.muted('·') + colors.muted(' Unchanged ') + colors.muted(result.path ?? ''));
43
599
  }
44
600
  else if (result.type === 'folder_created') {
45
- console.log(colors.success(' ✓') + colors.text(' Created dir ') + colors.muted(result.path ?? ''));
601
+ console.log(' ' + colors.success('✓') + colors.subtext(' Created dir ') + colors.text(result.path ?? ''));
46
602
  }
47
603
  else if (result.type === 'deleted') {
48
- console.log(colors.error(' ✗') + colors.text(' Deleted ') + colors.muted(result.path ?? ''));
604
+ console.log(' ' + colors.error('✗') + colors.subtext(' Deleted ') + colors.muted(result.path ?? ''));
49
605
  }
50
606
  else if (result.type === 'modified') {
51
607
  const diff = result.diff ?? [];
52
608
  const adds = diff.filter(d => d.kind === 'add').length;
53
609
  const removes = diff.filter(d => d.kind === 'remove').length;
54
- const cols = process.stdout.columns ?? 80;
55
- const displayAdds = adds > 0 ? adds : (result.linesAfter ?? 0) - Math.min(result.linesBefore ?? 0, result.linesAfter ?? 0);
56
- const displayRemoves = removes > 0 ? removes : (result.linesBefore ?? 0) - Math.min(result.linesBefore ?? 0, result.linesAfter ?? 0);
610
+ const displayAdds = adds > 0 ? adds : Math.max(0, (result.linesAfter ?? 0) - Math.min(result.linesBefore ?? 0, result.linesAfter ?? 0));
611
+ const displayRemoves = removes > 0 ? removes : Math.max(0, (result.linesBefore ?? 0) - Math.min(result.linesBefore ?? 0, result.linesAfter ?? 0));
57
612
  const statStr = [
58
- (adds > 0 || result.linesAfter !== undefined) && displayAdds > 0 ? colors.success.bold(`+${displayAdds}`) : '',
59
- (removes > 0 || result.linesBefore !== undefined) && displayRemoves > 0 ? colors.error.bold(`-${displayRemoves}`) : '',
613
+ displayAdds > 0 ? colors.success.bold(`+${displayAdds}`) : '',
614
+ displayRemoves > 0 ? colors.error.bold(`-${displayRemoves}`) : '',
60
615
  ].filter(Boolean).join(' ');
61
- const pathStr = colors.text(result.path ?? '');
62
- const iconStr = colors.warn(' ~');
63
- const labelStr = colors.subtext(' Updated ');
64
- const statPad = statStr ? ' ' + statStr : '';
65
- console.log(iconStr + labelStr + pathStr + statPad);
66
- const totalChanges = displayAdds + displayRemoves;
67
- if (totalChanges > 30) {
68
- if (result.linesBefore !== undefined && result.linesAfter !== undefined) {
69
- const delta = result.linesAfter - result.linesBefore;
70
- const deltaStr = delta > 0 ? colors.success(`+${delta}`) : delta < 0 ? colors.error(`${delta}`) : '=0';
71
- console.log(colors.muted(` ${result.linesBefore} → ${result.linesAfter} lines (${deltaStr})`));
72
- }
73
- else {
74
- console.log(colors.muted(` ${totalChanges} lines changed`));
75
- }
76
- console.log(colors.muted(` ${colors.muted('···')} ${colors.success(`+${displayAdds}`)} added, ${colors.error(`-${displayRemoves}`)} removed ${colors.muted('(more lines not shown)')}`));
77
- return;
616
+ console.log(' ' + colors.warn('~') + colors.subtext(' Updated ') +
617
+ colors.text(result.path ?? '') + (statStr ? ' ' + statStr : ''));
618
+ if (diff.length > 0 && (adds > 0 || removes > 0)) {
619
+ renderUnifiedDiff(diff, { maxLines: 36 });
78
620
  }
79
- if (diff.length === 0 && result.linesBefore !== undefined) {
621
+ else if (result.linesBefore !== undefined) {
80
622
  const delta = (result.linesAfter ?? 0) - (result.linesBefore ?? 0);
81
623
  const deltaStr = delta > 0 ? colors.success(`+${delta} lines`) : delta < 0 ? colors.error(`${delta} lines`) : 'no line count change';
82
624
  console.log(colors.muted(` ${result.linesBefore} → ${result.linesAfter} lines (${deltaStr})`));
83
- return;
84
625
  }
85
- if (diff.length === 0 || (adds === 0 && removes === 0)) {
626
+ else {
86
627
  console.log(colors.muted(' (formatting / whitespace change)'));
87
- return;
88
- }
89
- const CONTEXT = 2;
90
- const MAX_SIDE = 20;
91
- const show = new Uint8Array(diff.length);
92
- for (let i = 0; i < diff.length; i++) {
93
- if (diff[i].kind !== 'context') {
94
- for (let c = Math.max(0, i - CONTEXT); c <= Math.min(diff.length - 1, i + CONTEXT); c++)
95
- show[c] = 1;
96
- }
97
- }
98
- const maxTextW = cols - 12;
99
- const clip = (t) => t.length > maxTextW ? t.slice(0, maxTextW - 1) + '…' : t;
100
- const renderLine = (line) => {
101
- const num = String(line.lineNo).padStart(5, ' ');
102
- if (line.kind === 'remove') {
103
- const content = ` ${num} ${colors.error('-')} ${clip(line.text)}`;
104
- console.log(' ' + colors.error('▌') + chalk.bgHex('#1c0a0a')(content.padEnd(cols - 3)));
105
- }
106
- else if (line.kind === 'add') {
107
- const content = ` ${num} ${colors.success('+')} ${clip(line.text)}`;
108
- console.log(' ' + colors.success('▌') + chalk.bgHex('#021a0e')(content.padEnd(cols - 3)));
109
- }
110
- else {
111
- console.log(colors.dim(` ${num} ${clip(line.text)}`));
112
- }
113
- };
114
- const hunks = [];
115
- let curHunk = [];
116
- let lastIdx = -1;
117
- for (let i = 0; i < diff.length; i++) {
118
- if (!show[i])
119
- continue;
120
- if (lastIdx >= 0 && i > lastIdx + 1) {
121
- hunks.push(curHunk);
122
- curHunk = [];
123
- }
124
- lastIdx = i;
125
- curHunk.push(diff[i]);
126
- }
127
- if (curHunk.length > 0)
128
- hunks.push(curHunk);
129
- let shownRemoves = 0;
130
- let shownAdds = 0;
131
- for (let h = 0; h < hunks.length; h++) {
132
- if (shownRemoves >= MAX_SIDE && shownAdds >= MAX_SIDE)
133
- break;
134
- if (h > 0)
135
- console.log(colors.dim(' ╌╌╌'));
136
- const hunk = hunks[h];
137
- const before = [];
138
- const hRemoves = [];
139
- const hAdds = [];
140
- let pendingCtx = [];
141
- let seenChange = false;
142
- for (const line of hunk) {
143
- if (line.kind === 'context') {
144
- if (!seenChange)
145
- before.push(line);
146
- else
147
- pendingCtx.push(line);
148
- }
149
- else {
150
- seenChange = true;
151
- pendingCtx = [];
152
- if (line.kind === 'remove')
153
- hRemoves.push(line);
154
- else
155
- hAdds.push(line);
156
- }
157
- }
158
- for (const l of before)
159
- renderLine(l);
160
- for (const l of hRemoves) {
161
- if (shownRemoves >= MAX_SIDE)
162
- break;
163
- renderLine(l);
164
- shownRemoves++;
165
- }
166
- for (const l of hAdds) {
167
- if (shownAdds >= MAX_SIDE)
168
- break;
169
- renderLine(l);
170
- shownAdds++;
171
- }
172
- for (const l of pendingCtx)
173
- renderLine(l);
174
- }
175
- const hiddenRemoves = removes - shownRemoves;
176
- const hiddenAdds = adds - shownAdds;
177
- if (hiddenRemoves > 0 || hiddenAdds > 0) {
178
- const parts = [
179
- hiddenRemoves > 0 ? colors.error(`-${hiddenRemoves}`) : '',
180
- hiddenAdds > 0 ? colors.success(`+${hiddenAdds}`) : '',
181
- ].filter(Boolean).join(' ');
182
- console.log(colors.muted(` … ${parts} more lines not shown`));
183
628
  }
184
629
  }
185
630
  else if (result.type === 'run') {
186
631
  const cmd = result.message ?? '';
187
632
  const cols = process.stdout.columns ?? 80;
188
- console.log(colors.primary(' $') + ' ' + colors.text(cmd));
633
+ console.log(' ' + colors.primary('$') + ' ' + colors.text.bold(clipVis(cmd, Math.max(cols - 8, 24))));
189
634
  if (result.output) {
190
- const outLines = result.output.split('\n').filter(l => l.trim()).slice(0, 20);
191
- if (outLines.length > 0) {
192
- const maxW = Math.min(Math.max(...outLines.map(l => l.length), 10) + 2, cols - 8);
193
- console.log(colors.dim(' ╭' + '─'.repeat(maxW)));
194
- for (const line of outLines) {
195
- const clipped = line.length > maxW - 2 ? line.slice(0, maxW - 3) + '…' : line;
196
- console.log(colors.dim(' │') + ' ' + colors.subtext(clipped));
635
+ const outLines = result.output.split('\n').filter(l => l.trim());
636
+ const shown = outLines.slice(0, 18);
637
+ if (shown.length > 0) {
638
+ const maxW = Math.min(Math.max(...shown.map(l => visWidth(l)), 14) + 2, cols - 8);
639
+ console.log(' ' + colors.dim('╭' + '─'.repeat(maxW)));
640
+ for (const line of shown) {
641
+ const clipped = clipVis(line, Math.max(maxW - 2, 10));
642
+ console.log(' ' + colors.dim('│') + ' ' + colors.subtext(clipped));
643
+ }
644
+ if (outLines.length > shown.length) {
645
+ console.log(' ' + colors.dim('│') + ' ' + colors.muted(`… ${outLines.length - shown.length} more line(s)`));
197
646
  }
198
- console.log(colors.dim(' ╰' + '─'.repeat(maxW)));
647
+ console.log(' ' + colors.dim('╰' + '─'.repeat(maxW)));
199
648
  }
200
649
  }
201
650
  }
@@ -204,62 +653,73 @@ export function printOpResult(result) {
204
653
  const cols = process.stdout.columns ?? 80;
205
654
  const errLines = msg.split('\n').filter(l => l.trim());
206
655
  if (errLines.length <= 1) {
207
- console.log(colors.error(' ✗') + colors.text(' ' + msg));
656
+ for (const wl of wrapAnsi(colors.text(msg), cols - 6, ' ' + colors.error('✗') + ' ', ' ')) {
657
+ console.log(wl);
658
+ }
208
659
  }
209
660
  else {
210
- console.log(colors.error(' ✗') + colors.text(' ' + errLines[0]));
211
- const rest = errLines.slice(1);
212
- const maxW = Math.min(Math.max(...rest.map(l => l.length), 10) + 2, cols - 8);
213
- console.log(chalk.hex('#450a0a')(' ╭' + '─'.repeat(maxW)));
661
+ console.log(' ' + colors.error('✗') + ' ' + colors.text(clipVis(errLines[0], cols - 8)));
662
+ const rest = errLines.slice(1, 15);
663
+ const maxW = Math.min(Math.max(...rest.map(l => visWidth(l)), 14) + 2, cols - 8);
664
+ const redBar = chalk.hex('#7f1d1d');
665
+ console.log(' ' + redBar('╭' + '─'.repeat(maxW)));
214
666
  for (const line of rest) {
215
- const clipped = line.length > maxW - 2 ? line.slice(0, maxW - 3) + '…' : line;
216
- console.log(chalk.hex('#450a0a')(' │') + ' ' + colors.error(clipped));
667
+ console.log(' ' + redBar('│') + ' ' + colors.error(clipVis(line, Math.max(maxW - 2, 10))));
217
668
  }
218
- console.log(chalk.hex('#450a0a')(' ╰' + '─'.repeat(maxW)));
669
+ console.log(' ' + redBar('╰' + '─'.repeat(maxW)));
219
670
  }
220
671
  }
221
672
  }
222
673
  export function printError(msg) {
223
- console.log('\n' + colors.error(' ✗ ') + colors.text(msg) + '\n');
674
+ const cols = process.stdout.columns ?? 80;
675
+ console.log('');
676
+ for (const l of wrapAnsi(colors.text(msg), cols - 4, ' ' + colors.error('✗') + ' ', ' ')) {
677
+ console.log(l);
678
+ }
679
+ console.log('');
224
680
  }
225
681
  export function printInfo(msg) {
226
- console.log(colors.muted(' ' + msg));
682
+ const cols = process.stdout.columns ?? 80;
683
+ for (const l of wrapAnsi(colors.muted(msg), cols - 4, ' ', ' ')) {
684
+ console.log(l);
685
+ }
227
686
  }
228
687
  export function printHelp() {
229
688
  const C = colors.primary;
230
689
  const DIM = colors.muted;
231
690
  const W = colors.text;
232
691
  const cols = process.stdout.columns ?? 80;
233
- const line = DIM(' ' + '─'.repeat(Math.min(cols - 4, 60)));
692
+ const rule = colors.dim(' ' + '─'.repeat(Math.min(Math.max(cols - 4, 36), 64)));
234
693
  console.log(`
235
694
  ${colors.primary.bold(' Commands')}
236
- ${line}
695
+ ${rule}
237
696
  ${C('/files')} ${W('List project files and git status')}
238
697
  ${C('/resume')} ${W('Resume a saved conversation')}
239
698
  ${C('/retry')} ${W('Resend your last message')}
240
699
  ${C('/copy')} ${W('Copy last AI response to clipboard')}
241
700
  ${C('/model')} ${W('Show current AI model')}
242
- ${C('/clear')} ${W('Clear screen')}
701
+ ${C('/clear')} ${W('Clear chat view')}
243
702
  ${C('/whoami')} ${W('Show signed-in user')}
244
703
  ${C('/logout')} ${W('Sign out from Dravix Code')}
245
704
  ${C('/help')} ${W('Show this help')}
246
705
  ${C('/exit')} ${W('Exit Dravix Code')}
247
706
 
248
- ${colors.primary.bold(' Keyboard shortcuts')}
249
- ${line}
707
+ ${colors.primary.bold(' Input & Navigation')}
708
+ ${rule}
709
+ ${C('← →')} ${W('Move cursor inside input')}
710
+ ${C('↑ ↓')} ${W('Browse prompt history / navigate menus')}
711
+ ${C('Home / End')} ${W('Jump to start or end of input')}
712
+ ${C('Ctrl+W / Ctrl+U')} ${W('Delete word / clear line')}
250
713
  ${C('Tab')} ${W('Path autocomplete')}
251
- ${C('@')} ${W('File picker — attach file')}
252
- ${C('$')} ${W('Run subagent')}
253
- ${C('Ctrl+C')} ${W('Cancel AI response')}
254
- ${C('Ctrl+L')} ${W('Clear screen')}
255
- ${C('↑ ↓')} ${W('Navigate items')}
256
- ${C('Esc')} ${W('Close picker')}
714
+ ${C('@')} ${W('Attach file from workspace')}
715
+ ${C('/')} ${W('Open slash command picker')}
716
+ ${C('Ctrl+L')} ${W('Clear screen & redraw composer')}
717
+ ${C('Ctrl+C')} ${W('Clear input / cancel AI stream / 2× exit')}
257
718
 
258
719
  ${colors.primary.bold(' Tips')}
259
- ${line}
260
- ${colors.muted('·')} ${W('Start typing while AI responds — your message queues automatically')}
261
- ${colors.muted('·')} ${W('Mention a filename to auto-inject its content')}
262
- ${colors.muted('·')} ${W('Approve changes:')} ${C('y')} ${DIM('yes')} ${C('a')} ${DIM('always')} ${C('n')} ${DIM('no')}
263
- ${colors.muted('·')} ${W('Use /resume to continue a previous conversation')}
720
+ ${rule}
721
+ ${DIM('·')} ${W('Mention a filename (e.g. src/app.ts) to auto-inject its content')}
722
+ ${DIM('·')} ${W('Paste multi-line text directly into the composer')}
723
+ ${DIM('·')} ${W('Approve changes:')} ${C('y')} ${DIM('yes')} ${C('a')} ${DIM('always')} ${C('n')} ${DIM('no')}
264
724
  `);
265
725
  }