-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1704 lines (1494 loc) · 64.2 KB
/
Copy pathmain.py
File metadata and controls
1704 lines (1494 loc) · 64.2 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 platform
import os
import hashlib
import tempfile
from dataclasses import dataclass, asdict
from pydantic import BaseModel
from typing import Callable, Dict, List, Any, Optional
from openai import OpenAI
from dotenv import load_dotenv
from pathlib import Path
import subprocess
import time
from src.tools.security_tools.project_root_checker import check_project_root
from src.system_check import security_scan
from src.user_permission import user_permission
import json
load_dotenv()
@dataclass
class CommandResult:
success: bool
stdout: str
stderr: str
exit_code: int
# constants & env
openai = os.getenv("OPENAI_API")
system_prompt_path = os.getenv("SYSTEM_PROMPT_PATH")
project_root = Path.cwd().resolve()
MAX_OUTPUT = 100_000 # for truncating stdout / stderr from subprocesses
MAX_TOOL_CALLS_PER_TOOL = 5
def get_system_prompt(system_prompt_path: str):
""" safely loads system instructions from specified file """
if not system_prompt_path:
raise RuntimeError("SYSTEM_PROMPT_PATH is not set.")
try:
with open(system_prompt_path, "r", encoding="utf-8") as f:
return f.read().strip()
except FileNotFoundError as e:
raise RuntimeError(f"System prompt file not found: {str(e)}") from e
except Exception as e:
raise RuntimeError("Could not read the system prompt file.") from e
# 1 - create tool model
# standardized tool schema
class Tool(BaseModel):
name: str
description: str
parameters: Dict[str, Any]
# 2 - create agent class
# agent class
# use : colon for type annotation
# use = for assigning values
class Agent:
def __init__(
self,
api_key: str,
system_prompt: str,
event_handler: Optional[Callable[[Dict[str, Any]], None]] = None,
permission_handler: Optional[Callable[[str, str], bool]] = None,
):
self._api_key = api_key
self.client = OpenAI(api_key=api_key)
self.project_root = Path.cwd().resolve()
# initialize messages array with system prompt for the agent.
self.messages: List[Dict[str, Any]] = [
{"role":"system", "content": system_prompt}
]
self.tools: List[Tool] = []
self._event_handler = event_handler or (lambda event: None)
self._permission_handler = permission_handler or (lambda tool_name, command: False)
self._project_context_loaded = False
self._generating_project_context = False
self._setup_tools()
self._emit("status", message=f"Agent initialized with {len(self.tools)} tools")
def _emit(self, event_type: str, **payload: Any) -> None:
"""Notify the host about progress without depending on terminal rendering."""
self._event_handler({"type": event_type, **payload})
def _request_permission(self, tool_name: str, command: str) -> bool:
return user_permission(tool_name, command, self._permission_handler)
def _get_project_root(self) -> str:
return self.project_root.as_posix()
def _project_context_path(self) -> Path:
return self.project_root / "WASABI.md"
def _get_file_hash(self, file_path: Path) -> str:
"""Return the SHA-256 hash of a file's current contents."""
with open(file_path, "rb") as file:
return hashlib.sha256(file.read()).hexdigest()
def _validate_file_hash(self, file_path: Path, expected_hash: str) -> bool:
current_hash = self._get_file_hash(file_path)
return current_hash == expected_hash
def _atomic_write(self, file_path: Path, content: str) -> None:
temporary_path: Optional[Path] = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
newline="",
dir=file_path.parent,
delete=False,
) as temporary_file:
temporary_path = Path(temporary_file.name)
temporary_file.write(content)
temporary_file.flush()
os.fsync(temporary_file.fileno())
os.replace(temporary_path, file_path)
except Exception:
if temporary_path is not None:
temporary_path.unlink(missing_ok=True)
raise
@staticmethod
def _requires_project_context(user_input: str) -> bool:
"""Return whether a request needs repository knowledge beyond Git metadata."""
normalized_input = user_input.lower()
context_terms = (
"architecture",
"dependency",
"dependencies",
"module",
"modules",
"codebase",
"repository",
"project structure",
"how does",
"where is",
"implement",
"modify",
"change",
"fix",
"refactor",
"optimize",
"configure",
"add feature",
"update",
)
return any(term in normalized_input for term in context_terms)
def _ensure_project_context(self) -> str:
"""Load the saved context, generating it once when it does not exist."""
context_path = self._project_context_path()
if not context_path.exists():
self._generate_project_context()
context = self._load_project_context()
self._project_context_loaded = True
return context
def _generate_project_context(self) -> None:
"""
Invoke the agent internally with a specialized prompt to inspect
the repository and create WASABI.md.
"""
if self._generating_project_context:
raise RuntimeError("Project-context generation is already in progress.")
self._generating_project_context = True
try:
context_agent = Agent(
self._api_key,
self.messages[0]["content"],
self._event_handler,
self._permission_handler,
)
context_agent._generating_project_context = True
context_agent.chat(
"Create WASABI.md now. Inspect the repository with the available tools, "
"then use edit_file to write a concise, durable project summary. Include "
"the overview, architecture, key modules, dependencies, entry points, "
"commands, security constraints, and engineering decisions. Do not copy "
"source code, include chat history, or speculate."
)
finally:
self._generating_project_context = False
if not self._project_context_path().is_file():
raise RuntimeError("The agent did not create WASABI.md while generating project context.")
def _load_project_context(self) -> str:
try:
return self._project_context_path().read_text(encoding="utf-8").strip()
except OSError as error:
raise RuntimeError(f"Could not read WASABI.md: {error}") from error
def _setup_tools(self):
self.tools = [
#4 - create tool description, not the actual tool.
Tool(
name="read_file",
description="read the contents of a file at the specified path",
parameters={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "the path to the file to read"
}
},
"required": ["path"],
"additionalProperties": False
},
),
Tool(
name="read_lines",
description=(
"Read an inclusive, 1-based line range from a file and return "
"line-numbered content, the current SHA-256 file hash, and total lines."
),
parameters={
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the file, relative to the project root.",
},
"start_line": {
"type": "integer",
"minimum": 1,
"description": "First line to read, using 1-based inclusive numbering.",
},
"end_line": {
"type": "integer",
"minimum": 1,
"description": "Last line to read, using 1-based inclusive numbering.",
},
},
"required": ["path", "start_line", "end_line"],
"additionalProperties": False,
},
),
Tool(
name="list_files",
description="list all files and directories in the specified path",
parameters={
"type": "object",
"properties": {
"path": {
"type":"string",
"description": "the directory path to list (defaults to current directory)"
}
},
"required": [],
"additionalProperties": False
}
),
Tool(
name="edit_file",
description=(
"Create a new file with the supplied content. Do not use this tool to edit "
"an existing file; use replace_exact, insert_before, or insert_after instead."
),
parameters={
"type":"object",
"properties": {
"path": {
"type":"string",
"description":"the path to the file to edit",
},
"old_text": {
"type": "string",
"description": "The text to search for and replace (leave empty to create new file)"
},
"new_text": {
"type": "string",
"description": "The text to replace old_text with"
}
},
"required": ["path","new_text"],
"additionalProperties": False
}
),
Tool(
name="replace_exact",
description=(
"Atomically replace one unique exact text block in an existing file after "
"confirming its SHA-256 hash matches a prior read_lines result."
),
parameters={
"type": "object",
"properties": {
"path": {"type": "string", "description": "Path relative to the project root."},
"expected_hash": {
"type": "string",
"pattern": "^[a-f0-9]{64}$",
"description": "SHA-256 hash returned by read_lines for this file.",
},
"old_content": {
"type": "string",
"description": "The unique, exact text block to replace.",
},
"new_content": {
"type": "string",
"description": "Replacement text inserted verbatim.",
},
},
"required": ["path", "expected_hash", "old_content", "new_content"],
"additionalProperties": False,
},
),
Tool(
name="replace_lines",
description=(
"Atomically replace an inclusive 1-based line range in an existing file after "
"confirming its SHA-256 hash matches a prior read_lines result."
),
parameters={
"type": "object",
"properties": {
"path": {"type": "string", "description": "Path relative to the project root."},
"expected_hash": {
"type": "string",
"pattern": "^[a-f0-9]{64}$",
"description": "SHA-256 hash returned by read_lines for this file.",
},
"start_line": {
"type": "integer",
"minimum": 1,
"description": "First line to replace, using 1-based inclusive numbering.",
},
"end_line": {
"type": "integer",
"minimum": 1,
"description": "Last line to replace, using 1-based inclusive numbering.",
},
"replacement": {
"type": "string",
"description": "Replacement text inserted verbatim.",
},
},
"required": ["path", "expected_hash", "start_line", "end_line", "replacement"],
"additionalProperties": False,
},
),
Tool(
name="insert_before",
description=(
"Atomically insert text verbatim before one unique exact anchor in an existing "
"file after confirming its SHA-256 hash matches a prior read_lines result."
),
parameters={
"type": "object",
"properties": {
"path": {"type": "string", "description": "Path relative to the project root."},
"expected_hash": {
"type": "string",
"pattern": "^[a-f0-9]{64}$",
"description": "SHA-256 hash returned by read_lines for this file.",
},
"anchor": {"type": "string", "description": "The unique, exact anchor text."},
"new_content": {"type": "string", "description": "Text inserted verbatim."},
},
"required": ["path", "expected_hash", "anchor", "new_content"],
"additionalProperties": False,
},
),
Tool(
name="insert_after",
description=(
"Atomically insert text verbatim after one unique exact anchor in an existing "
"file after confirming its SHA-256 hash matches a prior read_lines result."
),
parameters={
"type": "object",
"properties": {
"path": {"type": "string", "description": "Path relative to the project root."},
"expected_hash": {
"type": "string",
"pattern": "^[a-f0-9]{64}$",
"description": "SHA-256 hash returned by read_lines for this file.",
},
"anchor": {"type": "string", "description": "The unique, exact anchor text."},
"new_content": {"type": "string", "description": "Text inserted verbatim."},
},
"required": ["path", "expected_hash", "anchor", "new_content"],
"additionalProperties": False,
},
),
Tool(
name="get_project_root",
description="get the path for current working directory",
parameters={},
),
Tool(
name="ensure_project_context",
description=(
"Load the durable WASABI.md project context, generating it only when "
"the file does not exist. Use when repository context is needed."
),
parameters={
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False,
},
),
Tool(
name="load_project_context",
description=(
"Load and return the existing WASABI.md project context. Use only "
"when the file is known to exist; this tool never generates or edits it."
),
parameters={
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False,
},
),
Tool(
name="generate_project_context",
description=(
"Inspect the repository and create WASABI.md when it is missing. "
"This tool does not overwrite an existing context file."
),
parameters={
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False,
},
),
Tool(
name="delete_file",
description="move a file to ./wasabi/trash for deletion, basically soft delete to enable recovery",
parameters={
"type":"object",
"properties": {
"file_path": {
"type":"string",
"description":"required. path of the file that needs to be moved to trash"
}
},
"required":["file_path"],
"additionalProperties": False
}
),
Tool(
name="git_diff",
description="get diffs for a particular file, by default whole project",
parameters={
"type":"object",
"properties": {
"file_path": {
"type":"string",
"description":"optional. Relative path to a file within the project root, path of the file to view changes in that particular file"
}
},
"required":[],
"additionalProperties": False
}
),
Tool(
name="restore_file",
description="move a file from ./wasabi/trash to its original path, restore a file from trash",
parameters={
"type":"object",
"properties": {
"file_path": {
"type":"string",
"description":"path of the file that needs to be recovered"
}
},
"required":["file_path"],
"additionalProperties": False
}
),
Tool(
name="git_blame",
description="get blame for a file specified by file_path",
parameters={
"type":"object",
"properties": {
"file_path": {
"type":"string",
"description":"path of the file for which you need to acquire the blame history"
}
},
"required":["file_path"],
"additionalProperties": False
}
),
Tool(
name="git_status",
description="Get the current Git repository status, purpose : Understand repository history and changes."
+ "Current branch, Modified files, Staged files, Untracked files",
parameters={}
),
Tool(
name="uv_sync",
description="Synchronizes the project's virtual environment with pyproject.toml and uv.lock, installs necessary and removes unnecessary ones",
parameters={}
),
Tool(
name="uv_version",
description="get version for uv tool",
parameters={}
),
Tool(
name="uv_add",
description="add python packages to project using uv",
parameters={
"type":"object",
"properties": {
"package_names": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of Python package names to add to the project."
}
},
"required":["package_names"],
"additionalProperties":False
}
),
Tool(
name="uv_remove",
description="remove python packages from project using uv",
parameters={
"type":"object",
"properties": {
"package_names": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of Python package names to be removed from the project."
}
},
"required":["package_names"],
"additionalProperties":False
}
),
Tool(
name="uv_run_script",
description=(
"Run a specific Python script file inside the project's uv-managed "
"environment. Use this when a Python file such as main.py, script.py, "
"or scripts/setup.py needs to be executed. The user will be asked for "
"permission before execution. Do not use this tool to bypass denied "
"operations, security restrictions, or dedicated tools."
),
parameters={
"type": "object",
"properties": {
"script_path": {
"type": "string",
"description": (
"Path to the Python script to execute, relative to the "
"project root. Example: 'main.py' or 'scripts/setup.py'."
)
},
"arguments": {
"type": "array",
"items": {
"type": "string"
},
"description": (
"Optional command-line arguments passed directly to the "
"Python script. Example: ['--verbose', '--port', '8000']."
)
}
},
"required": ["script_path"],
"additionalProperties": False
}
),
Tool(
name="uv_run_module",
description=(
"Run an importable Python module using 'python -m' inside the project's "
"uv-managed environment. Use this for modules designed to be executed "
"through Python's module system, such as pytest or project modules. "
"The user will be asked for permission before execution. Do not use "
"this tool to bypass script execution restrictions, denied operations, "
"or other security boundaries."
),
parameters={
"type": "object",
"properties": {
"module_name": {
"type": "string",
"description": (
"Fully qualified importable Python module name to execute. "
"Examples: 'pytest', 'http.server', or 'package.module'."
)
},
"arguments": {
"type": "array",
"items": {
"type": "string"
},
"description": (
"Optional command-line arguments passed to the module. "
"Example: ['tests/', '-v']."
)
}
},
"required": ["module_name"],
"additionalProperties": False
}
),
Tool(
name="uv_run_command",
description=(
"Run a command-line executable available inside the project's "
"uv-managed environment. Use this for development tools such as pytest, "
"ruff, mypy, or other legitimate project CLI commands. The user will "
"be asked for permission before execution. Never use this tool to run "
"shell interpreters, destructive system commands, chain commands, "
"perform command substitution, or bypass denied operations and security "
"restrictions. Prefer dedicated tools whenever one exists."
),
parameters={
"type": "object",
"properties": {
"command": {
"type": "string",
"description": (
"Name of the executable to run. Examples: 'pytest', "
"'ruff', or 'mypy'. Do not include arguments in this field."
)
},
"arguments": {
"type": "array",
"items": {
"type": "string"
},
"description": (
"Optional arguments passed directly to the executable. "
"Example for 'ruff': ['check', '.']. Example for 'pytest': "
"['tests/', '-v']."
)
}
},
"required": ["command"],
"additionalProperties": False
}
),
Tool(
name="git_diff_summary",
description="get a quick statistic summary of all the changed files.",
parameters={}
),
Tool(
name="uv_project_dependency_tree",
description="get quick project's dependency tree",
parameters={}
),
Tool(
name="system_info",
description="get information about operating system, python version, uv version, project root",
parameters={}
),
Tool(
name="git_log",
description="view one-line log of commits with commit hashes, commits hashes from this command can be used with git show and other tools recursively to perform complex actions.",
parameters={
"type":"object",
"properties": {
"limit": {
"type":"integer",
"description":"Optional. Numeric limit to control the number of commits listed by the command."
}
},
"required":[],
"additionalProperties":False
}
),
Tool(
name="git_show",
description="inspect single git commit with its commit hash; returns : author details, date of commit, diff, & commit message, extremely useful when you want to understand why something changed",
parameters={
"type":"object",
"properties": {
"commit_hash": {
"type":"string",
"description":"Required. string form of the commit hash of the commit which is supposed to be inspected."
}
},
"required":["commit_hash"],
"additionalProperties":False
}
),
Tool(
name="search_text",
description=(
"Search for text across files in the project using ripgrep. "
"Use this tool to locate where a function, class, variable, string, "
"configuration value, error message, or any other text appears in the codebase. "
"Returns the matching file path, exact line number, and matched line content. "
"Use the returned file path and line number with precise read tools to inspect "
"the relevant code instead of reading entire files unnecessarily."
),
parameters={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": (
"The text or pattern to search for across project files. "
"Examples: 'user_permission', 'class Agent', or 'TODO'."
)
}
},
"required": ["query"],
"additionalProperties": False
}
),
Tool(
name="find_files",
description=(
"Find files in the current project by filename or glob pattern using ripgrep. "
"Use this tool to discover files when you know the filename, extension, naming "
"pattern, or approximate file type but not the exact path. It respects the "
"project's .gitignore rules by default and returns matching file paths. "
"Examples include finding all Python files with '*.py', test files with "
"'test_*.py', configuration files with 'pyproject.toml', or files inside a "
"specific directory with 'src/*.py'. Use this tool for file discovery; use "
"search_text when searching for content inside files."
),
parameters={
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": (
"Filename or glob pattern used to find matching files. "
"Examples: '*.py', 'test_*.py', 'pyproject.toml', "
"'src/*.py', or '**/test_*.py'."
)
}
},
"required": ["pattern"],
"additionalProperties": False
}
),
Tool(
name="search_text_with_context",
description=(
"Search for text across project files using ripgrep and return each matching "
"line together with surrounding lines for additional context. Use this when "
"you need to understand nearby code around a search result without reading "
"the entire file. The search is case-insensitive and returns file paths, "
"line numbers, matching lines, and the requested number of lines before and "
"after each match."
),
parameters={
"type": "object",
"properties": {
"search_string": {
"type": "string",
"description": (
"The text or pattern to search for across project files. "
"Examples: 'user_permission', 'class Agent', or 'TODO'."
)
},
"context_length": {
"type": "integer",
"minimum": 0,
"description": (
"Number of surrounding lines to return before and after each "
"matching line. For example, 5 returns up to 5 lines before "
"and 5 lines after every match."
)
}
},
"required": ["search_string", "context_length"],
"additionalProperties": False
}
)
]
# 7 - cmd executor function
# tool -> git / python3 / uv / etc
# arguments -> flags & options.
# the agent doesn't have
def _run_command(self, tool: str, args: list[str]) -> CommandResult:
allowed_tools = ["git", "python3", "uv", "rg", "find"]
# need to scope permission prompt only for destructive cmds / tools
# if user_permission(tool, "") != True:
# return f"User Permission Denied"
if tool not in allowed_tools:
return f"ERROR : access denied; only git, python3, uv, rg, find are accessible"
try:
result = subprocess.run(
[tool, *args],
cwd=project_root,
shell=False,
capture_output=True,
text=True,
timeout=30,
check=False,
)
stdout = result.stdout
stderr = result.stderr
if len(stdout) > MAX_OUTPUT:
stdout = stdout[:MAX_OUTPUT] + "\n\n... OUTPUT TRUNCATED ..."
if len(stderr) > MAX_OUTPUT:
stderr = stderr[:MAX_OUTPUT] + "\n\n... OUTPUT TRUNCATED ..."
return json.dumps(asdict(CommandResult(
success=result.returncode == 0,
stdout=stdout.strip(),
stderr=stderr.strip(),
exit_code=result.returncode,
)))
except subprocess.TimeoutExpired:
return json.dumps(asdict(CommandResult(
success=False,
stdout="",
stderr="Git command timed out.",
exit_code=-1,
)))
except Exception as e:
return json.dumps(asdict(CommandResult(
success=False,
stdout="",
stderr=str(e),
exit_code=-1,
)))
# GIT TOOLS
def _git_status(self):
"""
Get the current Git repository status.
Returns:
Current branch, modified files,
staged files and untracked files.
"""
subprocess_result = self._run_command("git",["status", "--short", "--branch"])
return subprocess_result
def _git_diff(self, path: str=None):
"""
get diffs for a particular file, by default whole project
returns diff output.
"""
options = ["diff"]
if path:
options.append(path)
subprocess_result = self._run_command("git", options)
return subprocess_result
# replaced by diff summary function
# def _git_changed_files(self):
# """
# returns names of files that have changes since the last commit
# """
# subprocess_result = self._run_command("git", ["diff", "--name-only", "-w", "--stat"])
# return subprocess_result
def _git_log(self, limit: str = "20"):
"""
view one line log of the current repository
can also be used to get the git hash for commit to inspect a single commit with its author, date, diff
"""
options = ["log", "--oneline", f"-{limit}"]
subprocess_result = self._run_command("git", options)
return subprocess_result
def _git_show(self, commit_hash: str):
"""
requires : commit_hash : string
inspect single git commit with its commit hash
returns : author details, date of commit, diff, & commit message.
"""
options = [
"show",
f"{commit_hash}"
]
subprocess_result = self._run_command("git", options)
return subprocess_result
def _git_diff_summary(self):
"""
quick diff views, shows no of lines changed across all the changed files
"""
subprocess_result = self._run_command("git", ["diff", "--stat"])
return subprocess_result
def _git_blame(self, file_path: str):
"""
last modification in file a specific file
"""
options = [
"blame",
f"{file_path}"
]
subprocess_result = self._run_command("git",options)
return subprocess_result
def _system_info(self):
"""
returns os, cwd, project root, python version, git version, uv version, rg version
"""
platform_info = {
"system": platform.system(),
"release": platform.release(),
"version": platform.version(),
"mac_ver": platform.mac_ver()
}
python_info = {
"python" : platform.python_version(),
"python_compiler" : platform.python_compiler()
}
uv_info = {
"uv_version": self._run_command("uv", ["--version"])
}
result = json.dumps([platform_info, python_info, uv_info, str(project_root)])
return result
# UV TOOLS
# tool description added for : uv project dependency tree
# version, sync, add and remove
def _uv_project_dependency_tree(self):
"""
returns the dependency tree for current working directory
"""
subprocess_result = self._run_command("uv", ["tree"])
return subprocess_result
def _uv_version(self):
subprocess_result = self._run_command("uv", ["--version"])
return subprocess_result
def _uv_sync(self):
"""
Synchronizes the project's virtual environment with pyproject.toml and uv.lock.
Installs missing dependencies and removes unnecessary ones.
"""
subprocess_result = self._run_command("uv", ["sync"])
return subprocess_result