sapper-iq 1.1.29 → 1.1.31

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,1215 @@
1
+ #!/usr/bin/env node
2
+ import ollama from 'ollama';
3
+ import fs from 'fs';
4
+ import { spawn } from 'child_process';
5
+ import chalk from 'chalk';
6
+ import ora from 'ora';
7
+ import readline from 'readline';
8
+ import { fileURLToPath } from 'url';
9
+ import { dirname, join } from 'path';
10
+ import { marked } from 'marked';
11
+ import TerminalRenderer from 'marked-terminal';
12
+
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = dirname(__filename);
15
+
16
+ // Prevent process from exiting on unhandled errors
17
+ process.on('uncaughtException', (err) => {
18
+ console.error(chalk.red('\n❌ Uncaught exception:'), err.message);
19
+ });
20
+ process.on('unhandledRejection', (reason) => {
21
+ console.error(chalk.red('\n❌ Unhandled rejection:'), reason);
22
+ });
23
+
24
+ // Prevent Ctrl+C from killing the whole process
25
+ let ctrlCCount = 0;
26
+ process.on('SIGINT', () => {
27
+ ctrlCCount++;
28
+ if (ctrlCCount >= 2) {
29
+ console.log(chalk.red('\nForce quitting...'));
30
+ process.exit(1);
31
+ }
32
+ // Set flag to abort current stream
33
+ abortStream = true;
34
+
35
+ // Clear current line and move to new one - stops ghost output
36
+ process.stdout.clearLine(0);
37
+ process.stdout.cursorTo(0);
38
+ console.log(chalk.yellow('\n⏹️ Stopping response... (Ctrl+C again to force quit)'));
39
+
40
+ // Reset terminal immediately
41
+ resetTerminal();
42
+ setTimeout(() => { ctrlCCount = 0; }, 2000); // Reset after 2 seconds
43
+ });
44
+
45
+ // Reset terminal state - fixes "ghost input" after shell commands or AI streaming
46
+ function resetTerminal() {
47
+ if (process.stdin.isTTY) {
48
+ try {
49
+ process.stdin.setRawMode(false); // Disable raw mode
50
+ process.stdin.pause(); // Pause the stream
51
+ process.stdin.resume(); // Resume to clear buffers
52
+ } catch (e) {
53
+ // Ignore errors if terminal is in weird state
54
+ }
55
+ }
56
+ }
57
+
58
+ // Initialize versioning
59
+ let CURRENT_VERSION = "1.1.0";
60
+ try {
61
+ const pkg = JSON.parse(fs.readFileSync(join(__dirname, 'package.json'), 'utf8'));
62
+ CURRENT_VERSION = pkg.version;
63
+ } catch (e) {}
64
+
65
+ const spinner = ora();
66
+ const CONTEXT_FILE = '.sapper_context.json';
67
+ const EMBEDDINGS_FILE = '.sapper_embeddings.json';
68
+
69
+ // ═══════════════════════════════════════════════════════════════
70
+ // EMBEDDINGS & SEMANTIC SEARCH
71
+ // ═══════════════════════════════════════════════════════════════
72
+
73
+ // Load or create embeddings store
74
+ function loadEmbeddings() {
75
+ try {
76
+ if (fs.existsSync(EMBEDDINGS_FILE)) {
77
+ return JSON.parse(fs.readFileSync(EMBEDDINGS_FILE, 'utf8'));
78
+ }
79
+ } catch (e) {}
80
+ return { chunks: [] }; // { chunks: [{ text, embedding, timestamp }] }
81
+ }
82
+
83
+ function saveEmbeddings(embeddings) {
84
+ fs.writeFileSync(EMBEDDINGS_FILE, JSON.stringify(embeddings, null, 2));
85
+ }
86
+
87
+ // Get embedding from Ollama (returns null silently if model not available)
88
+ async function getEmbedding(text, model = 'nomic-embed-text') {
89
+ try {
90
+ const response = await ollama.embeddings({ model, prompt: text });
91
+ return response.embedding;
92
+ } catch (e) {
93
+ // Silently return null - caller handles missing embeddings
94
+ return null;
95
+ }
96
+ }
97
+
98
+ // Cosine similarity between two vectors
99
+ function cosineSimilarity(a, b) {
100
+ if (!a || !b || a.length !== b.length) return 0;
101
+ let dotProduct = 0, normA = 0, normB = 0;
102
+ for (let i = 0; i < a.length; i++) {
103
+ dotProduct += a[i] * b[i];
104
+ normA += a[i] * a[i];
105
+ normB += b[i] * b[i];
106
+ }
107
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
108
+ }
109
+
110
+ // Find most relevant chunks for a query
111
+ async function findRelevantContext(query, embeddings, topK = 3) {
112
+ const queryEmbedding = await getEmbedding(query);
113
+ if (!queryEmbedding || embeddings.chunks.length === 0) return [];
114
+
115
+ const scored = embeddings.chunks.map(chunk => ({
116
+ ...chunk,
117
+ score: cosineSimilarity(queryEmbedding, chunk.embedding)
118
+ }));
119
+
120
+ scored.sort((a, b) => b.score - a.score);
121
+ return scored.slice(0, topK).filter(c => c.score > 0.5); // Only return if similarity > 0.5
122
+ }
123
+
124
+ // Add text to embeddings store
125
+ async function addToEmbeddings(text, embeddings) {
126
+ const embedding = await getEmbedding(text);
127
+ if (embedding) {
128
+ embeddings.chunks.push({
129
+ text: text.substring(0, 2000), // Limit stored text
130
+ embedding,
131
+ timestamp: Date.now()
132
+ });
133
+ // Keep only last 100 chunks
134
+ if (embeddings.chunks.length > 100) {
135
+ embeddings.chunks = embeddings.chunks.slice(-100);
136
+ }
137
+ saveEmbeddings(embeddings);
138
+ }
139
+ }
140
+
141
+ // ═══════════════════════════════════════════════════════════════
142
+ // FANCY UI HELPERS
143
+ // ═══════════════════════════════════════════════════════════════
144
+
145
+ const BANNER = `
146
+ ${chalk.cyan(' ███████╗ █████╗ ██████╗ ██████╗ ███████╗██████╗ ')}
147
+ ${chalk.cyan(' ██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗')}
148
+ ${chalk.cyan(' ███████╗███████║██████╔╝██████╔╝█████╗ ██████╔╝')}
149
+ ${chalk.cyan(' ╚════██║██╔══██║██╔═══╝ ██╔═══╝ ██╔══╝ ██╔══██╗')}
150
+ ${chalk.cyan(' ███████║██║ ██║██║ ██║ ███████╗██║ ██║')}
151
+ ${chalk.cyan(' ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝')}
152
+ `;
153
+
154
+ function box(content, title = '', color = 'cyan') {
155
+ const lines = content.split('\n');
156
+ const maxLen = Math.max(...lines.map(l => l.length), title.length + 4);
157
+ const colorFn = chalk[color] || chalk.cyan;
158
+
159
+ let result = colorFn('╭' + (title ? `─ ${title} ` : '') + '─'.repeat(maxLen - title.length - (title ? 3 : 0)) + '╮') + '\n';
160
+ for (const line of lines) {
161
+ result += colorFn('│') + ' ' + line.padEnd(maxLen) + ' ' + colorFn('│') + '\n';
162
+ }
163
+ result += colorFn('╰' + '─'.repeat(maxLen + 2) + '╯');
164
+ return result;
165
+ }
166
+
167
+ function divider(char = '─', color = 'gray') {
168
+ const width = process.stdout.columns || 60;
169
+ return chalk[color](char.repeat(Math.min(width, 60)));
170
+ }
171
+
172
+ function statusBadge(text, type = 'info') {
173
+ const badges = {
174
+ info: chalk.bgCyan.black(` ${text} `),
175
+ success: chalk.bgGreen.black(` ${text} `),
176
+ warning: chalk.bgYellow.black(` ${text} `),
177
+ error: chalk.bgRed.white(` ${text} `),
178
+ action: chalk.bgMagenta.white(` ${text} `)
179
+ };
180
+ return badges[type] || badges.info;
181
+ }
182
+
183
+ // Configure marked with terminal renderer
184
+ marked.setOptions({
185
+ renderer: new TerminalRenderer({
186
+ code: chalk.cyan,
187
+ blockquote: chalk.gray.italic,
188
+ html: chalk.gray,
189
+ heading: chalk.bold.cyan,
190
+ firstHeading: chalk.bold.cyan,
191
+ hr: chalk.gray('─'.repeat(40)),
192
+ listitem: chalk.yellow('• ') + '%s',
193
+ table: chalk.white,
194
+ paragraph: chalk.white,
195
+ strong: chalk.bold.white,
196
+ em: chalk.italic,
197
+ codespan: chalk.cyan,
198
+ del: chalk.strikethrough,
199
+ link: chalk.underline.blue,
200
+ href: chalk.gray
201
+ })
202
+ });
203
+
204
+ // Render markdown to terminal
205
+ function renderMarkdown(text) {
206
+ try {
207
+ return marked(text).trim();
208
+ } catch (e) {
209
+ return text; // Fallback to raw text
210
+ }
211
+ }
212
+
213
+ let stepMode = false;
214
+ let debugMode = false; // Toggle with /debug command
215
+ let abortStream = false; // Flag to interrupt AI response
216
+ let rl = readline.createInterface({
217
+ input: process.stdin,
218
+ output: process.stdout,
219
+ terminal: true,
220
+ historySize: 100
221
+ });
222
+
223
+ function recreateReadline() {
224
+ if (rl) rl.close();
225
+ rl = readline.createInterface({
226
+ input: process.stdin,
227
+ output: process.stdout,
228
+ terminal: true,
229
+ historySize: 100
230
+ });
231
+ // Force resume stdin to keep process alive
232
+ process.stdin.resume();
233
+ }
234
+
235
+ async function safeQuestion(query) {
236
+ resetTerminal(); // Clear terminal state before asking
237
+ if (rl.closed) recreateReadline();
238
+
239
+ return new Promise((resolve) => {
240
+ rl.question(query, (answer) => {
241
+ resolve(answer ? answer.trim() : '');
242
+ });
243
+ });
244
+ }
245
+
246
+ // Directories to ignore when listing files
247
+ const IGNORE_DIRS = new Set([
248
+ 'node_modules', '.git', '.svn', '.hg', 'dist', 'build',
249
+ '.next', '.nuxt', '__pycache__', '.cache', 'coverage',
250
+ '.idea', '.vscode', 'vendor', 'target', '.gradle'
251
+ ]);
252
+
253
+ // File extensions to include when scanning codebase
254
+ const CODE_EXTENSIONS = new Set([
255
+ '.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.go', '.rs', '.rb', '.php',
256
+ '.c', '.cpp', '.h', '.hpp', '.cs', '.swift', '.kt', '.scala', '.vue', '.svelte',
257
+ '.css', '.scss', '.sass', '.less', '.html', '.htm', '.json', '.yaml', '.yml',
258
+ '.toml', '.xml', '.md', '.txt', '.sh', '.bash', '.zsh', '.sql', '.graphql',
259
+ '.env.example', '.gitignore', '.dockerignore', 'Dockerfile', 'Makefile',
260
+ '.prisma', '.proto'
261
+ ]);
262
+
263
+ // Max file size to include (skip large files like bundled/minified)
264
+ const MAX_FILE_SIZE = 100000; // 100KB per file
265
+ const MAX_TOTAL_SCAN_SIZE = 1000000; // 1000KB total scan limit
266
+
267
+ // Scan entire codebase and return summary
268
+ function scanCodebase(dir = '.', depth = 0, maxDepth = 5) {
269
+ if (depth > maxDepth) return { files: [], totalSize: 0 };
270
+
271
+ let files = [];
272
+ let totalSize = 0;
273
+
274
+ try {
275
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
276
+
277
+ for (const entry of entries) {
278
+ const fullPath = dir === '.' ? entry.name : `${dir}/${entry.name}`;
279
+
280
+ // Skip ignored directories
281
+ if (entry.isDirectory()) {
282
+ if (IGNORE_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
283
+ const subResult = scanCodebase(fullPath, depth + 1, maxDepth);
284
+ files = files.concat(subResult.files);
285
+ totalSize += subResult.totalSize;
286
+ } else {
287
+ // Check if file should be included
288
+ const ext = entry.name.includes('.') ? '.' + entry.name.split('.').pop() : entry.name;
289
+ const isCodeFile = CODE_EXTENSIONS.has(ext.toLowerCase()) || CODE_EXTENSIONS.has(entry.name);
290
+
291
+ if (!isCodeFile) continue;
292
+
293
+ try {
294
+ const stats = fs.statSync(fullPath);
295
+ if (stats.size > MAX_FILE_SIZE) {
296
+ files.push({ path: fullPath, size: stats.size, skipped: true, reason: 'too large' });
297
+ continue;
298
+ }
299
+ if (totalSize + stats.size > MAX_TOTAL_SCAN_SIZE) {
300
+ files.push({ path: fullPath, size: stats.size, skipped: true, reason: 'total limit reached' });
301
+ continue;
302
+ }
303
+
304
+ const content = fs.readFileSync(fullPath, 'utf8');
305
+ files.push({ path: fullPath, size: stats.size, content });
306
+ totalSize += stats.size;
307
+ } catch (e) {
308
+ files.push({ path: fullPath, skipped: true, reason: e.message });
309
+ }
310
+ }
311
+ }
312
+ } catch (e) {
313
+ // Directory not readable
314
+ }
315
+
316
+ return { files, totalSize };
317
+ }
318
+
319
+ // Scan directory for files (for @ file picker)
320
+ function getFilesForPicker(dir = '.', prefix = '', maxFiles = 50) {
321
+ let files = [];
322
+ try {
323
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
324
+ for (const entry of entries) {
325
+ if (files.length >= maxFiles) break;
326
+ if (IGNORE_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
327
+
328
+ const fullPath = prefix ? `${prefix}/${entry.name}` : entry.name;
329
+
330
+ if (entry.isDirectory()) {
331
+ files.push({ path: fullPath + '/', isDir: true });
332
+ // Recurse one level for common structures
333
+ const subFiles = getFilesForPicker(`${dir}/${entry.name}`, fullPath, 20);
334
+ files = files.concat(subFiles.slice(0, 15)); // Limit subdirectory files
335
+ } else {
336
+ const ext = entry.name.includes('.') ? '.' + entry.name.split('.').pop() : '';
337
+ if (CODE_EXTENSIONS.has(ext.toLowerCase()) || CODE_EXTENSIONS.has(entry.name)) {
338
+ try {
339
+ const stats = fs.statSync(`${dir}/${entry.name}`);
340
+ files.push({ path: fullPath, isDir: false, size: stats.size });
341
+ } catch (e) {
342
+ files.push({ path: fullPath, isDir: false, size: 0 });
343
+ }
344
+ }
345
+ }
346
+ }
347
+ } catch (e) {}
348
+ return files.slice(0, maxFiles);
349
+ }
350
+
351
+ // Interactive file picker with arrow keys
352
+ async function pickFiles() {
353
+ const files = getFilesForPicker('.', '', 50).filter(f => !f.isDir);
354
+
355
+ if (files.length === 0) {
356
+ console.log(chalk.yellow('No code files found in current directory.'));
357
+ return [];
358
+ }
359
+
360
+ const selected = new Set();
361
+ let cursor = 0;
362
+ const pageSize = Math.min(15, process.stdout.rows - 10 || 15);
363
+
364
+ // Enable raw mode for key capture
365
+ if (process.stdin.isTTY) {
366
+ process.stdin.setRawMode(true);
367
+ }
368
+ process.stdin.resume();
369
+
370
+ const renderList = () => {
371
+ // Clear screen and move cursor to top
372
+ console.clear();
373
+ console.log(box(
374
+ `${chalk.cyan('↑↓')} Navigate ${chalk.cyan('Space')} Toggle ${chalk.cyan('a')} All ${chalk.cyan('Enter')} Confirm ${chalk.cyan('q/Esc')} Cancel`,
375
+ '📎 Select Files', 'cyan'
376
+ ));
377
+ console.log();
378
+
379
+ // Calculate visible range (pagination)
380
+ const startIdx = Math.max(0, Math.min(cursor - Math.floor(pageSize / 2), files.length - pageSize));
381
+ const endIdx = Math.min(startIdx + pageSize, files.length);
382
+
383
+ // Show scroll indicator if needed
384
+ if (startIdx > 0) {
385
+ console.log(chalk.gray(' ↑ more files above...'));
386
+ }
387
+
388
+ for (let i = startIdx; i < endIdx; i++) {
389
+ const file = files[i];
390
+ const isSelected = selected.has(i);
391
+ const isCursor = i === cursor;
392
+
393
+ const checkbox = isSelected ? chalk.green('◉') : chalk.gray('○');
394
+ const prefix = isCursor ? chalk.cyan('▸ ') : ' ';
395
+ const name = isCursor ? chalk.cyan.bold(file.path) : chalk.white(file.path);
396
+ const size = file.size ? chalk.gray(` (${Math.round(file.size/1024)}KB)`) : '';
397
+
398
+ console.log(`${prefix}${checkbox} ${name}${size}`);
399
+ }
400
+
401
+ if (endIdx < files.length) {
402
+ console.log(chalk.gray(' ↓ more files below...'));
403
+ }
404
+
405
+ console.log();
406
+ console.log(chalk.gray(` Selected: ${selected.size} file${selected.size !== 1 ? 's' : ''}`));
407
+ };
408
+
409
+ return new Promise((resolve) => {
410
+ renderList();
411
+
412
+ const onKeypress = (chunk, key) => {
413
+ if (!key) {
414
+ // Handle raw chunk for arrow keys
415
+ const str = chunk.toString();
416
+ if (str === '\x1b[A') key = { name: 'up' };
417
+ else if (str === '\x1b[B') key = { name: 'down' };
418
+ else if (str === '\x1b[C') key = { name: 'right' };
419
+ else if (str === '\x1b[D') key = { name: 'left' };
420
+ else if (str === ' ') key = { name: 'space' };
421
+ else if (str === '\r' || str === '\n') key = { name: 'return' };
422
+ else if (str === '\x1b' || str === 'q') key = { name: 'escape' };
423
+ else if (str === 'a' || str === 'A') key = { name: 'a' };
424
+ else if (str === '\x03') key = { name: 'c', ctrl: true }; // Ctrl+C
425
+ }
426
+
427
+ if (!key) return;
428
+
429
+ if (key.name === 'up' || key.name === 'k') {
430
+ cursor = cursor > 0 ? cursor - 1 : files.length - 1;
431
+ renderList();
432
+ } else if (key.name === 'down' || key.name === 'j') {
433
+ cursor = cursor < files.length - 1 ? cursor + 1 : 0;
434
+ renderList();
435
+ } else if (key.name === 'space' || key.name === 'right') {
436
+ if (selected.has(cursor)) {
437
+ selected.delete(cursor);
438
+ } else {
439
+ selected.add(cursor);
440
+ }
441
+ renderList();
442
+ } else if (key.name === 'a') {
443
+ // Toggle all
444
+ if (selected.size === files.length) {
445
+ selected.clear();
446
+ } else {
447
+ for (let i = 0; i < files.length; i++) selected.add(i);
448
+ }
449
+ renderList();
450
+ } else if (key.name === 'return') {
451
+ cleanup();
452
+ const selectedFiles = Array.from(selected).map(i => files[i].path);
453
+ console.log(chalk.green(`\n✓ Selected ${selectedFiles.length} file${selectedFiles.length !== 1 ? 's' : ''}`));
454
+ resolve(selectedFiles);
455
+ } else if (key.name === 'escape' || key.name === 'q' || (key.ctrl && key.name === 'c')) {
456
+ cleanup();
457
+ console.log(chalk.gray('\nCancelled.'));
458
+ resolve([]);
459
+ }
460
+ };
461
+
462
+ const cleanup = () => {
463
+ process.stdin.removeListener('data', onKeypress);
464
+ if (process.stdin.isTTY) {
465
+ process.stdin.setRawMode(false);
466
+ }
467
+ };
468
+
469
+ process.stdin.on('data', onKeypress);
470
+ });
471
+ }
472
+
473
+ // Format scan results for AI context
474
+ function formatScanResults(scanResult) {
475
+ let output = `\n══════════════════════════════════════\n`;
476
+ output += `📁 CODEBASE SCAN (${scanResult.files.length} files, ~${Math.round(scanResult.totalSize/1024)}KB)\n`;
477
+ output += `══════════════════════════════════════\n\n`;
478
+
479
+ // First list all files
480
+ output += `FILE TREE:\n`;
481
+ for (const file of scanResult.files) {
482
+ if (file.skipped) {
483
+ output += ` ⏭️ ${file.path} (skipped: ${file.reason})\n`;
484
+ } else {
485
+ output += ` 📄 ${file.path} (${Math.round(file.size/1024)}KB)\n`;
486
+ }
487
+ }
488
+
489
+ output += `\n══════════════════════════════════════\n`;
490
+ output += `FILE CONTENTS:\n`;
491
+ output += `══════════════════════════════════════\n\n`;
492
+
493
+ // Then include contents
494
+ for (const file of scanResult.files) {
495
+ if (file.skipped) continue;
496
+ output += `┌─── ${file.path} ───\n`;
497
+ output += file.content;
498
+ if (!file.content.endsWith('\n')) output += '\n';
499
+ output += `└─── END ${file.path} ───\n\n`;
500
+ }
501
+
502
+ return output;
503
+ }
504
+
505
+ const tools = {
506
+ read: (path) => {
507
+ try { return fs.readFileSync(path.trim(), 'utf8'); }
508
+ catch (error) { return `Error reading file: ${error.message}`; }
509
+ },
510
+ patch: async (path, oldText, newText) => {
511
+ const trimmedPath = path.trim();
512
+ try {
513
+ const content = fs.readFileSync(trimmedPath, 'utf8');
514
+ if (!content.includes(oldText)) {
515
+ return `Error: Could not find the text to replace in ${trimmedPath}. Make sure oldText matches exactly (including whitespace).`;
516
+ }
517
+ const newContent = content.replace(oldText, newText);
518
+
519
+ // Show diff preview
520
+ console.log();
521
+ const diffContent =
522
+ `${chalk.white('File:')} ${chalk.cyan(trimmedPath)}\n` +
523
+ chalk.gray('─'.repeat(40)) + '\n' +
524
+ chalk.red('- ' + oldText.split('\n').join('\n- ')) + '\n' +
525
+ chalk.green('+ ' + newText.split('\n').join('\n+ '));
526
+ console.log(box(diffContent, '🔧 Patch', 'yellow'));
527
+
528
+ const confirm = await safeQuestion(chalk.yellow('\n↪ Apply patch? ') + chalk.gray('(y/n): '));
529
+ if (confirm.toLowerCase() === 'y') {
530
+ fs.writeFileSync(trimmedPath, newContent);
531
+ return `Successfully patched ${trimmedPath}`;
532
+ }
533
+ return 'Patch rejected by user.';
534
+ } catch (error) { return `Error patching file: ${error.message}`; }
535
+ },
536
+ write: async (path, content) => {
537
+ const trimmedPath = path.trim();
538
+ console.log();
539
+ console.log(box(
540
+ `${chalk.white('File:')} ${chalk.cyan(trimmedPath)}\n` +
541
+ `${chalk.white('Size:')} ${content?.length || 0} chars\n` +
542
+ chalk.gray('─'.repeat(40)) + '\n' +
543
+ chalk.gray(content?.substring(0, 300)?.split('\n').slice(0, 8).join('\n') + (content?.length > 300 ? '\n...' : '')),
544
+ '✏️ Write File', 'yellow'
545
+ ));
546
+ const confirm = await safeQuestion(chalk.yellow('\n↪ Allow write? ') + chalk.gray('(y/n): '));
547
+ if (confirm.toLowerCase() === 'y') {
548
+ try {
549
+ fs.writeFileSync(trimmedPath, content);
550
+ return `Successfully saved changes to ${trimmedPath}`;
551
+ } catch (error) { return `Error writing file: ${error.message}`; }
552
+ }
553
+ return "Write blocked by user.";
554
+ },
555
+ mkdir: (path) => {
556
+ try {
557
+ fs.mkdirSync(path.trim(), { recursive: true });
558
+ return `Directory created: ${path}`;
559
+ } catch (error) { return `Error creating directory: ${error.message}`; }
560
+ },
561
+ shell: async (cmd) => {
562
+ console.log();
563
+ console.log(box(
564
+ chalk.white.bold(cmd),
565
+ '🔐 Shell Command', 'red'
566
+ ));
567
+ const confirm = await safeQuestion(chalk.red('\n↪ Execute? ') + chalk.gray('(y/n): '));
568
+ if (confirm.toLowerCase() === 'y') {
569
+ return new Promise((resolve) => {
570
+ const useShell = cmd.includes('&&') || cmd.includes('|') || cmd.includes('cd ');
571
+ console.log(chalk.cyan(`\n[RUNNING] ${cmd}\n`));
572
+ const proc = spawn(useShell ? 'sh' : cmd.split(' ')[0], useShell ? ['-c', cmd] : cmd.split(' ').slice(1), {
573
+ stdio: 'inherit', shell: useShell
574
+ });
575
+ proc.on('close', (code) => {
576
+ // Crucial: give control back to Node
577
+ if (process.stdin.isTTY) {
578
+ try { process.stdin.setRawMode(false); } catch (e) {}
579
+ }
580
+ // Delay slightly to let terminal settle
581
+ setTimeout(() => {
582
+ recreateReadline();
583
+ resolve(`Command completed with code ${code}`);
584
+ }, 200);
585
+ });
586
+ });
587
+ }
588
+ return "Command blocked by user.";
589
+ },
590
+ list: (path) => {
591
+ try {
592
+ let dir = path.trim() || '.';
593
+ // If AI sends "/" (root), treat as current directory "."
594
+ if (dir === '/') dir = '.';
595
+ const entries = fs.readdirSync(dir);
596
+ // Filter out ignored directories
597
+ const filtered = entries.filter(entry => {
598
+ if (IGNORE_DIRS.has(entry)) return false;
599
+ // Also skip hidden files/folders (starting with .) except current dir
600
+ if (entry.startsWith('.') && entry !== '.') return false;
601
+ return true;
602
+ });
603
+ return filtered.length > 0 ? filtered.join('\n') : '(empty or all files filtered)';
604
+ } catch (e) { return `Error: ${e.message}`; }
605
+ },
606
+ search: (pattern) => {
607
+ return new Promise((resolve) => {
608
+ const excludeDirs = Array.from(IGNORE_DIRS).join(',');
609
+ // Use grep to search for pattern, excluding ignored directories
610
+ const cmd = `grep -rEin "${pattern.replace(/"/g, '\\"')}" . --exclude-dir={${excludeDirs}} --include="*.{js,ts,jsx,tsx,py,java,go,rs,rb,php,c,cpp,h,css,scss,html,json,md,txt,yml,yaml,toml,sh}" 2>/dev/null | head -50`;
611
+
612
+ const proc = spawn('sh', ['-c', cmd], { cwd: process.cwd() });
613
+ let output = '';
614
+
615
+ proc.stdout.on('data', (data) => { output += data.toString(); });
616
+ proc.stderr.on('data', (data) => { output += data.toString(); });
617
+
618
+ proc.on('close', () => {
619
+ if (output.trim()) {
620
+ resolve(`Found matches:\n${output.trim()}`);
621
+ } else {
622
+ resolve(`No matches found for: ${pattern}`);
623
+ }
624
+ });
625
+ });
626
+ }
627
+ };
628
+
629
+ async function checkForUpdates() {
630
+ try {
631
+ const response = await fetch('https://registry.npmjs.org/sapper-iq/latest');
632
+ const data = await response.json();
633
+ const latestVersion = data.version;
634
+
635
+ if (latestVersion && latestVersion !== CURRENT_VERSION) {
636
+ console.log(chalk.yellow('🔄 UPDATE AVAILABLE!'));
637
+ console.log(chalk.gray(` Current: v${CURRENT_VERSION}`));
638
+ console.log(chalk.green(` Latest: v${latestVersion}`));
639
+ console.log(chalk.cyan(' Run: npm update -g sapper-iq\n'));
640
+ }
641
+ } catch (error) {
642
+ // Silently fail if update check fails
643
+ }
644
+ }
645
+
646
+ async function runSapper() {
647
+ console.clear();
648
+ console.log(BANNER);
649
+ console.log(chalk.gray.dim(' ') + chalk.white.bold(`v${CURRENT_VERSION}`) + chalk.gray(' │ ') + chalk.cyan('Autonomous AI Coding Agent'));
650
+ console.log(chalk.gray.dim(' ') + chalk.gray('📁 ') + chalk.white(process.cwd()));
651
+ console.log();
652
+
653
+ // Quick tips box
654
+ console.log(box(
655
+ `${chalk.yellow('💡')} Use ${chalk.cyan('@file')} to attach files (e.g., "fix @app.js")\n` +
656
+ `${chalk.yellow('💡')} Type ${chalk.cyan('/scan')} to load entire codebase\n` +
657
+ `${chalk.yellow('💡')} Type ${chalk.cyan('/help')} for all commands`,
658
+ 'Quick Tips', 'gray'
659
+ ));
660
+ console.log();
661
+
662
+ // Check for updates
663
+ await checkForUpdates();
664
+
665
+ let messages = [];
666
+ if (fs.existsSync(CONTEXT_FILE)) {
667
+ console.log();
668
+ console.log(box('Previous session found! Resume where you left off?', '📂 Session', 'green'));
669
+ const resume = await safeQuestion(chalk.green('\n↪ Resume? ') + chalk.gray('(y/n): '));
670
+ if (resume.toLowerCase() === 'y') {
671
+ messages = JSON.parse(fs.readFileSync(CONTEXT_FILE, 'utf8'));
672
+ console.log(chalk.green(' ✓ Session restored\n'));
673
+ } else {
674
+ fs.unlinkSync(CONTEXT_FILE);
675
+ console.log(chalk.gray(' ✓ Starting fresh...\n'));
676
+ }
677
+ }
678
+
679
+ let localModels;
680
+ try {
681
+ localModels = await ollama.list();
682
+ } catch (e) {
683
+ console.error(chalk.red('\n❌ Cannot connect to Ollama!'));
684
+ console.log(chalk.yellow(' Make sure Ollama is running: ') + chalk.cyan('ollama serve'));
685
+ console.log(chalk.gray(' Or install from: https://ollama.ai\n'));
686
+ process.exit(1);
687
+ }
688
+
689
+ if (!localModels.models || localModels.models.length === 0) {
690
+ console.error(chalk.red('\n❌ No models found!'));
691
+ console.log(chalk.yellow(' Pull a model first: ') + chalk.cyan('ollama pull llama3.2'));
692
+ process.exit(1);
693
+ }
694
+
695
+ console.log(divider());
696
+ console.log(statusBadge('MODELS', 'info') + chalk.gray(' Available Ollama models:\n'));
697
+ localModels.models.forEach((m, i) => {
698
+ const num = chalk.cyan.bold(`[${i + 1}]`);
699
+ const name = chalk.white(m.name);
700
+ console.log(` ${num} ${name}`);
701
+ });
702
+ console.log(divider());
703
+ const choice = await safeQuestion(chalk.cyan('\n⚡ Select model: '));
704
+ const selectedModel = localModels.models[parseInt(choice) - 1]?.name || localModels.models[0].name;
705
+
706
+ if (messages.length === 0) {
707
+ messages = [{
708
+ role: 'system',
709
+ content: `You are Sapper, a high-level Autonomous Software Engineer.
710
+ Your goal is to solve the user's request by interacting with the filesystem and shell.
711
+
712
+ RULES:
713
+ 1. EXPLORE FIRST: Use LIST and READ to understand the codebase before making changes.
714
+ 2. THINK IN STEPS: Explain what you found and what you plan to do before executing tools.
715
+ 3. BE PRECISE: When using PATCH, ensure the 'oldText' matches exactly.
716
+ 4. VERIFY: After writing code, use the SHELL tool to run tests or linting.
717
+ 5. NO HALLUCINATIONS: If a file doesn't exist, don't guess its content. List the directory instead.
718
+
719
+ TOOL SYNTAX:
720
+ - [TOOL:LIST]dir[/TOOL] - List directory contents
721
+ - [TOOL:READ]file_path[/TOOL] - Read file contents
722
+ - [TOOL:SEARCH]pattern[/TOOL] - Search codebase for pattern
723
+ - [TOOL:WRITE]path:::content[/TOOL] - Create/overwrite file
724
+ - [TOOL:PATCH]path:::old|||new[/TOOL] - Edit existing file
725
+ - [TOOL:SHELL]command[/TOOL] - Run shell command`
726
+ }];
727
+ }
728
+
729
+ // Main conversation loop - never exits unless user types 'exit'
730
+ while (true) {
731
+ try {
732
+ // Context size warning - large context causes hangs
733
+ const contextSize = JSON.stringify(messages).length;
734
+ if (contextSize > 32000) {
735
+ console.log();
736
+ console.log(box(
737
+ `Context is ${chalk.red.bold(Math.round(contextSize/1024) + 'KB')} - this may cause slowdowns!\n` +
738
+ `${chalk.yellow('Tip:')} Type ${chalk.cyan('/prune')} to reduce context size`,
739
+ '⚠️ Warning', 'yellow'
740
+ ));
741
+ }
742
+
743
+ const input = await safeQuestion(chalk.cyan('\n┌─[') + chalk.white.bold('You') + chalk.cyan(']\n└─➤ '));
744
+
745
+ if (input.toLowerCase() === 'exit') process.exit();
746
+
747
+ // Handle reset command
748
+ if (input.toLowerCase() === '/reset' || input.toLowerCase() === '/clear') {
749
+ if (fs.existsSync(CONTEXT_FILE)) {
750
+ fs.unlinkSync(CONTEXT_FILE);
751
+ console.log(chalk.green('✅ Context cleared! Starting fresh...\n'));
752
+ }
753
+ messages = [{
754
+ role: 'system',
755
+ content: messages[0].content // Keep system prompt
756
+ }];
757
+ continue;
758
+ }
759
+
760
+ // Handle prune command - AUTO-EMBED then clear old context
761
+ if (input.toLowerCase() === '/prune') {
762
+ if (messages.length <= 5) {
763
+ console.log(chalk.yellow('Context is already small, nothing to prune.'));
764
+ continue;
765
+ }
766
+
767
+ // 1. AUTO-EMBED: Save conversation to memory BEFORE pruning (silently skip if no model)
768
+ const embeddings = loadEmbeddings();
769
+
770
+ // Get messages that will be pruned (all except system and last 4)
771
+ const messagesToEmbed = messages.slice(1, -4)
772
+ .filter(m => m.role !== 'system')
773
+ .map(m => m.content.substring(0, 500))
774
+ .join('\n---\n');
775
+
776
+ if (messagesToEmbed.length > 50) {
777
+ try {
778
+ const embedding = await getEmbedding(messagesToEmbed);
779
+ if (embedding) {
780
+ embeddings.chunks.push({
781
+ text: messagesToEmbed.substring(0, 2000),
782
+ embedding,
783
+ timestamp: Date.now()
784
+ });
785
+ if (embeddings.chunks.length > 100) {
786
+ embeddings.chunks = embeddings.chunks.slice(-100);
787
+ }
788
+ saveEmbeddings(embeddings);
789
+ console.log(chalk.green(`🧠 Saved to memory! (${embeddings.chunks.length} memories)`));
790
+ }
791
+ } catch (e) {
792
+ // Silently skip embedding if model not available - prune still works
793
+ }
794
+ }
795
+
796
+ // 2. Capture the ORIGINAL detailed system prompt from the very first message
797
+ const originalSystemPrompt = messages[0];
798
+
799
+ // 3. Capture the last 4 messages (the most recent conversation)
800
+ const recentMessages = messages.slice(-4);
801
+
802
+ // 4. Rebuild the messages array starting with the ORIGINAL prompt
803
+ messages = [originalSystemPrompt, ...recentMessages];
804
+
805
+ // 4. Add reminder to stay in Agent Mode (not chatbot mode)
806
+ messages.push({
807
+ role: 'system',
808
+ content: `CONTEXT PRUNED. REMINDER: You are Sapper, an Autonomous Software Engineer.
809
+
810
+ RULES:
811
+ 1. EXPLORE FIRST: Use LIST and READ before making changes.
812
+ 2. THINK IN STEPS: Explain your plan before executing tools.
813
+ 3. BE PRECISE: When using PATCH, ensure 'oldText' matches exactly.
814
+ 4. VERIFY: Run tests or linting after writing code.
815
+ 5. NO HALLUCINATIONS: Don't guess file contents.
816
+
817
+ TOOL SYNTAX:
818
+ - [TOOL:LIST]dir[/TOOL]
819
+ - [TOOL:READ]file_path[/TOOL]
820
+ - [TOOL:SEARCH]pattern[/TOOL]
821
+ - [TOOL:WRITE]path:::content[/TOOL]
822
+ - [TOOL:PATCH]path:::old|||new[/TOOL]
823
+ - [TOOL:SHELL]command[/TOOL]`
824
+ });
825
+
826
+ // 5. Save to context file so it persists
827
+ fs.writeFileSync(CONTEXT_FILE, JSON.stringify(messages, null, 2));
828
+
829
+ console.log(chalk.green(`✅ Pruned context. Sapper reminded to stay in Agent Mode.`));
830
+ console.log(chalk.gray(`Context size: ${messages.length} messages\n`));
831
+ continue;
832
+ }
833
+
834
+ // Handle help command
835
+ if (input.toLowerCase() === '/help') {
836
+ console.log();
837
+ const helpContent =
838
+ `${chalk.cyan('@')} or ${chalk.cyan('/attach')} ${chalk.gray('│')} Pick files to attach (interactive)\n` +
839
+ `${chalk.cyan('@file')} ${chalk.gray('│')} Attach file inline (e.g., @src/app.js)\n` +
840
+ `${chalk.cyan('/scan')} ${chalk.gray('│')} Scan codebase into context\n` +
841
+ `${chalk.cyan('/recall')} ${chalk.gray('│')} Search memory for relevant context\n` +
842
+ `${chalk.cyan('/reset /clear')} ${chalk.gray('│')} Clear all context\n` +
843
+ `${chalk.cyan('/prune')} ${chalk.gray('│')} Save to memory + keep last 4 msgs\n` +
844
+ `${chalk.cyan('/context')} ${chalk.gray('│')} Show context size\n` +
845
+ `${chalk.cyan('/debug')} ${chalk.gray('│')} Toggle debug mode\n` +
846
+ `${chalk.cyan('/help')} ${chalk.gray('│')} Show this help\n` +
847
+ `${chalk.cyan('exit')} ${chalk.gray('│')} Quit Sapper`;
848
+ console.log(box(helpContent, '📚 Commands', 'cyan'));
849
+ console.log();
850
+ continue;
851
+ }
852
+
853
+ // Handle context size command
854
+ if (input.toLowerCase() === '/context') {
855
+ const contextSize = JSON.stringify(messages).length;
856
+ console.log(chalk.cyan(`\n📊 Context: ${messages.length} messages, ~${Math.round(contextSize/1024)}KB`));
857
+ if (contextSize > 50000) {
858
+ console.log(chalk.yellow('⚠️ Context is large! Consider using /prune'));
859
+ }
860
+ continue;
861
+ }
862
+
863
+ // Handle debug mode toggle
864
+ if (input.toLowerCase() === '/debug') {
865
+ debugMode = !debugMode;
866
+ console.log(chalk.magenta(`🔧 Debug mode: ${debugMode ? 'ON' : 'OFF'}`));
867
+ if (debugMode) {
868
+ console.log(chalk.gray(' Will show regex matching details after each AI response.'));
869
+ }
870
+ continue;
871
+ }
872
+
873
+ // Handle recall command - search embeddings
874
+ if (input.toLowerCase().startsWith('/recall')) {
875
+ const query = input.slice(7).trim();
876
+ if (!query) {
877
+ console.log(chalk.yellow('Usage: /recall <search query>'));
878
+ continue;
879
+ }
880
+
881
+ const embeddings = loadEmbeddings();
882
+ if (embeddings.chunks.length === 0) {
883
+ console.log(chalk.yellow('No memories yet. Use /prune to auto-save conversations.'));
884
+ continue;
885
+ }
886
+
887
+ console.log(chalk.cyan(`\n🔍 Searching memory for: "${query}"...`));
888
+ const relevant = await findRelevantContext(query, embeddings, 3);
889
+
890
+ if (relevant.length === 0) {
891
+ console.log(chalk.yellow('No relevant memories found (or embedding model not available).'));
892
+ console.log(chalk.gray('Tip: Run "ollama pull nomic-embed-text" for semantic search.'));
893
+ } else {
894
+ console.log(chalk.green(`Found ${relevant.length} relevant memories:\n`));
895
+ relevant.forEach((chunk, i) => {
896
+ console.log(box(
897
+ chalk.gray(chunk.text.substring(0, 300) + '...') + '\n' +
898
+ chalk.cyan(`Similarity: ${(chunk.score * 100).toFixed(1)}%`),
899
+ `Memory ${i + 1}`, 'magenta'
900
+ ));
901
+ console.log();
902
+ });
903
+
904
+ // Optionally add to context
905
+ const addToContext = await safeQuestion(chalk.yellow('Add to current context? ') + chalk.gray('(y/n): '));
906
+ if (addToContext.toLowerCase() === 'y') {
907
+ const contextAddition = relevant.map(c => c.text).join('\n---\n');
908
+ messages.push({
909
+ role: 'user',
910
+ content: `Here is relevant context from memory:\n${contextAddition}\n\nUse this information to help me.`
911
+ });
912
+ console.log(chalk.green('✅ Added to context!'));
913
+ }
914
+ }
915
+ continue;
916
+ }
917
+
918
+ // Handle codebase scan command
919
+ if (input.toLowerCase() === '/scan') {
920
+ console.log(chalk.cyan('\n🔍 Scanning codebase...'));
921
+ const scanResult = scanCodebase('.');
922
+
923
+ if (scanResult.files.length === 0) {
924
+ console.log(chalk.yellow('No code files found in current directory.'));
925
+ continue;
926
+ }
927
+
928
+ const formattedScan = formatScanResults(scanResult);
929
+ const includedCount = scanResult.files.filter(f => !f.skipped).length;
930
+ const skippedCount = scanResult.files.filter(f => f.skipped).length;
931
+
932
+ console.log(chalk.green(`✅ Scanned ${includedCount} files (~${Math.round(scanResult.totalSize/1024)}KB)`));
933
+ if (skippedCount > 0) {
934
+ console.log(chalk.yellow(`⏭️ Skipped ${skippedCount} files (too large or limit reached)`));
935
+ }
936
+
937
+ // Add scan to context
938
+ messages.push({
939
+ role: 'user',
940
+ content: `I've scanned the entire codebase. Here are all the files:\n${formattedScan}\n\nYou now have the full codebase context. Use this information to help me.`
941
+ });
942
+
943
+ fs.writeFileSync(CONTEXT_FILE, JSON.stringify(messages, null, 2));
944
+ console.log(chalk.gray('📝 Codebase added to context. AI now has full picture.\n'));
945
+ continue;
946
+ }
947
+
948
+ // Handle @ alone or /attach command - interactive file picker
949
+ if (input.trim() === '@' || input.toLowerCase() === '/attach') {
950
+ const selectedFiles = await pickFiles();
951
+
952
+ if (selectedFiles.length === 0) continue;
953
+
954
+ // Read and attach selected files
955
+ const fileAttachments = [];
956
+ for (const filePath of selectedFiles) {
957
+ try {
958
+ const stats = fs.statSync(filePath);
959
+ if (stats.size > MAX_FILE_SIZE) {
960
+ console.log(chalk.yellow(`⚠️ ${filePath} is too large, skipping`));
961
+ continue;
962
+ }
963
+ const content = fs.readFileSync(filePath, 'utf8');
964
+ fileAttachments.push({ path: filePath, content, size: stats.size });
965
+ console.log(chalk.green(`📎 Attached: ${filePath}`));
966
+ } catch (e) {
967
+ console.log(chalk.yellow(`⚠️ Could not read ${filePath}`));
968
+ }
969
+ }
970
+
971
+ if (fileAttachments.length === 0) continue;
972
+
973
+ // Ask for the prompt to go with these files
974
+ console.log();
975
+ const prompt = await safeQuestion(chalk.cyan('Your prompt for these files: '));
976
+
977
+ if (!prompt.trim()) {
978
+ console.log(chalk.gray('Cancelled.'));
979
+ continue;
980
+ }
981
+
982
+ // Build message with attachments
983
+ let attachedContent = '\n\n══════════════════════════════════════\n';
984
+ attachedContent += `📎 ATTACHED FILES (${fileAttachments.length})\n`;
985
+ attachedContent += '══════════════════════════════════════\n\n';
986
+
987
+ for (const file of fileAttachments) {
988
+ attachedContent += `┌─── ${file.path} ───\n`;
989
+ attachedContent += file.content;
990
+ if (!file.content.endsWith('\n')) attachedContent += '\n';
991
+ attachedContent += `└─── END ${file.path} ───\n\n`;
992
+ }
993
+
994
+ messages.push({ role: 'user', content: prompt + attachedContent });
995
+ // Continue to AI response (don't use 'continue' here)
996
+ } else {
997
+ // Process @file attachments in prompt (e.g., "analyze @package.json" or "fix @src/index.js")
998
+ let processedInput = input;
999
+ const fileAttachments = [];
1000
+ const attachRegex = /@([\w.\/\-_]+)/g;
1001
+ let attachMatch;
1002
+
1003
+ while ((attachMatch = attachRegex.exec(input)) !== null) {
1004
+ const filePath = attachMatch[1];
1005
+ try {
1006
+ if (fs.existsSync(filePath)) {
1007
+ const stats = fs.statSync(filePath);
1008
+ if (stats.isFile()) {
1009
+ if (stats.size > MAX_FILE_SIZE) {
1010
+ console.log(chalk.yellow(`⚠️ @${filePath} is too large (${Math.round(stats.size/1024)}KB), skipping`));
1011
+ } else {
1012
+ const content = fs.readFileSync(filePath, 'utf8');
1013
+ fileAttachments.push({ path: filePath, content, size: stats.size });
1014
+ console.log(chalk.green(`📎 Attached: ${filePath} (${Math.round(stats.size/1024)}KB)`));
1015
+ }
1016
+ }
1017
+ } else {
1018
+ // Not a file - might be an @mention for something else, ignore
1019
+ }
1020
+ } catch (e) {
1021
+ console.log(chalk.yellow(`⚠️ Could not read @${filePath}: ${e.message}`));
1022
+ }
1023
+ }
1024
+
1025
+ // Build the final message with attachments
1026
+ if (fileAttachments.length > 0) {
1027
+ let attachedContent = '\n\n══════════════════════════════════════\n';
1028
+ attachedContent += `📎 ATTACHED FILES (${fileAttachments.length})\n`;
1029
+ attachedContent += '══════════════════════════════════════\n\n';
1030
+
1031
+ for (const file of fileAttachments) {
1032
+ attachedContent += `┌─── ${file.path} ───\n`;
1033
+ attachedContent += file.content;
1034
+ if (!file.content.endsWith('\n')) attachedContent += '\n';
1035
+ attachedContent += `└─── END ${file.path} ───\n\n`;
1036
+ }
1037
+
1038
+ processedInput = input + attachedContent;
1039
+ }
1040
+
1041
+ messages.push({ role: 'user', content: processedInput });
1042
+ } // End of else block for non-@ input
1043
+
1044
+ let toolRounds = 0; // Prevent infinite loops
1045
+ const MAX_TOOL_ROUNDS = 20;
1046
+
1047
+ let active = true;
1048
+ while (active) {
1049
+ if (stepMode) await safeQuestion(chalk.gray('[STEP] Press Enter to let AI think...'));
1050
+
1051
+ spinner.start('Thinking...');
1052
+ let response;
1053
+ try {
1054
+ response = await ollama.chat({ model: selectedModel, messages, stream: true });
1055
+ } catch (ollamaError) {
1056
+ spinner.stop();
1057
+ console.error(chalk.red('\n❌ Ollama error:'), ollamaError.message);
1058
+ active = false;
1059
+ continue;
1060
+ }
1061
+ spinner.stop();
1062
+
1063
+ let msg = '';
1064
+ const MAX_RESPONSE_LENGTH = 29000; // Guard against infinite loops (increased for multi-file reads)
1065
+ abortStream = false; // Reset abort flag before streaming
1066
+
1067
+ console.log(chalk.magenta('┌─[') + chalk.white.bold('Sapper') + chalk.magenta(']'));
1068
+ process.stdout.write(chalk.magenta('│ '));
1069
+ for await (const chunk of response) {
1070
+ // Check if user pressed Ctrl+C
1071
+ if (abortStream) {
1072
+ console.log(chalk.yellow('\n│ [Response interrupted]'));
1073
+ break;
1074
+ }
1075
+
1076
+ const content = chunk.message.content;
1077
+ process.stdout.write(content);
1078
+ msg += content;
1079
+
1080
+ if (msg.length > MAX_RESPONSE_LENGTH) {
1081
+ console.log(chalk.red('\n\n⚠️ RESPONSE TOO LONG: Forcing stop to prevent infinite loop.'));
1082
+ break;
1083
+ }
1084
+ }
1085
+ console.log();
1086
+
1087
+ // If response has markdown, show rendered version
1088
+ const hasMarkdown = /\*\*|__|`|^#|^[-*] /m.test(msg);
1089
+ if (hasMarkdown && !msg.includes('[TOOL:')) {
1090
+ console.log(chalk.gray('─'.repeat(40)));
1091
+ const rendered = renderMarkdown(msg);
1092
+ const lines = rendered.split('\n');
1093
+ for (const line of lines) {
1094
+ console.log(chalk.magenta('│ ') + line);
1095
+ }
1096
+ console.log();
1097
+ }
1098
+
1099
+ messages.push({ role: 'assistant', content: msg });
1100
+
1101
+ // Regex: supports both old format (path]content) and new format (path:::content)
1102
+ const toolMatches = [...msg.matchAll(/\[TOOL:(\w+)\]([^:\]]*?)(?:(?:::|\])([\s\S]*?))?\[\/TOOL\]/g)];
1103
+
1104
+ // Debug mode: show what regex sees
1105
+ if (debugMode) {
1106
+ console.log(chalk.magenta('\n═══ DEBUG: REGEX ANALYSIS ═══'));
1107
+ console.log(chalk.gray(`Response length: ${msg.length} chars`));
1108
+
1109
+ // Check for tool-like patterns
1110
+ const hasToolStart = msg.includes('[TOOL:');
1111
+ const hasToolEnd = msg.includes('[/TOOL]');
1112
+ const hasBrokenEnd = msg.includes('[/]') || msg.includes('[/WRITE]') || msg.includes('[/READ]');
1113
+
1114
+ console.log(chalk.gray(`Contains [TOOL:: ${hasToolStart ? chalk.green('YES') : chalk.red('NO')}`));
1115
+ console.log(chalk.gray(`Contains [/TOOL]: ${hasToolEnd ? chalk.green('YES') : chalk.red('NO')}`));
1116
+ if (hasBrokenEnd) {
1117
+ console.log(chalk.red(`⚠️ Found broken closing tag: [/] or [/WRITE] etc.`));
1118
+ }
1119
+
1120
+ console.log(chalk.gray(`Matches found: ${toolMatches.length}`));
1121
+
1122
+ if (toolMatches.length > 0) {
1123
+ toolMatches.forEach((m, i) => {
1124
+ console.log(chalk.cyan(` Match ${i+1}: type=${m[1]}, path=${m[2]?.substring(0,50)}...`));
1125
+ });
1126
+ } else if (hasToolStart) {
1127
+ // Show the raw tool attempt for debugging
1128
+ const toolAttempt = msg.match(/\[TOOL:[^\]]*\][^\[]{0,100}/s);
1129
+ if (toolAttempt) {
1130
+ console.log(chalk.yellow(` Raw tool attempt (first 150 chars):`));
1131
+ console.log(chalk.gray(` "${toolAttempt[0].substring(0, 150)}..."`));
1132
+ }
1133
+ }
1134
+ console.log(chalk.magenta('═══════════════════════════════\n'));
1135
+ }
1136
+
1137
+ if (toolMatches.length > 0) {
1138
+ toolRounds++;
1139
+
1140
+ // Prevent infinite tool loops
1141
+ if (toolRounds >= MAX_TOOL_ROUNDS) {
1142
+ console.log(chalk.yellow(`\n⚠️ Tool limit reached (${MAX_TOOL_ROUNDS} rounds). Stopping auto-execution.`));
1143
+ console.log(chalk.gray('💡 Tip: Type /prune after analysis to reduce context size.'));
1144
+ resetTerminal(); // Ensure terminal is responsive
1145
+ messages.push({
1146
+ role: 'user',
1147
+ content: 'STOP using tools now. You have enough information. Please provide your analysis based on what you have read.'
1148
+ });
1149
+ continue; // Let AI respond without tools
1150
+ }
1151
+
1152
+ for (const match of toolMatches) {
1153
+ const [_, type, path, content] = match;
1154
+ console.log();
1155
+ console.log(statusBadge(type.toUpperCase(), 'action') + chalk.gray(' → ') + chalk.white(path));
1156
+
1157
+ let result;
1158
+ if (type.toLowerCase() === 'list') result = tools.list(path);
1159
+ else if (type.toLowerCase() === 'read') result = tools.read(path);
1160
+ else if (type.toLowerCase() === 'mkdir') result = tools.mkdir(path);
1161
+ else if (type.toLowerCase() === 'write') {
1162
+ if (!content || content.trim() === '') {
1163
+ result = 'Error: WRITE requires content. Use [TOOL:WRITE]path]content here[/TOOL]';
1164
+ } else {
1165
+ result = await tools.write(path, content);
1166
+ }
1167
+ }
1168
+ else if (type.toLowerCase() === 'patch') {
1169
+ // PATCH format: [TOOL:PATCH]path]OLD_TEXT|||NEW_TEXT[/TOOL]
1170
+ const parts = content?.split('|||');
1171
+ if (parts && parts.length === 2) {
1172
+ result = await tools.patch(path, parts[0], parts[1]);
1173
+ } else {
1174
+ result = 'Error: PATCH requires format [TOOL:PATCH]path]OLD_TEXT|||NEW_TEXT[/TOOL]';
1175
+ }
1176
+ }
1177
+ else if (type.toLowerCase() === 'search') result = await tools.search(path);
1178
+ else if (type.toLowerCase() === 'shell') result = await tools.shell(path);
1179
+
1180
+ messages.push({ role: 'user', content: `RESULT (${path}): ${result}` });
1181
+ }
1182
+ fs.writeFileSync(CONTEXT_FILE, JSON.stringify(messages, null, 2));
1183
+
1184
+ if (toolMatches.length > 30) {
1185
+ console.log(chalk.yellow('\n⚠️ Reading 30+ files! This might take time.'));
1186
+ }
1187
+ } else {
1188
+ // No tools found - check if malformed command
1189
+ if (msg.includes('[TOOL:') && msg.includes('[/]')) {
1190
+ console.log(chalk.red('\n❌ Malformed tool command detected!'));
1191
+ messages.push({
1192
+ role: 'user',
1193
+ content: 'ERROR: Your tool command is malformed. Use [TOOL:TYPE]path]content[/TOOL] or [TOOL:TYPE]path[/TOOL]'
1194
+ });
1195
+ } else {
1196
+ // Normal response - save and wait for next input
1197
+ fs.writeFileSync(CONTEXT_FILE, JSON.stringify(messages, null, 2));
1198
+ active = false;
1199
+ spinner.stop(); // Ensure spinner is dead
1200
+ resetTerminal(); // Force terminal back to normal state
1201
+ process.stdout.write('\n'); // Force newline to break out of stream mode
1202
+ }
1203
+ }
1204
+ }
1205
+ } catch (error) {
1206
+ console.error(chalk.red('\n❌ Error:'), error.message);
1207
+ // Loop continues automatically
1208
+ }
1209
+ }
1210
+ }
1211
+
1212
+ // Keep-alive interval - prevents Node from exiting when event loop is empty
1213
+ setInterval(() => {}, 1000);
1214
+
1215
+ runSapper();