-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·2895 lines (2476 loc) · 124 KB
/
Copy pathcli.py
File metadata and controls
executable file
·2895 lines (2476 loc) · 124 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# TODO: Refactor into modular structure similar to Claude Code (lib/, commands/, tools/ directories)
# TODO: Add support for multiple LLM providers (Azure OpenAI, Anthropic, etc.)
# TODO: Implement telemetry and usage tracking (optional, with consent)
import os
import sys
import json
import typer
from rich.console import Console
from rich.markdown import Markdown
from rich.prompt import Prompt
from rich.panel import Panel
from rich.progress import Progress
from rich.syntax import Syntax
from rich.live import Live
from rich.layout import Layout
from rich.table import Table
from openai import OpenAI
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional, Union, Callable
import asyncio
import concurrent.futures
from dotenv import load_dotenv
import time
import re
import traceback
import requests
import urllib.parse
from uuid import uuid4
import socket
import threading
import multiprocessing
import pickle
import hashlib
import logging
import fastapi
import uvicorn
from fastapi import FastAPI, HTTPException, Depends, Request, BackgroundTasks
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
# Jina.ai client for search, fact-checking, and web reading
class JinaClient:
"""Client for interacting with Jina.ai endpoints"""
def __init__(self, token: Optional[str] = None):
"""Initialize with your Jina token"""
self.token = token or os.getenv("JINA_API_KEY", "")
self.headers = {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json"
}
def search(self, query: str) -> dict:
"""
Search using s.jina.ai endpoint
Args:
query: Search term
Returns:
API response as dict
"""
encoded_query = urllib.parse.quote(query)
url = f"https://s.jina.ai/{encoded_query}"
response = requests.get(url, headers=self.headers)
return response.json()
def fact_check(self, query: str) -> dict:
"""
Get grounding info using g.jina.ai endpoint
Args:
query: Query to ground
Returns:
API response as dict
"""
encoded_query = urllib.parse.quote(query)
url = f"https://g.jina.ai/{encoded_query}"
response = requests.get(url, headers=self.headers)
return response.json()
def reader(self, url: str) -> dict:
"""
Get ranking using r.jina.ai endpoint
Args:
url: URL to rank
Returns:
API response as dict
"""
encoded_url = urllib.parse.quote(url)
url = f"https://r.jina.ai/{encoded_url}"
response = requests.get(url, headers=self.headers)
return response.json()
# Check if RL tools are available
HAVE_RL_TOOLS = False
try:
# This is a placeholder for the actual import that would be used
from tool_optimizer import ToolSelectionManager
# If the import succeeds, set HAVE_RL_TOOLS to True
HAVE_RL_TOOLS = True
except ImportError:
# RL tools not available
# Define a dummy ToolSelectionManager to avoid NameError
class ToolSelectionManager:
def __init__(self, **kwargs):
self.optimizer = None
self.data_dir = kwargs.get('data_dir', '')
def record_tool_usage(self, **kwargs):
pass
# Load environment variables
load_dotenv()
# TODO: Add update checking similar to Claude Code's auto-update functionality
# TODO: Add configuration file support to store settings beyond environment variables
app = typer.Typer(help="OpenAI Code Assistant CLI")
console = Console()
# Global Constants
# TODO: Move these to a config file
DEFAULT_MODEL = "gpt-4o"
DEFAULT_TEMPERATURE = 0
MAX_TOKENS = 4096
TOKEN_LIMIT_WARNING = 0.8 # Warn when 80% of token limit is reached
# Models
# TODO: Implement more sophisticated schema validation similar to Zod in the original
# TODO: Add permission system for tools that require user approval
class ToolParameter(BaseModel):
name: str
description: str
type: str
required: bool = False
class Tool(BaseModel):
name: str
description: str
parameters: Dict[str, Any]
function: Callable
# TODO: Add needs_permission flag for sensitive operations
# TODO: Add category for organizing tools (file, search, etc.)
class Message(BaseModel):
role: str
content: Optional[str] = None
tool_calls: Optional[List[Dict[str, Any]]] = None
tool_call_id: Optional[str] = None
name: Optional[str] = None
# TODO: Add timestamp for message tracking
# TODO: Add token count for better context management
class Conversation:
def __init__(self):
self.messages = []
# TODO: Implement retry logic with exponential backoff for API calls
# TODO: Add support for multiple LLM providers
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
self.model = os.getenv("OPENAI_MODEL", DEFAULT_MODEL)
self.temperature = float(os.getenv("OPENAI_TEMPERATURE", DEFAULT_TEMPERATURE))
self.tools = self._register_tools()
self.tool_map = {tool.name: tool.function for tool in self.tools}
self.conversation_id = str(uuid4())
self.session_start_time = time.time()
self.token_usage = {"prompt": 0, "completion": 0, "total": 0}
self.verbose = False
self.max_tool_iterations = int(os.getenv("MAX_TOOL_ITERATIONS", "10"))
# Initialize tool selection optimizer if available
self.tool_optimizer = None
if HAVE_RL_TOOLS:
try:
# Create a simple tool registry adapter for the optimizer
class ToolRegistryAdapter:
def __init__(self, tools):
self.tools = tools
def get_all_tools(self):
return self.tools
def get_all_tool_names(self):
return [tool.name for tool in self.tools]
# Initialize the tool selection manager
self.tool_optimizer = ToolSelectionManager(
tool_registry=ToolRegistryAdapter(self.tools),
enable_optimization=os.getenv("ENABLE_TOOL_OPTIMIZATION", "1") == "1",
data_dir=os.path.join(os.path.dirname(os.path.abspath(__file__)), "data/rl")
)
if self.verbose:
print("Tool selection optimization enabled")
except Exception as e:
print(f"Warning: Failed to initialize tool optimizer: {e}")
# TODO: Implement context window management
# Jina.ai client for search, fact-checking, and web reading
def _init_jina_client(self):
"""Initialize the Jina.ai client"""
token = os.getenv("JINA_API_KEY", "")
return JinaClient(token)
def _jina_search(self, query: str) -> str:
"""Search the web using Jina.ai"""
try:
client = self._init_jina_client()
results = client.search(query)
if not results or not isinstance(results, dict):
return f"No search results found for '{query}'"
# Format the results
formatted_results = "Search Results:\n\n"
if "results" in results and isinstance(results["results"], list):
for i, result in enumerate(results["results"], 1):
title = result.get("title", "No title")
url = result.get("url", "No URL")
snippet = result.get("snippet", "No snippet")
formatted_results += f"{i}. {title}\n"
formatted_results += f" URL: {url}\n"
formatted_results += f" {snippet}\n\n"
else:
formatted_results += "Unexpected response format. Raw data:\n"
formatted_results += json.dumps(results, indent=2)[:1000]
return formatted_results
except Exception as e:
return f"Error performing search: {str(e)}"
def _jina_fact_check(self, statement: str) -> str:
"""Fact check a statement using Jina.ai"""
try:
client = self._init_jina_client()
results = client.fact_check(statement)
if not results or not isinstance(results, dict):
return f"No fact-checking results for '{statement}'"
# Format the results
formatted_results = "Fact Check Results:\n\n"
formatted_results += f"Statement: {statement}\n\n"
if "grounding" in results:
grounding = results["grounding"]
verdict = grounding.get("verdict", "Unknown")
confidence = grounding.get("confidence", 0)
formatted_results += f"Verdict: {verdict}\n"
formatted_results += f"Confidence: {confidence:.2f}\n\n"
if "sources" in grounding and isinstance(grounding["sources"], list):
formatted_results += "Sources:\n"
for i, source in enumerate(grounding["sources"], 1):
title = source.get("title", "No title")
url = source.get("url", "No URL")
formatted_results += f"{i}. {title}\n {url}\n\n"
else:
formatted_results += "Unexpected response format. Raw data:\n"
formatted_results += json.dumps(results, indent=2)[:1000]
return formatted_results
except Exception as e:
return f"Error performing fact check: {str(e)}"
def _jina_read_url(self, url: str) -> str:
"""Read and summarize a webpage using Jina.ai"""
try:
client = self._init_jina_client()
results = client.reader(url)
if not results or not isinstance(results, dict):
return f"No reading results for URL '{url}'"
# Format the results
formatted_results = f"Web Page Summary: {url}\n\n"
if "content" in results:
content = results["content"]
title = content.get("title", "No title")
summary = content.get("summary", "No summary available")
formatted_results += f"Title: {title}\n\n"
formatted_results += f"Summary:\n{summary}\n\n"
if "keyPoints" in content and isinstance(content["keyPoints"], list):
formatted_results += "Key Points:\n"
for i, point in enumerate(content["keyPoints"], 1):
formatted_results += f"{i}. {point}\n"
else:
formatted_results += "Unexpected response format. Raw data:\n"
formatted_results += json.dumps(results, indent=2)[:1000]
return formatted_results
except Exception as e:
return f"Error reading URL: {str(e)}"
def _register_tools(self) -> List[Tool]:
# TODO: Modularize tools into separate files
# TODO: Implement Tool decorators for easier registration
# TODO: Add more tools similar to Claude Code (ReadNotebook, NotebookEditCell, etc.)
# Define and register all tools
tools = [
Tool(
name="Weather",
description="Gets the current weather for a location",
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and optional state/country (e.g., 'San Francisco, CA' or 'London, UK')"
}
},
"required": ["location"]
},
function=self._get_weather
),
Tool(
name="View",
description="Reads a file from the local filesystem. The file_path parameter must be an absolute path, not a relative path.",
parameters={
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The absolute path to the file to read"
},
"limit": {
"type": "number",
"description": "The number of lines to read. Only provide if the file is too large to read at once."
},
"offset": {
"type": "number",
"description": "The line number to start reading from. Only provide if the file is too large to read at once"
}
},
"required": ["file_path"]
},
function=self._view_file
),
Tool(
name="Edit",
description="This is a tool for editing files.",
parameters={
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The absolute path to the file to modify"
},
"old_string": {
"type": "string",
"description": "The text to replace"
},
"new_string": {
"type": "string",
"description": "The text to replace it with"
}
},
"required": ["file_path", "old_string", "new_string"]
},
function=self._edit_file
),
Tool(
name="Replace",
description="Write a file to the local filesystem. Overwrites the existing file if there is one.",
parameters={
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The absolute path to the file to write"
},
"content": {
"type": "string",
"description": "The content to write to the file"
}
},
"required": ["file_path", "content"]
},
function=self._replace_file
),
Tool(
name="Bash",
description="Executes a given bash command in a persistent shell session.",
parameters={
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The command to execute"
},
"timeout": {
"type": "number",
"description": "Optional timeout in milliseconds (max 600000)"
}
},
"required": ["command"]
},
function=self._execute_bash
),
Tool(
name="GlobTool",
description="Fast file pattern matching tool that works with any codebase size.",
parameters={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The directory to search in. Defaults to the current working directory."
},
"pattern": {
"type": "string",
"description": "The glob pattern to match files against"
}
},
"required": ["pattern"]
},
function=self._glob_tool
),
Tool(
name="GrepTool",
description="Fast content search tool that works with any codebase size.",
parameters={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The directory to search in. Defaults to the current working directory."
},
"pattern": {
"type": "string",
"description": "The regular expression pattern to search for in file contents"
},
"include": {
"type": "string",
"description": "File pattern to include in the search (e.g. \"*.js\", \"*.{ts,tsx}\")"
}
},
"required": ["pattern"]
},
function=self._grep_tool
),
Tool(
name="LS",
description="Lists files and directories in a given path.",
parameters={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The absolute path to the directory to list"
},
"ignore": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of glob patterns to ignore"
}
},
"required": ["path"]
},
function=self._list_directory
),
Tool(
name="JinaSearch",
description="Search the web for information using Jina.ai",
parameters={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
}
},
"required": ["query"]
},
function=self._jina_search
),
Tool(
name="JinaFactCheck",
description="Fact check a statement using Jina.ai",
parameters={
"type": "object",
"properties": {
"statement": {
"type": "string",
"description": "The statement to fact check"
}
},
"required": ["statement"]
},
function=self._jina_fact_check
),
Tool(
name="JinaReadURL",
description="Read and summarize a webpage using Jina.ai",
parameters={
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL of the webpage to read"
}
},
"required": ["url"]
},
function=self._jina_read_url
)
]
return tools
# Tool implementations
# TODO: Add better error handling and user feedback
# TODO: Implement tool usage tracking and metrics
def _get_weather(self, location: str) -> str:
"""Get current weather for a location using OpenWeatherMap API"""
try:
# Get API key from environment or use a default for testing
api_key = os.getenv("OPENWEATHER_API_KEY", "")
if not api_key:
return "Error: OpenWeatherMap API key not found. Please set the OPENWEATHER_API_KEY environment variable."
# Prepare the API request
base_url = "https://api.openweathermap.org/data/2.5/weather"
params = {
"q": location,
"appid": api_key,
"units": "metric" # Use metric units (Celsius)
}
# Make the API request
response = requests.get(base_url, params=params)
# Check if the request was successful
if response.status_code == 200:
data = response.text
# Try to parse as JSON
try:
data = json.loads(data)
except json.JSONDecodeError:
return f"Error: Unable to parse weather data. Raw response: {data[:200]}..."
# Extract relevant weather information
weather_desc = data["weather"][0]["description"]
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
wind_speed = data["wind"]["speed"]
# Format the response
weather_info = (
f"Current weather in {location}:\n"
f"• Condition: {weather_desc.capitalize()}\n"
f"• Temperature: {temp}°C ({(temp * 9/5) + 32:.1f}°F)\n"
f"• Feels like: {feels_like}°C ({(feels_like * 9/5) + 32:.1f}°F)\n"
f"• Humidity: {humidity}%\n"
f"• Wind speed: {wind_speed} m/s ({wind_speed * 2.237:.1f} mph)"
)
return weather_info
else:
# Handle API errors
if response.status_code == 404:
return f"Error: Location '{location}' not found. Please check the spelling or try a different location."
elif response.status_code == 401:
return "Error: Invalid API key. Please check your OpenWeatherMap API key."
else:
return f"Error: Unable to fetch weather data. Status code: {response.status_code}"
except requests.exceptions.RequestException as e:
return f"Error: Network error when fetching weather data: {str(e)}"
except Exception as e:
return f"Error: Failed to get weather information: {str(e)}"
def _view_file(self, file_path: str, limit: Optional[int] = None, offset: Optional[int] = 0) -> str:
# TODO: Add special handling for binary files and images
# TODO: Add syntax highlighting for code files
try:
if not os.path.exists(file_path):
return f"Error: File not found: {file_path}"
# TODO: Handle file size limits better
with open(file_path, 'r') as f:
if limit is not None and offset is not None:
# Skip to offset
for _ in range(offset):
next(f, None)
# Read limited lines
lines = []
for _ in range(limit):
line = next(f, None)
if line is None:
break
lines.append(line)
content = ''.join(lines)
else:
content = f.read()
# TODO: Add file metadata like size, permissions, etc.
return content
except Exception as e:
return f"Error reading file: {str(e)}"
def _edit_file(self, file_path: str, old_string: str, new_string: str) -> str:
try:
# Create directory if creating new file
if not os.path.exists(os.path.dirname(file_path)) and old_string == "":
os.makedirs(os.path.dirname(file_path), exist_ok=True)
if old_string == "" and not os.path.exists(file_path):
# Creating new file
with open(file_path, 'w') as f:
f.write(new_string)
return f"Created new file: {file_path}"
# Reading existing file
if not os.path.exists(file_path):
return f"Error: File not found: {file_path}"
with open(file_path, 'r') as f:
content = f.read()
# Replace string
if old_string not in content:
return f"Error: Could not find the specified text in {file_path}"
# Count occurrences to ensure uniqueness
occurrences = content.count(old_string)
if occurrences > 1:
return f"Error: Found {occurrences} occurrences of the specified text in {file_path}. Please provide more context to uniquely identify the text to replace."
new_content = content.replace(old_string, new_string)
# Write back to file
with open(file_path, 'w') as f:
f.write(new_content)
return f"Successfully edited {file_path}"
except Exception as e:
return f"Error editing file: {str(e)}"
def _replace_file(self, file_path: str, content: str) -> str:
try:
# Create directory if it doesn't exist
directory = os.path.dirname(file_path)
if directory and not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
# Write content to file
with open(file_path, 'w') as f:
f.write(content)
return f"Successfully wrote to {file_path}"
except Exception as e:
return f"Error writing file: {str(e)}"
def _execute_bash(self, command: str, timeout: Optional[int] = None) -> str:
try:
import subprocess
import shlex
# Security check for banned commands
banned_commands = [
'alias', 'curl', 'curlie', 'wget', 'axel', 'aria2c', 'nc',
'telnet', 'lynx', 'w3m', 'links', 'httpie', 'xh', 'http-prompt',
'chrome', 'firefox', 'safari'
]
for banned in banned_commands:
if banned in command.split():
return f"Error: The command '{banned}' is not allowed for security reasons."
# Execute command
if timeout:
timeout_seconds = timeout / 1000 # Convert to seconds
else:
timeout_seconds = 1800 # 30 minutes default
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=timeout_seconds
)
output = result.stdout
if result.stderr:
output += f"\nErrors:\n{result.stderr}"
# Truncate if too long
if len(output) > 30000:
output = output[:30000] + "\n... (output truncated)"
return output
except subprocess.TimeoutExpired:
return f"Error: Command timed out after {timeout_seconds} seconds"
except Exception as e:
return f"Error executing command: {str(e)}"
def _glob_tool(self, pattern: str, path: Optional[str] = None) -> str:
try:
import glob
import os
if path is None:
path = os.getcwd()
# Build the full pattern path
if not os.path.isabs(path):
path = os.path.abspath(path)
full_pattern = os.path.join(path, pattern)
# Get matching files
matches = glob.glob(full_pattern, recursive=True)
# Sort by modification time (newest first)
matches.sort(key=os.path.getmtime, reverse=True)
if not matches:
return f"No files matching pattern '{pattern}' in {path}"
return "\n".join(matches)
except Exception as e:
return f"Error in glob search: {str(e)}"
def _grep_tool(self, pattern: str, path: Optional[str] = None, include: Optional[str] = None) -> str:
try:
import re
import os
import fnmatch
from concurrent.futures import ThreadPoolExecutor
if path is None:
path = os.getcwd()
if not os.path.isabs(path):
path = os.path.abspath(path)
# Compile regex pattern
regex = re.compile(pattern)
# Get all files
all_files = []
for root, _, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
# Apply include filter if provided
if include:
if not fnmatch.fnmatch(file, include):
continue
all_files.append(file_path)
# Sort by modification time (newest first)
all_files.sort(key=os.path.getmtime, reverse=True)
matches = []
def search_file(file_path):
try:
with open(file_path, 'r', errors='ignore') as f:
content = f.read()
if regex.search(content):
return file_path
except:
# Skip files that can't be read
pass
return None
# Search files in parallel
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(search_file, all_files)
for result in results:
if result:
matches.append(result)
if not matches:
return f"No matches found for pattern '{pattern}' in {path}"
return "\n".join(matches)
except Exception as e:
return f"Error in grep search: {str(e)}"
def _list_directory(self, path: str, ignore: Optional[List[str]] = None) -> str:
try:
import os
import fnmatch
# If path is not absolute, make it absolute from current directory
if not os.path.isabs(path):
path = os.path.abspath(os.path.join(os.getcwd(), path))
if not os.path.exists(path):
return f"Error: Directory not found: {path}"
if not os.path.isdir(path):
return f"Error: Path is not a directory: {path}"
# List directory contents
items = os.listdir(path)
# Apply ignore patterns
if ignore:
for pattern in ignore:
items = [item for item in items if not fnmatch.fnmatch(item, pattern)]
# Sort items
items.sort()
# Format output
result = []
for item in items:
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
result.append(f"{item}/")
else:
result.append(item)
if not result:
return f"Directory {path} is empty"
return "\n".join(result)
except Exception as e:
return f"Error listing directory: {str(e)}"
def add_message(self, role: str, content: str):
"""Legacy method to add messages - use direct append now"""
self.messages.append({"role": role, "content": content})
def process_tool_calls(self, tool_calls, query=None):
# TODO: Add tool call validation
# TODO: Add permission system for sensitive tools
# TODO: Add progress visualization for long-running tools
responses = []
# Process tool calls in parallel
from concurrent.futures import ThreadPoolExecutor
def process_single_tool(tool_call):
# Handle both object-style and dict-style tool calls
if isinstance(tool_call, dict):
function_name = tool_call["function"]["name"]
function_args = json.loads(tool_call["function"]["arguments"])
tool_call_id = tool_call["id"]
else:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
tool_call_id = tool_call.id
# Get the tool function
if function_name in self.tool_map:
# TODO: Add pre-execution validation
# TODO: Add permission check here
# Track start time for metrics
start_time = time.time()
try:
function = self.tool_map[function_name]
result = function(**function_args)
success = True
except Exception as e:
result = f"Error executing tool {function_name}: {str(e)}\n{traceback.format_exc()}"
success = False
# Calculate execution time
execution_time = time.time() - start_time
# Record tool usage for optimization if optimizer is available
if self.tool_optimizer is not None and query is not None:
try:
# Create current context snapshot
context = {
"messages": self.messages.copy(),
"conversation_id": self.conversation_id,
}
# Record tool usage
self.tool_optimizer.record_tool_usage(
query=query,
tool_name=function_name,
execution_time=execution_time,
token_usage=self.token_usage.copy(),
success=success,
context=context,
result=result
)
except Exception as e:
if self.verbose:
print(f"Warning: Failed to record tool usage: {e}")
return {
"tool_call_id": tool_call_id,
"function_name": function_name,
"result": result,
"name": function_name,
"execution_time": execution_time, # For metrics
"success": success
}
return None
# Process all tool calls in parallel
with ThreadPoolExecutor(max_workers=min(10, len(tool_calls))) as executor:
futures = [executor.submit(process_single_tool, tool_call) for tool_call in tool_calls]
for future in futures:
result = future.result()
if result:
# Add tool response to messages
self.messages.append({
"tool_call_id": result["tool_call_id"],
"role": "tool",
"name": result["name"],
"content": result["result"]
})
responses.append({
"tool_call_id": result["tool_call_id"],
"function_name": result["function_name"],
"result": result["result"]
})
# Log tool execution metrics if verbose
if self.verbose:
print(f"Tool {result['function_name']} executed in {result['execution_time']:.2f}s (success: {result['success']})")
# Return tool responses
return responses
def compact(self):
# TODO: Add more sophisticated compaction with token counting
# TODO: Implement selective retention of critical information
# TODO: Add option to save conversation history before compacting
system_prompt = next((m for m in self.messages if m["role"] == "system"), None)
user_messages = [m for m in self.messages if m["role"] == "user"]
if not user_messages:
return "No user messages to compact."
last_user_message = user_messages[-1]
# Create a compaction prompt
# TODO: Improve the compaction prompt with more guidance on what to retain
compact_prompt = (
"Summarize the conversation so far, focusing on the key points, decisions, and context. "
"Keep important details about the code and tasks. Retain critical file paths, commands, "
"and code snippets. The summary should be concise but complete enough to continue the "
"conversation effectively."
)
# Add compaction message
self.messages.append({"role": "user", "content": compact_prompt})
# Get compaction summary
# TODO: Add error handling for compaction API call
response = self.client.chat.completions.create(
model=self.model,
messages=self.messages,
stream=False
)
summary = response.choices[0].message.content
# Reset conversation with summary
if system_prompt:
self.messages = [system_prompt]
else:
self.messages = []
self.messages.append({"role": "system", "content": f"This is a compacted conversation. Previous context: {summary}"})
self.messages.append({"role": "user", "content": last_user_message["content"]})
# TODO: Add metrics for compaction (tokens before/after)
return "Conversation compacted successfully."
def get_response(self, user_input: str, stream: bool = True):
# TODO: Add more special commands similar to Claude Code (e.g., /version, /status)
# TODO: Implement binary feedback mechanism for comparing responses
# Special commands
if user_input.strip() == "/compact":