neuro-cli 4.1.2 → 4.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // ============================================================
3
3
  // NeuroCLI - Advanced AI Terminal Coding Assistant
4
- // Main Entry Point - v4.1.2 with cross-platform path fix
4
+ // Main Entry Point - v4.1.3 with robust error handling
5
5
  // ============================================================
6
6
  import { Command } from 'commander';
7
7
  import { createInterface } from 'readline';
@@ -16,7 +16,20 @@ import { HeadlessMode } from './core/headless.js';
16
16
  import { ShellCompletionGenerator } from './core/shell-completion.js';
17
17
  import chalk from 'chalk';
18
18
  import { AutoUpdater } from './core/updater.js';
19
- const VERSION = '4.1.2';
19
+ const VERSION = '4.1.3';
20
+ // ---- Global Error Handlers (prevent crashes) ----
21
+ process.on('unhandledRejection', (reason) => {
22
+ console.error(chalk.red('\n⚠️ Unhandled promise rejection:'), reason);
23
+ // Don't exit — log and continue
24
+ });
25
+ process.on('uncaughtException', (error) => {
26
+ console.error(chalk.red('\n⚠️ Uncaught exception:'), error.message);
27
+ // Only exit for truly fatal errors
28
+ if (error.message.includes('ENOMEM') || error.message.includes('EADDRINUSE') || error.message.includes('EPERM')) {
29
+ process.exit(1);
30
+ }
31
+ // Otherwise, try to continue
32
+ });
20
33
  // ---- CLI Setup ----
21
34
  const program = new Command();
22
35
  program
@@ -236,7 +249,13 @@ program
236
249
  transport: transport,
237
250
  command: transport === 'stdio' ? command : undefined,
238
251
  url: isUrl ? command : undefined,
239
- headers: opts.headers ? JSON.parse(opts.headers) : undefined,
252
+ headers: opts.headers ? (() => { try {
253
+ return JSON.parse(opts.headers);
254
+ }
255
+ catch {
256
+ console.log(chalk.red('Invalid JSON for --headers'));
257
+ return undefined;
258
+ } })() : undefined,
240
259
  });
241
260
  console.log(chalk.green(`MCP server "${name}" added (${transport})`));
242
261
  }))
@@ -437,703 +456,721 @@ async function startInteractive(options) {
437
456
  let currentAgent;
438
457
  let isProcessing = false;
439
458
  rl.on('line', async (line) => {
440
- const input = line.trim();
441
- if (!input) {
442
- rl.prompt();
443
- return;
444
- }
445
- // Prevent input while processing (approval prompt may be active)
446
- if (isProcessing) {
447
- return;
448
- }
449
- // Add to history
450
- completionEngine.addHistory(input);
451
- // Handle slash commands
452
- if (input.startsWith('/')) {
453
- const [cmd, ...args] = input.slice(1).split(' ');
454
- switch (cmd) {
455
- case 'help':
456
- printHelp(engine);
457
- break;
458
- case 'model':
459
- if (args[0]) {
460
- engine.switchModel(args[0]);
461
- engine.fallback.addFallbackModel(config.defaultModel);
462
- }
463
- else {
464
- engine.ui.modelList(config.defaultModel);
465
- }
466
- break;
467
- case 'agent':
468
- if (args[0]) {
469
- const agentNames = Array.from(engine.agents.keys());
470
- const found = agentNames.find(n => n.toLowerCase() === args[0].toLowerCase());
471
- if (found) {
472
- currentAgent = found;
473
- currentMode = 'direct';
474
- engine.ui.success(`Switched to agent: ${found}`);
459
+ try {
460
+ const input = line.trim();
461
+ if (!input) {
462
+ rl.prompt();
463
+ return;
464
+ }
465
+ // Prevent input while processing (approval prompt may be active)
466
+ if (isProcessing) {
467
+ return;
468
+ }
469
+ // Add to history
470
+ completionEngine.addHistory(input);
471
+ // Handle slash commands
472
+ if (input.startsWith('/')) {
473
+ const [cmd, ...args] = input.slice(1).split(' ');
474
+ switch (cmd) {
475
+ case 'help':
476
+ printHelp(engine);
477
+ break;
478
+ case 'model':
479
+ if (args[0]) {
480
+ engine.switchModel(args[0]);
481
+ engine.fallback.addFallbackModel(config.defaultModel);
475
482
  }
476
483
  else {
477
- engine.ui.error(`Agent not found. Available: ${agentNames.join(', ')}`);
478
- }
479
- }
480
- else {
481
- const agents = Array.from(engine.agents.entries()).map(([name]) => ({ name, description: '', model: config.defaultModel }));
482
- engine.ui.agentList(agents);
483
- }
484
- break;
485
- case 'auto':
486
- currentMode = 'auto';
487
- currentAgent = undefined;
488
- engine.ui.success('Mode: Auto (smart orchestration)');
489
- break;
490
- case 'orchestrate':
491
- case 'plan':
492
- currentMode = 'agent';
493
- currentAgent = undefined;
494
- engine.ui.success('Mode: Multi-agent orchestration');
495
- break;
496
- case 'direct':
497
- currentMode = 'direct';
498
- engine.ui.success('Mode: Direct (single agent)');
499
- break;
500
- case 'plan-mode':
501
- engine.approval.setMode('plan');
502
- engine.ui.success(`${engine.approval.getModeIcon()} Permission: plan (read-only)`);
503
- break;
504
- case 'stats':
505
- const stats = engine.getSessionStats();
506
- engine.ui.sessionStats(stats.inputTokens, stats.outputTokens, stats.cost);
507
- break;
508
- case 'clear':
509
- console.clear();
510
- engine.ui.banner();
511
- break;
512
- case 'theme':
513
- if (args[0]) {
514
- config.ui.theme = args[0];
515
- engine.ui = new TerminalUI(config.ui.theme, config.ui.showTokenCount, config.ui.showCost);
516
- engine.ui.success(`Theme: ${args[0]}`);
517
- }
518
- else {
519
- console.log('Available themes: dracula, dark, nord, light');
520
- }
521
- break;
522
- case 'resume':
523
- if (args[0]) {
524
- const sessionId = args[0] === 'latest' ? engine.sessionManager.list()[0]?.id : args[0];
525
- if (sessionId) {
526
- const session = engine.sessionManager.load(sessionId);
527
- if (session)
528
- engine.ui.success(`Resumed session: ${sessionId.slice(0, 20)}...`);
529
- else
530
- engine.ui.error(`Session not found: ${sessionId}`);
484
+ engine.ui.modelList(config.defaultModel);
531
485
  }
532
- else {
533
- engine.ui.error('No sessions found');
486
+ break;
487
+ case 'agent':
488
+ if (args[0]) {
489
+ const agentNames = Array.from(engine.agents.keys());
490
+ const found = agentNames.find(n => n.toLowerCase() === args[0].toLowerCase());
491
+ if (found) {
492
+ currentAgent = found;
493
+ currentMode = 'direct';
494
+ engine.ui.success(`Switched to agent: ${found}`);
495
+ }
496
+ else {
497
+ engine.ui.error(`Agent not found. Available: ${agentNames.join(', ')}`);
498
+ }
534
499
  }
535
- }
536
- else {
537
- const sessions = engine.sessionManager.list();
538
- if (sessions.length === 0) {
539
- engine.ui.info('No sessions found');
540
- break;
500
+ else {
501
+ const agents = Array.from(engine.agents.entries()).map(([name]) => ({ name, description: '', model: config.defaultModel }));
502
+ engine.ui.agentList(agents);
541
503
  }
542
- console.log(chalk.bold('\nRecent sessions:\n'));
543
- for (const s of sessions.slice(0, 10)) {
544
- const date = new Date(s.createdAt).toLocaleString();
545
- console.log(` ${chalk.cyan(s.id.slice(0, 20))} ${chalk.gray(date)} ${chalk.gray(`${s.messageCount} msgs`)}`);
546
- }
547
- console.log(chalk.gray('\nUse /resume <id> to resume a session'));
548
- }
549
- break;
550
- case 'compact':
551
- engine.ui.info('Compacting conversation context...');
552
- engine.contextManager.manage(engine.sessionManager.getCurrent()?.messages || []);
553
- engine.ui.success('Context compacted');
554
- break;
555
- case 'undo':
556
- engine.ui.info('Undoing last change...');
557
- const undoAction = engine.undoRedo.undo();
558
- if (undoAction) {
559
- engine.ui.success(`Undone: ${undoAction.description}`);
560
- }
561
- else {
562
- engine.ui.warning('Nothing to undo');
563
- }
564
- break;
565
- case 'redo':
566
- engine.ui.info('Redoing...');
567
- const redoAction = engine.undoRedo.redo();
568
- if (redoAction) {
569
- engine.ui.success(`Redone: ${redoAction.description}`);
570
- }
571
- else {
572
- engine.ui.warning('Nothing to redo');
573
- }
574
- break;
575
- case 'rewind':
576
- const rewindN = args[0] ? parseInt(args[0]) : 1;
577
- if (isNaN(rewindN) || rewindN < 1) {
578
- engine.ui.error('Usage: /rewind <n>');
579
504
  break;
580
- }
581
- const undone = engine.undoRedo.undoN(rewindN);
582
- engine.ui.success(`Rewound ${undone.length} action(s)`);
583
- break;
584
- case 'fork':
585
- engine.ui.info('Forking current session...');
586
- const currentSession = engine.sessionManager.getCurrent();
587
- if (currentSession) {
588
- const forked = engine.sessionManager.create(process.cwd(), config.defaultModel);
589
- forked.messages = [...currentSession.messages];
590
- forked.forkedFrom = currentSession.id;
591
- engine.sessionManager.save();
592
- engine.ui.success(`Forked to new session: ${forked.id.slice(0, 20)}...`);
593
- }
594
- else {
595
- engine.ui.error('No active session to fork');
596
- }
597
- break;
598
- case 'mcp':
599
- const mcpSub = args[0];
600
- if (mcpSub === 'list') {
601
- const servers = engine.mcpClient.listServers();
602
- if (servers.length === 0) {
603
- engine.ui.info('No MCP servers configured');
604
- break;
505
+ case 'auto':
506
+ currentMode = 'auto';
507
+ currentAgent = undefined;
508
+ engine.ui.success('Mode: Auto (smart orchestration)');
509
+ break;
510
+ case 'orchestrate':
511
+ case 'plan':
512
+ currentMode = 'agent';
513
+ currentAgent = undefined;
514
+ engine.ui.success('Mode: Multi-agent orchestration');
515
+ break;
516
+ case 'direct':
517
+ currentMode = 'direct';
518
+ engine.ui.success('Mode: Direct (single agent)');
519
+ break;
520
+ case 'plan-mode':
521
+ engine.approval.setMode('plan');
522
+ engine.ui.success(`${engine.approval.getModeIcon()} Permission: plan (read-only)`);
523
+ break;
524
+ case 'stats':
525
+ const stats = engine.getSessionStats();
526
+ engine.ui.sessionStats(stats.inputTokens, stats.outputTokens, stats.cost);
527
+ break;
528
+ case 'clear':
529
+ console.clear();
530
+ engine.ui.banner();
531
+ break;
532
+ case 'theme':
533
+ if (args[0]) {
534
+ config.ui.theme = args[0];
535
+ engine.ui = new TerminalUI(config.ui.theme, config.ui.showTokenCount, config.ui.showCost);
536
+ engine.ui.success(`Theme: ${args[0]}`);
605
537
  }
606
- console.log(chalk.bold('\nMCP Servers:\n'));
607
- for (const s of servers) {
608
- const status = s.connected ? chalk.green('connected') : chalk.gray('disconnected');
609
- console.log(` ${chalk.cyan(s.name.padEnd(20))} ${status} ${chalk.gray(`${s.toolCount} tools`)} ${chalk.gray(s.config.transport)}`);
538
+ else {
539
+ console.log('Available themes: dracula, dark, nord, light');
610
540
  }
611
- }
612
- else if (mcpSub === 'connect' && args[1]) {
613
- try {
614
- const cfg = engine.mcpClient.loadConfig();
615
- if (cfg.mcpServers[args[1]]) {
616
- await engine.mcpClient.connect(args[1], cfg.mcpServers[args[1]]);
617
- engine.ui.success(`Connected to MCP server: ${args[1]}`);
541
+ break;
542
+ case 'resume':
543
+ if (args[0]) {
544
+ const sessionId = args[0] === 'latest' ? engine.sessionManager.list()[0]?.id : args[0];
545
+ if (sessionId) {
546
+ const session = engine.sessionManager.load(sessionId);
547
+ if (session)
548
+ engine.ui.success(`Resumed session: ${sessionId.slice(0, 20)}...`);
549
+ else
550
+ engine.ui.error(`Session not found: ${sessionId}`);
618
551
  }
619
552
  else {
620
- engine.ui.error(`MCP server "${args[1]}" not found`);
553
+ engine.ui.error('No sessions found');
621
554
  }
622
555
  }
623
- catch (e) {
624
- engine.ui.error(`Failed to connect: ${e instanceof Error ? e.message : String(e)}`);
625
- }
626
- }
627
- else if (mcpSub === 'disconnect' && args[1]) {
628
- await engine.mcpClient.disconnect(args[1]);
629
- engine.ui.success(`Disconnected from ${args[1]}`);
630
- }
631
- else if (mcpSub === 'health') {
632
- engine.mcpClient.healthReport();
633
- }
634
- else {
635
- console.log(chalk.bold('\nMCP Commands:\n'));
636
- console.log(' /mcp list List MCP servers');
637
- console.log(' /mcp connect <name> Connect to a server');
638
- console.log(' /mcp disconnect <name> Disconnect from a server');
639
- console.log(' /mcp health Show MCP health report');
640
- }
641
- break;
642
- case 'permission':
643
- case 'perm':
644
- if (args[0]) {
645
- const validModes = ['manual', 'auto', 'plan', 'yolo'];
646
- if (validModes.includes(args[0])) {
647
- engine.approval.setMode(args[0]);
648
- engine.ui.success(`${engine.approval.getModeIcon()} Permission: ${args[0]} (${engine.approval.getModeDescription()})`);
556
+ else {
557
+ const sessions = engine.sessionManager.list();
558
+ if (sessions.length === 0) {
559
+ engine.ui.info('No sessions found');
560
+ break;
561
+ }
562
+ console.log(chalk.bold('\nRecent sessions:\n'));
563
+ for (const s of sessions.slice(0, 10)) {
564
+ const date = new Date(s.createdAt).toLocaleString();
565
+ console.log(` ${chalk.cyan(s.id.slice(0, 20))} ${chalk.gray(date)} ${chalk.gray(`${s.messageCount} msgs`)}`);
566
+ }
567
+ console.log(chalk.gray('\nUse /resume <id> to resume a session'));
568
+ }
569
+ break;
570
+ case 'compact':
571
+ engine.ui.info('Compacting conversation context...');
572
+ engine.contextManager.manage(engine.sessionManager.getCurrent()?.messages || []);
573
+ engine.ui.success('Context compacted');
574
+ break;
575
+ case 'undo':
576
+ engine.ui.info('Undoing last change...');
577
+ const undoAction = engine.undoRedo.undo();
578
+ if (undoAction) {
579
+ engine.ui.success(`Undone: ${undoAction.description}`);
580
+ }
581
+ else {
582
+ engine.ui.warning('Nothing to undo');
583
+ }
584
+ break;
585
+ case 'redo':
586
+ engine.ui.info('Redoing...');
587
+ const redoAction = engine.undoRedo.redo();
588
+ if (redoAction) {
589
+ engine.ui.success(`Redone: ${redoAction.description}`);
649
590
  }
650
591
  else {
651
- engine.ui.error(`Invalid mode. Use: ${validModes.join(', ')}`);
652
- }
653
- }
654
- else {
655
- const newMode = engine.approval.cycleMode();
656
- engine.ui.success(`${engine.approval.getModeIcon()} Permission: ${newMode} (${engine.approval.getModeDescription()})`);
657
- }
658
- break;
659
- case 'init':
660
- engine.ui.info('Initializing NEURO.md for this project...');
661
- try {
662
- const { NeuroMdSystem } = await import('./context/neuro-md.js');
663
- const nmd = new NeuroMdSystem(process.cwd());
664
- nmd.load();
665
- const content = `# Project Context\n\nThis file provides persistent context for NeuroCLI.\n\n## Tech Stack\n- [Detected automatically]\n\n## Conventions\n- Follow existing code patterns\n- Use TypeScript for all new files\n\n## Notes\n- This file is auto-generated by /init\n`;
666
- const { writeFileSync } = await import('fs');
667
- const { join } = await import('path');
668
- writeFileSync(join(process.cwd(), 'NEURO.md'), content, 'utf-8');
669
- engine.ui.success('NEURO.md created');
670
- }
671
- catch (e) {
672
- engine.ui.error('Could not create NEURO.md: ' + (e instanceof Error ? e.message : String(e)));
673
- }
674
- break;
675
- case 'unpause':
676
- engine.doomLoop.unpause();
677
- break;
678
- case 'sandbox':
679
- if (args[0] === 'on' || args[0] === 'enable') {
680
- engine.sandbox.enable();
681
- engine.ui.success('Sandbox mode enabled');
682
- }
683
- else if (args[0] === 'off' || args[0] === 'disable') {
684
- engine.sandbox.disable();
685
- engine.ui.success('Sandbox mode disabled');
686
- }
687
- else if (args[0] === 'status') {
688
- engine.sandbox.printStatus();
689
- }
690
- else if (args[0] === 'undo') {
691
- const undone = engine.sandbox.undoAll();
692
- engine.ui.success(`Undone ${undone} file modifications`);
693
- }
694
- else {
695
- const enabled = engine.sandbox.toggle();
696
- engine.ui.success(enabled ? 'Sandbox mode enabled' : 'Sandbox mode disabled');
697
- }
698
- break;
699
- case 'plugins':
700
- case 'plugin':
701
- const pluginSub = args[0];
702
- if (pluginSub === 'list') {
703
- const plugins = engine.pluginManager.listPlugins();
704
- if (plugins.length === 0) {
705
- engine.ui.info('No plugins loaded');
592
+ engine.ui.warning('Nothing to redo');
593
+ }
594
+ break;
595
+ case 'rewind':
596
+ const rewindN = args[0] ? parseInt(args[0]) : 1;
597
+ if (isNaN(rewindN) || rewindN < 1) {
598
+ engine.ui.error('Usage: /rewind <n>');
706
599
  break;
707
600
  }
708
- console.log(chalk.bold('\nPlugins:\n'));
709
- for (const p of plugins) {
710
- console.log(` ${chalk.cyan(p.name)} v${p.version} - ${chalk.gray(p.description)} ${chalk.green(`${p.toolCount} tools`)}`);
601
+ const undone = engine.undoRedo.undoN(rewindN);
602
+ engine.ui.success(`Rewound ${undone.length} action(s)`);
603
+ break;
604
+ case 'fork':
605
+ engine.ui.info('Forking current session...');
606
+ const currentSession = engine.sessionManager.getCurrent();
607
+ if (currentSession) {
608
+ const forked = engine.sessionManager.create(process.cwd(), config.defaultModel);
609
+ forked.messages = [...currentSession.messages];
610
+ forked.forkedFrom = currentSession.id;
611
+ engine.sessionManager.save();
612
+ engine.ui.success(`Forked to new session: ${forked.id.slice(0, 20)}...`);
613
+ }
614
+ else {
615
+ engine.ui.error('No active session to fork');
711
616
  }
712
- }
713
- else if (pluginSub === 'load' && args[1]) {
617
+ break;
618
+ case 'mcp':
619
+ const mcpSub = args[0];
620
+ if (mcpSub === 'list') {
621
+ const servers = engine.mcpClient.listServers();
622
+ if (servers.length === 0) {
623
+ engine.ui.info('No MCP servers configured');
624
+ break;
625
+ }
626
+ console.log(chalk.bold('\nMCP Servers:\n'));
627
+ for (const s of servers) {
628
+ const status = s.connected ? chalk.green('connected') : chalk.gray('disconnected');
629
+ console.log(` ${chalk.cyan(s.name.padEnd(20))} ${status} ${chalk.gray(`${s.toolCount} tools`)} ${chalk.gray(s.config.transport)}`);
630
+ }
631
+ }
632
+ else if (mcpSub === 'connect' && args[1]) {
633
+ try {
634
+ const cfg = engine.mcpClient.loadConfig();
635
+ if (cfg.mcpServers[args[1]]) {
636
+ await engine.mcpClient.connect(args[1], cfg.mcpServers[args[1]]);
637
+ engine.ui.success(`Connected to MCP server: ${args[1]}`);
638
+ }
639
+ else {
640
+ engine.ui.error(`MCP server "${args[1]}" not found`);
641
+ }
642
+ }
643
+ catch (e) {
644
+ engine.ui.error(`Failed to connect: ${e instanceof Error ? e.message : String(e)}`);
645
+ }
646
+ }
647
+ else if (mcpSub === 'disconnect' && args[1]) {
648
+ await engine.mcpClient.disconnect(args[1]);
649
+ engine.ui.success(`Disconnected from ${args[1]}`);
650
+ }
651
+ else if (mcpSub === 'health') {
652
+ engine.mcpClient.healthReport();
653
+ }
654
+ else {
655
+ console.log(chalk.bold('\nMCP Commands:\n'));
656
+ console.log(' /mcp list List MCP servers');
657
+ console.log(' /mcp connect <name> Connect to a server');
658
+ console.log(' /mcp disconnect <name> Disconnect from a server');
659
+ console.log(' /mcp health Show MCP health report');
660
+ }
661
+ break;
662
+ case 'permission':
663
+ case 'perm':
664
+ if (args[0]) {
665
+ const validModes = ['manual', 'auto', 'plan', 'yolo'];
666
+ if (validModes.includes(args[0])) {
667
+ engine.approval.setMode(args[0]);
668
+ engine.ui.success(`${engine.approval.getModeIcon()} Permission: ${args[0]} (${engine.approval.getModeDescription()})`);
669
+ }
670
+ else {
671
+ engine.ui.error(`Invalid mode. Use: ${validModes.join(', ')}`);
672
+ }
673
+ }
674
+ else {
675
+ const newMode = engine.approval.cycleMode();
676
+ engine.ui.success(`${engine.approval.getModeIcon()} Permission: ${newMode} (${engine.approval.getModeDescription()})`);
677
+ }
678
+ break;
679
+ case 'init':
680
+ engine.ui.info('Initializing NEURO.md for this project...');
714
681
  try {
715
- await engine.pluginManager.loadByName(args[1]);
716
- engine.ui.success(`Plugin "${args[1]}" loaded`);
682
+ const { NeuroMdSystem } = await import('./context/neuro-md.js');
683
+ const nmd = new NeuroMdSystem(process.cwd());
684
+ nmd.load();
685
+ const content = `# Project Context\n\nThis file provides persistent context for NeuroCLI.\n\n## Tech Stack\n- [Detected automatically]\n\n## Conventions\n- Follow existing code patterns\n- Use TypeScript for all new files\n\n## Notes\n- This file is auto-generated by /init\n`;
686
+ const { writeFileSync } = await import('fs');
687
+ const { join } = await import('path');
688
+ writeFileSync(join(process.cwd(), 'NEURO.md'), content, 'utf-8');
689
+ engine.ui.success('NEURO.md created');
717
690
  }
718
691
  catch (e) {
719
- engine.ui.error(`Failed to load plugin: ${e instanceof Error ? e.message : String(e)}`);
720
- }
721
- }
722
- else {
723
- console.log(chalk.bold('\nPlugin Commands:\n'));
724
- console.log(' /plugins list List loaded plugins');
725
- console.log(' /plugins load <name> Load a plugin');
726
- }
727
- break;
728
- case 'whitelist':
729
- if (args[0] === 'add' && args[1]) {
730
- engine.approval.addToWhitelist(args[1]);
731
- engine.ui.success(`Added "${args[1]}" to whitelist`);
732
- }
733
- else if (args[0] === 'remove' && args[1]) {
734
- engine.approval.removeFromWhitelist(args[1]);
735
- engine.ui.success(`Removed "${args[1]}" from whitelist`);
736
- }
737
- else if (args[0] === 'list') {
738
- const wl = engine.approval.getWhitelist();
739
- console.log(chalk.bold('\nWhitelisted tools:\n'));
740
- for (const t of wl)
741
- console.log(` ${chalk.green('+')} ${t}`);
742
- }
743
- else {
744
- console.log('Usage: /whitelist add|remove|list <tool>');
745
- }
746
- break;
747
- case 'blacklist':
748
- if (args[0] === 'add' && args[1]) {
749
- engine.approval.addToBlacklist(args[1]);
750
- engine.ui.success(`Added "${args[1]}" to blacklist`);
751
- }
752
- else if (args[0] === 'remove' && args[1]) {
753
- engine.approval.removeFromBlacklist(args[1]);
754
- engine.ui.success(`Removed "${args[1]}" from blacklist`);
755
- }
756
- else if (args[0] === 'list') {
757
- const bl = engine.approval.getBlacklist();
758
- console.log(chalk.bold('\nBlacklisted tools:\n'));
759
- for (const t of bl)
760
- console.log(` ${chalk.red('-')} ${t}`);
761
- }
762
- else {
763
- console.log('Usage: /blacklist add|remove|list <tool>');
764
- }
765
- break;
766
- // --- v3.0 New Commands ---
767
- case 'style':
768
- if (args[0]) {
769
- if (engine.styleManager.setStyle(args[0])) {
770
- engine.ui.success(`Output style: ${args[0]}`);
692
+ engine.ui.error('Could not create NEURO.md: ' + (e instanceof Error ? e.message : String(e)));
693
+ }
694
+ break;
695
+ case 'unpause':
696
+ engine.doomLoop.unpause();
697
+ break;
698
+ case 'sandbox':
699
+ if (args[0] === 'on' || args[0] === 'enable') {
700
+ engine.sandbox.enable();
701
+ engine.ui.success('Sandbox mode enabled');
702
+ }
703
+ else if (args[0] === 'off' || args[0] === 'disable') {
704
+ engine.sandbox.disable();
705
+ engine.ui.success('Sandbox mode disabled');
706
+ }
707
+ else if (args[0] === 'status') {
708
+ engine.sandbox.printStatus();
709
+ }
710
+ else if (args[0] === 'undo') {
711
+ const undone = engine.sandbox.undoAll();
712
+ engine.ui.success(`Undone ${undone} file modifications`);
771
713
  }
772
714
  else {
773
- engine.ui.error(`Unknown style. Available: ${engine.styleManager.listStyles().map(s => s.name).join(', ')}`);
774
- }
775
- }
776
- else {
777
- engine.styleManager.printStyles();
778
- }
779
- break;
780
- case 'thinking':
781
- if (args[0]) {
782
- const modes = ['none', 'brief', 'full', 'ultrathink'];
783
- if (modes.includes(args[0])) {
784
- engine.extendedThinking.setMode(args[0]);
785
- if (args[0] !== 'none' && !engine.extendedThinking.isDisplayEnabled()) {
786
- engine.extendedThinking.toggleDisplay();
715
+ const enabled = engine.sandbox.toggle();
716
+ engine.ui.success(enabled ? 'Sandbox mode enabled' : 'Sandbox mode disabled');
717
+ }
718
+ break;
719
+ case 'plugins':
720
+ case 'plugin':
721
+ const pluginSub = args[0];
722
+ if (pluginSub === 'list') {
723
+ const plugins = engine.pluginManager.listPlugins();
724
+ if (plugins.length === 0) {
725
+ engine.ui.info('No plugins loaded');
726
+ break;
727
+ }
728
+ console.log(chalk.bold('\nPlugins:\n'));
729
+ for (const p of plugins) {
730
+ console.log(` ${chalk.cyan(p.name)} v${p.version} - ${chalk.gray(p.description)} ${chalk.green(`${p.toolCount} tools`)}`);
731
+ }
732
+ }
733
+ else if (pluginSub === 'load' && args[1]) {
734
+ try {
735
+ await engine.pluginManager.loadByName(args[1]);
736
+ engine.ui.success(`Plugin "${args[1]}" loaded`);
737
+ }
738
+ catch (e) {
739
+ engine.ui.error(`Failed to load plugin: ${e instanceof Error ? e.message : String(e)}`);
787
740
  }
788
- engine.ui.success(`Thinking mode: ${args[0]}`);
789
741
  }
790
742
  else {
791
- engine.ui.error(`Invalid mode. Use: ${modes.join(', ')}`);
792
- }
793
- }
794
- else {
795
- const currentMode = engine.extendedThinking.getMode();
796
- const showing = engine.extendedThinking.isDisplayEnabled() ? 'visible' : 'hidden';
797
- console.log(chalk.bold(`\nThinking Mode: ${chalk.cyan(currentMode)} (display: ${showing})`));
798
- console.log(chalk.gray(' Toggle display: /thinking toggle'));
799
- console.log(chalk.gray(' Set mode: /thinking none|brief|full|ultrathink'));
800
- console.log();
801
- }
802
- break;
803
- case 'skills':
804
- const skillSub = args[0];
805
- if (skillSub === 'list') {
806
- engine.skillSystem.listSkills();
807
- }
808
- else if (skillSub === 'activate' && args[1]) {
809
- const activated = engine.skillSystem.activate(args[1]);
810
- if (activated) {
811
- engine.ui.success(`Skill activated: ${args[1]}`);
743
+ console.log(chalk.bold('\nPlugin Commands:\n'));
744
+ console.log(' /plugins list List loaded plugins');
745
+ console.log(' /plugins load <name> Load a plugin');
746
+ }
747
+ break;
748
+ case 'whitelist':
749
+ if (args[0] === 'add' && args[1]) {
750
+ engine.approval.addToWhitelist(args[1]);
751
+ engine.ui.success(`Added "${args[1]}" to whitelist`);
752
+ }
753
+ else if (args[0] === 'remove' && args[1]) {
754
+ engine.approval.removeFromWhitelist(args[1]);
755
+ engine.ui.success(`Removed "${args[1]}" from whitelist`);
756
+ }
757
+ else if (args[0] === 'list') {
758
+ const wl = engine.approval.getWhitelist();
759
+ console.log(chalk.bold('\nWhitelisted tools:\n'));
760
+ for (const t of wl)
761
+ console.log(` ${chalk.green('+')} ${t}`);
812
762
  }
813
763
  else {
814
- engine.ui.error(`Skill not found: ${args[1]}`);
764
+ console.log('Usage: /whitelist add|remove|list <tool>');
765
+ }
766
+ break;
767
+ case 'blacklist':
768
+ if (args[0] === 'add' && args[1]) {
769
+ engine.approval.addToBlacklist(args[1]);
770
+ engine.ui.success(`Added "${args[1]}" to blacklist`);
771
+ }
772
+ else if (args[0] === 'remove' && args[1]) {
773
+ engine.approval.removeFromBlacklist(args[1]);
774
+ engine.ui.success(`Removed "${args[1]}" from blacklist`);
815
775
  }
816
- }
817
- else if (skillSub === 'deactivate' && args[1]) {
818
- if (engine.skillSystem.deactivate(args[1])) {
819
- engine.ui.success(`Skill deactivated: ${args[1]}`);
776
+ else if (args[0] === 'list') {
777
+ const bl = engine.approval.getBlacklist();
778
+ console.log(chalk.bold('\nBlacklisted tools:\n'));
779
+ for (const t of bl)
780
+ console.log(` ${chalk.red('-')} ${t}`);
820
781
  }
821
782
  else {
822
- engine.ui.error(`Skill not active: ${args[1]}`);
823
- }
824
- }
825
- else if (skillSub === 'clear') {
826
- engine.skillSystem.deactivateAll();
827
- engine.ui.success('All skills deactivated');
828
- }
829
- else {
830
- console.log(chalk.bold('\nSkill Commands:\n'));
831
- console.log(' /skills list List all skills');
832
- console.log(' /skills activate <name> Activate a skill');
833
- console.log(' /skills deactivate <name> Deactivate a skill');
834
- console.log(' /skills clear Deactivate all skills');
835
- }
836
- break;
837
- case 'effort':
838
- if (args[0]) {
839
- const levels = ['low', 'medium', 'high', 'ultrathink'];
840
- if (levels.includes(args[0])) {
841
- engine.modelRouter.setEffort(args[0]);
842
- engine.ui.success(`Effort level: ${args[0]}`);
783
+ console.log('Usage: /blacklist add|remove|list <tool>');
784
+ }
785
+ break;
786
+ // --- v3.0 New Commands ---
787
+ case 'style':
788
+ if (args[0]) {
789
+ if (engine.styleManager.setStyle(args[0])) {
790
+ engine.ui.success(`Output style: ${args[0]}`);
791
+ }
792
+ else {
793
+ engine.ui.error(`Unknown style. Available: ${engine.styleManager.listStyles().map(s => s.name).join(', ')}`);
794
+ }
843
795
  }
844
796
  else {
845
- engine.ui.error(`Invalid level. Use: ${levels.join(', ')}`);
797
+ engine.styleManager.printStyles();
846
798
  }
847
- }
848
- else {
849
- console.log(chalk.bold(`\nEffort Level: ${chalk.cyan(engine.modelRouter.getEffort())}`));
850
- console.log(chalk.gray(' Set level: /effort low|medium|high|ultrathink'));
851
- console.log();
852
- }
853
- break;
854
- case 'cache':
855
- const cacheSub = args[0];
856
- if (cacheSub === 'on') {
857
- config.promptCache.enabled = true;
858
- engine.ui.success('Prompt cache enabled');
859
- }
860
- else if (cacheSub === 'off') {
861
- config.promptCache.enabled = false;
862
- engine.ui.success('Prompt cache disabled');
863
- }
864
- else if (cacheSub === 'clear') {
865
- engine.promptCache.clear();
866
- engine.ui.success('Cache cleared');
867
- }
868
- else if (cacheSub === 'stats') {
869
- engine.promptCache.printStats();
870
- }
871
- else {
872
- const status = config.promptCache.enabled ? chalk.green('enabled') : chalk.gray('disabled');
873
- console.log(chalk.bold(`\nPrompt Cache: ${status}`));
874
- console.log(chalk.gray(' /cache on|off|clear|stats'));
799
+ break;
800
+ case 'thinking':
801
+ if (args[0]) {
802
+ const modes = ['none', 'brief', 'full', 'ultrathink'];
803
+ if (modes.includes(args[0])) {
804
+ engine.extendedThinking.setMode(args[0]);
805
+ if (args[0] !== 'none' && !engine.extendedThinking.isDisplayEnabled()) {
806
+ engine.extendedThinking.toggleDisplay();
807
+ }
808
+ engine.ui.success(`Thinking mode: ${args[0]}`);
809
+ }
810
+ else {
811
+ engine.ui.error(`Invalid mode. Use: ${modes.join(', ')}`);
812
+ }
813
+ }
814
+ else {
815
+ const currentMode = engine.extendedThinking.getMode();
816
+ const showing = engine.extendedThinking.isDisplayEnabled() ? 'visible' : 'hidden';
817
+ console.log(chalk.bold(`\nThinking Mode: ${chalk.cyan(currentMode)} (display: ${showing})`));
818
+ console.log(chalk.gray(' Toggle display: /thinking toggle'));
819
+ console.log(chalk.gray(' Set mode: /thinking none|brief|full|ultrathink'));
820
+ console.log();
821
+ }
822
+ break;
823
+ case 'skills':
824
+ const skillSub = args[0];
825
+ if (skillSub === 'list') {
826
+ engine.skillSystem.listSkills();
827
+ }
828
+ else if (skillSub === 'activate' && args[1]) {
829
+ const activated = engine.skillSystem.activate(args[1]);
830
+ if (activated) {
831
+ engine.ui.success(`Skill activated: ${args[1]}`);
832
+ }
833
+ else {
834
+ engine.ui.error(`Skill not found: ${args[1]}`);
835
+ }
836
+ }
837
+ else if (skillSub === 'deactivate' && args[1]) {
838
+ if (engine.skillSystem.deactivate(args[1])) {
839
+ engine.ui.success(`Skill deactivated: ${args[1]}`);
840
+ }
841
+ else {
842
+ engine.ui.error(`Skill not active: ${args[1]}`);
843
+ }
844
+ }
845
+ else if (skillSub === 'clear') {
846
+ engine.skillSystem.deactivateAll();
847
+ engine.ui.success('All skills deactivated');
848
+ }
849
+ else {
850
+ console.log(chalk.bold('\nSkill Commands:\n'));
851
+ console.log(' /skills list List all skills');
852
+ console.log(' /skills activate <name> Activate a skill');
853
+ console.log(' /skills deactivate <name> Deactivate a skill');
854
+ console.log(' /skills clear Deactivate all skills');
855
+ }
856
+ break;
857
+ case 'effort':
858
+ if (args[0]) {
859
+ const levels = ['low', 'medium', 'high', 'ultrathink'];
860
+ if (levels.includes(args[0])) {
861
+ engine.modelRouter.setEffort(args[0]);
862
+ engine.ui.success(`Effort level: ${args[0]}`);
863
+ }
864
+ else {
865
+ engine.ui.error(`Invalid level. Use: ${levels.join(', ')}`);
866
+ }
867
+ }
868
+ else {
869
+ console.log(chalk.bold(`\nEffort Level: ${chalk.cyan(engine.modelRouter.getEffort())}`));
870
+ console.log(chalk.gray(' Set level: /effort low|medium|high|ultrathink'));
871
+ console.log();
872
+ }
873
+ break;
874
+ case 'cache':
875
+ const cacheSub = args[0];
876
+ if (cacheSub === 'on') {
877
+ config.promptCache.enabled = true;
878
+ engine.ui.success('Prompt cache enabled');
879
+ }
880
+ else if (cacheSub === 'off') {
881
+ config.promptCache.enabled = false;
882
+ engine.ui.success('Prompt cache disabled');
883
+ }
884
+ else if (cacheSub === 'clear') {
885
+ engine.promptCache.clear();
886
+ engine.ui.success('Cache cleared');
887
+ }
888
+ else if (cacheSub === 'stats') {
889
+ engine.promptCache.printStats();
890
+ }
891
+ else {
892
+ const status = config.promptCache.enabled ? chalk.green('enabled') : chalk.gray('disabled');
893
+ console.log(chalk.bold(`\nPrompt Cache: ${status}`));
894
+ console.log(chalk.gray(' /cache on|off|clear|stats'));
895
+ console.log();
896
+ }
897
+ break;
898
+ case 'spending':
899
+ engine.spendingMonitor.printReport();
900
+ break;
901
+ case 'ignore':
902
+ if (args[0] === 'list') {
903
+ engine.neuroIgnore.printRules();
904
+ }
905
+ else if (args[0] === 'add' && args[1]) {
906
+ engine.neuroIgnore.addRule(args[1], 'manual');
907
+ engine.ui.success(`Added ignore rule: ${args[1]}`);
908
+ }
909
+ else if (args[0] === 'check' && args[1]) {
910
+ const ignored = engine.neuroIgnore.isIgnored(args[1]);
911
+ console.log(` ${args[1]}: ${ignored ? chalk.red('ignored') : chalk.green('allowed')}`);
912
+ }
913
+ else {
914
+ console.log(chalk.bold('\nIgnore Commands:\n'));
915
+ console.log(' /ignore list List ignore rules');
916
+ console.log(' /ignore add <pattern> Add an ignore pattern');
917
+ console.log(' /ignore check <path> Check if a path is ignored');
918
+ }
919
+ break;
920
+ case 'ollama':
921
+ try {
922
+ const available = await engine.ollamaProvider.isAvailable();
923
+ if (!available) {
924
+ engine.ui.error('Ollama is not running. Start it with: ollama serve');
925
+ break;
926
+ }
927
+ const models = await engine.ollamaProvider.listModels();
928
+ console.log(chalk.bold('\nOllama Local Models:\n'));
929
+ for (const m of models) {
930
+ const isActive = config.defaultModel === m.name;
931
+ console.log(` ${isActive ? chalk.green('*') : ' '} ${chalk.cyan(m.name.padEnd(40))} ${chalk.gray(m.details?.parameter_size || '')} ${chalk.gray(m.details?.quantization_level || '')}`);
932
+ }
933
+ console.log(chalk.gray('\nSwitch model: /model <name>'));
934
+ }
935
+ catch (e) {
936
+ engine.ui.error('Could not connect to Ollama');
937
+ }
938
+ break;
939
+ case 'doctor':
940
+ console.log(chalk.bold('\nNeuroCLI v4.1.2 Health Check:\n'));
941
+ console.log(` API Key: ${config.apiKey ? chalk.green('configured') : chalk.red('MISSING')}`);
942
+ console.log(` Default Model: ${chalk.cyan(config.defaultModel)} ${MODELS[config.defaultModel] ? chalk.green('valid') : chalk.red('INVALID')}`);
943
+ console.log(` MCP Servers: ${chalk.cyan(String(engine.mcpClient.listServers().length))}`);
944
+ console.log(` Permission Mode: ${chalk.cyan(engine.approval.getMode())}`);
945
+ console.log(` Diff Preview: ${config.diffPreview ? chalk.green('enabled') : chalk.gray('disabled')}`);
946
+ console.log(` Fallback Chain: ${config.fallbackChain.models.length > 0 ? chalk.green(config.fallbackChain.models.length + ' models') : chalk.yellow('none')}`);
947
+ console.log(` Doom Loop Protection: ${config.doomLoop.autoBreak ? chalk.green('enabled') : chalk.yellow('disabled')}`);
948
+ console.log(` Sandbox: ${engine.sandbox.isEnabled() ? chalk.green('enabled') : chalk.gray('disabled')}`);
949
+ console.log(` Plugins: ${chalk.cyan(String(engine.pluginManager.listPlugins().length))}`);
950
+ console.log(` Custom Agents: ${chalk.cyan(String(engine.customAgentLoader.getAll().length))}`);
951
+ console.log(` Custom Tools: ${chalk.cyan(String(engine.customToolLoader.getAll().length))}`);
952
+ console.log(` Skills: ${chalk.cyan(String(engine.skillSystem.getAllSkills().length))} (${chalk.cyan(String(engine.skillSystem.getActiveSkills().length))} active)`);
953
+ console.log(` Prompt Cache: ${config.promptCache.enabled ? chalk.green('enabled') : chalk.gray('disabled')}`);
954
+ console.log(` Output Style: ${chalk.cyan(engine.styleManager.getStyle().name)}`);
955
+ console.log(` Thinking Mode: ${chalk.cyan(engine.extendedThinking.getMode())}`);
956
+ console.log(` Effort Level: ${chalk.cyan(engine.modelRouter.getEffort())}`);
957
+ console.log(` Sessions: ${chalk.cyan(String(engine.sessionManager.list().length))}`);
958
+ console.log(` Spending Limit: ${config.spendingLimit > 0 ? chalk.cyan('$' + config.spendingLimit.toFixed(2)) : chalk.gray('unlimited')}`);
959
+ console.log(` Ignore Rules: ${chalk.cyan(String(engine.neuroIgnore.getRules().length))}`);
960
+ // Check Ollama availability
961
+ const ollamaAvail = await engine.ollamaProvider.isAvailable().catch(() => false);
962
+ console.log(` Ollama: ${ollamaAvail ? chalk.green('available') : chalk.gray('not running')}`);
963
+ // Update check status
964
+ const lastUpdateCheck = updater.getLastCheck();
965
+ const updateStatus = lastUpdateCheck?.hasUpdate ? chalk.yellow(`update available (v${lastUpdateCheck.latestVersion})`) : chalk.green('up to date');
966
+ console.log(` Auto-Update: ${updateStatus}`);
967
+ const nextCheck = updater.timeUntilNextCheck();
968
+ const nextCheckStr = nextCheck > 0 ? ` (next check in ${Math.floor(nextCheck / 3600000)}h)` : '';
969
+ console.log(` Update Check: ${chalk.gray('enabled' + nextCheckStr)}`);
875
970
  console.log();
876
- }
877
- break;
878
- case 'spending':
879
- engine.spendingMonitor.printReport();
880
- break;
881
- case 'ignore':
882
- if (args[0] === 'list') {
883
- engine.neuroIgnore.printRules();
884
- }
885
- else if (args[0] === 'add' && args[1]) {
886
- engine.neuroIgnore.addRule(args[1], 'manual');
887
- engine.ui.success(`Added ignore rule: ${args[1]}`);
888
- }
889
- else if (args[0] === 'check' && args[1]) {
890
- const ignored = engine.neuroIgnore.isIgnored(args[1]);
891
- console.log(` ${args[1]}: ${ignored ? chalk.red('ignored') : chalk.green('allowed')}`);
892
- }
893
- else {
894
- console.log(chalk.bold('\nIgnore Commands:\n'));
895
- console.log(' /ignore list List ignore rules');
896
- console.log(' /ignore add <pattern> Add an ignore pattern');
897
- console.log(' /ignore check <path> Check if a path is ignored');
898
- }
899
- break;
900
- case 'ollama':
901
- try {
902
- const available = await engine.ollamaProvider.isAvailable();
903
- if (!available) {
904
- engine.ui.error('Ollama is not running. Start it with: ollama serve');
971
+ break;
972
+ case 'export':
973
+ const exportSession = engine.sessionManager.getCurrent();
974
+ if (exportSession) {
975
+ const exportPath = args[0] || 'neuro-session-export.json';
976
+ const exportData = {
977
+ version: VERSION,
978
+ exportedAt: Date.now(),
979
+ session: exportSession,
980
+ neuroVersion: VERSION,
981
+ };
982
+ try {
983
+ writeFileSync(exportPath, JSON.stringify(exportData, null, 2), 'utf-8');
984
+ engine.ui.success(`Session exported to ${exportPath}`);
985
+ }
986
+ catch (e) {
987
+ console.log(JSON.stringify(exportSession, null, 2));
988
+ }
989
+ }
990
+ else {
991
+ engine.ui.warning('No active session to export');
992
+ }
993
+ break;
994
+ case 'import':
995
+ const importPath = args[0];
996
+ if (!importPath) {
997
+ engine.ui.error('Usage: /import <path-to-json-file>');
905
998
  break;
906
999
  }
907
- const models = await engine.ollamaProvider.listModels();
908
- console.log(chalk.bold('\nOllama Local Models:\n'));
909
- for (const m of models) {
910
- const isActive = config.defaultModel === m.name;
911
- console.log(` ${isActive ? chalk.green('*') : ' '} ${chalk.cyan(m.name.padEnd(40))} ${chalk.gray(m.details?.parameter_size || '')} ${chalk.gray(m.details?.quantization_level || '')}`);
912
- }
913
- console.log(chalk.gray('\nSwitch model: /model <name>'));
914
- }
915
- catch (e) {
916
- engine.ui.error('Could not connect to Ollama');
917
- }
918
- break;
919
- case 'doctor':
920
- console.log(chalk.bold('\nNeuroCLI v4.1.2 Health Check:\n'));
921
- console.log(` API Key: ${config.apiKey ? chalk.green('configured') : chalk.red('MISSING')}`);
922
- console.log(` Default Model: ${chalk.cyan(config.defaultModel)} ${MODELS[config.defaultModel] ? chalk.green('valid') : chalk.red('INVALID')}`);
923
- console.log(` MCP Servers: ${chalk.cyan(String(engine.mcpClient.listServers().length))}`);
924
- console.log(` Permission Mode: ${chalk.cyan(engine.approval.getMode())}`);
925
- console.log(` Diff Preview: ${config.diffPreview ? chalk.green('enabled') : chalk.gray('disabled')}`);
926
- console.log(` Fallback Chain: ${config.fallbackChain.models.length > 0 ? chalk.green(config.fallbackChain.models.length + ' models') : chalk.yellow('none')}`);
927
- console.log(` Doom Loop Protection: ${config.doomLoop.autoBreak ? chalk.green('enabled') : chalk.yellow('disabled')}`);
928
- console.log(` Sandbox: ${engine.sandbox.isEnabled() ? chalk.green('enabled') : chalk.gray('disabled')}`);
929
- console.log(` Plugins: ${chalk.cyan(String(engine.pluginManager.listPlugins().length))}`);
930
- console.log(` Custom Agents: ${chalk.cyan(String(engine.customAgentLoader.getAll().length))}`);
931
- console.log(` Custom Tools: ${chalk.cyan(String(engine.customToolLoader.getAll().length))}`);
932
- console.log(` Skills: ${chalk.cyan(String(engine.skillSystem.getAllSkills().length))} (${chalk.cyan(String(engine.skillSystem.getActiveSkills().length))} active)`);
933
- console.log(` Prompt Cache: ${config.promptCache.enabled ? chalk.green('enabled') : chalk.gray('disabled')}`);
934
- console.log(` Output Style: ${chalk.cyan(engine.styleManager.getStyle().name)}`);
935
- console.log(` Thinking Mode: ${chalk.cyan(engine.extendedThinking.getMode())}`);
936
- console.log(` Effort Level: ${chalk.cyan(engine.modelRouter.getEffort())}`);
937
- console.log(` Sessions: ${chalk.cyan(String(engine.sessionManager.list().length))}`);
938
- console.log(` Spending Limit: ${config.spendingLimit > 0 ? chalk.cyan('$' + config.spendingLimit.toFixed(2)) : chalk.gray('unlimited')}`);
939
- console.log(` Ignore Rules: ${chalk.cyan(String(engine.neuroIgnore.getRules().length))}`);
940
- // Check Ollama availability
941
- const ollamaAvail = await engine.ollamaProvider.isAvailable().catch(() => false);
942
- console.log(` Ollama: ${ollamaAvail ? chalk.green('available') : chalk.gray('not running')}`);
943
- // Update check status
944
- const lastUpdateCheck = updater.getLastCheck();
945
- const updateStatus = lastUpdateCheck?.hasUpdate ? chalk.yellow(`update available (v${lastUpdateCheck.latestVersion})`) : chalk.green('up to date');
946
- console.log(` Auto-Update: ${updateStatus}`);
947
- const nextCheck = updater.timeUntilNextCheck();
948
- const nextCheckStr = nextCheck > 0 ? ` (next check in ${Math.floor(nextCheck / 3600000)}h)` : '';
949
- console.log(` Update Check: ${chalk.gray('enabled' + nextCheckStr)}`);
950
- console.log();
951
- break;
952
- case 'export':
953
- const exportSession = engine.sessionManager.getCurrent();
954
- if (exportSession) {
955
- const exportPath = args[0] || 'neuro-session-export.json';
956
- const exportData = {
957
- version: VERSION,
958
- exportedAt: Date.now(),
959
- session: exportSession,
960
- neuroVersion: VERSION,
961
- };
962
1000
  try {
963
- writeFileSync(exportPath, JSON.stringify(exportData, null, 2), 'utf-8');
964
- engine.ui.success(`Session exported to ${exportPath}`);
1001
+ const importData = JSON.parse(readFileSync(importPath, 'utf-8'));
1002
+ const sessionData = importData.session || importData;
1003
+ const newSession = engine.sessionManager.create(process.cwd(), sessionData.model || config.defaultModel);
1004
+ if (sessionData.messages)
1005
+ newSession.messages = sessionData.messages;
1006
+ if (sessionData.totalInputTokens)
1007
+ newSession.totalInputTokens = sessionData.totalInputTokens;
1008
+ if (sessionData.totalOutputTokens)
1009
+ newSession.totalOutputTokens = sessionData.totalOutputTokens;
1010
+ if (sessionData.totalCost)
1011
+ newSession.totalCost = sessionData.totalCost;
1012
+ engine.sessionManager.save();
1013
+ engine.ui.success(`Session imported: ${newSession.id.slice(0, 20)}... (${newSession.messages.length} messages)`);
965
1014
  }
966
1015
  catch (e) {
967
- console.log(JSON.stringify(exportSession, null, 2));
968
- }
969
- }
970
- else {
971
- engine.ui.warning('No active session to export');
972
- }
973
- break;
974
- case 'import':
975
- const importPath = args[0];
976
- if (!importPath) {
977
- engine.ui.error('Usage: /import <path-to-json-file>');
1016
+ engine.ui.error(`Failed to import: ${e instanceof Error ? e.message : String(e)}`);
1017
+ }
978
1018
  break;
979
- }
980
- try {
981
- const importData = JSON.parse(readFileSync(importPath, 'utf-8'));
982
- const sessionData = importData.session || importData;
983
- const newSession = engine.sessionManager.create(process.cwd(), sessionData.model || config.defaultModel);
984
- if (sessionData.messages)
985
- newSession.messages = sessionData.messages;
986
- if (sessionData.totalInputTokens)
987
- newSession.totalInputTokens = sessionData.totalInputTokens;
988
- if (sessionData.totalOutputTokens)
989
- newSession.totalOutputTokens = sessionData.totalOutputTokens;
990
- if (sessionData.totalCost)
991
- newSession.totalCost = sessionData.totalCost;
992
- engine.sessionManager.save();
993
- engine.ui.success(`Session imported: ${newSession.id.slice(0, 20)}... (${newSession.messages.length} messages)`);
994
- }
995
- catch (e) {
996
- engine.ui.error(`Failed to import: ${e instanceof Error ? e.message : String(e)}`);
997
- }
998
- break;
999
- case 'commit-push-pr':
1000
- engine.ui.info('Running commit + push + PR workflow...');
1001
- try {
1002
- const { execSync } = await import('child_process');
1003
- // Stage all
1004
- execSync('git add -A', { cwd: process.cwd(), encoding: 'utf-8' });
1005
- // Commit
1006
- const commitMsg = args.join(' ') || 'Update from NeuroCLI';
1007
- execSync(`git commit -m "${commitMsg}" --no-gpg-sign`, { cwd: process.cwd(), encoding: 'utf-8' });
1008
- // Push
1009
- execSync('git push', { cwd: process.cwd(), encoding: 'utf-8' });
1010
- engine.ui.success('Changes committed and pushed');
1011
- // Try to create PR with gh CLI
1019
+ case 'commit-push-pr':
1020
+ engine.ui.info('Running commit + push + PR workflow...');
1012
1021
  try {
1013
- const prResult = execSync(`gh pr create --title "${commitMsg}" --body "Auto-generated by NeuroCLI"`, { cwd: process.cwd(), encoding: 'utf-8' });
1014
- engine.ui.success(`PR created: ${prResult.trim()}`);
1015
- }
1016
- catch {
1017
- engine.ui.info('Could not create PR (gh CLI not available or not a GitHub repo)');
1018
- }
1019
- }
1020
- catch (e) {
1021
- engine.ui.error(`Git operation failed: ${e instanceof Error ? e.message : String(e)}`);
1022
- }
1023
- break;
1024
- case 'code-review':
1025
- engine.ui.info('Starting multi-agent code review...');
1026
- try {
1027
- const reviewResult = await engine.processMessage('Perform a thorough code review of all recent changes in this repository. Check for: bugs, security issues, performance problems, code style, test coverage. Provide findings with severity levels (CRITICAL, WARNING, INFO).', 'agent');
1028
- }
1029
- catch (e) {
1030
- engine.ui.error(`Code review failed: ${e instanceof Error ? e.message : String(e)}`);
1031
- }
1032
- break;
1033
- case 'feedback':
1034
- console.log(chalk.bold('\nFeedback:\n'));
1035
- console.log(' Report issues: https://github.com/neuro-cli/neuro/issues');
1036
- console.log(' Discussions: https://github.com/neuro-cli/neuro/discussions');
1037
- console.log(chalk.gray('\n Your feedback helps make NeuroCLI better!'));
1038
- console.log();
1039
- break;
1040
- case 'cost':
1041
- engine.spendingMonitor.printReport();
1042
- if (engine.promptCache) {
1043
- console.log(chalk.bold('\nCache Savings:'));
1044
- engine.promptCache.printStats();
1045
- }
1046
- break;
1047
- case 'update':
1048
- case 'upgrade':
1049
- const updateSub = args[0];
1050
- if (updateSub === 'now') {
1051
- engine.ui.info('Updating NeuroCLI...');
1052
- const updateResult = await updater.performUpdate();
1053
- if (updateResult.success) {
1054
- engine.ui.success(updateResult.message);
1055
- console.log(chalk.yellow(' Please restart NeuroCLI to use the new version.'));
1022
+ const { execSync } = await import('child_process');
1023
+ // Stage all
1024
+ execSync('git add -A', { cwd: process.cwd(), encoding: 'utf-8' });
1025
+ // Commit
1026
+ const commitMsg = args.join(' ') || 'Update from NeuroCLI';
1027
+ execSync(`git commit -m "${commitMsg}" --no-gpg-sign`, { cwd: process.cwd(), encoding: 'utf-8' });
1028
+ // Push
1029
+ execSync('git push', { cwd: process.cwd(), encoding: 'utf-8' });
1030
+ engine.ui.success('Changes committed and pushed');
1031
+ // Try to create PR with gh CLI
1032
+ try {
1033
+ const prResult = execSync(`gh pr create --title "${commitMsg}" --body "Auto-generated by NeuroCLI"`, { cwd: process.cwd(), encoding: 'utf-8' });
1034
+ engine.ui.success(`PR created: ${prResult.trim()}`);
1035
+ }
1036
+ catch {
1037
+ engine.ui.info('Could not create PR (gh CLI not available or not a GitHub repo)');
1038
+ }
1056
1039
  }
1057
- else {
1058
- engine.ui.error(updateResult.message);
1040
+ catch (e) {
1041
+ engine.ui.error(`Git operation failed: ${e instanceof Error ? e.message : String(e)}`);
1059
1042
  }
1060
- }
1061
- else if (updateSub === 'check') {
1062
- engine.ui.info('Checking for updates...');
1063
- const checkResult = await updater.checkForUpdate(true);
1064
- if (checkResult.hasUpdate) {
1065
- updater.showUpdateDetails(checkResult);
1066
- updater.showUpdateNotification(checkResult);
1043
+ break;
1044
+ case 'code-review':
1045
+ engine.ui.info('Starting multi-agent code review...');
1046
+ try {
1047
+ const reviewResult = await engine.processMessage('Perform a thorough code review of all recent changes in this repository. Check for: bugs, security issues, performance problems, code style, test coverage. Provide findings with severity levels (CRITICAL, WARNING, INFO).', 'agent');
1067
1048
  }
1068
- else {
1069
- updater.showUpToDate();
1049
+ catch (e) {
1050
+ engine.ui.error(`Code review failed: ${e instanceof Error ? e.message : String(e)}`);
1070
1051
  }
1071
- }
1072
- else if (updateSub === 'dismiss') {
1073
- const checkResult = await updater.checkForUpdate(true);
1074
- if (checkResult.hasUpdate) {
1075
- updater.dismissVersion(checkResult.latestVersion);
1076
- engine.ui.success(`Dismissed update notification for v${checkResult.latestVersion}`);
1052
+ break;
1053
+ case 'feedback':
1054
+ console.log(chalk.bold('\nFeedback:\n'));
1055
+ console.log(' Report issues: https://github.com/neuro-cli/neuro/issues');
1056
+ console.log(' Discussions: https://github.com/neuro-cli/neuro/discussions');
1057
+ console.log(chalk.gray('\n Your feedback helps make NeuroCLI better!'));
1058
+ console.log();
1059
+ break;
1060
+ case 'cost':
1061
+ engine.spendingMonitor.printReport();
1062
+ if (engine.promptCache) {
1063
+ console.log(chalk.bold('\nCache Savings:'));
1064
+ engine.promptCache.printStats();
1077
1065
  }
1078
- else {
1079
- engine.ui.info('No update to dismiss');
1080
- }
1081
- }
1082
- else if (updateSub === 'auto') {
1083
- const enableAuto = args[1] !== 'off';
1084
- updater.setAutoUpdate(enableAuto);
1085
- engine.ui.success(`Auto-update: ${enableAuto ? 'enabled' : 'disabled'}`);
1086
- }
1087
- else if (updateSub === 'interval') {
1088
- const hours = args[1] ? parseFloat(args[1]) : 24;
1089
- if (isNaN(hours) || hours < 1) {
1090
- engine.ui.error('Interval must be at least 1 hour');
1066
+ break;
1067
+ case 'update':
1068
+ case 'upgrade':
1069
+ const updateSub = args[0];
1070
+ if (updateSub === 'now') {
1071
+ engine.ui.info('Updating NeuroCLI...');
1072
+ const updateResult = await updater.performUpdate();
1073
+ if (updateResult.success) {
1074
+ engine.ui.success(updateResult.message);
1075
+ console.log(chalk.yellow(' Please restart NeuroCLI to use the new version.'));
1076
+ }
1077
+ else {
1078
+ engine.ui.error(updateResult.message);
1079
+ }
1080
+ }
1081
+ else if (updateSub === 'check') {
1082
+ engine.ui.info('Checking for updates...');
1083
+ const checkResult = await updater.checkForUpdate(true);
1084
+ if (checkResult.hasUpdate) {
1085
+ updater.showUpdateDetails(checkResult);
1086
+ updater.showUpdateNotification(checkResult);
1087
+ }
1088
+ else {
1089
+ updater.showUpToDate();
1090
+ }
1091
+ }
1092
+ else if (updateSub === 'dismiss') {
1093
+ const checkResult = await updater.checkForUpdate(true);
1094
+ if (checkResult.hasUpdate) {
1095
+ updater.dismissVersion(checkResult.latestVersion);
1096
+ engine.ui.success(`Dismissed update notification for v${checkResult.latestVersion}`);
1097
+ }
1098
+ else {
1099
+ engine.ui.info('No update to dismiss');
1100
+ }
1101
+ }
1102
+ else if (updateSub === 'auto') {
1103
+ const enableAuto = args[1] !== 'off';
1104
+ updater.setAutoUpdate(enableAuto);
1105
+ engine.ui.success(`Auto-update: ${enableAuto ? 'enabled' : 'disabled'}`);
1106
+ }
1107
+ else if (updateSub === 'interval') {
1108
+ const hours = args[1] ? parseFloat(args[1]) : 24;
1109
+ if (isNaN(hours) || hours < 1) {
1110
+ engine.ui.error('Interval must be at least 1 hour');
1111
+ }
1112
+ else {
1113
+ updater.setCheckInterval(hours);
1114
+ engine.ui.success(`Update check interval set to ${hours} hours`);
1115
+ }
1116
+ }
1117
+ else if (updateSub === 'reset') {
1118
+ updater.resetDismissed();
1119
+ updater.forceNextCheck();
1120
+ engine.ui.success('Update preferences reset');
1091
1121
  }
1092
1122
  else {
1093
- updater.setCheckInterval(hours);
1094
- engine.ui.success(`Update check interval set to ${hours} hours`);
1095
- }
1096
- }
1097
- else if (updateSub === 'reset') {
1098
- updater.resetDismissed();
1099
- updater.forceNextCheck();
1100
- engine.ui.success('Update preferences reset');
1101
- }
1102
- else {
1103
- // Default: interactive update flow
1104
- await updater.interactiveUpdate();
1105
- }
1106
- break;
1107
- case 'exit':
1108
- case 'quit':
1109
- case 'q':
1110
- engine.mcpClient.disconnectAll().catch(() => { });
1111
- engine.approval.close();
1112
- engine.ui.info('Goodbye!');
1113
- process.exit(0);
1114
- break;
1115
- default:
1116
- engine.ui.error(`Unknown command: /${cmd}. Type /help for available commands.`);
1123
+ // Default: interactive update flow
1124
+ await updater.interactiveUpdate();
1125
+ }
1126
+ break;
1127
+ case 'exit':
1128
+ case 'quit':
1129
+ case 'q':
1130
+ engine.mcpClient.disconnectAll().catch(() => { });
1131
+ engine.approval.close();
1132
+ engine.ui.info('Goodbye!');
1133
+ process.exit(0);
1134
+ break;
1135
+ default:
1136
+ engine.ui.error(`Unknown command: /${cmd}. Type /help for available commands.`);
1137
+ }
1138
+ rl.prompt();
1139
+ return;
1140
+ }
1141
+ // Process message with the engine
1142
+ try {
1143
+ isProcessing = true;
1144
+ await engine.processMessage(input, currentMode, currentAgent);
1145
+ }
1146
+ catch (error) {
1147
+ engine.ui.error(error instanceof Error ? error.message : String(error));
1148
+ }
1149
+ finally {
1150
+ isProcessing = false;
1117
1151
  }
1118
1152
  rl.prompt();
1119
- return;
1120
- }
1121
- // Process message with the engine
1122
- try {
1123
- isProcessing = true;
1124
- await engine.processMessage(input, currentMode, currentAgent);
1125
1153
  }
1126
1154
  catch (error) {
1127
- engine.ui.error(error instanceof Error ? error.message : String(error));
1128
- }
1129
- finally {
1155
+ // Catch-all for any unhandled error in the line handler
1156
+ console.error(chalk.red(`\n⚠️ Error: ${error instanceof Error ? error.message : String(error)}`));
1130
1157
  isProcessing = false;
1158
+ rl.prompt();
1131
1159
  }
1132
- rl.prompt();
1133
1160
  });
1134
- rl.on('close', () => {
1135
- engine.mcpClient.disconnectAll().catch(() => { });
1136
- engine.approval.close();
1161
+ rl.on('close', async () => {
1162
+ try {
1163
+ await engine.mcpClient.disconnectAll();
1164
+ }
1165
+ catch { }
1166
+ try {
1167
+ engine.approval.close();
1168
+ }
1169
+ catch { }
1170
+ try {
1171
+ engine.sessionManager.save();
1172
+ }
1173
+ catch { }
1137
1174
  engine.ui.info('Goodbye!');
1138
1175
  process.exit(0);
1139
1176
  });