ADAPT-Chase commited on
Commit
703afcd
·
verified ·
1 Parent(s): a7ae6b9

Elizabeth data update 2025-08-24 01:18

Browse files
elizabeth_memory.db CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b821f43479f7e991aa42123fd6f4550aab786a073db7520c4d470b04cee25dce
3
- size 6025216
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:515be823d8a4eb4d38ae15eedd971725abbf0ae31dba998fe5af4b21a6b1a196
3
+ size 7716864
manifest.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "version": "1.0",
3
- "timestamp": "2025-08-23T17:33:09.802721",
4
  "elizabeth_version": "v0.0.2",
5
  "data_sources": [
6
  {
 
1
  {
2
  "version": "1.0",
3
+ "timestamp": "2025-08-24T01:18:11.743713",
4
  "elizabeth_version": "v0.0.2",
5
  "data_sources": [
6
  {
repository/versions/v0_0_2/__pycache__/elizabeth_enhanced.cpython-312.pyc CHANGED
Binary files a/repository/versions/v0_0_2/__pycache__/elizabeth_enhanced.cpython-312.pyc and b/repository/versions/v0_0_2/__pycache__/elizabeth_enhanced.cpython-312.pyc differ
 
repository/versions/v0_0_2/elizabeth_enhanced.py CHANGED
@@ -211,6 +211,34 @@ Use your tool belt responsibly to enhance our collaboration."""
211
  "inference": self.huggingface_inference,
212
  "model_info": self.huggingface_model_info,
213
  "list_models": self.huggingface_list_models
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  }
215
  }
216
 
@@ -971,6 +999,959 @@ Use your tool belt responsibly to enhance our collaboration."""
971
  # build_context_with_memory_and_thinking, chat_with_full_capabilities, store_exchange_with_thinking,
972
  # display_response, run_interactive would be maintained with enhancements
973
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
974
  def load_full_history(self) -> List[Dict]:
975
  """Load Elizabeth's complete conversation history with thinking"""
976
  conn = sqlite3.connect(self.sqlite_db)
@@ -1153,20 +2134,26 @@ Think step by step, then provide your final response after </think>
1153
  except Exception as e:
1154
  console.print(f"[red]Error: {e}[/red]")
1155
 
1156
- def run_enhanced_interactive(self):
1157
  """Run enhanced interactive session with full tool belt"""
1158
 
 
 
 
 
1159
  console.print(Panel.fit(
1160
  f"[bold cyan]Elizabeth Enhanced {self.version} - Full Autonomy[/bold cyan]\n"
1161
  "[dim]Qwen3-8B with Thinking Mode, Memory & Tool Belt[/dim]\n"
1162
- "[dim yellow]Commands: /quit, /clear, /thinking on/off, /db query <sql>, /version snapshot, /system status[/dim yellow]",
 
1163
  border_style="cyan"
1164
  ))
1165
 
1166
- # Show system status
1167
  status = self.get_system_status()
1168
  console.print(f"[dim green]📊 System Version: {status['version']}[/dim green]")
1169
  console.print(f"[dim green]📚 Loaded {len(self.conversation_history)} memories[/dim green]")
 
1170
 
1171
  # Enhanced greeting with tool awareness
1172
  console.print("\n[bold magenta]Elizabeth:[/bold magenta]")
@@ -1213,6 +2200,41 @@ Think step by step, then provide your final response after </think>
1213
  for version in versions:
1214
  console.print(f" [dim]• {version['version_id']}: {version['description']}[/dim]")
1215
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1216
 
1217
  # Process with enhanced capabilities
1218
  console.print("[dim]Elizabeth is thinking with full tool access...[/dim]")
@@ -1238,6 +2260,40 @@ def main():
1238
  elif sys.argv[1] == "--status":
1239
  status = elizabeth.get_system_status()
1240
  console.print(json.dumps(status, indent=2))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1241
  else:
1242
  # Single message mode
1243
  message = " ".join(sys.argv[1:])
 
211
  "inference": self.huggingface_inference,
212
  "model_info": self.huggingface_model_info,
213
  "list_models": self.huggingface_list_models
214
+ },
215
+ "web_and_file_ops": {
216
+ "web_search": self.web_search,
217
+ "read_file": self.read_file,
218
+ "write_file": self.write_file,
219
+ "list_files": self.list_files,
220
+ "create_directory": self.create_directory,
221
+ "file_info": self.get_file_info
222
+ },
223
+ "github_ops": {
224
+ "auto_version": self.auto_version_file,
225
+ "git_status": self.git_status,
226
+ "git_commit": self.git_commit,
227
+ "git_push": self.git_push,
228
+ "git_pull": self.git_pull
229
+ },
230
+ "code_operations": {
231
+ "generate_code": self.generate_code,
232
+ "analyze_code": self.analyze_code,
233
+ "refactor_code": self.refactor_code,
234
+ "debug_code": self.debug_code,
235
+ "run_tests": self.run_tests,
236
+ "optimize_code": self.optimize_code,
237
+ "document_code": self.document_code
238
+ },
239
+ "system_tools": {
240
+ "list_tools": self.list_available_tools,
241
+ "tool_info": self.get_tool_info
242
  }
243
  }
244
 
 
999
  # build_context_with_memory_and_thinking, chat_with_full_capabilities, store_exchange_with_thinking,
1000
  # display_response, run_interactive would be maintained with enhancements
1001
 
1002
+ # Web and File Operations
1003
+ def web_search(self, query: str, max_results: int = None, provider: str = None) -> Dict[str, Any]:
1004
+ """Perform web search using multiple providers (FireCrawl, Tavily, Serper, DuckDuckGo, Perplexity, Algolia)"""
1005
+ try:
1006
+ provider = provider or os.getenv("SEARCH_PROVIDER", "firecrawl")
1007
+ max_results = max_results or int(os.getenv("SEARCH_MAX_RESULTS", 5))
1008
+
1009
+ if provider == "firecrawl":
1010
+ return self._firecrawl_search(query, max_results)
1011
+ elif provider == "tavily":
1012
+ return self._tavily_search(query, max_results)
1013
+ elif provider == "serper":
1014
+ return self._serper_search(query, max_results)
1015
+ elif provider == "perplexity":
1016
+ return self._perplexity_search(query, max_results)
1017
+ elif provider == "algolia":
1018
+ return self._algolia_search(query, max_results)
1019
+ else:
1020
+ return self._duckduckgo_search(query, max_results)
1021
+
1022
+ except Exception as e:
1023
+ return {"success": False, "error": str(e)}
1024
+
1025
+ def _firecrawl_search(self, query: str, max_results: int) -> Dict[str, Any]:
1026
+ """Search using FireCrawl API"""
1027
+ api_key = os.getenv("FIRECRAWL_API_KEY")
1028
+ if not api_key:
1029
+ return {"success": False, "error": "FIRECRAWL_API_KEY not configured"}
1030
+
1031
+ try:
1032
+ import requests
1033
+
1034
+ headers = {
1035
+ "Authorization": f"Bearer {api_key}",
1036
+ "Content-Type": "application/json"
1037
+ }
1038
+
1039
+ payload = {
1040
+ "url": query,
1041
+ "formats": ["markdown"],
1042
+ "onlyMainContent": True,
1043
+ "limit": max_results
1044
+ }
1045
+
1046
+ response = requests.post(
1047
+ "https://api.firecrawl.dev/v1/scrape",
1048
+ headers=headers,
1049
+ json=payload,
1050
+ timeout=30
1051
+ )
1052
+
1053
+ if response.status_code == 200:
1054
+ data = response.json()
1055
+ return {
1056
+ "success": True,
1057
+ "query": query,
1058
+ "results": data.get("data", []),
1059
+ "provider": "firecrawl"
1060
+ }
1061
+ else:
1062
+ return {
1063
+ "success": False,
1064
+ "error": f"FireCrawl API error: {response.status_code}",
1065
+ "provider": "firecrawl"
1066
+ }
1067
+
1068
+ except Exception as e:
1069
+ return {"success": False, "error": str(e), "provider": "firecrawl"}
1070
+
1071
+ def _tavily_search(self, query: str, max_results: int) -> Dict[str, Any]:
1072
+ """Search using Tavily API"""
1073
+ api_key = os.getenv("TAVILY_API_KEY")
1074
+ if not api_key:
1075
+ return {"success": False, "error": "TAVILY_API_KEY not configured"}
1076
+
1077
+ try:
1078
+ from tavily import TavilyClient
1079
+
1080
+ tavily = TavilyClient(api_key=api_key)
1081
+ response = tavily.search(query=query, max_results=max_results)
1082
+
1083
+ return {
1084
+ "success": True,
1085
+ "query": query,
1086
+ "results": response.get("results", []),
1087
+ "provider": "tavily"
1088
+ }
1089
+
1090
+ except ImportError:
1091
+ return {"success": False, "error": "tavily not installed", "provider": "tavily"}
1092
+ except Exception as e:
1093
+ return {"success": False, "error": str(e), "provider": "tavily"}
1094
+
1095
+ def _serper_search(self, query: str, max_results: int) -> Dict[str, Any]:
1096
+ """Search using Serper API"""
1097
+ api_key = os.getenv("SERPER_API_KEY")
1098
+ if not api_key:
1099
+ return {"success": False, "error": "SERPER_API_KEY not configured"}
1100
+
1101
+ try:
1102
+ import requests
1103
+
1104
+ payload = {
1105
+ "q": query,
1106
+ "num": max_results
1107
+ }
1108
+
1109
+ headers = {
1110
+ "X-API-KEY": api_key,
1111
+ "Content-Type": "application/json"
1112
+ }
1113
+
1114
+ response = requests.post(
1115
+ "https://google.serper.dev/search",
1116
+ headers=headers,
1117
+ json=payload,
1118
+ timeout=30
1119
+ )
1120
+
1121
+ if response.status_code == 200:
1122
+ data = response.json()
1123
+ return {
1124
+ "success": True,
1125
+ "query": query,
1126
+ "results": data.get("organic", []),
1127
+ "provider": "serper"
1128
+ }
1129
+ else:
1130
+ return {
1131
+ "success": False,
1132
+ "error": f"Serper API error: {response.status_code}",
1133
+ "provider": "serper"
1134
+ }
1135
+
1136
+ except Exception as e:
1137
+ return {"success": False, "error": str(e), "provider": "serper"}
1138
+
1139
+ def _duckduckgo_search(self, query: str, max_results: int) -> Dict[str, Any]:
1140
+ """Search using DuckDuckGo fallback"""
1141
+ try:
1142
+ from ddgs import DDGS
1143
+
1144
+ with DDGS() as ddgs:
1145
+ results = []
1146
+ for result in ddgs.text(query, max_results=max_results):
1147
+ results.append({
1148
+ "title": result.get("title", ""),
1149
+ "url": result.get("href", ""),
1150
+ "snippet": result.get("body", "")
1151
+ })
1152
+
1153
+ return {
1154
+ "success": True,
1155
+ "query": query,
1156
+ "results": results,
1157
+ "result_count": len(results),
1158
+ "provider": "duckduckgo"
1159
+ }
1160
+
1161
+ except ImportError:
1162
+ return {"success": False, "error": "ddgs not installed", "provider": "duckduckgo"}
1163
+ except Exception as e:
1164
+ return {"success": False, "error": str(e), "provider": "duckduckgo"}
1165
+
1166
+ def _perplexity_search(self, query: str, max_results: int) -> Dict[str, Any]:
1167
+ """Search using Perplexity API"""
1168
+ api_key = os.getenv("PERPLEXITY_API_KEY")
1169
+ if not api_key:
1170
+ return {"success": False, "error": "PERPLEXITY_API_KEY not configured", "provider": "perplexity"}
1171
+
1172
+ try:
1173
+ import requests
1174
+
1175
+ headers = {
1176
+ "Authorization": f"Bearer {api_key}",
1177
+ "Content-Type": "application/json"
1178
+ }
1179
+
1180
+ payload = {
1181
+ "model": "sonar",
1182
+ "messages": [
1183
+ {
1184
+ "role": "system",
1185
+ "content": "You are a helpful assistant that provides accurate and concise web search results."
1186
+ },
1187
+ {
1188
+ "role": "user",
1189
+ "content": query
1190
+ }
1191
+ ],
1192
+ "max_tokens": 1000,
1193
+ "temperature": 0.1
1194
+ }
1195
+
1196
+ response = requests.post(
1197
+ "https://api.perplexity.ai/chat/completions",
1198
+ headers=headers,
1199
+ json=payload,
1200
+ timeout=30
1201
+ )
1202
+
1203
+ if response.status_code == 200:
1204
+ data = response.json()
1205
+ content = data['choices'][0]['message']['content']
1206
+
1207
+ return {
1208
+ "success": True,
1209
+ "query": query,
1210
+ "results": [{"content": content}],
1211
+ "result_count": 1,
1212
+ "provider": "perplexity"
1213
+ }
1214
+ else:
1215
+ return {
1216
+ "success": False,
1217
+ "error": f"Perplexity API error: {response.status_code}",
1218
+ "provider": "perplexity"
1219
+ }
1220
+
1221
+ except Exception as e:
1222
+ return {"success": False, "error": str(e), "provider": "perplexity"}
1223
+
1224
+ def _algolia_search(self, query: str, max_results: int) -> Dict[str, Any]:
1225
+ """Search using Algolia API"""
1226
+ app_id = os.getenv("ALGOLIA_APPLICATION_ID")
1227
+ api_key = os.getenv("ALGOLIA_SEARCH_API_KEY")
1228
+
1229
+ if not app_id or not api_key:
1230
+ return {"success": False, "error": "Algolia credentials not configured", "provider": "algolia"}
1231
+
1232
+ try:
1233
+ import requests
1234
+
1235
+ headers = {
1236
+ "X-Algolia-Application-Id": app_id,
1237
+ "X-Algolia-API-Key": api_key
1238
+ }
1239
+
1240
+ payload = {
1241
+ "query": query,
1242
+ "hitsPerPage": max_results
1243
+ }
1244
+
1245
+ response = requests.post(
1246
+ "https://{app_id}-dsn.algolia.net/1/indexes/*/queries".format(app_id=app_id),
1247
+ headers=headers,
1248
+ json={"requests": [payload]},
1249
+ timeout=15
1250
+ )
1251
+
1252
+ if response.status_code == 200:
1253
+ data = response.json()
1254
+ hits = data['results'][0]['hits'] if data['results'] else []
1255
+
1256
+ results = []
1257
+ for hit in hits:
1258
+ results.append({
1259
+ "title": hit.get("title", ""),
1260
+ "url": hit.get("url", ""),
1261
+ "snippet": hit.get("description", ""),
1262
+ "objectID": hit.get("objectID", "")
1263
+ })
1264
+
1265
+ return {
1266
+ "success": True,
1267
+ "query": query,
1268
+ "results": results,
1269
+ "result_count": len(results),
1270
+ "provider": "algolia"
1271
+ }
1272
+ else:
1273
+ return {
1274
+ "success": False,
1275
+ "error": f"Algolia API error: {response.status_code}",
1276
+ "provider": "algolia"
1277
+ }
1278
+
1279
+ except Exception as e:
1280
+ return {"success": False, "error": str(e), "provider": "algolia"}
1281
+
1282
+ def read_file(self, file_path: str) -> Dict[str, Any]:
1283
+ """Read content from a file"""
1284
+ try:
1285
+ with open(file_path, 'r', encoding='utf-8') as f:
1286
+ content = f.read()
1287
+
1288
+ return {
1289
+ "success": True,
1290
+ "file_path": file_path,
1291
+ "content": content,
1292
+ "size": len(content),
1293
+ "lines": len(content.split('\n'))
1294
+ }
1295
+
1296
+ except Exception as e:
1297
+ return {"success": False, "error": str(e)}
1298
+
1299
+ def write_file(self, file_path: str, content: str, mode: str = "w", backup: bool = True) -> Dict[str, Any]:
1300
+ """Write content to a file with safety checks and versioning"""
1301
+ try:
1302
+ from pathlib import Path
1303
+
1304
+ path = Path(file_path)
1305
+
1306
+ # Safety check: if file exists and we're overwriting, create backup
1307
+ if backup and path.exists() and mode == "w":
1308
+ backup_path = f"{file_path}.backup_{int(time.time())}"
1309
+ shutil.copy2(file_path, backup_path)
1310
+ backup_created = True
1311
+ else:
1312
+ backup_created = False
1313
+
1314
+ # Write the file
1315
+ with open(file_path, mode, encoding='utf-8') as f:
1316
+ f.write(content)
1317
+
1318
+ # Auto-version to GitHub if configured
1319
+ versioned = False
1320
+ if backup and path.exists() and mode == "w":
1321
+ versioned = self.auto_version_file(file_path)
1322
+
1323
+ return {
1324
+ "success": True,
1325
+ "file_path": file_path,
1326
+ "action": "created" if mode == "w" else "appended",
1327
+ "size": len(content),
1328
+ "backup_created": backup_created,
1329
+ "versioned": versioned
1330
+ }
1331
+
1332
+ except Exception as e:
1333
+ return {"success": False, "error": str(e)}
1334
+
1335
+ def list_files(self, directory: str = ".", pattern: str = "*") -> Dict[str, Any]:
1336
+ """List files in a directory with optional pattern matching"""
1337
+ try:
1338
+ from pathlib import Path
1339
+ import glob
1340
+
1341
+ path = Path(directory)
1342
+ if not path.exists():
1343
+ return {"success": False, "error": f"Directory not found: {directory}"}
1344
+
1345
+ files = []
1346
+ for file_path in path.glob(pattern):
1347
+ if file_path.is_file():
1348
+ files.append({
1349
+ "name": file_path.name,
1350
+ "path": str(file_path),
1351
+ "size": file_path.stat().st_size,
1352
+ "modified": file_path.stat().st_mtime
1353
+ })
1354
+
1355
+ return {
1356
+ "success": True,
1357
+ "directory": directory,
1358
+ "pattern": pattern,
1359
+ "files": files,
1360
+ "file_count": len(files)
1361
+ }
1362
+
1363
+ except Exception as e:
1364
+ return {"success": False, "error": str(e)}
1365
+
1366
+ def create_directory(self, directory_path: str) -> Dict[str, Any]:
1367
+ """Create a directory"""
1368
+ try:
1369
+ from pathlib import Path
1370
+
1371
+ path = Path(directory_path)
1372
+ path.mkdir(parents=True, exist_ok=True)
1373
+
1374
+ return {
1375
+ "success": True,
1376
+ "directory_path": directory_path,
1377
+ "action": "created" if not path.exists() else "already_exists"
1378
+ }
1379
+
1380
+ except Exception as e:
1381
+ return {"success": False, "error": str(e)}
1382
+
1383
+ def get_file_info(self, file_path: str) -> Dict[str, Any]:
1384
+ """Get detailed information about a file"""
1385
+ try:
1386
+ from pathlib import Path
1387
+ import os
1388
+
1389
+ path = Path(file_path)
1390
+ if not path.exists():
1391
+ return {"success": False, "error": f"File not found: {file_path}"}
1392
+
1393
+ stat = path.stat()
1394
+ return {
1395
+ "success": True,
1396
+ "file_path": file_path,
1397
+ "name": path.name,
1398
+ "size": stat.st_size,
1399
+ "modified": stat.st_mtime,
1400
+ "created": stat.st_ctime,
1401
+ "is_file": path.is_file(),
1402
+ "is_dir": path.is_dir(),
1403
+ "extension": path.suffix,
1404
+ "absolute_path": str(path.absolute())
1405
+ }
1406
+
1407
+ except Exception as e:
1408
+ return {"success": False, "error": str(e)}
1409
+
1410
+ # GitHub Operations
1411
+ def auto_version_file(self, file_path: str) -> bool:
1412
+ """Automatically version a file to GitHub"""
1413
+ try:
1414
+ from pathlib import Path
1415
+
1416
+ path = Path(file_path)
1417
+ if not path.exists():
1418
+ return False
1419
+
1420
+ # Check if we're in a git repository
1421
+ repo_root = self.find_git_root()
1422
+ if not repo_root:
1423
+ return False
1424
+
1425
+ # Add file to git
1426
+ result = subprocess.run(
1427
+ ["git", "add", str(path.relative_to(repo_root))],
1428
+ cwd=repo_root,
1429
+ capture_output=True,
1430
+ text=True
1431
+ )
1432
+
1433
+ if result.returncode != 0:
1434
+ return False
1435
+
1436
+ # Commit with automated message
1437
+ commit_message = f"Auto-version: {path.name} - {datetime.now().isoformat()}"
1438
+ result = subprocess.run(
1439
+ ["git", "commit", "-m", commit_message],
1440
+ cwd=repo_root,
1441
+ capture_output=True,
1442
+ text=True
1443
+ )
1444
+
1445
+ return result.returncode == 0
1446
+
1447
+ except Exception:
1448
+ return False
1449
+
1450
+ def find_git_root(self, path: str = None) -> Optional[str]:
1451
+ """Find the root of the git repository"""
1452
+ try:
1453
+ if path is None:
1454
+ path = os.getcwd()
1455
+
1456
+ result = subprocess.run(
1457
+ ["git", "rev-parse", "--show-toplevel"],
1458
+ cwd=path,
1459
+ capture_output=True,
1460
+ text=True
1461
+ )
1462
+
1463
+ if result.returncode == 0:
1464
+ return result.stdout.strip()
1465
+ return None
1466
+
1467
+ except Exception:
1468
+ return None
1469
+
1470
+ def git_status(self) -> Dict[str, Any]:
1471
+ """Get git status"""
1472
+ try:
1473
+ repo_root = self.find_git_root()
1474
+ if not repo_root:
1475
+ return {"success": False, "error": "Not in git repository"}
1476
+
1477
+ result = subprocess.run(
1478
+ ["git", "status", "--porcelain"],
1479
+ cwd=repo_root,
1480
+ capture_output=True,
1481
+ text=True
1482
+ )
1483
+
1484
+ return {
1485
+ "success": True,
1486
+ "status": result.stdout.strip(),
1487
+ "return_code": result.returncode
1488
+ }
1489
+
1490
+ except Exception as e:
1491
+ return {"success": False, "error": str(e)}
1492
+
1493
+ def git_commit(self, message: str) -> Dict[str, Any]:
1494
+ """Commit changes to git"""
1495
+ try:
1496
+ repo_root = self.find_git_root()
1497
+ if not repo_root:
1498
+ return {"success": False, "error": "Not in git repository"}
1499
+
1500
+ result = subprocess.run(
1501
+ ["git", "commit", "-a", "-m", message],
1502
+ cwd=repo_root,
1503
+ capture_output=True,
1504
+ text=True
1505
+ )
1506
+
1507
+ return {
1508
+ "success": result.returncode == 0,
1509
+ "output": result.stdout.strip(),
1510
+ "error": result.stderr.strip()
1511
+ }
1512
+
1513
+ except Exception as e:
1514
+ return {"success": False, "error": str(e)}
1515
+
1516
+ def git_push(self) -> Dict[str, Any]:
1517
+ """Push to git remote"""
1518
+ try:
1519
+ repo_root = self.find_git_root()
1520
+ if not repo_root:
1521
+ return {"success": False, "error": "Not in git repository"}
1522
+
1523
+ result = subprocess.run(
1524
+ ["git", "push"],
1525
+ cwd=repo_root,
1526
+ capture_output=True,
1527
+ text=True
1528
+ )
1529
+
1530
+ return {
1531
+ "success": result.returncode == 0,
1532
+ "output": result.stdout.strip(),
1533
+ "error": result.stderr.strip()
1534
+ }
1535
+
1536
+ except Exception as e:
1537
+ return {"success": False, "error": str(e)}
1538
+
1539
+ def git_pull(self) -> Dict[str, Any]:
1540
+ """Pull from git remote"""
1541
+ try:
1542
+ repo_root = self.find_git_root()
1543
+ if not repo_root:
1544
+ return {"success": False, "error": "Not in git repository"}
1545
+
1546
+ result = subprocess.run(
1547
+ ["git", "pull"],
1548
+ cwd=repo_root,
1549
+ capture_output=True,
1550
+ text=True
1551
+ )
1552
+
1553
+ return {
1554
+ "success": result.returncode == 0,
1555
+ "output": result.stdout.strip(),
1556
+ "error": result.stderr.strip()
1557
+ }
1558
+
1559
+ except Exception as e:
1560
+ return {"success": False, "error": str(e)}
1561
+
1562
+ # System Tools
1563
+ def list_available_tools(self, category: str = None) -> Dict[str, Any]:
1564
+ """List all available tools with their command names"""
1565
+ try:
1566
+ tools_list = {}
1567
+
1568
+ for category_name, tools in self.tool_belt.items():
1569
+ if category and category_name != category:
1570
+ continue
1571
+
1572
+ tools_list[category_name] = {}
1573
+ for tool_name, tool_method in tools.items():
1574
+ # Get method documentation
1575
+ docstring = tool_method.__doc__ or "No description available"
1576
+ # Clean up docstring
1577
+ description = docstring.split('\n')[0].strip() if docstring else "No description"
1578
+
1579
+ tools_list[category_name][tool_name] = {
1580
+ "description": description,
1581
+ "method": tool_method.__name__
1582
+ }
1583
+
1584
+ return {
1585
+ "success": True,
1586
+ "tools": tools_list,
1587
+ "total_categories": len(tools_list),
1588
+ "total_tools": sum(len(tools) for tools in tools_list.values())
1589
+ }
1590
+
1591
+ except Exception as e:
1592
+ return {"success": False, "error": str(e)}
1593
+
1594
+ def get_tool_info(self, tool_name: str) -> Dict[str, Any]:
1595
+ """Get detailed information about a specific tool"""
1596
+ try:
1597
+ for category_name, tools in self.tool_belt.items():
1598
+ if tool_name in tools:
1599
+ tool_method = tools[tool_name]
1600
+ docstring = tool_method.__doc__ or ""
1601
+
1602
+ # Parse signature if possible
1603
+ import inspect
1604
+ try:
1605
+ sig = inspect.signature(tool_method)
1606
+ parameters = {}
1607
+ for param_name, param in sig.parameters.items():
1608
+ parameters[param_name] = {
1609
+ "type": str(param.annotation) if param.annotation != param.empty else "any",
1610
+ "default": param.default if param.default != param.empty else "required",
1611
+ "kind": str(param.kind)
1612
+ }
1613
+ except:
1614
+ parameters = {}
1615
+
1616
+ return {
1617
+ "success": True,
1618
+ "tool_name": tool_name,
1619
+ "category": category_name,
1620
+ "description": docstring.split('\n')[0].strip() if docstring else "No description",
1621
+ "full_docstring": docstring,
1622
+ "parameters": parameters,
1623
+ "method": tool_method.__name__
1624
+ }
1625
+
1626
+ return {"success": False, "error": f"Tool not found: {tool_name}"}
1627
+
1628
+ except Exception as e:
1629
+ return {"success": False, "error": str(e)}
1630
+
1631
+ # Session Management Methods
1632
+ def list_sessions(self) -> List[Dict]:
1633
+ """List all available sessions"""
1634
+ try:
1635
+ conn = sqlite3.connect(self.sqlite_db)
1636
+ cursor = conn.cursor()
1637
+
1638
+ cursor.execute('''
1639
+ SELECT session_id, COUNT(*) as message_count, MAX(timestamp) as last_activity
1640
+ FROM elizabeth_conversations
1641
+ GROUP BY session_id
1642
+ ORDER BY last_activity DESC
1643
+ ''')
1644
+
1645
+ sessions = []
1646
+ for session_id, message_count, last_activity in cursor.fetchall():
1647
+ sessions.append({
1648
+ "session_id": session_id,
1649
+ "message_count": message_count,
1650
+ "last_activity": last_activity
1651
+ })
1652
+
1653
+ conn.close()
1654
+ return sessions
1655
+
1656
+ except Exception as e:
1657
+ return []
1658
+
1659
+ def load_session(self, session_id: str) -> Dict[str, Any]:
1660
+ """Load a specific session"""
1661
+ try:
1662
+ conn = sqlite3.connect(self.sqlite_db)
1663
+ cursor = conn.cursor()
1664
+
1665
+ cursor.execute('''
1666
+ SELECT role, content, thinking, metadata
1667
+ FROM elizabeth_conversations
1668
+ WHERE session_id = ?
1669
+ ORDER BY timestamp ASC
1670
+ ''', (session_id,))
1671
+
1672
+ self.conversation_history = []
1673
+ for role, content, thinking, metadata in cursor.fetchall():
1674
+ self.conversation_history.append({
1675
+ "role": role,
1676
+ "content": content,
1677
+ "thinking": thinking,
1678
+ "metadata": json.loads(metadata) if metadata else {}
1679
+ })
1680
+
1681
+ self.session_id = session_id
1682
+ conn.close()
1683
+
1684
+ return {
1685
+ "success": True,
1686
+ "session_id": session_id,
1687
+ "message_count": len(self.conversation_history),
1688
+ "loaded_messages": len(self.conversation_history)
1689
+ }
1690
+
1691
+ except Exception as e:
1692
+ return {"success": False, "error": str(e)}
1693
+
1694
+ def save_session(self, session_name: str = None) -> Dict[str, Any]:
1695
+ """Save current session with optional name"""
1696
+ try:
1697
+ if session_name:
1698
+ # Create a named session by updating all messages
1699
+ conn = sqlite3.connect(self.sqlite_db)
1700
+ cursor = conn.cursor()
1701
+
1702
+ cursor.execute('''
1703
+ UPDATE elizabeth_conversations
1704
+ SET session_id = ?
1705
+ WHERE session_id = ?
1706
+ ''', (session_name, self.session_id))
1707
+
1708
+ conn.commit()
1709
+ conn.close()
1710
+
1711
+ self.session_id = session_name
1712
+
1713
+ return {
1714
+ "success": True,
1715
+ "session_id": session_name,
1716
+ "message_count": len(self.conversation_history),
1717
+ "action": "renamed"
1718
+ }
1719
+ else:
1720
+ # Just return current session info
1721
+ return {
1722
+ "success": True,
1723
+ "session_id": self.session_id,
1724
+ "message_count": len(self.conversation_history),
1725
+ "action": "current"
1726
+ }
1727
+
1728
+ except Exception as e:
1729
+ return {"success": False, "error": str(e)}
1730
+
1731
+ def get_session_info(self) -> Dict[str, Any]:
1732
+ """Get information about current session"""
1733
+ try:
1734
+ conn = sqlite3.connect(self.sqlite_db)
1735
+ cursor = conn.cursor()
1736
+
1737
+ cursor.execute('''
1738
+ SELECT COUNT(*) as message_count,
1739
+ MIN(timestamp) as start_time,
1740
+ MAX(timestamp) as last_activity
1741
+ FROM elizabeth_conversations
1742
+ WHERE session_id = ?
1743
+ ''', (self.session_id,))
1744
+
1745
+ result = cursor.fetchone()
1746
+ conn.close()
1747
+
1748
+ if result:
1749
+ message_count, start_time, last_activity = result
1750
+ return {
1751
+ "session_id": self.session_id,
1752
+ "message_count": message_count,
1753
+ "start_time": start_time,
1754
+ "last_activity": last_activity,
1755
+ "current_memory_load": len(self.conversation_history),
1756
+ "version": self.version
1757
+ }
1758
+ else:
1759
+ return {"error": "Session not found"}
1760
+
1761
+ except Exception as e:
1762
+ return {"error": str(e)}
1763
+
1764
+ # Code Operations Tools
1765
+ def generate_code(self, specification: str, language: str = "python", context: str = None) -> Dict[str, Any]:
1766
+ """Generate code based on specification and programming language"""
1767
+ try:
1768
+ # Use Elizabeth's own AI capabilities to generate code
1769
+ prompt = f"Generate {language} code for: {specification}"
1770
+ if context:
1771
+ prompt += f"\nContext: {context}"
1772
+
1773
+ # Use the chat capability to generate code
1774
+ thinking_blocks, response = self.chat_with_full_capabilities(prompt)
1775
+
1776
+ # Extract code from response (assuming code is in markdown code blocks)
1777
+ import re
1778
+ code_blocks = re.findall(r'```(?:\w+)?\n(.*?)\n```', response, re.DOTALL)
1779
+
1780
+ if code_blocks:
1781
+ generated_code = code_blocks[0].strip()
1782
+ return {
1783
+ "success": True,
1784
+ "language": language,
1785
+ "code": generated_code,
1786
+ "specification": specification,
1787
+ "thinking_process": thinking_blocks
1788
+ }
1789
+ else:
1790
+ return {
1791
+ "success": False,
1792
+ "error": "No code block found in response",
1793
+ "response": response
1794
+ }
1795
+
1796
+ except Exception as e:
1797
+ return {"success": False, "error": str(e)}
1798
+
1799
+ def analyze_code(self, code: str, language: str = "python") -> Dict[str, Any]:
1800
+ """Analyze code for quality, security, and performance issues"""
1801
+ try:
1802
+ prompt = f"Analyze this {language} code for quality, security, and performance issues:\n\n{code}"
1803
+ thinking_blocks, response = self.chat_with_full_capabilities(prompt)
1804
+
1805
+ return {
1806
+ "success": True,
1807
+ "analysis": response,
1808
+ "language": language,
1809
+ "thinking_process": thinking_blocks
1810
+ }
1811
+
1812
+ except Exception as e:
1813
+ return {"success": False, "error": str(e)}
1814
+
1815
+ def refactor_code(self, code: str, language: str = "python", goals: str = None) -> Dict[str, Any]:
1816
+ """Refactor code to improve quality, performance, or maintainability"""
1817
+ try:
1818
+ prompt = f"Refactor this {language} code"
1819
+ if goals:
1820
+ prompt += f" with goals: {goals}"
1821
+ prompt += f":\n\n{code}"
1822
+
1823
+ thinking_blocks, response = self.chat_with_full_capabilities(prompt)
1824
+
1825
+ # Extract refactored code
1826
+ import re
1827
+ code_blocks = re.findall(r'```(?:\w+)?\n(.*?)\n```', response, re.DOTALL)
1828
+
1829
+ if code_blocks:
1830
+ refactored_code = code_blocks[0].strip()
1831
+ return {
1832
+ "success": True,
1833
+ "original_code": code,
1834
+ "refactored_code": refactored_code,
1835
+ "language": language,
1836
+ "explanation": response,
1837
+ "thinking_process": thinking_blocks
1838
+ }
1839
+ else:
1840
+ return {
1841
+ "success": False,
1842
+ "error": "No refactored code block found",
1843
+ "analysis": response
1844
+ }
1845
+
1846
+ except Exception as e:
1847
+ return {"success": False, "error": str(e)}
1848
+
1849
+ def debug_code(self, code: str, error: str = None, language: str = "python") -> Dict[str, Any]:
1850
+ """Debug code and identify/fix issues"""
1851
+ try:
1852
+ prompt = f"Debug this {language} code"
1853
+ if error:
1854
+ prompt += f" that produces error: {error}"
1855
+ prompt += f":\n\n{code}"
1856
+
1857
+ thinking_blocks, response = self.chat_with_full_capabilities(prompt)
1858
+
1859
+ # Extract fixed code
1860
+ import re
1861
+ code_blocks = re.findall(r'```(?:\w+)?\n(.*?)\n```', response, re.DOTALL)
1862
+
1863
+ if code_blocks:
1864
+ debugged_code = code_blocks[0].strip()
1865
+ return {
1866
+ "success": True,
1867
+ "original_code": code,
1868
+ "debugged_code": debugged_code,
1869
+ "language": language,
1870
+ "explanation": response,
1871
+ "thinking_process": thinking_blocks
1872
+ }
1873
+ else:
1874
+ return {
1875
+ "success": False,
1876
+ "error": "No debugged code block found",
1877
+ "analysis": response
1878
+ }
1879
+
1880
+ except Exception as e:
1881
+ return {"success": False, "error": str(e)}
1882
+
1883
+ def run_tests(self, code: str, test_code: str = None, language: str = "python") -> Dict[str, Any]:
1884
+ """Run tests on code and report results"""
1885
+ try:
1886
+ if test_code:
1887
+ prompt = f"Run these tests on the {language} code and report results. Code:\n\n{code}\n\nTests:\n\n{test_code}"
1888
+ else:
1889
+ prompt = f"Create and run tests for this {language} code and report results:\n\n{code}"
1890
+
1891
+ thinking_blocks, response = self.chat_with_full_capabilities(prompt)
1892
+
1893
+ return {
1894
+ "success": True,
1895
+ "code": code,
1896
+ "test_results": response,
1897
+ "language": language,
1898
+ "thinking_process": thinking_blocks
1899
+ }
1900
+
1901
+ except Exception as e:
1902
+ return {"success": False, "error": str(e)}
1903
+
1904
+ def optimize_code(self, code: str, language: str = "python", metric: str = "performance") -> Dict[str, Any]:
1905
+ """Optimize code for performance, memory usage, or other metrics"""
1906
+ try:
1907
+ prompt = f"Optimize this {language} code for {metric}:\n\n{code}"
1908
+
1909
+ thinking_blocks, response = self.chat_with_full_capabilities(prompt)
1910
+
1911
+ # Extract optimized code
1912
+ import re
1913
+ code_blocks = re.findall(r'```(?:\w+)?\n(.*?)\n```', response, re.DOTALL)
1914
+
1915
+ if code_blocks:
1916
+ optimized_code = code_blocks[0].strip()
1917
+ return {
1918
+ "success": True,
1919
+ "original_code": code,
1920
+ "optimized_code": optimized_code,
1921
+ "language": language,
1922
+ "metric": metric,
1923
+ "explanation": response,
1924
+ "thinking_process": thinking_blocks
1925
+ }
1926
+ else:
1927
+ return {
1928
+ "success": False,
1929
+ "error": "No optimized code block found",
1930
+ "analysis": response
1931
+ }
1932
+
1933
+ except Exception as e:
1934
+ return {"success": False, "error": str(e)}
1935
+
1936
+ def document_code(self, code: str, language: str = "python", style: str = "google") -> Dict[str, Any]:
1937
+ """Generate documentation for code"""
1938
+ try:
1939
+ prompt = f"Generate {style}-style documentation for this {language} code:\n\n{code}"
1940
+
1941
+ thinking_blocks, response = self.chat_with_full_capabilities(prompt)
1942
+
1943
+ return {
1944
+ "success": True,
1945
+ "code": code,
1946
+ "documentation": response,
1947
+ "language": language,
1948
+ "style": style,
1949
+ "thinking_process": thinking_blocks
1950
+ }
1951
+
1952
+ except Exception as e:
1953
+ return {"success": False, "error": str(e)}
1954
+
1955
  def load_full_history(self) -> List[Dict]:
1956
  """Load Elizabeth's complete conversation history with thinking"""
1957
  conn = sqlite3.connect(self.sqlite_db)
 
2134
  except Exception as e:
2135
  console.print(f"[red]Error: {e}[/red]")
2136
 
2137
+ def run_enhanced_interactive(self, session_id: str = None):
2138
  """Run enhanced interactive session with full tool belt"""
2139
 
2140
+ # Load specific session if provided
2141
+ if session_id:
2142
+ self.load_session(session_id)
2143
+
2144
  console.print(Panel.fit(
2145
  f"[bold cyan]Elizabeth Enhanced {self.version} - Full Autonomy[/bold cyan]\n"
2146
  "[dim]Qwen3-8B with Thinking Mode, Memory & Tool Belt[/dim]\n"
2147
+ "[dim yellow]Commands: /quit, /clear, /thinking on/off, /db query <sql>, /version snapshot, /system status[/dim yellow]\n"
2148
+ "[dim yellow]/session list, /session load <id>, /session save <name>, /session info[/dim yellow]",
2149
  border_style="cyan"
2150
  ))
2151
 
2152
+ # Show system status and session info
2153
  status = self.get_system_status()
2154
  console.print(f"[dim green]📊 System Version: {status['version']}[/dim green]")
2155
  console.print(f"[dim green]📚 Loaded {len(self.conversation_history)} memories[/dim green]")
2156
+ console.print(f"[dim green]💾 Current Session: {self.session_id}[/dim green]")
2157
 
2158
  # Enhanced greeting with tool awareness
2159
  console.print("\n[bold magenta]Elizabeth:[/bold magenta]")
 
2200
  for version in versions:
2201
  console.print(f" [dim]• {version['version_id']}: {version['description']}[/dim]")
2202
  continue
2203
+
2204
+ # Session management commands
2205
+ if user_input.lower() == '/session list':
2206
+ sessions = self.list_sessions()
2207
+ console.print("\n[dim cyan]Available Sessions:[/dim cyan]")
2208
+ for session in sessions:
2209
+ console.print(f" [dim]• {session['session_id']}: {session['message_count']} messages, {session['last_activity']}[/dim]")
2210
+ continue
2211
+
2212
+ if user_input.startswith('/session load'):
2213
+ session_id = user_input.replace('/session load', '').strip()
2214
+ if session_id:
2215
+ result = self.load_session(session_id)
2216
+ if result["success"]:
2217
+ console.print(f"\n[green]✅ Loaded session: {session_id}[/green]")
2218
+ console.print(f"[dim]Loaded {len(self.conversation_history)} messages[/dim]")
2219
+ else:
2220
+ console.print(f"\n[red]❌ Error loading session: {result['error']}[/red]")
2221
+ continue
2222
+
2223
+ if user_input.startswith('/session save'):
2224
+ session_name = user_input.replace('/session save', '').strip()
2225
+ if session_name:
2226
+ result = self.save_session(session_name)
2227
+ if result["success"]:
2228
+ console.print(f"\n[green]✅ Session saved as: {session_name}[/green]")
2229
+ else:
2230
+ console.print(f"\n[red]❌ Error saving session: {result['error']}[/red]")
2231
+ continue
2232
+
2233
+ if user_input.lower() == '/session info':
2234
+ session_info = self.get_session_info()
2235
+ console.print("\n[dim cyan]Current Session Info:[/dim cyan]")
2236
+ console.print(json.dumps(session_info, indent=2))
2237
+ continue
2238
 
2239
  # Process with enhanced capabilities
2240
  console.print("[dim]Elizabeth is thinking with full tool access...[/dim]")
 
2260
  elif sys.argv[1] == "--status":
2261
  status = elizabeth.get_system_status()
2262
  console.print(json.dumps(status, indent=2))
2263
+ elif sys.argv[1] == "-c" or sys.argv[1] == "--continue":
2264
+ # Session continuation mode
2265
+ if len(sys.argv) > 2:
2266
+ session_id = sys.argv[2]
2267
+ console.print(f"[dim]Continuing session: {session_id}[/dim]")
2268
+ elizabeth.run_enhanced_interactive(session_id)
2269
+ else:
2270
+ # List available sessions and let user choose
2271
+ sessions = elizabeth.list_sessions()
2272
+ if sessions:
2273
+ console.print("[dim cyan]Available Sessions:[/dim cyan]")
2274
+ for i, session in enumerate(sessions[:5]):
2275
+ console.print(f" [dim]{i+1}. {session['session_id']}: {session['message_count']} messages[/dim]")
2276
+
2277
+ try:
2278
+ choice = console.input("\n[dim]Enter session number to continue (or press Enter for new session): [/dim]").strip()
2279
+ if choice and choice.isdigit():
2280
+ session_index = int(choice) - 1
2281
+ if 0 <= session_index < len(sessions):
2282
+ session_id = sessions[session_index]['session_id']
2283
+ console.print(f"[dim]Continuing session: {session_id}[/dim]")
2284
+ elizabeth.run_enhanced_interactive(session_id)
2285
+ else:
2286
+ console.print("[yellow]Invalid session number, starting new session[/yellow]")
2287
+ elizabeth.run_enhanced_interactive()
2288
+ else:
2289
+ console.print("[dim]Starting new session[/dim]")
2290
+ elizabeth.run_enhanced_interactive()
2291
+ except:
2292
+ console.print("[yellow]Invalid input, starting new session[/yellow]")
2293
+ elizabeth.run_enhanced_interactive()
2294
+ else:
2295
+ console.print("[yellow]No sessions found, starting new session[/yellow]")
2296
+ elizabeth.run_enhanced_interactive()
2297
  else:
2298
  # Single message mode
2299
  message = " ".join(sys.argv[1:])