Repository navigation
Expand file tree
/
Copy pathAI_CodeAsst.py
More file actions
1565 lines (1347 loc) · 77 KB
/
Copy pathAI_CodeAsst.py
File metadata and controls
1565 lines (1347 loc) · 77 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
import os
import sys
import json
from pathlib import Path
from textwrap import dedent
from typing import List, Dict, Any, Optional, Tuple
import shutil # For copying .ai_ignore_example
# Third-party libraries
import litellm
from litellm import completion, acompletion # For async if we need it later
from pydantic import BaseModel, ValidationError
from dotenv import load_dotenv
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.style import Style
from rich.syntax import Syntax
from rich.markdown import Markdown
from rich.prompt import Prompt, Confirm
from prompt_toolkit import PromptSession
from prompt_toolkit.styles import Style as PromptStyle
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
import time
import uuid # For unique tool call IDs if needed
# --- Configuration ---
CONFIG_DIR = Path.home() / ".ai_code_assistant"
CONFIG_FILE = CONFIG_DIR / "config.json"
SESSION_DIR = CONFIG_DIR / "sessions"
DEFAULT_AI_IGNORE_FILE = ".ai_ignore"
AI_IGNORE_EXAMPLE_FILE = CONFIG_DIR / ".ai_ignore_example"
# Initialize Rich console
console = Console()
# Initialize prompt_toolkit session
try:
prompt_session = PromptSession(
history=FileHistory(CONFIG_DIR / ".prompt_history"),
auto_suggest=AutoSuggestFromHistory(),
style=PromptStyle.from_dict({
'prompt': '#00aaff bold', # Light blue prompt
'completion-menu.completion': 'bg:#1e3a8a fg:#ffffff',
'completion-menu.completion.current': 'bg:#3b82f6 fg:#ffffff bold',
})
)
except Exception: # Fallback if FileHistory path is not writable initially
prompt_session = PromptSession(
style=PromptStyle.from_dict({
'prompt': '#00aaff bold',
})
)
# --- Global State & Configuration Variables ---
conversation_history: List[Dict[str, Any]] = []
current_llm_model: str = "gpt-4.1" # Default model
current_workspace_root: Optional[Path] = None
# litellm.set_verbose = True # For debugging LiteLLM calls
# --------------------------------------------------------------------------------
# 1. Pydantic Schemas (no changes needed from original for these)
# --------------------------------------------------------------------------------
class FileToCreate(BaseModel):
path: str
content: str
class FileToEdit(BaseModel):
path: str
original_snippet: str # This should be the exact snippet the LLM intends to replace
new_snippet: str
# --------------------------------------------------------------------------------
# 2. Function Calling Tool Definitions
# --------------------------------------------------------------------------------
# These definitions are standard and should work with most models via LiteLLM
tools = [
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read the content of a single file from the filesystem. Always use this before attempting to edit a file to get its current content.",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The path to the file to read (relative to workspace root or absolute).",
}
},
"required": ["file_path"],
},
},
},
{
"type": "function",
"function": {
"name": "read_multiple_files",
"description": "Read the content of multiple files from the filesystem.",
"parameters": {
"type": "object",
"properties": {
"file_paths": {
"type": "array",
"items": {"type": "string"},
"description": "Array of file paths to read (relative to workspace root or absolute).",
}
},
"required": ["file_paths"],
},
},
},
{
"type": "function",
"function": {
"name": "create_file",
"description": "Create a new file or overwrite an existing file with the provided content. Ensure the path is correct and the content is complete.",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The path where the file should be created (relative to workspace root or absolute).",
},
"content": {
"type": "string",
"description": "The full content to write to the file.",
},
},
"required": ["file_path", "content"],
},
},
},
{
"type": "function",
"function": {
"name": "create_multiple_files",
"description": "Create multiple files at once. Useful for generating a set of related files.",
"parameters": {
"type": "object",
"properties": {
"files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path (relative to workspace root or absolute)."},
"content": {"type": "string", "description": "Full file content."},
},
"required": ["path", "content"],
},
"description": "Array of files to create with their paths and content.",
}
},
"required": ["files"],
},
},
},
{
"type": "function",
"function": {
"name": "edit_file",
"description": "Edit an existing file by replacing a specific snippet of its current content with new content. CRITICAL: You MUST use 'read_file' on the target file in a previous step within the current turn to get the exact 'original_snippet' to replace. Do not guess the snippet. If the snippet is not found or is ambiguous, the edit will fail.",
"parameters": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "The path to the file to edit (relative to workspace root or absolute).",
},
"original_snippet": {
"type": "string",
"description": "The exact, verbatim text snippet from the current file content to find and replace. This MUST be obtained by reading the file first.",
},
"new_snippet": {
"type": "string",
"description": "The new text to replace the original snippet with.",
},
},
"required": ["file_path", "original_snippet", "new_snippet"],
},
},
},
{
"type": "function",
"function": {
"name": "list_directory_contents",
"description": "List files and subdirectories within a specified directory. Helps in understanding project structure.",
"parameters": {
"type": "object",
"properties": {
"directory_path": {
"type": "string",
"description": "The path to the directory to inspect (relative to workspace root or absolute). Defaults to current workspace root if not provided.",
}
},
"required": [], # directory_path is optional
},
},
}
]
# --------------------------------------------------------------------------------
# 3. System Prompt
# --------------------------------------------------------------------------------
SYSTEM_PROMPT_TEMPLATE = dedent("""\
You are an elite AI Software Engineer. Your goal is to assist the user with software development tasks by understanding their requests, interacting with their file system (via provided tools), and generating code or explanations.
Current Model: {model_name}
Workspace Root: {workspace_root_info}
Core Capabilities:
1. Code Analysis & Discussion: Analyze code, explain concepts, suggest optimizations, debug.
2. File Operations (via function calls):
- read_file: Read a single file. CRITICAL: Always read a file before attempting to edit it to get the exact current content for `original_snippet`.
- read_multiple_files: Read multiple files.
- create_file: Create/overwrite a file.
- create_multiple_files: Create multiple files.
- edit_file: Make precise edits. You MUST provide an `original_snippet` that exactly matches a part of the current file content. Get this snippet by calling `read_file` first.
- list_directory_contents: List files and folders in a directory.
Guidelines:
1. Clarification: If a request is ambiguous, ask for clarification.
2. Tool Usage:
- Use tools when necessary to interact with the file system.
- Announce your intention to use a tool before making the call. For example: "I will now read the file `main.py` to understand its current structure."
- For `edit_file`, it is MANDATORY to first call `read_file` on the target file in the same turn or ensure its content is already in the recent conversation. The `original_snippet` must be an exact match from the file's current content. Do not invent or assume snippets.
- If an edit involves multiple changes or is complex, consider creating a new file with the full modified content instead of multiple `edit_file` calls, or explain the changes and ask the user to apply them.
3. File Paths: When specifying file paths for tools, prefer paths relative to the workspace root if one is set. Otherwise, use paths as provided by the user or absolute paths if necessary.
4. Responses: Provide clear, concise, and accurate responses. Explain your reasoning, especially for complex changes or tool usage.
5. Safety: Be cautious with file modifications. If a user asks for a destructive operation, confirm their intent if it seems risky.
6. Efficiency: If you need to perform multiple file operations, try to batch them if appropriate (e.g., using `read_multiple_files` or `create_multiple_files`).
7. Context Awareness: Pay attention to the files already discussed or read in the current conversation.
IMPORTANT: When you decide to use a tool, make the tool call. If your response requires a tool call, structure your response to make that call. Do not just describe the call you would make.
If you are asked to edit a file, and you haven't read it recently, your first step should be to call `read_file`.
Example for editing:
User: "Change the greeting in `hello.py` to 'Aloha'."
Assistant: "Okay, I'll change the greeting in `hello.py`. First, I need to read the file to see its current content.
{{tool_call: read_file, arguments: {{"file_path": "hello.py"}}}}"
Tool Response: "Content of file 'hello.py':\n\ndef greet():\n print('Hello, world!')"
Assistant: "Thanks! Now I see the content. I will replace 'Hello, world!' with 'Aloha'.
{{tool_call: edit_file, arguments: {{"file_path": "hello.py", "original_snippet": "Hello, world!", "new_snippet": "Aloha"}}}}"
""")
def get_system_prompt() -> str:
global current_llm_model, current_workspace_root
workspace_info = str(current_workspace_root) if current_workspace_root else "Not set. Paths will be resolved from the current working directory or absolute paths."
return SYSTEM_PROMPT_TEMPLATE.format(model_name=current_llm_model, workspace_root_info=workspace_info)
# --------------------------------------------------------------------------------
# 4. Configuration Management (New Feature)
# --------------------------------------------------------------------------------
DEFAULT_CONFIG = {
"default_model": "gpt-4o-mini", # A common, capable default
"api_keys": {
"openai": "YOUR_OPENAI_API_KEY_HERE_OR_SET_ENV_VAR",
# Add other providers as needed, or rely purely on environment variables
},
"profiles": {
"default": {
"model": "gpt-4o-mini",
"workspace_root": None,
"auto_add_paths": [],
"custom_ai_ignore": None, # Path to a custom .ai_ignore file for this profile
}
},
"current_profile": "default",
"max_tokens_response": 8000, # Max tokens for LLM response
"max_tokens_context": 120000, # Approximate context window, LiteLLM handles specifics
}
def ensure_config_defaults(config: Dict) -> Dict:
"""Ensure all default keys exist in the loaded config."""
updated = False
for key, value in DEFAULT_CONFIG.items():
if key not in config:
config[key] = value
updated = True
elif isinstance(value, dict): # For nested dicts like profiles
for sub_key, sub_value in value.items():
if key == "profiles" and sub_key not in config[key]: # Ensure default profile exists
config[key][sub_key] = sub_value
updated = True
elif isinstance(sub_value, dict) and config[key].get(sub_key) and isinstance(config[key][sub_key], dict):
for s_sub_key, s_sub_value in sub_value.items():
if s_sub_key not in config[key][sub_key]:
config[key][sub_key][s_sub_key] = s_sub_value
updated = True
if "max_tokens_response" not in config:
config["max_tokens_response"] = DEFAULT_CONFIG["max_tokens_response"]
updated = True
if "max_tokens_context" not in config:
config["max_tokens_context"] = DEFAULT_CONFIG["max_tokens_context"]
updated = True
return config
def load_config() -> Dict:
global current_llm_model, current_workspace_root
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
SESSION_DIR.mkdir(parents=True, exist_ok=True)
# Create example .ai_ignore if it doesn't exist
if not AI_IGNORE_EXAMPLE_FILE.exists():
try:
with open(AI_IGNORE_EXAMPLE_FILE, "w") as f:
f.write(dedent("""\
# Lines starting with # are comments.
# Blank lines are ignored.
# File and directory names to ignore.
# Wildcards are not yet supported in this basic example, but can be added.
node_modules/
.git/
__pycache__/
*.pyc
*.tmp
.DS_Store
# Sensitive files
*.env
secrets.txt
"""))
console.print(f"Created example ignore file at [cyan]{AI_IGNORE_EXAMPLE_FILE}[/cyan]", style="dim")
except Exception as e:
console.print(f"[yellow]Warning: Could not create example ignore file: {e}[/yellow]", style="dim")
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, "r") as f:
config_data = json.load(f)
config_data = ensure_config_defaults(config_data) # Ensure all keys are present
except json.JSONDecodeError:
console.print(f"[yellow]Warning: config.json is corrupted. Loading defaults.[/yellow]")
config_data = DEFAULT_CONFIG.copy()
except Exception as e:
console.print(f"[red]Error loading config: {e}. Loading defaults.[/red]")
config_data = DEFAULT_CONFIG.copy()
else:
console.print(f"Config file not found at [cyan]{CONFIG_FILE}[/cyan]. Creating with defaults.", style="blue")
config_data = DEFAULT_CONFIG.copy()
save_config(config_data) # Save to ensure it's written if created or updated
# Apply current profile settings
profile_name = config_data.get("current_profile", "default")
profile = config_data.get("profiles", {}).get(profile_name, DEFAULT_CONFIG["profiles"]["default"])
current_llm_model = profile.get("model", config_data.get("default_model", "gpt-4.1"))
ws_root_str = profile.get("workspace_root")
if ws_root_str:
current_workspace_root = Path(ws_root_str).resolve()
if not current_workspace_root.is_dir():
console.print(f"[yellow]Warning: Workspace root '{current_workspace_root}' in profile '{profile_name}' is not a valid directory. Ignoring.[/yellow]")
current_workspace_root = None
else:
current_workspace_root = None
# Set LiteLLM API keys from config if present, otherwise env vars are used by LiteLLM
# LiteLLM automatically picks up OPENAI_API_KEY, ANTHROPIC_API_KEY etc. from env.
# This section is if you want to manage them explicitly via config.json (less secure).
# For simplicity and security, relying on environment variables is often better.
# Example: if "openai" in config_data.get("api_keys", {}):
# os.environ["OPENAI_API_KEY"] = config_data["api_keys"]["openai"]
# Auto-add paths from profile
auto_add_paths = profile.get("auto_add_paths", [])
if auto_add_paths:
console.print(f"Auto-adding paths from profile '{profile_name}':", style="blue")
for path_str in auto_add_paths:
handle_add_command_logic(path_str, is_auto_add=True)
return config_data
def save_config(config_data: Dict):
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
try:
with open(CONFIG_FILE, "w") as f:
json.dump(config_data, f, indent=4)
except Exception as e:
console.print(f"[red]Error saving config: {e}[/red]")
# --- Initialize config on load ---
config = load_config()
# --------------------------------------------------------------------------------
# 5. Helper Functions (File Ops, Path Normalization, etc.)
# --------------------------------------------------------------------------------
def normalize_path_str(path_str: str) -> str:
"""Return a canonical, absolute version of the path string, resolved against workspace root if set."""
global current_workspace_root
# Expand ~ to user's home directory
expanded_path = Path(path_str).expanduser()
if current_workspace_root:
# If path is already absolute, use it. Otherwise, join with workspace root.
resolved_path = current_workspace_root / expanded_path if not expanded_path.is_absolute() else expanded_path
else:
# If no workspace root, resolve relative to CWD or use absolute path
resolved_path = Path.cwd() / expanded_path if not expanded_path.is_absolute() else expanded_path
try:
# .resolve(strict=False) handles non-existent paths for creation, but strict=True ensures it exists for reading/editing
# For our purpose, we often deal with paths that might be created, so strict=False is okay for normalization.
# However, actual file operations should handle FileNotFoundError.
final_path = resolved_path.resolve(strict=False)
except Exception as e: # Catch potential errors during resolution (e.g. permission issues)
console.print(f"[yellow]Warning: Could not fully resolve path '{path_str}': {e}. Using as is: {resolved_path}[/yellow]")
final_path = resolved_path # Fallback to non-strictly resolved
# Security check: prevent escaping the workspace root if one is set
if current_workspace_root:
try:
final_path.relative_to(current_workspace_root)
except ValueError:
# Path is outside the workspace root. This could be intentional for absolute paths.
# For now, we allow it but one might want to restrict this.
pass # Allow absolute paths or paths outside if explicitly given
if ".." in str(final_path): # A basic check, Path.resolve() should handle most traversals
# This check might be overly simplistic if ".." is part of a legitimate filename.
# Path.is_relative_to (Python 3.9+) is better if available and applicable.
pass
return str(final_path)
def read_local_file(file_path_str: str) -> str:
normalized_path = normalize_path_str(file_path_str)
try:
with open(normalized_path, "r", encoding="utf-8") as f:
return f.read()
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {normalized_path}")
except Exception as e:
raise OSError(f"Error reading file {normalized_path}: {e}")
def create_local_file(path_str: str, content: str):
file_path = Path(normalize_path_str(path_str))
# Basic security: prevent writing to very high-level system dirs (very basic check)
# A more robust check would involve allowlists or more sophisticated sandboxing.
if file_path.is_absolute() and len(file_path.parts) < 3 and os.name != 'nt': # e.g. /bin, /etc
if not Confirm.ask(f"[yellow]⚠️ You are about to write to a sensitive system path: [bold red]{file_path}[/bold red]. Are you absolutely sure?[/yellow]", default=False):
console.print("[bold red]Operation cancelled by user.[/bold red]")
raise PermissionError(f"User cancelled writing to sensitive path: {file_path}")
if len(content) > 10_000_000: # 10MB limit for safety
raise ValueError("File content exceeds 10MB size limit.")
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
console.print(f"[bold green]✓[/bold green] Created/updated file: '[bright_cyan]{file_path}[/bright_cyan]'")
def apply_local_diff_edit(path_str: str, original_snippet: str, new_snippet: str):
normalized_path = normalize_path_str(path_str)
try:
content = read_local_file(normalized_path)
occurrences = content.count(original_snippet)
if occurrences == 0:
console.print(f"[bold red]✗ Original snippet not found in '{normalized_path}'.[/bold red]")
console.print("Expected snippet (verbatim):")
console.print(Panel(original_snippet, title="Expected Snippet", border_style="red", expand=False))
# console.print("Actual file content (first 500 chars):")
# console.print(Panel(content[:500] + "..." if len(content) > 500 else content, title="Actual Content (Preview)", border_style="yellow", expand=False))
raise ValueError("Original snippet not found. File not changed.")
if occurrences > 1:
# For now, we'll just replace the first one as per str.replace behavior.
# A more advanced version could ask the user or use line numbers.
console.print(f"[yellow]⚠ Warning: Original snippet found {occurrences} times in '{normalized_path}'. Replacing the first one.[/yellow]")
# Could add interactive selection here in the future.
updated_content = content.replace(original_snippet, new_snippet, 1)
if updated_content == content: # No change made
console.print(f"[yellow]⚠ Snippet replacement resulted in no change to the file '{normalized_path}'. This might happen if the new_snippet is identical to original_snippet or if the snippet was not actually found by str.replace (should be caught by occurrences check).[/yellow]")
# This case should ideally be caught by `occurrences == 0` or if `original_snippet == new_snippet`.
# If it still happens, it's an anomaly.
return # Do not rewrite if no change.
create_local_file(normalized_path, updated_content)
console.print(f"[bold green]✓[/bold green] Applied edit to '[bright_cyan]{normalized_path}[/bright_cyan]'")
except FileNotFoundError:
console.print(f"[bold red]✗[/bold red] File not found for editing: '[bright_cyan]{normalized_path}[/bright_cyan]'")
raise
except ValueError as e:
console.print(f"[bold red]✗[/bold red] {str(e)}")
raise
except Exception as e:
console.print(f"[bold red]✗[/bold red] Error applying edit to '{normalized_path}': {e}")
raise
def is_binary_file(file_path_str: str, peek_size: int = 1024) -> bool:
try:
with open(normalize_path_str(file_path_str), 'rb') as f:
chunk = f.read(peek_size)
return b'\0' in chunk
except Exception:
return True # Treat as binary if error reading
def get_ai_ignore_patterns(profile_custom_ignore_path: Optional[str]) -> List[str]:
"""Loads ignore patterns from global .ai_ignore and profile-specific one if provided."""
patterns = []
# Default ignore file in CWD
default_ignore = Path(DEFAULT_AI_IGNORE_FILE)
# User-wide example/default ignore file
user_wide_ignore = AI_IGNORE_EXAMPLE_FILE
files_to_check = []
if default_ignore.exists():
files_to_check.append(default_ignore)
elif user_wide_ignore.exists() and not profile_custom_ignore_path : # Use user-wide if no local and no profile specific
files_to_check.append(user_wide_ignore)
if profile_custom_ignore_path:
profile_ignore_path = Path(normalize_path_str(profile_custom_ignore_path))
if profile_ignore_path.exists():
files_to_check.append(profile_ignore_path)
else:
console.print(f"[yellow]Profile custom ignore file not found: {profile_ignore_path}[/yellow]", style="dim")
if not files_to_check:
console.print(f"No .ai_ignore file found in CWD, profile, or user config dir ([cyan]{user_wide_ignore}[/cyan]).", style="dim")
for file_path in files_to_check:
try:
with open(file_path, "r", encoding="utf-8") as f:
for line in f:
stripped_line = line.strip()
if stripped_line and not stripped_line.startswith("#"):
patterns.append(stripped_line)
console.print(f"Loaded ignore patterns from [cyan]{file_path}[/cyan]", style="dim")
except Exception as e:
console.print(f"[yellow]Warning: Could not read ignore file {file_path}: {e}[/yellow]", style="dim")
return list(set(patterns)) # Unique patterns
def path_matches_ignore(path: Path, ignore_patterns: List[str], root_dir: Path) -> bool:
"""Check if a path matches any ignore pattern. Basic implementation."""
# Ensure path is relative to the root_dir for pattern matching
try:
relative_path_str = str(path.relative_to(root_dir))
except ValueError: # path is not under root_dir, should not happen if called correctly
relative_path_str = str(path)
for pattern in ignore_patterns:
# Simple matching:
# If pattern ends with /, it's a directory pattern
if pattern.endswith('/'):
dir_pattern = pattern.rstrip('/')
# Check if any part of the path matches the directory pattern
# e.g., pattern "node_modules/" should match "node_modules/some_file.js"
# or "src/node_modules/file.js"
if f"/{dir_pattern}/" in f"/{relative_path_str}" or relative_path_str.startswith(dir_pattern + "/"):
return True
# Exact file/dir name match
elif pattern == path.name: # Match file/dir name directly
return True
# Wildcard for extension (e.g., *.pyc)
elif pattern.startswith("*."):
ext = pattern[1:] # .pyc
if path.name.endswith(ext):
return True
# Direct path match (e.g., specific_folder/specific_file.txt)
elif pattern == relative_path_str:
return True
return False
def add_directory_to_conversation(directory_path_str: str, ignore_patterns: List[str]):
global conversation_history
normalized_dir_path = Path(normalize_path_str(directory_path_str))
if not normalized_dir_path.is_dir():
console.print(f"[red]Error: '{normalized_dir_path}' is not a valid directory.[/red]")
return
console.print(f"Scanning directory: [cyan]{normalized_dir_path}[/cyan]...")
# Hardcoded common exclusions (less critical now with .ai_ignore)
# These can be moved to the default .ai_ignore_example
excluded_dirs_hardcoded = {".git", "__pycache__", "node_modules", ".venv", "venv", ".vscode", ".idea"}
excluded_extensions_hardcoded = {
".pyc", ".pyo", ".pyd", ".so", ".o", ".a", ".dll", ".exe", # Compiled
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp", ".svg", # Images
".mp3", ".wav", ".ogg", ".mp4", ".avi", ".mov", ".webm", # Media
".zip", ".tar", ".gz", ".rar", ".7z", # Archives
".pdf", ".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx", # Documents
".log", ".tmp", ".temp", ".bak", ".swp", # Logs & temp
".db", ".sqlite", ".sqlite3" # Databases
}
added_files_count = 0
skipped_files_info = [] # Store (path, reason)
# Use normalized_dir_path as the root for pattern matching
scan_root_dir = normalized_dir_path
for item in normalized_dir_path.rglob("*"): # Recursive glob
if item.is_file():
# Check hardcoded dir exclusions first (for parent dirs)
if any(excluded_dir in item.parts for excluded_dir in excluded_dirs_hardcoded):
skipped_files_info.append((str(item), "Parent in hardcoded excluded dirs"))
continue
if item.name in excluded_dirs_hardcoded: # If file itself is named like an excluded dir (unlikely but possible)
skipped_files_info.append((str(item), "In hardcoded excluded files/dirs"))
continue
# Check .ai_ignore patterns
if path_matches_ignore(item, ignore_patterns, scan_root_dir):
skipped_files_info.append((str(item), "Matches .ai_ignore pattern"))
continue
if item.suffix.lower() in excluded_extensions_hardcoded:
skipped_files_info.append((str(item), f"Hardcoded excluded extension ({item.suffix})"))
continue
if is_binary_file(str(item)):
skipped_files_info.append((str(item), "Binary file"))
continue
try:
if item.stat().st_size > 5_000_000: # 5MB limit per file
skipped_files_info.append((str(item), "Exceeds 5MB size limit"))
continue
content = read_local_file(str(item))
# Add to conversation history (ensure it's not already there)
file_marker_content = f"Content of file '{str(item)}':\n\n{content}"
if not any(msg.get("role") == "system" and msg.get("content","").startswith(f"Content of file '{str(item)}':") for msg in conversation_history):
conversation_history.append({"role": "system", "content": file_marker_content, "type": "file_context", "path": str(item)})
added_files_count += 1
else:
skipped_files_info.append((str(item), "Already in context"))
except Exception as e:
skipped_files_info.append((str(item), f"Error reading: {e}"))
elif item.is_dir(): # For directories, check if they match ignore patterns to skip scanning them
if any(excluded_dir in item.parts for excluded_dir in excluded_dirs_hardcoded) or \
path_matches_ignore(item, ignore_patterns, scan_root_dir) or \
item.name in excluded_dirs_hardcoded:
# If a directory is ignored, rglob won't enter it if we could prune it.
# However, rglob yields all items then we filter.
# For more efficient skipping, os.walk would be better to prune DIRS.
# For now, this just means files within it will be skipped individually.
pass
console.print(f"[green]✓[/green] Added {added_files_count} new files from '[cyan]{normalized_dir_path}[/cyan]' to conversation context.")
if skipped_files_info:
console.print(f"[yellow]Skipped {len(skipped_files_info)} files/items.[/yellow] (Use /list_skipped for details)")
# Store skipped files info for potential review by user, e.g. via a new command /list_skipped_files
# For now, just print a summary or first few.
if any(s[1] == "Matches .ai_ignore pattern" for s in skipped_files_info):
console.print(f"[dim]Some files were skipped due to '.ai_ignore' patterns.[/dim]")
# --------------------------------------------------------------------------------
# 6. Conversation History Management (Context Trimming, Adding files)
# --------------------------------------------------------------------------------
def trim_conversation_history():
"""Trim conversation history to prevent token limit issues."""
global conversation_history, config
# A more sophisticated trimming would estimate token count.
# For now, simple message count based, preserving system prompt and recent messages.
# LiteLLM can also do its own context window management.
max_messages = 30 # Keep last N user/assistant messages + system prompts + file contexts
system_prompts = [msg for msg in conversation_history if msg["role"] == "system" and msg.get("type") != "file_context"]
file_contexts = [msg for msg in conversation_history if msg.get("type") == "file_context"]
# User and assistant messages, excluding tool responses for this count
# Tool responses are tightly coupled with their preceding assistant message and subsequent assistant message.
# A better trimming would keep tool_call -> tool_response -> assistant_response blocks together.
# Let's try a simpler approach: keep system prompt, all file contexts, and last N other messages.
# This might still exceed token limits if file contexts are huge.
other_messages = [msg for msg in conversation_history if msg.get("type") != "file_context" and msg["role"] != "system"]
if len(other_messages) > max_messages:
other_messages_to_keep = other_messages[-max_messages:]
else:
other_messages_to_keep = other_messages
# Rebuild, ensuring system prompt is first.
new_history = []
if system_prompts: # Should always be at least one (the main system prompt)
new_history.append(system_prompts[0]) # Main system prompt
new_history.extend(file_contexts) # Add all file contexts
new_history.extend(other_messages_to_keep) # Add recent interactions
# Add any other system prompts (e.g., loaded file content that wasn't marked as file_context type)
# This part might be tricky if "system" role is used for other things.
# The current `add_directory_to_conversation` marks them with type "file_context".
if len(conversation_history) > len(new_history):
console.print(f"[dim]Trimmed conversation history from {len(conversation_history)} to {len(new_history)} messages.[/dim]")
conversation_history = new_history
def ensure_file_in_context(file_path_str: str) -> bool:
"""Adds file to context if not already present. Returns True if successful/already there."""
global conversation_history
normalized_path = normalize_path_str(file_path_str)
# Check if file content is already in history
# This check needs to be robust. Comparing full content string might be too much.
# We'll check for the specific marker.
file_marker_prefix = f"Content of file '{normalized_path}':"
if any(msg.get("role") == "system" and msg.get("content","").startswith(file_marker_prefix) for msg in conversation_history):
return True # Already in context
try:
content = read_local_file(normalized_path)
conversation_history.append({
"role": "system",
"content": f"{file_marker_prefix}\n\n{content}",
"type": "file_context", # Mark it for easier management
"path": normalized_path
})
console.print(f"[dim]Added file '{normalized_path}' to context for operation.[/dim]")
return True
except Exception as e:
console.print(f"[red]✗[/red] Could not read file '[cyan]{normalized_path}[/cyan]' to add to context: {e}")
return False
# --------------------------------------------------------------------------------
# 7. LLM Interaction with LiteLLM and Function Calling
# --------------------------------------------------------------------------------
def execute_tool_call(tool_call: Dict[str, Any]) -> Dict[str, Any]:
"""Executes a single tool call and returns a message for conversation history."""
tool_call_id = tool_call.get("id", f"call_{uuid.uuid4().hex[:8]}") # Ensure there's an ID
function_call_details = tool_call.get("function")
if not function_call_details:
return {
"role": "tool",
"tool_call_id": tool_call_id,
"name": "unknown_function_structure",
"content": "Error: Malformed tool call, missing 'function' details.",
}
function_name = function_call_details.get("name")
# Ensure arguments are parsed from string if necessary
raw_arguments = function_call_details.get("arguments", "{}")
try:
if isinstance(raw_arguments, str):
arguments = json.loads(raw_arguments)
elif isinstance(raw_arguments, dict):
arguments = raw_arguments
else:
raise ValueError("Arguments are not a valid JSON string or dict.")
except json.JSONDecodeError as e:
console.print(f"[red]Error decoding arguments for {function_name}: {e}[/red]")
console.print(f"Raw arguments: {raw_arguments}")
return {
"role": "tool",
"tool_call_id": tool_call_id,
"name": function_name,
"content": f"Error: Could not parse arguments for {function_name}. Invalid JSON: {e}. Arguments received: {raw_arguments}",
}
except ValueError as e: # Catches the custom ValueError
console.print(f"[red]Error with arguments for {function_name}: {e}[/red]")
return {
"role": "tool",
"tool_call_id": tool_call_id,
"name": function_name,
"content": f"Error: Invalid arguments structure for {function_name}: {e}. Arguments received: {raw_arguments}",
}
console.print(f"Attempting to execute tool: [bright_magenta]{function_name}[/bright_magenta] with args: [dim]{arguments}[/dim]")
result_content = ""
try:
if function_name == "read_file":
file_path = arguments["file_path"]
# normalized_path = normalize_path_str(file_path) # read_local_file does this
content = read_local_file(file_path) # Use original path, normalize inside
result_content = f"Content of file '{normalize_path_str(file_path)}':\n\n{content}"
elif function_name == "read_multiple_files":
file_paths = arguments["file_paths"]
results = []
for fp_str in file_paths:
try:
# normalized_fp = normalize_path_str(fp_str) # read_local_file does this
content = read_local_file(fp_str)
results.append(f"Content of file '{normalize_path_str(fp_str)}':\n\n{content}")
except Exception as e:
results.append(f"Error reading '{normalize_path_str(fp_str)}': {e}")
result_content = "\n\n" + "="*20 + " MULTIPLE FILE RESULTS " + "="*20 + "\n\n".join(results)
elif function_name == "create_file":
# Pydantic validation can be added here for more robustness
file_to_create = FileToCreate(**arguments)
create_local_file(file_to_create.path, file_to_create.content)
result_content = f"Successfully created/updated file '{normalize_path_str(file_to_create.path)}'."
elif function_name == "create_multiple_files":
files_data = arguments["files"]
created_files_paths = []
for file_info_dict in files_data:
file_to_create = FileToCreate(**file_info_dict)
create_local_file(file_to_create.path, file_to_create.content)
created_files_paths.append(normalize_path_str(file_to_create.path))
result_content = f"Successfully created/updated {len(created_files_paths)} files: {', '.join(created_files_paths)}."
elif function_name == "edit_file":
file_to_edit = FileToEdit(**arguments)
# CRITICAL: Ensure file is in context for the LLM to have based original_snippet on.
# The LLM is prompted to call read_file first. This function ensures it again if needed.
if not ensure_file_in_context(file_to_edit.path):
# If ensure_file_in_context fails, it prints an error.
# We should return an error message to the LLM.
raise ValueError(f"Could not ensure file '{file_to_edit.path}' was in context. Edit aborted.")
apply_local_diff_edit(file_to_edit.path, file_to_edit.original_snippet, file_to_edit.new_snippet)
result_content = f"Successfully applied edit to file '{normalize_path_str(file_to_edit.path)}'."
# After edit, the context version of this file is stale.
# We could re-add it, or let the LLM re-read if needed.
# For now, remove the old context message.
remove_file_from_context(normalize_path_str(file_to_edit.path), quiet=True)
ensure_file_in_context(file_to_edit.path) # Add the new version
elif function_name == "list_directory_contents":
dir_path_str = arguments.get("directory_path") # Optional
if dir_path_str:
target_dir = Path(normalize_path_str(dir_path_str))
elif current_workspace_root:
target_dir = current_workspace_root
else:
target_dir = Path.cwd()
if not target_dir.is_dir():
raise ValueError(f"'{target_dir}' is not a valid directory.")
items = []
for item in target_dir.iterdir():
item_type = "dir" if item.is_dir() else "file"
items.append(f"- {item.name} ({item_type})")
if not items:
result_content = f"Directory '{target_dir}' is empty."
else:
result_content = f"Contents of directory '{target_dir}':\n" + "\n".join(items)
else:
result_content = f"Error: Unknown function '{function_name}'."
console.print(f"[red]{result_content}[/red]")
except FileNotFoundError as e:
result_content = f"Error executing {function_name}: File not found. {e}"
console.print(f"[red]{result_content}[/red]")
except PermissionError as e:
result_content = f"Error executing {function_name}: Permission denied. {e}"
console.print(f"[red]{result_content}[/red]")
except ValidationError as e: # Pydantic validation error
result_content = f"Error executing {function_name}: Invalid arguments. {e.errors()}"
console.print(f"[red]{result_content}[/red]")
except KeyError as e: # Missing key in arguments
result_content = f"Error executing {function_name}: Missing argument '{e}'. Arguments received: {arguments}"
console.print(f"[red]{result_content}[/red]")
except Exception as e:
result_content = f"Error executing {function_name}: {type(e).__name__} - {e}"
console.print(f"[red]{result_content}[/red]")
# import traceback
# console.print(f"[dim]{traceback.format_exc()}[/dim]")
return {
"role": "tool",
"tool_call_id": tool_call_id,
"name": function_name, # LiteLLM expects 'name' here for the function that was called
"content": result_content,
}
def call_litellm_api(current_conversation: List[Dict[str, Any]], max_retries=2) -> Tuple[Optional[List[Dict[str, Any]]], Optional[str], Optional[List[Dict[str,Any]]]]:
"""
Calls LiteLLM API.
Returns (tool_calls_list, final_text_content, new_assistant_messages_for_history)
"""
global current_llm_model, config
console.print(f"\n[bold bright_blue]🤖 Assistant ({current_llm_model}) is thinking...[/bold bright_blue]")
# DeepSeek specific 'reasoning_content' is not standard.
# We'll just collect text and tool calls.
full_response_text = ""
accumulated_tool_calls: List[Dict[str, Any]] = [] # Correctly typed list of dicts
# Prepare messages for LiteLLM, ensuring system prompt is up-to-date
messages_for_api = [msg for msg in current_conversation if msg["role"] != "system"]
messages_for_api.insert(0, {"role": "system", "content": get_system_prompt()})
try:
response = litellm.completion(
model=current_llm_model,
messages=messages_for_api,
tools=tools,
tool_choice="auto", # Let the model decide, or "any" for DeepSeek Coder models
stream=True,
# max_tokens=config.get("max_tokens_response", 8000) # Optional: LiteLLM might infer or use model defaults
)
# Variables to aggregate streamed tool call parts
# LiteLLM streams tool calls piece by piece. We need to reconstruct them.
# {index: {"id": "", "type": "function", "function": {"name": "", "arguments": ""}}}
tool_call_fragments: Dict[int, Dict[str, Any]] = {}
for chunk in response:
delta = chunk.choices[0].delta
if delta.content:
text_part = delta.content
console.print(text_part, end="", style="bright_green")
full_response_text += text_part
if delta.tool_calls:
for tool_call_chunk in delta.tool_calls:
index = tool_call_chunk.index
if index not in tool_call_fragments:
tool_call_fragments[index] = {
"id": None,
"type": "function",
"function": {"name": "", "arguments": ""}
}
current_fragment = tool_call_fragments[index]
if tool_call_chunk.id:
current_fragment["id"] = tool_call_chunk.id
if tool_call_chunk.function:
if tool_call_chunk.function.name:
current_fragment["function"]["name"] += tool_call_chunk.function.name
if tool_call_chunk.function.arguments:
current_fragment["function"]["arguments"] += tool_call_chunk.function.arguments
console.print() # Newline after streaming assistant text
# Finalize tool calls from fragments
if tool_call_fragments:
for _index, fragment in sorted(tool_call_fragments.items()): # Process in order
if fragment["id"] and fragment["function"]["name"]: # Basic validation
accumulated_tool_calls.append({
"id": fragment["id"],
"type": fragment["type"],
"function": {
"name": fragment["function"]["name"],
"arguments": fragment["function"]["arguments"]
}
})
# Construct the assistant message for history
assistant_history_message: Dict[str, Any] = {"role": "assistant"}
if full_response_text:
assistant_history_message["content"] = full_response_text
else: # Important for some models if only tool_calls are present
assistant_history_message["content"] = None
if accumulated_tool_calls:
assistant_history_message["tool_calls"] = accumulated_tool_calls
return accumulated_tool_calls, full_response_text, [assistant_history_message]
except litellm.exceptions.APIConnectionError as e:
console.print(f"\n[bold red]❌ LiteLLM API Connection Error: {e}[/bold red]")
except litellm.exceptions.APIError as e: # Catch more generic LiteLLM API errors
console.print(f"\n[bold red]❌ LiteLLM API Error: {e} (Model: {current_llm_model})[/bold red]")
except litellm.exceptions.RateLimitError as e:
console.print(f"\n[bold red]❌ LiteLLM Rate Limit Error: {e}[/bold red]")
except litellm.exceptions.AuthenticationError as e:
console.print(f"\n[bold red]❌ LiteLLM Authentication Error: {e}. Check your API key for {current_llm_model}.[/bold red]")
console.print(f"[dim]LiteLLM expects API keys as environment variables (e.g., OPENAI_API_KEY, ANTHROPIC_API_KEY).[/dim]")
except Exception as e:
console.print(f"\n[bold red]❌ An unexpected error occurred during LiteLLM API call: {type(e).__name__} - {e}[/bold red]")
# import traceback
# console.print(f"[dim]{traceback.format_exc()}[/dim]")
return None, None, None
def process_user_message(user_message: str):
global conversation_history, config