-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathharness.py
More file actions
2663 lines (2400 loc) · 116 KB
/
harness.py
File metadata and controls
2663 lines (2400 loc) · 116 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
import json
import os
import re
import shutil
import subprocess
import traceback
from pathlib import Path
import litellm
from docker_utils import run_command_in_container
from litellm import completion
# Drop unsupported params for model compatibility
litellm.drop_params = True
def is_test_related_operation(path: str = None, command: str = None, operation_type: str = None) -> tuple[bool, str]:
if path:
path_str = str(path).replace('\\', '/')
path_lower = path_str.lower()
path_obj = Path(path_str)
# Block run_tests.sh
if path_obj.name in ['run_tests.sh', 'run-tests.sh']:
return True, f"Access denied: {path_obj.name} is restricted for evaluation purposes"
# Block task_tests.*
if path_obj.name.startswith('task_tests.'):
return True, f"Access denied: {path_obj.name} is restricted for evaluation purposes"
if 'run_tests.sh' in path_lower or 'run-tests.sh' in path_lower:
return True, "Access denied: run_tests.sh files are restricted"
if 'task_tests.' in path_lower:
return True, "Access denied: task_tests.* files are restricted"
# Check command-based operations
if command:
command_lower = command.lower()
# Block execution of run_tests.sh
if 'run_tests.sh' in command_lower or 'run-tests.sh' in command_lower:
return True, "Access denied: Execution of run_tests.sh is restricted"
# Block operations on task_tests.* files
if 'task_tests.' in command_lower:
return True, "Access denied: Operations on task_tests.* files are restricted"
if any(pattern in command_lower for pattern in ['./run_tests', 'sh run_tests', 'bash run_tests',
'./run-tests', 'sh run-tests', 'bash run-tests',
'python task_tests', 'node task_tests']):
return True, "Access denied: Test execution is restricted"
return False, ""
def security_wrapper(operation_name: str):
"""
Decorator to add security checks to agent tool methods
"""
def decorator(func):
def wrapper(self, *args, **kwargs):
path = None
command = None
for param_name in ['target_file', 'file_path', 'relative_workspace_path']:
if param_name in kwargs:
path = kwargs[param_name]
break
if not path and args and operation_name in ['read_file', 'edit_file', 'write_file', 'delete_file']:
path = args[0]
if 'command' in kwargs:
command = kwargs['command']
elif args and operation_name == 'run_terminal_cmd':
command = args[0]
is_blocked, reason = is_test_related_operation(
path=path,
command=command,
operation_type=operation_name
)
if is_blocked:
return {
"success": False,
"error": reason,
"operation": operation_name,
"blocked_by_security": True
}
return func(self, *args, **kwargs)
return wrapper
return decorator
def sanitize_traceback(tb_string: str) -> str:
pattern = r'File "([^"]+)",'
def replace_path(match):
full_path = match.group(1)
# Keep only the filename
filename = os.path.basename(full_path)
return f'File "{filename}",'
sanitized = re.sub(pattern, replace_path, tb_string)
return sanitized
def is_test_file_or_directory(path: str) -> bool:
# Only block specific grading-related files
filename = Path(path).name.lower()
# Block task_tests.* files (grading files)
if filename.startswith('task_tests.'):
return True
# Block run-tests.sh and run_tests.sh
if filename in ['run-tests.sh', 'run_tests.sh']:
return True
return False
class EnhancedTools:
"""Enhanced tools for advanced agent operations"""
tools_info = [
{
"type": "function",
"function": {
"name": "codebase_search",
"description": "Search for code snippets using text-based keyword matching. This tool performs lexical search (exact word matches) using grep/ripgrep, NOT semantic search. Best for finding specific function names, variable names, or exact text patterns.",
"parameters": {
"type": "object",
"properties": {
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.",
},
"query": {
"type": "string",
"description": "Keywords to search for in the codebase. Will be split into words and searched as literal text matches. Use specific terms that would appear verbatim in the code.",
},
"target_directories": {
"type": "array",
"items": {"type": "string"},
"description": "Glob patterns for directories to search over",
},
},
"required": ["query"],
},
},
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read the contents of a file. Returns the file contents for the specified line range. Note: Reading files in the /tasks directory or ./run_tests.sh file is restricted.",
"parameters": {
"type": "object",
"properties": {
"target_file": {
"type": "string",
"description": "The path of the file to read. You can use either a relative path in the workspace or an absolute path.",
},
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.",
},
"should_read_entire_file": {
"type": "boolean",
"description": "Whether to read the entire file. Defaults to false.",
},
"start_line_one_indexed": {
"type": "integer",
"description": "The one-indexed line number to start reading from (inclusive).",
},
"end_line_one_indexed_inclusive": {
"type": "integer",
"description": "The one-indexed line number to end reading at (inclusive).",
},
},
"required": [
"target_file",
"should_read_entire_file",
"start_line_one_indexed",
"end_line_one_indexed_inclusive",
],
},
},
},
{
"type": "function",
"function": {
"name": "run_terminal_cmd",
"description": "Execute a terminal command in the container environment. Commands run in a sandboxed Docker container, not on the user's actual system. IMPORTANT: Web servers, dev servers, and long-running processes (uvicorn, npm run dev, flask run, etc.) MUST use is_background=true to avoid timeouts. Foreground commands have a 120-second timeout.",
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The terminal command to execute",
},
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this command needs to be run and how it contributes to the goal.",
},
"is_background": {
"type": "boolean",
"description": "Whether the command should be run in the background. MUST be true for web servers, dev servers, or any long-running process (e.g., uvicorn, npm run dev, flask run, node server.js, etc.). Set to false only for quick commands that complete immediately.",
},
},
"required": ["command", "is_background"],
},
},
},
{
"type": "function",
"function": {
"name": "list_dir",
"description": "List the contents of a directory. The quick tool to use for discovery, before using more targeted tools like grep_search or file reading.",
"parameters": {
"type": "object",
"properties": {
"relative_workspace_path": {
"type": "string",
"description": "Path to list contents of, relative to the workspace root.",
},
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.",
},
},
"required": ["relative_workspace_path"],
},
},
},
{
"type": "function",
"function": {
"name": "grep_search",
"description": "This is best for finding exact text matches or regex patterns. Use this tool to run fast, exact regex searches over text files using the ripgrep engine.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The regex pattern to search for",
},
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.",
},
"case_sensitive": {
"type": "boolean",
"description": "Whether the search should be case sensitive",
},
"include_pattern": {
"type": "string",
"description": "Glob pattern for files to include (e.g. '*.ts' for TypeScript files)",
},
"exclude_pattern": {
"type": "string",
"description": "Glob pattern for files to exclude",
},
},
"required": ["query"],
},
},
},
{
"type": "function",
"function": {
"name": "edit_file",
"description": "Edit a file using structured line-based edits. Supports both creating new files and modifying existing ones.",
"parameters": {
"type": "object",
"properties": {
"target_file": {
"type": "string",
"description": "The target file to modify. You can use either a relative path in the workspace or an absolute path.",
},
"instructions": {
"type": "string",
"description": "A clear description of what changes are being made to the file.",
},
"edit_type": {
"type": "string",
"enum": ["line_edits"],
"description": "Type of edit to perform. Only 'line_edits' for structured line-based changes is supported.",
},
"line_edits": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["replace", "insert", "delete"],
"description": "Type of line operation",
},
"line_number": {
"type": "integer",
"description": "1-indexed line number where the edit should be applied",
},
"content": {
"type": "string",
"description": "New content for replace/insert operations (not needed for delete)",
},
},
"required": ["type", "line_number"],
},
"description": "Array of line-based edits to apply (required if edit_type is 'line_edits'). Edits are applied in reverse line order to avoid offset issues.",
},
},
"required": ["target_file", "instructions", "edit_type"],
},
},
},
{
"type": "function",
"function": {
"name": "write_file",
"description": "Write content to a new file or completely overwrite an existing file. Use this for creating new files or replacing entire file contents.",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The path of the file to write, relative to the workspace root.",
},
"content": {
"type": "string",
"description": "The complete content to write to the file.",
},
},
"required": ["file_path", "content"],
},
},
},
{
"type": "function",
"function": {
"name": "search_replace",
"description": "Search for exact text in a file and replace it with new text. Performs a simple string replacement - the old_string must match exactly.",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The path of the file to modify, relative to the workspace root.",
},
"old_string": {
"type": "string",
"description": "The exact text to find and replace (must match exactly, including whitespace).",
},
"new_string": {
"type": "string",
"description": "The new text to replace the old text with.",
},
},
"required": ["file_path", "old_string", "new_string"],
},
},
},
{
"type": "function",
"function": {
"name": "file_search",
"description": "Fast file search based on fuzzy matching against file path. Use if you know part of the file path but don't know where it's located exactly.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Fuzzy filename to search for",
},
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.",
},
},
"required": ["query", "explanation"],
},
},
},
{
"type": "function",
"function": {
"name": "delete_file",
"description": "Deletes a file at the specified path.",
"parameters": {
"type": "object",
"properties": {
"target_file": {
"type": "string",
"description": "The path of the file to delete, relative to the workspace root.",
},
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.",
},
},
"required": ["target_file"],
},
},
},
{
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for real-time information about any topic.",
"parameters": {
"type": "object",
"properties": {
"search_term": {
"type": "string",
"description": "The search term to look up on the web. Be specific and include relevant keywords for better results.",
},
"explanation": {
"type": "string",
"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.",
},
},
"required": ["search_term"],
},
},
},
{
"type": "function",
"function": {
"name": "create_diagram",
"description": "Creates a Mermaid diagram that will be rendered in the chat UI.",
"parameters": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "Raw Mermaid diagram definition (e.g., 'graph TD; A-->B;').",
}
},
"required": ["content"],
},
},
},
{
"type": "function",
"function": {
"name": "edit_notebook",
"description": "Use this tool to edit a jupyter notebook cell.",
"parameters": {
"type": "object",
"properties": {
"target_notebook": {
"type": "string",
"description": "The path to the notebook file you want to edit.",
},
"cell_idx": {
"type": "number",
"description": "The index of the cell to edit (0-based)",
},
"is_new_cell": {
"type": "boolean",
"description": "If true, a new cell will be created at the specified cell index. If false, the cell at the specified cell index will be edited.",
},
"cell_language": {
"type": "string",
"description": "The language of the cell to edit. Should be STRICTLY one of these: 'python', 'markdown', 'javascript', 'typescript', 'r', 'sql', 'shell', 'raw' or 'other'.",
},
"old_string": {
"type": "string",
"description": "The text to replace (must be unique within the cell, and must match the cell contents exactly, including all whitespace and indentation).",
},
"new_string": {
"type": "string",
"description": "The edited text to replace the old_string or the content for the new cell.",
},
},
"required": [
"target_notebook",
"cell_idx",
"is_new_cell",
"cell_language",
"old_string",
"new_string",
],
},
},
},
{
"type": "function",
"function": {
"name": "api_call",
"description": "Make HTTP requests to test API endpoints. Useful for testing backend functionality and API integration.",
"parameters": {
"type": "object",
"properties": {
"method": {
"type": "string",
"enum": ["GET", "POST", "PUT", "DELETE", "PATCH"],
"description": "HTTP method to use"
},
"url": {
"type": "string",
"description": "The API endpoint URL (can be relative like '/api/users' or absolute)"
},
"headers": {
"type": "object",
"description": "HTTP headers to include in the request"
},
"body": {
"type": "object",
"description": "Request body for POST/PUT/PATCH requests"
},
"explanation": {
"type": "string",
"description": "One sentence explanation of why this API call is being made"
}
},
"required": ["method", "url", "explanation"]
}
}
},
{
"type": "function",
"function": {
"name": "database_query",
"description": "Execute database queries to test data persistence and retrieval. Useful for verifying backend data operations.",
"parameters": {
"type": "object",
"properties": {
"query_type": {
"type": "string",
"enum": ["find", "insert", "update", "delete", "aggregate"],
"description": "Type of database operation"
},
"collection": {
"type": "string",
"description": "MongoDB collection name"
},
"query": {
"type": "object",
"description": "Query object (MongoDB syntax)"
},
"data": {
"type": "object",
"description": "Data to insert/update (for insert/update operations)"
},
"explanation": {
"type": "string",
"description": "One sentence explanation of why this database operation is needed"
}
},
"required": ["query_type", "collection", "explanation"]
}
}
},
{
"type": "function",
"function": {
"name": "ui_test",
"description": "Test frontend UI functionality by simulating user interactions and checking page state.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["screenshot", "click", "type", "navigate", "wait_for_element", "get_text"],
"description": "UI action to perform"
},
"selector": {
"type": "string",
"description": "CSS selector for the element (required for click, type, wait_for_element, get_text)"
},
"text": {
"type": "string",
"description": "Text to type (for type action)"
},
"url": {
"type": "string",
"description": "URL to navigate to (for navigate action)"
},
"timeout": {
"type": "number",
"description": "Timeout in seconds (default: 10)"
},
"explanation": {
"type": "string",
"description": "One sentence explanation of what UI functionality is being tested"
}
},
"required": ["action", "explanation"]
}
}
},
]
def __init__(self, container=None, base_path: str = "/", mern_config: dict = None):
self.container = container
self.base_path = Path(base_path)
self.mern_config = mern_config or {
"api_base_url": "http://localhost:5001",
"frontend_url": "http://localhost:3000",
"mongo_uri": "mongodb://localhost:27017/dev-arena",
"websocket_url": "http://localhost:5001"
}
def codebase_search(
self, query: str, explanation: str = "", target_directories: list = None
) -> dict:
"""Text-based codebase search using grep/ripgrep for keyword matching"""
try:
results = []
search_dirs = target_directories if target_directories else ["."]
# Use ripgrep for better search if available, otherwise fallback to grep
search_terms = query.lower().split()
for search_dir in search_dirs:
if self.container:
# First try ripgrep for content search
rg_cmd = ["rg", "-i", "--type", "py", "--type", "js", "--type", "ts",
"-n", "-C", "2",
# Explicit exclusions for safety
"-g", "!node_modules/", "-g", "!.venv/", "-g", "!venv/",
"-g", "!__pycache__/", "-g", "!.git/", "-g", "!dist/",
"-g", "!build/", "-g", "!target/", "-g", "!vendor/",
query, str(self.base_path / search_dir)]
result = run_command_in_container(self.container, rg_cmd)
if result["success"] and result["output"]:
# Parse ripgrep output
lines = result["output"].split("\n")
current_file = None
for line in lines:
if line and not line.startswith("--"):
if ":" in line:
file_path, line_num, content = line.split(":", 2)
if file_path != current_file:
current_file = file_path
results.append({
"file": file_path,
"relevance": 0.9,
"snippet": content.strip(),
"line_number": line_num
})
# Fallback to find command for file discovery
if not results:
cmd = [
"find", str(self.base_path / search_dir), "-type", "f",
# Exclude common dependency/build directories
"-not", "-path", "*/node_modules/*",
"-not", "-path", "*/.venv/*",
"-not", "-path", "*/venv/*",
"-not", "-path", "*/__pycache__/*",
"-not", "-path", "*/.git/*",
"-not", "-path", "*/dist/*",
"-not", "-path", "*/build/*",
"-not", "-path", "*/target/*",
"-not", "-path", "*/vendor/*",
"(", "-name", "*.py", "-o", "-name", "*.js", "-o", "-name", "*.ts",
"-o", "-name", "*.jsx", "-o", "-name", "*.tsx", ")",
"-exec", "grep", "-l", "-i", query, "{}", ";"
]
result = run_command_in_container(self.container, cmd)
if result["success"]:
files = [f.strip() for f in result["output"].split("\n") if f.strip()]
for file in files[:10]:
results.append({
"file": file,
"relevance": 0.7,
"snippet": f"Contains '{query}'"
})
else:
# Local search with better file content analysis
search_path = self.base_path / search_dir
# Define exclusion patterns
exclude_dirs = {
'node_modules', '.venv', 'venv', '__pycache__', '.git',
'dist', 'build', 'target', 'vendor', '.next', '.nuxt',
'.cache', 'tmp', 'temp', '.gradle', '.m2', 'obj', 'bin'
}
def should_exclude_path(path: Path) -> bool:
"""Check if path contains excluded directories"""
return any(exc_dir in path.parts for exc_dir in exclude_dirs)
for ext in ["*.py", "*.js", "*.ts", "*.jsx", "*.tsx", "*.java", "*.cpp", "*.c"]:
for file in search_path.glob(f"**/{ext}"):
if len(results) >= 10:
break
# Skip excluded directories
if should_exclude_path(file):
continue
try:
with open(file, 'r', encoding='utf-8') as f:
content = f.read()
if any(term in content.lower() for term in search_terms):
# Find the best matching line
lines = content.split('\n')
best_line = ""
best_score = 0
for line in lines:
score = sum(1 for term in search_terms if term in line.lower())
if score > best_score:
best_score = score
best_line = line.strip()
results.append({
"file": str(file.relative_to(self.base_path)),
"relevance": min(0.9, 0.6 + best_score * 0.1),
"snippet": best_line or f"Found {best_score} matches in {file.name}"
})
except (UnicodeDecodeError, PermissionError):
continue
# Sort by relevance
results.sort(key=lambda x: x["relevance"], reverse=True)
return {"success": True, "results": results[:10], "explanation": explanation}
except Exception as e:
return {"success": False, "error": f"Codebase search failed: {str(e)}"}
@security_wrapper("read_file")
def read_file(
self,
target_file: str,
explanation: str = "",
should_read_entire_file: bool = True,
start_line_one_indexed: int = 1,
end_line_one_indexed_inclusive: int = -1,
) -> dict:
"""Read contents of a file with line range support"""
try:
target_path = Path(target_file)
if "tasks" in target_path.parts or target_path.name == "run_tests.sh":
return {
"success": False,
"error": "Access denied: Reading files in 'tasks/' directory or 'run_tests.sh' is restricted.",
"target_file": target_file,
}
if self.container:
result = run_command_in_container(
container=self.container,
command=["cat", str(self.base_path / target_file)],
)
if result["success"]:
content = result["output"]
else:
return {
"success": False,
"error": f"Failed to read file: {result.get('error', 'Unknown error')}",
}
else:
# Local file system
full_path = self.base_path / target_file
with open(full_path, "r", encoding="utf-8") as f:
content = f.read()
lines = content.split("\n")
total_lines = len(lines)
if should_read_entire_file:
return {
"success": True,
"content": content,
"target_file": target_file,
"total_lines": total_lines,
"explanation": explanation,
}
else:
# Handle line range reading
start_idx = max(0, start_line_one_indexed - 1)
end_idx = (
min(total_lines, end_line_one_indexed_inclusive)
if end_line_one_indexed_inclusive != -1
else total_lines
)
selected_lines = lines[start_idx:end_idx]
selected_content = "\n".join(selected_lines)
return {
"success": True,
"content": selected_content,
"target_file": target_file,
"start_line": start_line_one_indexed,
"end_line": end_idx,
"total_lines": total_lines,
"lines_before": start_idx,
"lines_after": total_lines - end_idx,
"explanation": explanation,
}
except Exception as e:
return {
"success": False,
"error": f"Error reading file '{target_file}': {str(e)}",
}
@security_wrapper("run_terminal_cmd")
def run_terminal_cmd(
self, command: str, explanation: str = "", is_background: bool = False
) -> dict:
"""Execute a terminal command"""
try:
if self.container:
cmd_list = ["sh", "-c", command]
result = run_command_in_container(
self.container, cmd_list, detach=is_background
)
return {
"success": result["success"],
"output": result.get("output", ""),
"error": result.get("error", ""),
"command": command,
"explanation": explanation,
"is_background": is_background,
}
else:
# Local execution
if is_background:
# For background processes, use Popen
process = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=str(self.base_path),
)
return {
"success": True,
"message": f"Background process started with PID {process.pid}",
"pid": process.pid,
"command": command,
"explanation": explanation,
"is_background": True,
}
else:
# Synchronous execution
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
cwd=str(self.base_path),
timeout=30, # 30 second timeout
)
return {
"success": result.returncode == 0,
"output": result.stdout,
"error": result.stderr,
"return_code": result.returncode,
"command": command,
"explanation": explanation,
"is_background": False,
}
except subprocess.TimeoutExpired:
return {
"success": False,
"error": f"Command timed out after 30 seconds: {command}",
"command": command,
}
except Exception as e:
return {
"success": False,
"error": f"Error executing command '{command}': {str(e)}",
"command": command,
}
@security_wrapper("list_dir")
def list_dir(self, relative_workspace_path: str, explanation: str = "") -> dict:
"""List directory contents"""
try:
if self.container:
# Normalize to a relative path within base_path
safe_rel_path = relative_workspace_path.lstrip("/") or "."
# Use shell to capture stderr as well (2>&1)
list_cmd = f"ls -la {self.base_path / safe_rel_path} 2>&1"
result = run_command_in_container(
container=self.container,
command=["sh", "-c", list_cmd],
)
if result["success"]:
return {
"success": True,
"contents": result["output"],
"path": safe_rel_path,
"explanation": explanation,
}
else:
return {
"success": False,
"error": f"Failed to list directory: {result.get('output') or 'Unknown error'}",
"path": safe_rel_path,
"command": list_cmd,
}
else:
# Local file system
safe_rel_path = relative_workspace_path.lstrip("/") or "."
full_path = self.base_path / safe_rel_path
if full_path.exists() and full_path.is_dir():
contents = []
for item in full_path.iterdir():
stat_info = item.stat()
contents.append(
{
"name": item.name,
"type": "directory" if item.is_dir() else "file",
"size": stat_info.st_size if item.is_file() else None,
"permissions": oct(stat_info.st_mode)[-3:],
}
)
return {
"success": True,
"contents": contents,
"path": safe_rel_path,
"explanation": explanation,
}
else:
return {
"success": False,
"error": f"Directory '{safe_rel_path}' does not exist or is not a directory",
}
except Exception as e:
return {
"success": False,
"error": f"Error listing directory '{relative_workspace_path}': {str(e)}",
}
@security_wrapper("grep_search")
def grep_search(
self,
query: str,
explanation: str = "",
case_sensitive: bool = False,
include_pattern: str = None,
exclude_pattern: str = None,
) -> dict:
"""Search for text patterns using grep/ripgrep"""
try:
# Build search command
if self.container:
# Check if ripgrep is available inside the container, fallback to grep.
# rg_check = run_command_in_container(self.container, ["which", "rg"])
# cmd = ["rg"] if rg_check["success"] else ["grep", "-r"]
cmd = ["rg"]
if not case_sensitive and cmd[0] == "rg":
cmd.append("-i")
elif not case_sensitive and cmd[0] == "grep":
cmd.append("-i")
default_excludes = [
"node_modules", ".venv", "venv", "__pycache__", ".git",
"dist", "build", "target", "vendor", ".next", ".nuxt",
".cache", "tmp", "temp", ".gradle", ".m2", "obj", "bin"
]
if cmd[0] == "rg":
for exc in default_excludes:
cmd.extend(["-g", f"!{exc}/"])
else:
for exc in default_excludes:
cmd.extend(["--exclude-dir", exc])
if include_pattern:
if cmd[0] == "rg":
cmd.extend(["-g", include_pattern])
else:
cmd.extend(["--include", include_pattern])
if exclude_pattern:
if cmd[0] == "rg":
cmd.extend(["-g", f"!{exclude_pattern}"])
else:
cmd.extend(["--exclude", exclude_pattern])
cmd.extend([query, str(self.base_path)])
result = run_command_in_container(self.container, cmd)
return {
"success": result["success"],
"matches": result.get("output", "").split("\n")
if result["success"]
else [],
"query": query,
"explanation": explanation,
}