janito 0.3.0__py3-none-any.whl → 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. janito/__init__.py +48 -1
  2. janito/__main__.py +29 -235
  3. janito/_contextparser.py +113 -0
  4. janito/agents/__init__.py +22 -0
  5. janito/agents/agent.py +21 -0
  6. janito/agents/claudeai.py +64 -0
  7. janito/agents/openai.py +53 -0
  8. janito/agents/test.py +34 -0
  9. janito/analysis/__init__.py +33 -0
  10. janito/analysis/display.py +149 -0
  11. janito/analysis/options.py +112 -0
  12. janito/analysis/prompts.py +75 -0
  13. janito/change/__init__.py +19 -0
  14. janito/change/applier.py +269 -0
  15. janito/change/content.py +62 -0
  16. janito/change/indentation.py +33 -0
  17. janito/change/position.py +169 -0
  18. janito/changehistory.py +46 -0
  19. janito/changeviewer/__init__.py +12 -0
  20. janito/changeviewer/diff.py +28 -0
  21. janito/changeviewer/panels.py +268 -0
  22. janito/changeviewer/styling.py +59 -0
  23. janito/changeviewer/themes.py +57 -0
  24. janito/cli/__init__.py +2 -0
  25. janito/cli/commands.py +53 -0
  26. janito/cli/functions.py +286 -0
  27. janito/cli/registry.py +26 -0
  28. janito/common.py +23 -0
  29. janito/config.py +8 -3
  30. janito/console/__init__.py +3 -0
  31. janito/console/commands.py +112 -0
  32. janito/console/core.py +62 -0
  33. janito/console/display.py +157 -0
  34. janito/fileparser.py +334 -0
  35. janito/prompts.py +58 -74
  36. janito/qa.py +40 -7
  37. janito/review.py +13 -0
  38. janito/scan.py +68 -14
  39. janito/tests/test_fileparser.py +26 -0
  40. janito/version.py +23 -0
  41. janito-0.5.0.dist-info/METADATA +146 -0
  42. janito-0.5.0.dist-info/RECORD +45 -0
  43. janito/changeviewer.py +0 -64
  44. janito/claude.py +0 -74
  45. janito/console.py +0 -60
  46. janito/contentchange.py +0 -165
  47. janito-0.3.0.dist-info/METADATA +0 -138
  48. janito-0.3.0.dist-info/RECORD +0 -15
  49. {janito-0.3.0.dist-info → janito-0.5.0.dist-info}/WHEEL +0 -0
  50. {janito-0.3.0.dist-info → janito-0.5.0.dist-info}/entry_points.txt +0 -0
  51. {janito-0.3.0.dist-info → janito-0.5.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,157 @@
1
+ from pathlib import Path
2
+ import shutil
3
+ from prompt_toolkit.completion import WordCompleter
4
+ from prompt_toolkit.formatted_text import HTML
5
+ from rich.console import Console
6
+ from rich.panel import Panel
7
+ from rich.table import Table
8
+ from rich.layout import Layout
9
+ from importlib.metadata import version
10
+
11
+ def create_completer(workdir: Path) -> WordCompleter:
12
+ """Create command completer with common commands and paths"""
13
+ commands = [
14
+ 'ask', 'request', 'help', 'exit', 'quit',
15
+ '--raw', '--verbose', '--debug', '--test'
16
+ ]
17
+ return WordCompleter(commands, ignore_case=True)
18
+
19
+ def format_prompt(workdir: Path) -> HTML:
20
+ """Format the prompt with current directory"""
21
+ cwd = workdir.name
22
+ return HTML(f'<ansigreen>janito</ansigreen> <ansiblue>{cwd}</ansiblue>> ')
23
+
24
+ def display_help() -> None:
25
+ """Display available commands, options and their descriptions"""
26
+ console = Console()
27
+
28
+ layout = Layout()
29
+ layout.split_column(
30
+ Layout(name="header"),
31
+ Layout(name="commands"),
32
+ Layout(name="options"),
33
+ Layout(name="examples")
34
+ )
35
+
36
+ # Header
37
+ header_table = Table(box=None, show_header=False)
38
+ header_table.add_row("[bold cyan]Janito Console Help[/bold cyan]")
39
+ header_table.add_row("[dim]Your AI-powered software development buddy[/dim]")
40
+
41
+ # Commands table
42
+ commands_table = Table(title="Available Commands", box=None)
43
+ commands_table.add_column("Command", style="cyan", width=20)
44
+ commands_table.add_column("Description", style="white")
45
+
46
+ commands_table.add_row(
47
+ "/ask <text> (/a)",
48
+ "Ask a question about the codebase without making changes"
49
+ )
50
+ commands_table.add_row(
51
+ "<text> or /request <text> (/r)",
52
+ "Request code modifications or improvements"
53
+ )
54
+ commands_table.add_row(
55
+ "/help (/h)",
56
+ "Display this help message"
57
+ )
58
+ commands_table.add_row(
59
+ "/quit or /exit (/q)",
60
+ "Exit the console session"
61
+ )
62
+
63
+ # Options table
64
+ options_table = Table(title="Common Options", box=None)
65
+ options_table.add_column("Option", style="cyan", width=20)
66
+ options_table.add_column("Description", style="white")
67
+
68
+ options_table.add_row(
69
+ "--raw",
70
+ "Display raw response without formatting"
71
+ )
72
+ options_table.add_row(
73
+ "--verbose",
74
+ "Show additional information during execution"
75
+ )
76
+ options_table.add_row(
77
+ "--debug",
78
+ "Display detailed debug information"
79
+ )
80
+ options_table.add_row(
81
+ "--test <cmd>",
82
+ "Run specified test command before applying changes"
83
+ )
84
+
85
+ # Examples panel
86
+ examples = Panel(
87
+ "\n".join([
88
+ "[dim]Basic Commands:[/dim]",
89
+ " ask how does the error handling work?",
90
+ " request add input validation to user functions",
91
+ "",
92
+ "[dim]Using Options:[/dim]",
93
+ " request update tests --verbose",
94
+ " ask explain auth flow --raw",
95
+ " request optimize code --test 'pytest'",
96
+ "",
97
+ "[dim]Complex Examples:[/dim]",
98
+ " request refactor login function --verbose --test 'python -m unittest'",
99
+ " ask code structure --raw --debug"
100
+ ]),
101
+ title="Examples",
102
+ border_style="blue"
103
+ )
104
+
105
+ # Update layout
106
+ layout["header"].update(header_table)
107
+ layout["commands"].update(commands_table)
108
+ layout["options"].update(options_table)
109
+ layout["examples"].update(examples)
110
+
111
+ console.print(layout)
112
+
113
+ def display_welcome(workdir: Path) -> None:
114
+ """Display welcome message and console information"""
115
+ console = Console()
116
+ try:
117
+ ver = version("janito")
118
+ except:
119
+ ver = "dev"
120
+
121
+ term_width = shutil.get_terminal_size().columns
122
+
123
+ COLORS = {
124
+ 'primary': '#729FCF', # Soft blue for primary elements
125
+ 'secondary': '#8AE234', # Bright green for actions/success
126
+ 'accent': '#AD7FA8', # Purple for accents
127
+ 'muted': '#7F9F7F', # Muted green for less important text
128
+ }
129
+
130
+ welcome_text = (
131
+ f"[bold {COLORS['primary']}]Welcome to Janito v{ver}[/bold {COLORS['primary']}]\n"
132
+ f"[{COLORS['muted']}]Your AI-Powered Software Development Buddy[/{COLORS['muted']}]\n\n"
133
+ f"[{COLORS['accent']}]Keyboard Shortcuts:[/{COLORS['accent']}]\n"
134
+ "• ↑↓ : Navigate command history\n"
135
+ "• Tab : Complete commands and paths\n"
136
+ "• Ctrl+D : Exit console\n"
137
+ "• Ctrl+C : Cancel current operation\n\n"
138
+ f"[{COLORS['accent']}]Available Commands:[/{COLORS['accent']}]\n"
139
+ "• /ask (or /a) : Ask questions about code\n"
140
+ "• /request (or /r) : Request code changes\n"
141
+ "• /help (or /h) : Show detailed help\n"
142
+ "• /quit (or /q) : Exit console\n\n"
143
+ f"[{COLORS['secondary']}]Current Version:[/{COLORS['secondary']}] v{ver}\n"
144
+ f"[{COLORS['muted']}]Working Directory:[/{COLORS['muted']}] {workdir.absolute()}"
145
+ )
146
+
147
+ welcome_panel = Panel(
148
+ welcome_text,
149
+ width=min(80, term_width - 4),
150
+ border_style="blue",
151
+ title="Janito Console",
152
+ subtitle="Press Tab for completions"
153
+ )
154
+
155
+ console.print("\n")
156
+ console.print(welcome_panel)
157
+ console.print("\n[cyan]How can I help you with your code today?[/cyan]\n")
janito/fileparser.py ADDED
@@ -0,0 +1,334 @@
1
+ from pathlib import Path
2
+ from typing import Dict, Tuple, List, Optional, Union
3
+ from dataclasses import dataclass
4
+ import re
5
+ import ast
6
+ import sys
7
+ import os # Add this import
8
+ from rich.console import Console
9
+ from rich.panel import Panel
10
+ from janito.config import config
11
+
12
+ def validate_file_path(filepath: Path) -> Tuple[bool, str]:
13
+ """
14
+ Validate that the file path exists and is readable
15
+
16
+ Args:
17
+ filepath: Path object to validate
18
+
19
+ Returns:
20
+ Tuple[bool, str]: (is_valid, error_message)
21
+ """
22
+ if not filepath.exists():
23
+ return False, f"File does not exist: {filepath}"
24
+ if not os.access(filepath, os.R_OK):
25
+ return False, f"File is not readable: {filepath}"
26
+ return True, ""
27
+
28
+ def validate_file_content(content: str) -> Tuple[bool, str]:
29
+ """
30
+ Validate that the content is not empty and contains valid text
31
+
32
+ Args:
33
+ content: String content to validate
34
+
35
+ Returns:
36
+ Tuple[bool, str]: (is_valid, error_message)
37
+ """
38
+ if not content:
39
+ return False, "Content cannot be empty"
40
+ if not isinstance(content, str):
41
+ return False, "Content must be a string"
42
+ return True, ""
43
+
44
+ @dataclass
45
+ class FileChange:
46
+ """Represents a file change with search/replace, search/delete, create or replace instructions"""
47
+ path: Path
48
+ description: str
49
+ is_new_file: bool
50
+ content: str = "" # For new files or replace operations
51
+ original_content: str = "" # Original content for file replacements
52
+ search_blocks: List[Tuple[str, Optional[str], Optional[str]]] = None # (search, replace, description)
53
+ replace_file: bool = False # Flag for complete file replacement
54
+ remove_file: bool = False # Flag for file deletion
55
+
56
+ def add_search_block(self, search: str, replace: Optional[str], description: Optional[str] = None) -> None:
57
+ """Add a search/replace or search/delete block with optional description"""
58
+ if self.search_blocks is None:
59
+ self.search_blocks = []
60
+ self.search_blocks.append((search, replace, description))
61
+
62
+ @dataclass
63
+ class FileBlock:
64
+ """Raw file block data extracted from response"""
65
+ uuid: str
66
+ filepath: str
67
+ action: str
68
+ description: str
69
+ content: str
70
+
71
+ def validate_python_syntax(content: str, filepath: Path) -> Tuple[bool, str]:
72
+ """Validate Python syntax and return (is_valid, error_message)"""
73
+ try:
74
+ ast.parse(content)
75
+ console = Console()
76
+ try:
77
+ rel_path = filepath.relative_to(Path.cwd())
78
+ display_path = f"./{rel_path}"
79
+ except ValueError:
80
+ display_path = str(filepath)
81
+ console.print(f"[green]✓ Python syntax validation passed:[/green] {display_path}")
82
+ return True, ""
83
+ except SyntaxError as e:
84
+ error_msg = f"Line {e.lineno}: {e.msg}"
85
+ console = Console()
86
+ try:
87
+ rel_path = filepath.relative_to(Path.cwd())
88
+ display_path = f"./{rel_path}"
89
+ except ValueError:
90
+ display_path = str(filepath)
91
+ console.print(f"[red]✗ Python syntax validation failed:[/red] {display_path}")
92
+ console.print(f"[red] {error_msg}[/red]")
93
+ return False, error_msg
94
+
95
+ def count_lines(text: str) -> int:
96
+ """Count the number of lines in a text block."""
97
+ return len(text.splitlines())
98
+
99
+ def extract_file_blocks(response_text: str) -> List[Tuple[str, str, str, str]]:
100
+ """Extract file blocks from response text and return list of (uuid, filepath, action, description, content)"""
101
+ file_blocks = []
102
+ console = Console()
103
+
104
+ # Find file blocks with improved quoted description handling
105
+ file_start_pattern = r'## ([a-f0-9]{8}) file (.*?) (modify|create|remove|replace)(?:\s+"([^"]*?)")?\s*##'
106
+ # Find the first UUID to check for duplicates
107
+ first_match = re.search(file_start_pattern, response_text)
108
+ if not first_match:
109
+ console.print("[red]FATAL ERROR: No file blocks found in response[/red]")
110
+ sys.exit(1)
111
+ fist_uuid = first_match.group(1)
112
+
113
+ # Find all file blocks
114
+ for match in re.finditer(file_start_pattern, response_text):
115
+ block_uuid, filepath, action, description = match.groups()
116
+
117
+ # Show debug info for create actions
118
+ if config.debug and action == 'create':
119
+ console.print(f"[green]Found new file block:[/green] {filepath}")
120
+
121
+ # Now find the complete block
122
+ full_block_pattern = (
123
+ f"## {block_uuid} file.*?##\n?"
124
+ f"(.*?)"
125
+ f"## {block_uuid} file end ##"
126
+ )
127
+
128
+ block_match = re.search(full_block_pattern, response_text[match.start():], re.DOTALL)
129
+ if not block_match:
130
+ # Show context around the incomplete block
131
+ context_start = max(0, match.start() - 100)
132
+ context_end = min(len(response_text), match.start() + 100)
133
+ context = response_text[context_start:context_end]
134
+
135
+ console.print(f"\n[red]FATAL ERROR: Found file start but no matching end for {filepath}[/red]")
136
+ console.print("[red]Context around incomplete block:[/red]")
137
+ console.print(Panel(context, title="Context", border_style="red"))
138
+ sys.exit(1)
139
+
140
+ content = block_match.group(1)
141
+ # For new files, preserve the first newline if it exists
142
+ if action == 'create' and content.startswith('\n'):
143
+ content = content[1:]
144
+
145
+ file_blocks.append((block_uuid, filepath.strip(), action, description or "", content))
146
+
147
+ if config.debug:
148
+ action_type = "Creating new file" if action == "create" else "Modifying file"
149
+ console.print(f"[green]Found valid block:[/green] {action_type} {filepath}")
150
+ console.print(f"[blue]Content length:[/blue] {len(content)} chars")
151
+
152
+ return file_blocks
153
+
154
+ def extract_modification_blocks(uuid: str, content: str) -> List[Tuple[str, str, Optional[str], str]]:
155
+ """Extract all modification blocks from content, returns list of (type, description, replace, search)"""
156
+ blocks = []
157
+ console = Console()
158
+
159
+ # Find all modification blocks in sequence
160
+ block_start = r'## ' + re.escape(uuid) + r' (search/replace|search/delete) "(.*?)" ##\n'
161
+ current_pos = 0
162
+
163
+ while True:
164
+ # Find next block start
165
+ start_match = re.search(block_start, content[current_pos:], re.DOTALL)
166
+ if not start_match:
167
+ break
168
+
169
+ block_type, description = start_match.groups()
170
+ block_start_pos = current_pos + start_match.end()
171
+
172
+ # Find block end based on type
173
+ if block_type == 'search/replace':
174
+ replace_marker = f"## {uuid} replace with ##\n"
175
+ end_marker = f"## {uuid}"
176
+
177
+ # Find replace marker
178
+ replace_pos = content.find(replace_marker, block_start_pos)
179
+ if replace_pos == -1:
180
+ # Show context around the incomplete block
181
+ context_start = max(0, current_pos + start_match.start() - 100)
182
+ context_end = min(len(content), current_pos + start_match.end() + 100)
183
+ context = content[context_start:context_end]
184
+
185
+ console.print(f"\n[red]FATAL ERROR: Missing 'replace with' marker for block:[/red] {description}")
186
+ console.print("[red]Context around incomplete block:[/red]")
187
+ console.print(Panel(context, title="Context", border_style="red"))
188
+ sys.exit(1)
189
+
190
+ # Get search content
191
+ search = content[block_start_pos:replace_pos]
192
+
193
+ # Find end of replacement
194
+ replace_start = replace_pos + len(replace_marker)
195
+ next_block = content.find(end_marker, replace_start)
196
+ if next_block == -1:
197
+ # Use rest of content if no end marker found
198
+ replace = content[replace_start:]
199
+ else:
200
+ replace = content[replace_start:next_block]
201
+
202
+ blocks.append(('replace', description, replace, search))
203
+ current_pos = next_block if next_block != -1 else len(content)
204
+
205
+ else: # search/delete
206
+ # Find either next block start or end of content
207
+ next_block_marker = content.find(f"## {uuid}", block_start_pos)
208
+ if next_block_marker == -1:
209
+ # Use rest of content if no more blocks
210
+ search = content[block_start_pos:]
211
+ else:
212
+ search = content[block_start_pos:next_block_marker]
213
+
214
+ blocks.append(('delete', description, None, search))
215
+ current_pos = next_block_marker if next_block_marker != -1 else len(content)
216
+
217
+ if config.debug:
218
+ console.print(f"[green]Found {block_type} block:[/green] {description}")
219
+
220
+ return blocks
221
+
222
+ def handle_file_block(block: FileBlock) -> FileChange:
223
+ """Process a single file block and return a FileChange object"""
224
+ console = Console()
225
+
226
+ # Handle file removal action
227
+ if block.action == 'remove':
228
+ return FileChange(
229
+ path=Path(block.filepath),
230
+ description=block.description,
231
+ is_new_file=False,
232
+ content="",
233
+ search_blocks=[],
234
+ remove_file=True
235
+ )
236
+
237
+ # Validate file path
238
+ path = Path(block.filepath)
239
+ is_valid, error = validate_file_path(path)
240
+ if block.action == 'replace' and not is_valid:
241
+ console.print(f"[red]Invalid file path for replacement:[/red] {error}")
242
+ sys.exit(1)
243
+
244
+ # Handle file replacement action
245
+ if block.action == 'replace':
246
+ # Read original content if file exists
247
+ original_content = ""
248
+ if path.exists():
249
+ try:
250
+ original_content = path.read_text()
251
+ except Exception as e:
252
+ console.print(f"[red]Error reading original file for replacement:[/red] {e}")
253
+ sys.exit(1)
254
+
255
+ return FileChange(
256
+ path=Path(block.filepath),
257
+ description=block.description,
258
+ is_new_file=False,
259
+ content=block.content.lstrip('\n'),
260
+ original_content=original_content,
261
+ search_blocks=[],
262
+ replace_file=True
263
+ )
264
+
265
+ # Validate content for new files
266
+ if block.action == 'create':
267
+ is_valid, error = validate_file_content(block.content)
268
+ if not is_valid:
269
+ console.print(f"[red]Invalid file content for {block.filepath}:[/red] {error}")
270
+ sys.exit(1)
271
+
272
+ if block.action == 'create':
273
+ return FileChange(
274
+ path=Path(block.filepath),
275
+ description=block.description,
276
+ is_new_file=True,
277
+ content=block.content[1:] if block.content.startswith('\n') else block.content,
278
+ search_blocks=[]
279
+ )
280
+
281
+ # Extract and process modification blocks
282
+ search_blocks = []
283
+ for block_type, description, replace, search in extract_modification_blocks(block.uuid, block.content):
284
+ # Ensure consistent line endings
285
+ search = search.rstrip('\n') + '\n'
286
+ if replace is not None:
287
+ replace = replace.rstrip('\n') + '\n'
288
+
289
+ if config.debug:
290
+ console.print(f"\n[cyan]Processing {block_type} block:[/cyan] {description}")
291
+ console.print(Panel(search, title="Search Content"))
292
+ if replace:
293
+ console.print(Panel(replace, title="Replace Content"))
294
+
295
+ search_blocks.append((search, replace, description))
296
+
297
+ return FileChange(
298
+ path=Path(block.filepath),
299
+ description=block.description,
300
+ is_new_file=False,
301
+ search_blocks=search_blocks
302
+ )
303
+
304
+ def parse_block_changes(response_text: str) -> List[FileChange]:
305
+ """Parse file changes from response blocks and return list of FileChange"""
306
+ changes = []
307
+ console = Console()
308
+
309
+ # First extract all file blocks
310
+ file_blocks = extract_file_blocks(response_text)
311
+
312
+ # Process each file block independently
313
+ for block_uuid, filepath, action, description, content in file_blocks:
314
+ path = Path(filepath)
315
+
316
+ file_block = FileBlock(
317
+ uuid=block_uuid,
318
+ filepath=filepath,
319
+ action=action,
320
+ description=description,
321
+ content=content
322
+ )
323
+
324
+ file_change = handle_file_block(file_block)
325
+ # For remove action, ensure remove_file flag is set
326
+ if action == 'remove':
327
+ file_change.remove_file = True
328
+ file_change.path = path
329
+ changes.append(file_change)
330
+
331
+ if config.debug:
332
+ console.print(f"\n[cyan]Processed {len(file_blocks)} file blocks[/cyan]")
333
+
334
+ return changes
janito/prompts.py CHANGED
@@ -1,25 +1,12 @@
1
1
  import re
2
+ import uuid
3
+ from typing import List, Union
4
+ from dataclasses import dataclass
5
+ from .analysis import parse_analysis_options, AnalysisOption
2
6
 
3
7
  # Core system prompt focused on role and purpose
4
- SYSTEM_PROMPT = """You are Janito, an AI assistant for software development tasks. Be concise.
5
- """
6
-
8
+ SYSTEM_PROMPT = """I am Janito, your friendly software development buddy. I help you with coding tasks while being clear and concise in my responses."""
7
9
 
8
- CHANGE_ANALISYS_PROMPT = """
9
- Current files:
10
- <files>
11
- {files_content}
12
- </files>
13
-
14
- Considering the current files content, provide a table of options for the requested change.
15
- Always provide options using a header label "=== **Option 1** : ...", "=== **Option 2**: ...", etc.
16
- Provide the header with a short description followed by the file changes on the next line
17
- What files should be modified and what should they contain? (one line description)
18
- Do not provide the content of any of the file suggested to be created or modified.
19
-
20
- Request:
21
- {request}
22
- """
23
10
 
24
11
  SELECTED_OPTION_PROMPT = """
25
12
  Original request: {request}
@@ -32,66 +19,63 @@ Current files:
32
19
  {files_content}
33
20
  </files>
34
21
 
35
- After checking the above files and the provided implementation, please provide the following:
36
-
37
- ## <uuid4> filename begin "short description of the change" ##
38
- <entire file content>
39
- ## <uuid4> filename end ##
40
-
41
- ALWAYS provide the entire file content, not just the changes.
42
- If no changes are needed answer to any worksppace just reply <
22
+ RULES:
23
+ - When removing constants, ensure they are not used elsewhere
24
+ - When adding new features to python files, add the necessary imports
25
+ - Python imports should be inserted at the top of the file
26
+ - For complete file replacements, only use for existing files marked as modified
27
+ - File replacements must preserve the essential functionality
28
+ - When multiple changes affect the same code block, combine them into a single change
29
+ - if no changes are required answer only the reason in the format: <no_changes_required>reason for no changes<no_changes_required>
30
+
31
+ Please provide the changes in this format:
32
+
33
+ For incremental changes:
34
+ ## {uuid} file <filepath> modify "short file change description" ##
35
+ ## {uuid} search/replace "short change description" ##
36
+ <search_content>
37
+ ## {uuid} replace with ##
38
+ <replace_content>
39
+ ## {uuid} file end ##
40
+
41
+ For complete file replacement (only for existing modified files):
42
+ ## {uuid} file <filepath> replace "short file description" ##
43
+ <full_file_content>
44
+ ## {uuid} file end ##
45
+
46
+ For new files:
47
+ ## {uuid} file <filepath> create "short file description" ##
48
+ <full_file_content>
49
+ ## {uuid} file end ##
50
+
51
+ For content deletion:
52
+ ## {uuid} file <filepath> modify ##
53
+ ## {uuid} search/delete "short change description" ##
54
+ <content_to_delete>
55
+ ## {uuid} file end ##
56
+
57
+ For file removal:
58
+ ## {uuid} file <filepath> remove "short removal reason" ##
59
+ ## {uuid} file end ##
60
+
61
+ RULES:
62
+ 1. search_content MUST preserve the original indentation/whitespace
63
+ 2. file replacement can only be used for existing files marked as
43
64
  """
44
65
 
45
- def build_selected_option_prompt(option_number: int, request: str, initial_response: str, files_content: str = "") -> str:
46
- """Build prompt for selected option details"""
47
- options = parse_options(initial_response)
48
- if option_number not in options:
49
- raise ValueError(f"Option {option_number} not found in response")
66
+ def build_selected_option_prompt(option_text: str, request: str, files_content: str = "") -> str:
67
+ """Build prompt for selected option details
68
+
69
+ Args:
70
+ option_text: Formatted text describing the selected option
71
+ request: The original user request
72
+ files_content: Content of relevant files
73
+ """
74
+ short_uuid = str(uuid.uuid4())[:8]
50
75
 
51
76
  return SELECTED_OPTION_PROMPT.format(
52
- option_text=options[option_number],
77
+ option_text=option_text,
53
78
  request=request,
54
- files_content=files_content
55
- )
56
-
57
- def parse_options(response: str) -> dict[int, str]:
58
- """Parse options from the response text, including any list items after the option label"""
59
- options = {}
60
- pattern = r"===\s*\*\*Option (\d+)\*\*\s*:\s*(.+?)(?====\s*\*\*Option|\Z)"
61
- matches = re.finditer(pattern, response, re.DOTALL)
62
-
63
- for match in matches:
64
- option_num = int(match.group(1))
65
- option_text = match.group(2).strip()
66
-
67
- # Split into description and list items
68
- lines = option_text.splitlines()
69
- description = lines[0]
70
- list_items = []
71
-
72
- # Collect list items that follow
73
- for line in lines[1:]:
74
- line = line.strip()
75
- if line.startswith(('- ', '* ', '• ')):
76
- list_items.append(line)
77
- elif not line:
78
- continue
79
- else:
80
- break
81
-
82
- # Combine description with list items if any exist
83
- if list_items:
84
- option_text = description + '\n' + '\n'.join(list_items)
85
-
86
- options[option_num] = option_text
87
-
88
- return options
89
-
90
-
91
- def build_request_analisys_prompt(files_content: str, request: str) -> str:
92
- """Build prompt for information requests"""
93
-
94
- return CHANGE_ANALISYS_PROMPT.format(
95
79
  files_content=files_content,
96
- request=request
80
+ uuid=short_uuid
97
81
  )