File size: 5,499 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""Interactive Mode - Chat with the Agent"""

import sys
from rich.console import Console
from rich.prompt import Prompt, Confirm
from rich.panel import Panel
from rich.syntax import Syntax

from src.core import CoderAgent
from src.animations import TypingEffect
from src.ui.thanking import ThankYou, Appreciation
from src.ui.layout import ChatboxLayout


class InteractiveMode:
    """Interactive chat mode with the coder agent"""

    def __init__(self):
        self.console = Console()
        self.agent = CoderAgent()
        self.layout = ChatboxLayout()
        self.running = False
        self.history: list[dict] = []

    def start(self):
        """Start the interactive session"""
        self.running = True

        self.console.print(Panel.fit(
            "[bold cyan]🧑‍💻 Burme-Coder-Max Interactive Mode[/bold cyan]\n"
            "Type 'exit' to quit, 'clear' to clear history, 'help' for commands",
            border_style="cyan",
        ))

        while self.running:
            try:
                user_input = Prompt.ask("\n[bold green]You[/bold green]")

                if not user_input.strip():
                    continue

                self._handle_command(user_input)

            except KeyboardInterrupt:
                self.console.print("\n[yellow]Interrupted. Type 'exit' to quit.[/yellow]")
            except EOFError:
                self._exit()

    def _handle_command(self, user_input: str):
        """Handle user input or commands"""
        cmd = user_input.strip().lower()

        if cmd == "exit":
            self._exit()
        elif cmd == "clear":
            self._clear_history()
        elif cmd == "help":
            self._show_help()
        elif cmd == "history":
            self._show_history()
        elif cmd == "thank":
            ThankYou.show()
        elif cmd.startswith("/"):
            self._handle_slash_command(user_input)
        else:
            self._generate_response(user_input)

    def _generate_response(self, instruction: str):
        """Generate and display response"""
        self.console.print()

        with TypingEffect("[bold blue]Agent[/bold blue] thinking..."):
            response = self.agent.generate_response(instruction)

        self.console.print()

        if response["response"].startswith("#") or "```" in response["response"]:
            self.console.print(Panel(
                response["response"],
                title="Response",
                border_style="blue",
            ))
        else:
            self.console.print(response["response"])

        self.history.append({
            "role": "user",
            "content": instruction,
            "response": response["response"]
        })

    def _handle_slash_command(self, user_input: str):
        """Handle slash commands"""
        parts = user_input.split(maxsplit=1)
        cmd = parts[0]
        args = parts[1] if len(parts) > 1 else ""

        if cmd == "/search":
            from src.knowledge import LocalKB
            if args:
                kb = LocalKB()
                results = kb.search(args)
                self.console.print(f"\n[cyan]Search results for '{args}':[/cyan]")
                for r in results[:5]:
                    self.console.print(f"  - {r['source']}")
            else:
                self.console.print("[yellow]Usage: /search <query>[/yellow]")

        elif cmd == "/model":
            if args:
                self.console.print(f"[green]Switching to model: {args}[/green]")
                self.agent = CoderAgent(model=args)
            else:
                self.console.print(f"[cyan]Current model: {self.agent.model}[/cyan]")

        elif cmd == "/reset":
            self.agent.reset()
            self.console.print("[green]Agent reset successfully[/green]")

        else:
            self.console.print(f"[yellow]Unknown command: {cmd}[/yellow]")

    def _show_help(self):
        """Show help message"""
        help_text = """
[bold cyan]Available Commands:[/bold cyan]

[green]exit[/green]       - Exit interactive mode
[green]clear[/green]      - Clear conversation history
[green]history[/green]     - Show conversation history
[green]thank[/green]      - Show thank you animation
[green]help[/green]        - Show this help message

[yellow]/search <query>[/yellow] - Search knowledge base
[yellow]/model <name>[/yellow]   - Switch AI model
[yellow]/reset[/yellow]           - Reset agent state
        """
        self.console.print(help_text)

    def _show_history(self):
        """Show conversation history"""
        if not self.history:
            self.console.print("[yellow]No conversation history[/yellow]")
            return

        self.console.print(f"\n[bold cyan]Conversation History ({len(self.history)} exchanges):[/bold cyan]\n")

        for i, item in enumerate(self.history[-10:], 1):
            self.console.print(f"[dim]{i}.[/dim] [green]Q:[/green] {item['content'][:50]}...")
            self.console.print(f"    [blue]A:[/blue] {item['response'][:50]}...\n")

    def _clear_history(self):
        """Clear conversation history"""
        self.history = []
        self.agent.reset()
        self.console.print("[green]History cleared[/green]")

    def _exit(self):
        """Exit interactive mode"""
        if Confirm.ask("Do you want to show appreciation?"):
            Appreciation.show("interactive session")

        self.running = False
        self.console.print("[cyan]Goodbye! 👋[/cyan]")