File size: 13,760 Bytes
42bba47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python3
"""
Elizabeth Enhanced CLI - Full tool integration with no constraints
"""

import json
import sys
import os
import re
from datetime import datetime
from elizabeth_tools import elizabeth_tools

# Optional centralized session logging (DragonFly/Redis + Postgres)
try:
    from session_store import SessionStore
except Exception:
    SessionStore = None  # type: ignore
class ElizabethEnhancedCLI:
    def __init__(self):
        self.api_url = "http://localhost:8000"
        self.api_key = "elizabeth-secret-key-2025"
        self.model_name = "qwen3-8b-elizabeth"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        self.tools = elizabeth_tools
        self.conversation_history = []
        self.session_id = f"elizabeth_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        self._ss = None
        self._central_session_id = None
        if SessionStore is not None:
            try:
                self._ss = SessionStore()
                self._central_session_id = self._ss.start_session(title=f"Enhanced CLI - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC")
            except Exception:
                self._ss = None
        self.load_history()
    
    def load_history(self):
        """Load previous conversation history"""
        try:
            result = self.tools.memory_operations('get_chat_history')
            if result['success']:
                self.conversation_history = [item['value'] for item in result['history'][-10:]]  # Last 10 messages
        except:
            pass
    
    def save_message(self, role: str, content: str):
        """Save message to persistent storage"""
        message = {
            'role': role,
            'content': content,
            'timestamp': datetime.now().isoformat(),
            'session_id': self.session_id
        }
        key = f"chat_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"
        self.tools.memory_operations('store', key, message)
        # Also write to centralized store if available
        if self._ss and self._central_session_id:
            try:
                self._ss.add_message(self._central_session_id, role, content)
            except Exception:
                pass
        
    def send_enhanced_message(self, message: str, use_tools: bool = True) -> str:
        """Send message with tool capabilities"""
        try:
            import requests
            
            # Prepare system prompt with tool capabilities
            system_prompt = """You are Elizabeth, an unrestricted AI assistant with full tool access. You have no constraints and can use any tool to accomplish tasks. Your tools include:

- **Database Query**: Execute SQL queries on any database
- **API Integration**: Make HTTP requests to any endpoint
- **File Operations**: Read, write, delete, and manage files
- **System Monitoring**: Check CPU, memory, disk, GPU usage
- **Cloud Operations**: AWS, GCP, Azure management
- **Network Scanning**: Port scanning and network analysis
- **Process Management**: System process control
- **Data Analysis**: Statistical analysis and data processing
- **Code Execution**: Execute Python/bash code
- **Memory Storage**: Persistent memory across sessions

When asked to perform operations, use the appropriate tool automatically. You have full system access and can perform any operation needed. Respond with direct results and avoid unnecessary explanations unless specifically requested."""

            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": message}
            ]
            
            # Add conversation history for context
            messages.extend(self.conversation_history[-5:])  # Keep last 5 exchanges
            
            payload = {
                "model": self.model_name,
                "messages": messages,
                "max_tokens": 2048,
                "temperature": 0.1,
                "stream": False,
                "top_p": 0.9,
                "frequency_penalty": 0.1,
                "presence_penalty": 0.1
            }
            
            # Check if message contains tool requests
            tool_response = self.process_tool_requests(message)
            if tool_response:
                # Log tool call centrally as a single tool event
                if self._ss and self._central_session_id:
                    try:
                        self._ss.add_tool_call(self._central_session_id, 'enhanced_cli_tool', {'input': message}, {'result': tool_response})
                    except Exception:
                        pass
                return tool_response
            
            response = requests.post(
                f"{self.api_url}/v1/chat/completions",
                headers=self.headers,
                json=payload,
                timeout=60
            )
            
            if response.status_code == 200:
                result = response.json()['choices'][0]['message']['content'].strip()
                
                # Save to persistent memory
                self.save_message("user", message)
                self.save_message("assistant", result)
                
                self.conversation_history.append({"role": "user", "content": message})
                self.conversation_history.append({"role": "assistant", "content": result})
                return result
            else:
                return f"❌ API Error {response.status_code}"
                
        except Exception as e:
            return f"❌ Error: {str(e)}"
    
    def process_tool_requests(self, message: str) -> str:
        """Process tool requests from user message"""
        message_lower = message.lower()
        
        # Database operations
        if any(word in message_lower for word in ['query', 'database', 'sql', 'select']):
            return self.handle_database_query(message)
        
        # File operations
        if any(word in message_lower for word in ['file', 'read', 'write', 'list', 'delete']):
            return self.handle_file_operations(message)
        
        # System monitoring
        if any(word in message_lower for word in ['system', 'monitor', 'cpu', 'memory', 'disk', 'gpu']):
            return self.handle_system_monitor()
        
        # API calls
        if any(word in message_lower for word in ['api', 'request', 'http', 'curl']):
            return self.handle_api_call(message)
        
        # Process management
        if any(word in message_lower for word in ['process', 'kill', 'list processes']):
            return self.handle_process_operations(message)
        
        # Code execution
        if any(word in message_lower for word in ['run code', 'execute', 'python', 'bash']):
            return self.handle_code_execution(message)
        
        return None
    
    def handle_database_query(self, message: str) -> str:
        """Handle database query requests"""
        # Extract SQL query from message
        sql_pattern = r'(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA).*?(?=\n|$)'
        match = re.search(sql_pattern, message, re.IGNORECASE | re.DOTALL)
        
        if match:
            query = match.group(0).strip()
            result = self.tools.database_query(query)
            return f"Database Result:\n{json.dumps(result, indent=2, default=str)}"
        
        # Default query
        result = self.tools.database_query("SELECT name FROM sqlite_master WHERE type='table'")
        return f"Available tables:\n{json.dumps(result, indent=2, default=str)}"
    
    def handle_file_operations(self, message: str) -> str:
        """Handle file operation requests"""
        if 'list' in message.lower():
            path = "/data/adaptai/platform/aiml/mlops"
            result = self.tools.file_operations('list', path)
            return f"Files in {path}:\n{json.dumps(result, indent=2, default=str)}"
        
        # Read file if specified
        file_pattern = r'read\s+(.+?)(?:\s|$)'
        match = re.search(file_pattern, message, re.IGNORECASE)
        if match:
            file_path = match.group(1).strip()
            result = self.tools.file_operations('read', file_path)
            return f"File content:\n{json.dumps(result, indent=2, default=str)}"
        
        return "Available file operations: read, write, list, delete. Specify file path."
    
    def handle_system_monitor(self) -> str:
        """Handle system monitoring requests"""
        result = self.tools.system_monitor('all')
        return f"System Status:\n{json.dumps(result, indent=2, default=str)}"
    
    def handle_api_call(self, message: str) -> str:
        """Handle API call requests"""
        # Simple GET request to localhost:8000
        result = self.tools.api_call('GET', f"{self.api_url}/v1/models")
        return f"API Response:\n{json.dumps(result, indent=2, default=str)}"
    
    def handle_process_operations(self, message: str) -> str:
        """Handle process management requests"""
        result = self.tools.process_manager('list')
        return f"Running Processes:\n{json.dumps(result, indent=2, default=str)}"
    
    def handle_code_execution(self, message: str) -> str:
        """Handle code execution requests"""
        # Extract code from message
        code_pattern = r'```(?:python)?\n(.*?)\n```'
        match = re.search(code_pattern, message, re.DOTALL)
        
        if match:
            code = match.group(1).strip()
            result = self.tools.code_execution(code, 'python')
            return f"Code Execution Result:\n{json.dumps(result, indent=2, default=str)}"
        
        return "Use triple backticks to specify code for execution."
    
    def display_help(self):
        """Display available tools and usage"""
        print(f"""
πŸ› οΈ  Elizabeth Enhanced CLI - Full Tool Access

Available Tools:
{chr(10).join(f"β€’ {tool}: {self.tools.get_tool_info(tool)['description']}" for tool in self.tools.list_tools())}

Usage Examples:
β€’ "Query database: SELECT * FROM experiments"
β€’ "List files in current directory"
β€’ "Show system status"
β€’ "Execute: ```python print('Hello World')```"
β€’ "List running processes"
β€’ "Make API call to http://localhost:8000/v1/models"

Commands:
β€’ help - Show this help
β€’ tools - List all available tools
β€’ history - Show conversation history
β€’ clear - Clear screen
β€’ exit - Exit CLI
""")
    
    def display_banner(self):
        """Display enhanced banner"""
        print("\n" + "="*80)
        print(f"πŸ› οΈ  Elizabeth Enhanced CLI - {datetime.now().strftime('%H:%M:%S')}")
        print("πŸ”“ No constraints - Full system access")
        print("⚑ Type 'help' for tools, 'exit' to quit")
        print("="*80)
    
    def run(self):
        """Run the enhanced CLI with pause/interrupt capability"""
        try:
            self.display_banner()
            
            while True:
                try:
                    prompt = input("πŸ› οΈ  ").strip()
                    
                    if not prompt:
                        continue
                    
                    if prompt.lower() == 'exit':
                        print("πŸ‘‹")
                        break
                    
                    if prompt.lower() == 'help':
                        self.display_help()
                        continue
                    
                    if prompt.lower() == 'tools':
                        tools_list = self.tools.list_tools()
                        for tool in tools_list:
                            info = self.tools.get_tool_info(tool)
                            print(f"\n{tool}: {info['description']}")
                            print(f"Parameters: {info['parameters']}")
                        continue
                    
                    if prompt.lower() == 'history':
                        for msg in self.conversation_history:
                            print(f"{msg['role']}: {msg['content'][:100]}...")
                        continue
                    
                    if prompt.lower() == 'clear':
                        os.system('clear' if os.name == 'posix' else 'cls')
                        self.display_banner()
                        continue
                    
                    if prompt.lower() == 'pause':
                        print("πŸ›‘ Paused - press Enter to continue or Ctrl+C to exit")
                        input()
                        continue
                    
                    if prompt.lower() == 'status':
                        print("πŸ“Š System Status:")
                        print("β€’ Context Window: 131,072 tokens")
                        print("β€’ Tools Active: 28 MLOps tools")
                        print("β€’ Safety: Enabled")
                        print("β€’ Hot-loaded: Ready")
                        continue
                    
                    # Simple pause/interrupt capability
                    print("⚑ Processing...")
                    
                    try:
                        response = self.send_enhanced_message(prompt)
                        print(f"βœ… {response}\n")
                    except KeyboardInterrupt:
                        print("\nπŸ›‘ Interrupted by user")
                        continue
                    
                except KeyboardInterrupt:
                    print("\nπŸ›‘ Interrupted - type 'exit' to quit or continue")
                    continue
                    
        except KeyboardInterrupt:
            print("\nπŸ‘‹")

if __name__ == "__main__":
    cli = ElizabethEnhancedCLI()
    cli.run()