gitarsenal-cli 1.9.21 → 1.9.23

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 (34) hide show
  1. package/.venv_status.json +1 -1
  2. package/package.json +1 -1
  3. package/python/__pycache__/auth_manager.cpython-313.pyc +0 -0
  4. package/python/__pycache__/command_manager.cpython-313.pyc +0 -0
  5. package/python/__pycache__/fetch_modal_tokens.cpython-313.pyc +0 -0
  6. package/python/__pycache__/llm_debugging.cpython-313.pyc +0 -0
  7. package/python/__pycache__/modal_container.cpython-313.pyc +0 -0
  8. package/python/__pycache__/shell.cpython-313.pyc +0 -0
  9. package/python/api_integration.py +0 -0
  10. package/python/command_manager.py +605 -0
  11. package/python/credentials_manager.py +0 -0
  12. package/python/fetch_modal_tokens.py +0 -0
  13. package/python/fix_modal_token.py +0 -0
  14. package/python/fix_modal_token_advanced.py +0 -0
  15. package/python/gitarsenal.py +0 -0
  16. package/python/gitarsenal_proxy_client.py +0 -0
  17. package/python/llm_debugging.py +1061 -0
  18. package/python/modal_container.py +626 -0
  19. package/python/setup.py +15 -0
  20. package/python/setup_modal_token.py +0 -39
  21. package/python/shell.py +610 -0
  22. package/python/test_modalSandboxScript.py +2 -2
  23. package/scripts/postinstall.js +22 -23
  24. package/python/__pycache__/credentials_manager.cpython-313.pyc +0 -0
  25. package/python/__pycache__/test_modalSandboxScript.cpython-313.pyc +0 -0
  26. package/python/__pycache__/test_modalSandboxScript_stable.cpython-313.pyc +0 -0
  27. package/python/debug_delete.py +0 -167
  28. package/python/documentation.py +0 -76
  29. package/python/fix_setup_commands.py +0 -116
  30. package/python/modal_auth_patch.py +0 -178
  31. package/python/modal_proxy_service.py +0 -665
  32. package/python/modal_token_solution.py +0 -293
  33. package/python/test_dynamic_commands.py +0 -147
  34. package/test_modalSandboxScript.py +0 -5004
@@ -0,0 +1,1061 @@
1
+ import os
2
+ import re
3
+ import json
4
+ import requests
5
+ import openai
6
+ import anthropic
7
+
8
+ def call_openai_for_debug(command, error_output, api_key=None, current_dir=None, sandbox=None):
9
+ """Call OpenAI to debug a failed command and suggest a fix"""
10
+ print("\nšŸ” DEBUG: Starting LLM debugging...")
11
+ print(f"šŸ” DEBUG: Command: {command}")
12
+ print(f"šŸ” DEBUG: Error output length: {len(error_output) if error_output else 0}")
13
+ print(f"šŸ” DEBUG: Current directory: {current_dir}")
14
+ print(f"šŸ” DEBUG: Sandbox available: {sandbox is not None}")
15
+
16
+ # Define _to_str function locally to avoid NameError
17
+ def _to_str(maybe_bytes):
18
+ try:
19
+ return (maybe_bytes.decode('utf-8') if isinstance(maybe_bytes, (bytes, bytearray)) else maybe_bytes)
20
+ except UnicodeDecodeError:
21
+ # Handle non-UTF-8 bytes by replacing invalid characters
22
+ if isinstance(maybe_bytes, (bytes, bytearray)):
23
+ return maybe_bytes.decode('utf-8', errors='replace')
24
+ else:
25
+ return str(maybe_bytes)
26
+ except Exception:
27
+ # Last resort fallback
28
+ return str(maybe_bytes)
29
+
30
+ # Skip debugging for certain commands that commonly return non-zero exit codes
31
+ # but aren't actually errors (like test commands)
32
+ if command.strip().startswith("test "):
33
+ print("šŸ” Skipping debugging for test command - non-zero exit code is expected behavior")
34
+ return None
35
+
36
+ # Validate error_output - if it's empty, we can't debug effectively
37
+ if not error_output or not error_output.strip():
38
+ print("āš ļø Error output is empty. Cannot effectively debug the command.")
39
+ print("āš ļø Skipping OpenAI debugging due to lack of error information.")
40
+ return None
41
+
42
+ # Try to get API key from multiple sources
43
+ if not api_key:
44
+ print("šŸ” DEBUG: No API key provided, searching for one...")
45
+
46
+ # First try environment variable
47
+ api_key = os.environ.get("OPENAI_API_KEY")
48
+ print(f"šŸ” DEBUG: API key from environment: {'Found' if api_key else 'Not found'}")
49
+ if api_key:
50
+ print(f"šŸ” DEBUG: Environment API key value: {api_key}")
51
+
52
+ # If not in environment, try to fetch from server using fetch_modal_tokens
53
+ if not api_key:
54
+ try:
55
+ print("šŸ” DEBUG: Trying to fetch API key from server...")
56
+ from fetch_modal_tokens import get_tokens
57
+ _, _, api_key, _ = get_tokens()
58
+ if api_key:
59
+ # Set in environment for this session
60
+ os.environ["OPENAI_API_KEY"] = api_key
61
+ else:
62
+ print("āš ļø Could not fetch OpenAI API key from server")
63
+ except Exception as e:
64
+ print(f"āš ļø Error fetching API key from server: {e}")
65
+
66
+ # Store the API key in a persistent file if found
67
+ if api_key:
68
+ try:
69
+ os.makedirs(os.path.expanduser("~/.gitarsenal"), exist_ok=True)
70
+ with open(os.path.expanduser("~/.gitarsenal/openai_key"), "w") as f:
71
+ f.write(api_key)
72
+ print("āœ… Saved OpenAI API key for future use")
73
+ except Exception as e:
74
+ print(f"āš ļø Could not save API key: {e}")
75
+
76
+ # Try to load from saved file if not in environment
77
+ if not api_key:
78
+ try:
79
+ key_file = os.path.expanduser("~/.gitarsenal/openai_key")
80
+ print(f"šŸ” DEBUG: Checking for saved API key at: {key_file}")
81
+ if os.path.exists(key_file):
82
+ with open(key_file, "r") as f:
83
+ api_key = f.read().strip()
84
+ if api_key:
85
+ print("āœ… Loaded OpenAI API key from saved file")
86
+ print(f"šŸ” DEBUG: API key from file: {api_key}")
87
+ print(f"šŸ” DEBUG: API key length: {len(api_key)}")
88
+ # Also set in environment for this session
89
+ os.environ["OPENAI_API_KEY"] = api_key
90
+ else:
91
+ print("šŸ” DEBUG: Saved file exists but is empty")
92
+ else:
93
+ print("šŸ” DEBUG: No saved API key file found")
94
+ except Exception as e:
95
+ print(f"āš ļø Could not load saved API key: {e}")
96
+
97
+ # Then try credentials manager
98
+ if not api_key:
99
+ print("šŸ” DEBUG: Trying credentials manager...")
100
+ try:
101
+ from credentials_manager import CredentialsManager
102
+ credentials_manager = CredentialsManager()
103
+ api_key = credentials_manager.get_openai_api_key()
104
+ if api_key:
105
+ print(f"šŸ” DEBUG: API key from credentials manager: Found")
106
+ print(f"šŸ” DEBUG: Credentials manager API key value: {api_key}")
107
+ # Set in environment for this session
108
+ os.environ["OPENAI_API_KEY"] = api_key
109
+ else:
110
+ print(f"šŸ” DEBUG: API key from credentials manager: Not found")
111
+ except ImportError as e:
112
+ print(f"šŸ” DEBUG: Credentials manager not available: {e}")
113
+ # Fall back to direct input if credentials_manager is not available
114
+ pass
115
+
116
+ # Finally, prompt the user if still no API key
117
+ if not api_key:
118
+ print("šŸ” DEBUG: No API key found in any source, prompting user...")
119
+ print("\n" + "="*60)
120
+ print("šŸ”‘ OPENAI API KEY REQUIRED FOR DEBUGGING")
121
+ print("="*60)
122
+ print("To debug failed commands, an OpenAI API key is needed.")
123
+ print("šŸ“ Please paste your OpenAI API key below:")
124
+ print(" (Your input will be hidden for security)")
125
+ print("-" * 60)
126
+
127
+ try:
128
+ api_key = getpass.getpass("OpenAI API Key: ").strip()
129
+ if not api_key:
130
+ print("āŒ No API key provided. Skipping debugging.")
131
+ return None
132
+ print("āœ… API key received successfully!")
133
+ print(f"šŸ” DEBUG: User-provided API key: {api_key}")
134
+ # Save the API key to environment for future use in this session
135
+ os.environ["OPENAI_API_KEY"] = api_key
136
+ except KeyboardInterrupt:
137
+ print("\nāŒ API key input cancelled by user.")
138
+ return None
139
+ except Exception as e:
140
+ print(f"āŒ Error getting API key: {e}")
141
+ return None
142
+
143
+ # If we still don't have an API key, we can't proceed
144
+ if not api_key:
145
+ print("āŒ No OpenAI API key available. Cannot perform LLM debugging.")
146
+ print("šŸ’” To enable LLM debugging, set the OPENAI_API_KEY environment variable")
147
+ return None
148
+
149
+ # print(f"āœ… OpenAI API key available (length: {len(api_key)})")
150
+
151
+ # Gather additional context to help with debugging
152
+ directory_context = ""
153
+ system_info = ""
154
+ command_history = ""
155
+ file_context = ""
156
+
157
+ if sandbox:
158
+ try:
159
+ print("šŸ” Getting system information for better debugging...")
160
+
161
+ # Get OS information
162
+ os_info_cmd = """
163
+ echo "OS Information:"
164
+ cat /etc/os-release 2>/dev/null || echo "OS release info not available"
165
+ echo -e "\nKernel Information:"
166
+ uname -a
167
+ echo -e "\nPython Information:"
168
+ python --version
169
+ pip --version
170
+ echo -e "\nPackage Manager:"
171
+ which apt 2>/dev/null && echo "apt available" || echo "apt not available"
172
+ which yum 2>/dev/null && echo "yum available" || echo "yum not available"
173
+ which dnf 2>/dev/null && echo "dnf available" || echo "dnf not available"
174
+ which apk 2>/dev/null && echo "apk available" || echo "apk not available"
175
+ echo -e "\nEnvironment Variables:"
176
+ env | grep -E "^(PATH|PYTHON|VIRTUAL_ENV|HOME|USER|SHELL|LANG)" || echo "No relevant env vars found"
177
+ """
178
+
179
+ os_result = sandbox.exec("bash", "-c", os_info_cmd)
180
+ os_output = ""
181
+ for line in os_result.stdout:
182
+ os_output += _to_str(line)
183
+ os_result.wait()
184
+
185
+ system_info = f"""
186
+ System Information:
187
+ {os_output}
188
+ """
189
+ print("āœ… System information gathered successfully")
190
+ except Exception as e:
191
+ print(f"āš ļø Error getting system information: {e}")
192
+ system_info = "System information not available\n"
193
+
194
+ if current_dir and sandbox:
195
+ try:
196
+ # print("šŸ” Getting directory context for better debugging...")
197
+
198
+ # Get current directory contents
199
+ ls_result = sandbox.exec("bash", "-c", "ls -la")
200
+ ls_output = ""
201
+ for line in ls_result.stdout:
202
+ ls_output += _to_str(line)
203
+ ls_result.wait()
204
+
205
+ # Get parent directory contents
206
+ parent_result = sandbox.exec("bash", "-c", "ls -la ../")
207
+ parent_ls = ""
208
+ for line in parent_result.stdout:
209
+ parent_ls += _to_str(line)
210
+ parent_result.wait()
211
+
212
+ directory_context = f"""
213
+ Current directory contents:
214
+ {ls_output}
215
+
216
+ Parent directory contents:
217
+ {parent_ls}
218
+ """
219
+ print("āœ… Directory context gathered successfully")
220
+
221
+ # Check for relevant files that might provide additional context
222
+ # For example, if error mentions a specific file, try to get its content
223
+ relevant_files = []
224
+ error_files = re.findall(r'(?:No such file or directory|cannot open|not found): ([^\s:]+)', error_output)
225
+ if error_files:
226
+ for file_path in error_files:
227
+ # Clean up the file path
228
+ file_path = file_path.strip("'\"")
229
+ if not os.path.isabs(file_path):
230
+ file_path = os.path.join(current_dir, file_path)
231
+
232
+ # Try to get the parent directory if the file doesn't exist
233
+ if '/' in file_path:
234
+ parent_file_dir = os.path.dirname(file_path)
235
+ relevant_files.append(parent_file_dir)
236
+
237
+ # Look for package.json, requirements.txt, etc.
238
+ common_config_files = ["package.json", "requirements.txt", "pyproject.toml", "setup.py",
239
+ "Pipfile", "Dockerfile", "docker-compose.yml", "Makefile"]
240
+
241
+ for config_file in common_config_files:
242
+ check_cmd = f"test -f {current_dir}/{config_file}"
243
+ check_result = sandbox.exec("bash", "-c", check_cmd)
244
+ check_result.wait()
245
+ if check_result.returncode == 0:
246
+ relevant_files.append(f"{current_dir}/{config_file}")
247
+
248
+ # Get content of relevant files
249
+ if relevant_files:
250
+ file_context = "\nRelevant file contents:\n"
251
+ for file_path in relevant_files[:2]: # Limit to 2 files to avoid too much context
252
+ try:
253
+ file_check_cmd = f"test -f {file_path}"
254
+ file_check = sandbox.exec("bash", "-c", file_check_cmd)
255
+ file_check.wait()
256
+
257
+ if file_check.returncode == 0:
258
+ # It's a file, get its content
259
+ cat_cmd = f"cat {file_path}"
260
+ cat_result = sandbox.exec("bash", "-c", cat_cmd)
261
+ file_content = ""
262
+ for line in cat_result.stdout:
263
+ file_content += _to_str(line)
264
+ cat_result.wait()
265
+
266
+ # Truncate if too long
267
+ if len(file_content) > 1000:
268
+ file_content = file_content[:1000] + "\n... (truncated)"
269
+
270
+ file_context += f"\n--- {file_path} ---\n{file_content}\n"
271
+ else:
272
+ # It's a directory, list its contents
273
+ ls_cmd = f"ls -la {file_path}"
274
+ ls_dir_result = sandbox.exec("bash", "-c", ls_cmd)
275
+ dir_content = ""
276
+ for line in ls_dir_result.stdout:
277
+ dir_content += _to_str(line)
278
+ ls_dir_result.wait()
279
+
280
+ file_context += f"\n--- Directory: {file_path} ---\n{dir_content}\n"
281
+ except Exception as e:
282
+ print(f"āš ļø Error getting content of {file_path}: {e}")
283
+
284
+ # print(f"āœ… Additional file context gathered from {len(relevant_files)} relevant files")
285
+
286
+ except Exception as e:
287
+ print(f"āš ļø Error getting directory context: {e}")
288
+ directory_context = f"\nCurrent directory: {current_dir}\n"
289
+
290
+ # Prepare the API request
291
+ headers = {
292
+ "Content-Type": "application/json",
293
+ "Authorization": f"Bearer {api_key}"
294
+ }
295
+
296
+ stored_credentials = get_stored_credentials()
297
+ auth_context = generate_auth_context(stored_credentials)
298
+
299
+ # Create a prompt for the LLM
300
+ print("\n" + "="*60)
301
+ print("DEBUG: ERROR_OUTPUT SENT TO LLM:")
302
+ print("="*60)
303
+ print(f"{error_output}")
304
+ print("="*60 + "\n")
305
+
306
+ prompt = f"""
307
+ I'm trying to run the following command in a Linux environment:
308
+
309
+ ```
310
+ {command}
311
+ ```
312
+
313
+ But it failed with this error:
314
+
315
+ ```
316
+ {error_output}
317
+ ```
318
+ {system_info}
319
+ {directory_context}
320
+ {file_context}
321
+
322
+ AVAILABLE CREDENTIALS:
323
+ {auth_context}
324
+
325
+ Please analyze the error and provide ONLY a single terminal command that would fix the issue.
326
+ Consider the current directory, system information, directory contents, and available credentials carefully before suggesting a solution.
327
+
328
+ IMPORTANT GUIDELINES:
329
+ 1. For any commands that might ask for yes/no confirmation, use the appropriate non-interactive flag:
330
+ - For apt/apt-get: use -y or --yes
331
+ - For rm: use -f or --force
332
+
333
+ 2. If the error indicates a file is not found:
334
+ - FIRST try to search for the file using: find . -name "filename" -type f 2>/dev/null
335
+ - If found, navigate to that directory using: cd /path/to/directory
336
+ - If not found, then consider creating the file or installing missing packages
337
+
338
+ 3. For missing packages or dependencies:
339
+ - Use pip install for Python packages
340
+ - Use apt-get install -y for system packages
341
+ - Use npm install for Node.js packages
342
+
343
+ 4. For authentication issues:
344
+ - Analyze the error to determine what type of authentication is needed
345
+ - ALWAYS use the actual credential values from the AVAILABLE CREDENTIALS section above (NOT placeholders)
346
+ - Look for the specific API key or token needed in the auth_context and use its exact value
347
+ - Common patterns:
348
+ * wandb errors: use wandb login with the actual WANDB_API_KEY value from auth_context
349
+ * huggingface errors: use huggingface-cli login with the actual HF_TOKEN or HUGGINGFACE_TOKEN value from auth_context
350
+ * github errors: configure git credentials with the actual GITHUB_TOKEN value from auth_context
351
+ * kaggle errors: create ~/.kaggle/kaggle.json with the actual KAGGLE_USERNAME and KAGGLE_KEY values from auth_context
352
+ * API errors: export the appropriate API key as environment variable using the actual value from auth_context
353
+
354
+ 5. Environment variable exports:
355
+ - Use export commands for API keys that need to be in environment
356
+ - ALWAYS use the actual credential values from auth_context, never use placeholders like "YOUR_API_KEY"
357
+ - Example: export OPENAI_API_KEY="sk-..." (using the actual key from auth_context)
358
+
359
+ 6. CRITICAL: When using any API key, token, or credential:
360
+ - Find the exact value in the AVAILABLE CREDENTIALS section
361
+ - Use that exact value in your command
362
+ - Do not use generic placeholders or dummy values
363
+ - The auth_context contains real, usable credentials
364
+
365
+ 7. For Git SSH authentication failures:
366
+ - If the error contains "Host key verification failed" or "Could not read from remote repository"
367
+ - ALWAYS convert SSH URLs to HTTPS URLs for public repositories
368
+ - Replace git@github.com:username/repo.git with https://github.com/username/repo.git
369
+ - This works for public repositories without authentication
370
+ - Example: git clone https://github.com/xg-chu/ARTalk.git
371
+
372
+ Do not provide any explanations, just the exact command to run.
373
+ """
374
+
375
+ # Prepare the API request payload
376
+ # print("šŸ” DEBUG: Preparing API request...")
377
+
378
+ # Try to use GPT-4 first, but fall back to other models if needed
379
+ models_to_try = [
380
+ "gpt-4o-mini", # First choice: GPT-4o (most widely available)
381
+ ]
382
+
383
+ # Check if we have a preferred model in environment
384
+ preferred_model = os.environ.get("OPENAI_MODEL")
385
+ if preferred_model:
386
+ # Insert the preferred model at the beginning of the list
387
+ models_to_try.insert(0, preferred_model)
388
+ # print(f"āœ… Using preferred model from environment: {preferred_model}")
389
+
390
+ # Remove duplicates while preserving order
391
+ models_to_try = list(dict.fromkeys(models_to_try))
392
+ # print(f"šŸ” DEBUG: Models to try: {models_to_try}")
393
+
394
+ # Function to make the API call with a specific model
395
+ def try_api_call(model_name, retries=2, backoff_factor=1.5):
396
+ # print(f"šŸ” DEBUG: Attempting API call with model: {model_name}")
397
+ # print(f"šŸ” DEBUG: API key available: {'Yes' if api_key else 'No'}")
398
+ # if api_key:
399
+ # print(f"šŸ” DEBUG: API key length: {len(api_key)}")
400
+ # print(f"šŸ” DEBUG: API key starts with: {api_key[:10]}...")
401
+
402
+ payload = {
403
+ "model": model_name,
404
+ "messages": [
405
+ {"role": "system", "content": "You are a debugging assistant. Provide only the terminal command to fix the issue. Analyze the issue first, understand why it's happening, then provide the command to fix it. For file not found errors, first search for the file using 'find . -name filename -type f' and navigate to the directory if found. For missing packages, use appropriate package managers (pip, apt-get, npm). For Git SSH authentication failures, always convert SSH URLs to HTTPS URLs (git@github.com:user/repo.git -> https://github.com/user/repo.git). For authentication, suggest login commands with placeholders."},
406
+ {"role": "user", "content": prompt}
407
+ ],
408
+ "temperature": 0.2,
409
+ "max_tokens": 300
410
+ }
411
+
412
+ print(f"šŸ” DEBUG: Payload prepared, prompt length: {len(prompt)}")
413
+
414
+ # Add specific handling for common errors
415
+ last_error = None
416
+ for attempt in range(retries + 1):
417
+ try:
418
+ if attempt > 0:
419
+ # Exponential backoff
420
+ wait_time = backoff_factor * (2 ** (attempt - 1))
421
+ print(f"ā±ļø Retrying in {wait_time:.1f} seconds... (attempt {attempt+1}/{retries+1})")
422
+ time.sleep(wait_time)
423
+
424
+ print(f"šŸ¤– Calling OpenAI with {model_name} model to debug the failed command...")
425
+ print(f"šŸ” DEBUG: Making POST request to OpenAI API...")
426
+ response = requests.post(
427
+ "https://api.openai.com/v1/chat/completions",
428
+ headers=headers,
429
+ json=payload,
430
+ timeout=45 # Increased timeout for reliability
431
+ )
432
+
433
+ print(f"šŸ” DEBUG: Response received, status code: {response.status_code}")
434
+
435
+ # Handle specific status codes
436
+ if response.status_code == 200:
437
+ print(f"šŸ” DEBUG: Success! Response length: {len(response.text)}")
438
+ return response.json(), None
439
+ elif response.status_code == 401:
440
+ error_msg = "Authentication error: Invalid API key"
441
+ print(f"āŒ {error_msg}")
442
+ print(f"šŸ” DEBUG: Response text: {response.text}")
443
+ # Don't retry auth errors
444
+ return None, error_msg
445
+ elif response.status_code == 429:
446
+ error_msg = "Rate limit exceeded or quota reached"
447
+ print(f"āš ļø {error_msg}")
448
+ print(f"šŸ” DEBUG: Response text: {response.text}")
449
+ # Always retry rate limit errors with increasing backoff
450
+ last_error = error_msg
451
+ continue
452
+ elif response.status_code == 500:
453
+ error_msg = "OpenAI server error"
454
+ print(f"āš ļø {error_msg}")
455
+ print(f"šŸ” DEBUG: Response text: {response.text}")
456
+ # Retry server errors
457
+ last_error = error_msg
458
+ continue
459
+ else:
460
+ error_msg = f"Status code: {response.status_code}, Response: {response.text}"
461
+ print(f"āš ļø OpenAI API error: {error_msg}")
462
+ print(f"šŸ” DEBUG: Full response text: {response.text}")
463
+ last_error = error_msg
464
+ # Only retry if we have attempts left
465
+ if attempt < retries:
466
+ continue
467
+ return None, error_msg
468
+ except requests.exceptions.Timeout:
469
+ error_msg = "Request timed out"
470
+ # print(f"āš ļø {error_msg}")
471
+ # print(f"šŸ” DEBUG: Timeout after 45 seconds")
472
+ last_error = error_msg
473
+ # Always retry timeouts
474
+ continue
475
+ except requests.exceptions.ConnectionError:
476
+ error_msg = "Connection error"
477
+ print(f"āš ļø {error_msg}")
478
+ print(f"šŸ” DEBUG: Connection failed to api.openai.com")
479
+ last_error = error_msg
480
+ # Always retry connection errors
481
+ continue
482
+ except Exception as e:
483
+ error_msg = str(e)
484
+ print(f"āš ļø Unexpected error: {error_msg}")
485
+ print(f"šŸ” DEBUG: Exception type: {type(e).__name__}")
486
+ print(f"šŸ” DEBUG: Exception details: {str(e)}")
487
+ last_error = error_msg
488
+ # Only retry if we have attempts left
489
+ if attempt < retries:
490
+ continue
491
+ return None, error_msg
492
+
493
+ # If we get here, all retries failed
494
+ return None, last_error
495
+
496
+ # Try each model in sequence until one works
497
+ result = None
498
+ last_error = None
499
+
500
+ for model in models_to_try:
501
+ result, error = try_api_call(model)
502
+ if result:
503
+ # print(f"āœ… Successfully got response from {model}")
504
+ break
505
+ else:
506
+ print(f"āš ļø Failed to get response from {model}: {error}")
507
+ last_error = error
508
+
509
+ if not result:
510
+ print(f"āŒ All model attempts failed. Last error: {last_error}")
511
+ return None
512
+
513
+ # Process the response
514
+ try:
515
+ print(f"šŸ” DEBUG: Processing OpenAI response...")
516
+ # print(f"šŸ” DEBUG: Response structure: {list(result.keys())}")
517
+ print(f"šŸ” DEBUG: Choices count: {len(result.get('choices', []))}")
518
+
519
+ fix_command = result["choices"][0]["message"]["content"].strip()
520
+ print(f"šŸ” DEBUG: Raw response content: {fix_command}")
521
+
522
+ # Save the original response for debugging
523
+ original_response = fix_command
524
+
525
+ # Extract just the command if it's wrapped in backticks or explanation
526
+ if "```" in fix_command:
527
+ # Extract content between backticks
528
+ import re
529
+ code_blocks = re.findall(r'```(?:bash|sh)?\s*(.*?)\s*```', fix_command, re.DOTALL)
530
+ if code_blocks:
531
+ fix_command = code_blocks[0].strip()
532
+ print(f"āœ… Extracted command from code block: {fix_command}")
533
+
534
+ # If the response still has explanatory text, try to extract just the command
535
+ if len(fix_command.split('\n')) > 1:
536
+ # First try to find lines that look like commands (start with common command prefixes)
537
+ command_prefixes = ['sudo', 'apt', 'pip', 'npm', 'yarn', 'git', 'cd', 'mv', 'cp', 'rm', 'mkdir', 'touch',
538
+ 'chmod', 'chown', 'echo', 'cat', 'python', 'python3', 'node', 'export',
539
+ 'curl', 'wget', 'docker', 'make', 'gcc', 'g++', 'javac', 'java',
540
+ 'conda', 'uv', 'poetry', 'nvm', 'rbenv', 'pyenv', 'rustup']
541
+
542
+ # Check for lines that start with common command prefixes
543
+ command_lines = [line.strip() for line in fix_command.split('\n')
544
+ if any(line.strip().startswith(prefix) for prefix in command_prefixes)]
545
+
546
+ if command_lines:
547
+ # Use the first command line found
548
+ fix_command = command_lines[0]
549
+ print(f"āœ… Identified command by prefix: {fix_command}")
550
+ else:
551
+ # Try to find lines that look like commands (contain common shell patterns)
552
+ shell_patterns = [' | ', ' > ', ' >> ', ' && ', ' || ', ' ; ', '$(', '`', ' -y ', ' --yes ']
553
+ command_lines = [line.strip() for line in fix_command.split('\n')
554
+ if any(pattern in line for pattern in shell_patterns)]
555
+
556
+ if command_lines:
557
+ # Use the first command line found
558
+ fix_command = command_lines[0]
559
+ print(f"āœ… Identified command by shell pattern: {fix_command}")
560
+ else:
561
+ # Fall back to the shortest non-empty line as it's likely the command
562
+ lines = [line.strip() for line in fix_command.split('\n') if line.strip()]
563
+ if lines:
564
+ # Exclude very short lines that are likely not commands
565
+ valid_lines = [line for line in lines if len(line) > 5]
566
+ if valid_lines:
567
+ fix_command = min(valid_lines, key=len)
568
+ else:
569
+ fix_command = min(lines, key=len)
570
+ print(f"āœ… Selected shortest line as command: {fix_command}")
571
+
572
+ # Clean up the command - remove any trailing periods or quotes
573
+ fix_command = fix_command.rstrip('.;"\'')
574
+
575
+ # Remove common prefixes that LLMs sometimes add
576
+ prefixes_to_remove = [
577
+ "Run: ", "Execute: ", "Try: ", "Command: ", "Fix: ", "Solution: ",
578
+ "You should run: ", "You can run: ", "You need to run: "
579
+ ]
580
+ for prefix in prefixes_to_remove:
581
+ if fix_command.startswith(prefix):
582
+ fix_command = fix_command[len(prefix):].strip()
583
+ print(f"āœ… Removed prefix: {prefix}")
584
+ break
585
+
586
+ # If the command is still multi-line or very long, it might not be a valid command
587
+ if len(fix_command.split('\n')) > 1 or len(fix_command) > 500:
588
+ print("āš ļø Extracted command appears invalid (multi-line or too long)")
589
+ print("šŸ” Original response from LLM:")
590
+ print("-" * 60)
591
+ print(original_response)
592
+ print("-" * 60)
593
+ print("āš ļø Using best guess for command")
594
+
595
+ print(f"šŸ”§ Suggested fix: {fix_command}")
596
+ print(f"šŸ” DEBUG: Returning fix command: {fix_command}")
597
+ return fix_command
598
+ except Exception as e:
599
+ print(f"āŒ Error processing OpenAI response: {e}")
600
+ print(f"šŸ” DEBUG: Exception type: {type(e).__name__}")
601
+ print(f"šŸ” DEBUG: Exception details: {str(e)}")
602
+ return None
603
+
604
+ def call_openai_for_batch_debug(failed_commands, api_key=None, current_dir=None, sandbox=None):
605
+ """Call OpenAI to debug multiple failed commands and suggest fixes for all of them at once"""
606
+ print("\nšŸ” DEBUG: Starting batch LLM debugging...")
607
+ print(f"šŸ” DEBUG: Analyzing {len(failed_commands)} failed commands")
608
+
609
+ if not failed_commands:
610
+ print("āš ļø No failed commands to analyze")
611
+ return []
612
+
613
+ if not api_key:
614
+ print("āŒ No OpenAI API key provided for batch debugging")
615
+ return []
616
+
617
+ # Prepare context for batch analysis
618
+ context_parts = []
619
+ context_parts.append(f"Current directory: {current_dir}")
620
+ context_parts.append(f"Sandbox available: {sandbox is not None}")
621
+
622
+ # Add failed commands with their errors
623
+ for i, failed_cmd in enumerate(failed_commands, 1):
624
+ cmd_type = failed_cmd.get('type', 'main')
625
+ original_cmd = failed_cmd.get('original_command', '')
626
+ cmd_text = failed_cmd['command']
627
+ stderr = failed_cmd.get('stderr', '')
628
+ stdout = failed_cmd.get('stdout', '')
629
+
630
+ context_parts.append(f"\n--- Failed Command {i} ({cmd_type}) ---")
631
+ context_parts.append(f"Command: {cmd_text}")
632
+ if original_cmd and original_cmd != cmd_text:
633
+ context_parts.append(f"Original Command: {original_cmd}")
634
+ if stderr:
635
+ context_parts.append(f"Error Output: {stderr}")
636
+ if stdout:
637
+ context_parts.append(f"Standard Output: {stdout}")
638
+
639
+ # Create the prompt for batch analysis
640
+ prompt = f"""You are a debugging assistant analyzing multiple failed commands.
641
+
642
+ Context:
643
+ {chr(10).join(context_parts)}
644
+
645
+ Please analyze each failed command and provide a fix command for each one. For each failed command, respond with:
646
+
647
+ FIX_COMMAND_{i}: <the fix command>
648
+ REASON_{i}: <brief explanation of why the original command failed and how the fix addresses it>
649
+
650
+ Guidelines:
651
+ - For file not found errors, first search for the file using 'find . -name filename -type f'
652
+ - For missing packages, use appropriate package managers (pip, apt-get, npm)
653
+ - For Git SSH authentication failures, convert SSH URLs to HTTPS URLs
654
+ - For permission errors, suggest commands with sudo if appropriate
655
+ - For network issues, suggest retry commands or alternative URLs
656
+ - Keep each fix command simple and focused on the specific error
657
+
658
+ Provide fixes for all {len(failed_commands)} failed commands:"""
659
+
660
+ # Make the API call
661
+ headers = {
662
+ "Authorization": f"Bearer {api_key}",
663
+ "Content-Type": "application/json"
664
+ }
665
+
666
+ payload = {
667
+ "model": "gpt-4o-mini", # Use a more capable model for batch analysis
668
+ "messages": [
669
+ {"role": "system", "content": "You are a debugging assistant. Analyze failed commands and provide specific fix commands. Return only the fix commands and reasons in the specified format."},
670
+ {"role": "user", "content": prompt}
671
+ ],
672
+ "temperature": 0.1,
673
+ "max_tokens": 1000
674
+ }
675
+
676
+ try:
677
+ print(f"šŸ¤– Calling OpenAI for batch debugging of {len(failed_commands)} commands...")
678
+ response = requests.post(
679
+ "https://api.openai.com/v1/chat/completions",
680
+ headers=headers,
681
+ json=payload,
682
+ timeout=60
683
+ )
684
+
685
+ if response.status_code == 200:
686
+ result = response.json()
687
+ content = result['choices'][0]['message']['content']
688
+ print(f"āœ… Batch analysis completed")
689
+
690
+ # Parse the response to extract fix commands
691
+ fixes = []
692
+ for i in range(1, len(failed_commands) + 1):
693
+ fix_pattern = f"FIX_COMMAND_{i}: (.+)"
694
+ reason_pattern = f"REASON_{i}: (.+)"
695
+
696
+ fix_match = re.search(fix_pattern, content, re.MULTILINE)
697
+ reason_match = re.search(reason_pattern, content, re.MULTILINE)
698
+
699
+ if fix_match:
700
+ fix_command = fix_match.group(1).strip()
701
+ reason = reason_match.group(1).strip() if reason_match else "LLM suggested fix"
702
+
703
+ # Clean up the fix command
704
+ if fix_command.startswith('`') and fix_command.endswith('`'):
705
+ fix_command = fix_command[1:-1]
706
+
707
+ fixes.append({
708
+ 'original_command': failed_commands[i-1]['command'],
709
+ 'fix_command': fix_command,
710
+ 'reason': reason,
711
+ 'command_index': i-1
712
+ })
713
+
714
+ print(f"šŸ”§ Generated {len(fixes)} fix commands from batch analysis")
715
+ return fixes
716
+ else:
717
+ print(f"āŒ OpenAI API error: {response.status_code} - {response.text}")
718
+ return []
719
+
720
+ except Exception as e:
721
+ print(f"āŒ Error during batch debugging: {e}")
722
+ return []
723
+
724
+ def call_anthropic_for_debug(command, error_output, api_key=None, current_dir=None, sandbox=None):
725
+ """Call Anthropic Claude to debug a failed command and suggest a fix"""
726
+ print("\nšŸ” DEBUG: Starting Anthropic Claude debugging...")
727
+ print(f"šŸ” DEBUG: Command: {command}")
728
+ print(f"šŸ” DEBUG: Error output length: {len(error_output) if error_output else 0}")
729
+ print(f"šŸ” DEBUG: Current directory: {current_dir}")
730
+ print(f"šŸ” DEBUG: Sandbox available: {sandbox is not None}")
731
+
732
+ # Define _to_str function locally to avoid NameError
733
+ def _to_str(maybe_bytes):
734
+ try:
735
+ return (maybe_bytes.decode('utf-8') if isinstance(maybe_bytes, (bytes, bytearray)) else maybe_bytes)
736
+ except UnicodeDecodeError:
737
+ # Handle non-UTF-8 bytes by replacing invalid characters
738
+ if isinstance(maybe_bytes, (bytes, bytearray)):
739
+ return maybe_bytes.decode('utf-8', errors='replace')
740
+ else:
741
+ return str(maybe_bytes)
742
+ except Exception:
743
+ # Last resort fallback
744
+ return str(maybe_bytes)
745
+
746
+ # Skip debugging for certain commands that commonly return non-zero exit codes
747
+ # but aren't actually errors (like test commands)
748
+ if command.strip().startswith("test "):
749
+ print("šŸ” Skipping debugging for test command - non-zero exit code is expected behavior")
750
+ return None
751
+
752
+ # Validate error_output - if it's empty, we can't debug effectively
753
+ if not error_output or not error_output.strip():
754
+ print("āš ļø Error output is empty. Cannot effectively debug the command.")
755
+ print("āš ļø Skipping Anthropic debugging due to lack of error information.")
756
+ return None
757
+
758
+ # Try to get API key from multiple sources
759
+ if not api_key:
760
+ print("šŸ” DEBUG: No Anthropic API key provided, searching for one...")
761
+
762
+ # First try environment variable
763
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
764
+ print(f"šŸ” DEBUG: API key from environment: {'Found' if api_key else 'Not found'}")
765
+ if api_key:
766
+ print(f"šŸ” DEBUG: Environment API key value: {api_key}")
767
+
768
+ # If not in environment, try to fetch from server using fetch_modal_tokens
769
+ if not api_key:
770
+ try:
771
+ print("šŸ” DEBUG: Trying to fetch API key from server...")
772
+ from fetch_modal_tokens import get_tokens
773
+ _, _, _, api_key = get_tokens()
774
+ if api_key:
775
+ # Set in environment for this session
776
+ os.environ["ANTHROPIC_API_KEY"] = api_key
777
+ else:
778
+ print("āš ļø Could not fetch Anthropic API key from server")
779
+ except Exception as e:
780
+ print(f"āš ļø Error fetching API key from server: {e}")
781
+
782
+ # Then try credentials manager
783
+ if not api_key:
784
+ print("šŸ” DEBUG: Trying credentials manager...")
785
+ try:
786
+ from credentials_manager import CredentialsManager
787
+ credentials_manager = CredentialsManager()
788
+ api_key = credentials_manager.get_anthropic_api_key()
789
+ if api_key:
790
+ print(f"šŸ” DEBUG: API key from credentials manager: Found")
791
+ print(f"šŸ” DEBUG: Credentials manager API key value: {api_key}")
792
+ # Set in environment for this session
793
+ os.environ["ANTHROPIC_API_KEY"] = api_key
794
+ else:
795
+ print("āš ļø Could not fetch Anthropic API key from credentials manager")
796
+ except Exception as e:
797
+ print(f"āš ļø Error fetching API key from credentials manager: {e}")
798
+
799
+ # Store the API key in a persistent file if found
800
+ if api_key:
801
+ try:
802
+ os.makedirs(os.path.expanduser("~/.gitarsenal"), exist_ok=True)
803
+ with open(os.path.expanduser("~/.gitarsenal/anthropic_key"), "w") as f:
804
+ f.write(api_key)
805
+ print("āœ… Saved Anthropic API key for future use")
806
+ except Exception as e:
807
+ print(f"āš ļø Could not save API key: {e}")
808
+
809
+ # Try to load from saved file if not in environment
810
+ if not api_key:
811
+ try:
812
+ key_file = os.path.expanduser("~/.gitarsenal/anthropic_key")
813
+ print(f"šŸ” DEBUG: Checking for saved API key at: {key_file}")
814
+ if os.path.exists(key_file):
815
+ with open(key_file, "r") as f:
816
+ api_key = f.read().strip()
817
+ if api_key:
818
+ print("āœ… Loaded Anthropic API key from saved file")
819
+ print(f"šŸ” DEBUG: API key from file: {api_key}")
820
+ print(f"šŸ” DEBUG: API key length: {len(api_key)}")
821
+ # Also set in environment for this session
822
+ os.environ["ANTHROPIC_API_KEY"] = api_key
823
+ else:
824
+ print("šŸ” DEBUG: Saved file exists but is empty")
825
+ else:
826
+ print("šŸ” DEBUG: No saved API key file found")
827
+ except Exception as e:
828
+ print(f"āš ļø Could not load saved API key: {e}")
829
+
830
+ if not api_key:
831
+ print("āŒ No Anthropic API key available for debugging")
832
+ return None
833
+
834
+ # Prepare the prompt for debugging
835
+ error_str = _to_str(error_output)
836
+ prompt = f"""You are a debugging assistant. Provide only the terminal command to fix the issue.
837
+
838
+ Context:
839
+ - Current directory: {current_dir}
840
+ - Sandbox available: {sandbox is not None}
841
+ - Failed command: {command}
842
+ - Error output: {error_str}
843
+
844
+ Analyze the issue first, understand why it's happening, then provide the command to fix it.
845
+
846
+ Guidelines:
847
+ - For file not found errors, first search for the file using 'find . -name filename -type f' and navigate to the directory if found
848
+ - For missing packages, use appropriate package managers (pip, apt-get, npm)
849
+ - For Git SSH authentication failures, always convert SSH URLs to HTTPS URLs (git@github.com:user/repo.git -> https://github.com/user/repo.git)
850
+ - For authentication, suggest login commands with placeholders
851
+ - For permission errors, suggest commands with sudo if appropriate
852
+ - For network issues, suggest retry commands or alternative URLs
853
+
854
+ Return only the command to fix the issue, nothing else."""
855
+
856
+ # Set up headers for Anthropic API
857
+ headers = {
858
+ "x-api-key": api_key,
859
+ "anthropic-version": "2023-06-01",
860
+ "content-type": "application/json"
861
+ }
862
+
863
+ # Models to try in order of preference
864
+ models_to_try = ["claude-4-sonnet"]
865
+
866
+ def try_api_call(model_name, retries=2, backoff_factor=1.5):
867
+ payload = {
868
+ "model": model_name,
869
+ "max_tokens": 300,
870
+ "messages": [
871
+ {"role": "user", "content": prompt}
872
+ ]
873
+ }
874
+
875
+ print(f"šŸ” DEBUG: Payload prepared, prompt length: {len(prompt)}")
876
+
877
+ # Add specific handling for common errors
878
+ last_error = None
879
+ for attempt in range(retries + 1):
880
+ try:
881
+ if attempt > 0:
882
+ # Exponential backoff
883
+ wait_time = backoff_factor * (2 ** (attempt - 1))
884
+ print(f"ā±ļø Retrying in {wait_time:.1f} seconds... (attempt {attempt+1}/{retries+1})")
885
+ time.sleep(wait_time)
886
+
887
+ print(f"šŸ¤– Calling Anthropic Claude with {model_name} model to debug the failed command...")
888
+ print(f"šŸ” DEBUG: Making POST request to Anthropic API...")
889
+ response = requests.post(
890
+ "https://api.anthropic.com/v1/messages",
891
+ headers=headers,
892
+ json=payload,
893
+ timeout=45 # Increased timeout for reliability
894
+ )
895
+
896
+ print(f"šŸ” DEBUG: Response received, status code: {response.status_code}")
897
+
898
+ # Handle specific status codes
899
+ if response.status_code == 200:
900
+ print(f"šŸ” DEBUG: Success! Response length: {len(response.text)}")
901
+ return response.json(), None
902
+ elif response.status_code == 401:
903
+ error_msg = "Authentication error: Invalid API key"
904
+ print(f"āŒ {error_msg}")
905
+ print(f"šŸ” DEBUG: Response text: {response.text}")
906
+ # Don't retry auth errors
907
+ return None, error_msg
908
+ elif response.status_code == 429:
909
+ error_msg = "Rate limit exceeded or quota reached"
910
+ print(f"āš ļø {error_msg}")
911
+ print(f"šŸ” DEBUG: Response text: {response.text}")
912
+ # Always retry rate limit errors with increasing backoff
913
+ last_error = error_msg
914
+ continue
915
+ elif response.status_code == 500:
916
+ error_msg = "Anthropic server error"
917
+ print(f"āš ļø {error_msg}")
918
+ print(f"šŸ” DEBUG: Response text: {response.text}")
919
+ # Retry server errors
920
+ last_error = error_msg
921
+ continue
922
+ else:
923
+ error_msg = f"Status code: {response.status_code}, Response: {response.text}"
924
+ print(f"āš ļø Anthropic API error: {error_msg}")
925
+ print(f"šŸ” DEBUG: Full response text: {response.text}")
926
+ last_error = error_msg
927
+ # Only retry if we have attempts left
928
+ if attempt < retries:
929
+ continue
930
+ return None, error_msg
931
+ except requests.exceptions.Timeout:
932
+ error_msg = "Request timed out"
933
+ last_error = error_msg
934
+ # Always retry timeouts
935
+ continue
936
+ except requests.exceptions.ConnectionError:
937
+ error_msg = "Connection error"
938
+ print(f"āš ļø {error_msg}")
939
+ print(f"šŸ” DEBUG: Connection failed to api.anthropic.com")
940
+ last_error = error_msg
941
+ # Always retry connection errors
942
+ continue
943
+ except Exception as e:
944
+ error_msg = str(e)
945
+ print(f"āš ļø Unexpected error: {error_msg}")
946
+ print(f"šŸ” DEBUG: Exception type: {type(e).__name__}")
947
+ print(f"šŸ” DEBUG: Exception details: {str(e)}")
948
+ last_error = error_msg
949
+ # Only retry if we have attempts left
950
+ if attempt < retries:
951
+ continue
952
+ return None, error_msg
953
+
954
+ # If we get here, all retries failed
955
+ return None, last_error
956
+
957
+ # Try each model in sequence until one works
958
+ result = None
959
+ last_error = None
960
+
961
+ for model in models_to_try:
962
+ result, error = try_api_call(model)
963
+ if result:
964
+ break
965
+ else:
966
+ print(f"āš ļø Failed to get response from {model}: {error}")
967
+ last_error = error
968
+
969
+ if not result:
970
+ print(f"āŒ All model attempts failed. Last error: {last_error}")
971
+ return None
972
+
973
+ # Process the response
974
+ try:
975
+ print(f"šŸ” DEBUG: Processing Anthropic response...")
976
+ print(f"šŸ” DEBUG: Choices count: {len(result.get('content', []))}")
977
+
978
+ fix_command = result["content"][0]["text"].strip()
979
+ print(f"šŸ” DEBUG: Raw response content: {fix_command}")
980
+
981
+ # Save the original response for debugging
982
+ original_response = fix_command
983
+
984
+ # Extract just the command if it's wrapped in backticks or explanation
985
+ if "```" in fix_command:
986
+ # Extract content between backticks
987
+ import re
988
+ code_blocks = re.findall(r'```(?:bash|sh)?\s*(.*?)\s*```', fix_command, re.DOTALL)
989
+ if code_blocks:
990
+ fix_command = code_blocks[0].strip()
991
+ print(f"āœ… Extracted command from code block: {fix_command}")
992
+
993
+ # If the response still has explanatory text, try to extract just the command
994
+ if len(fix_command.split('\n')) > 1:
995
+ # First try to find lines that look like commands (start with common command prefixes)
996
+ command_prefixes = ['sudo', 'apt', 'pip', 'npm', 'yarn', 'git', 'cd', 'mv', 'cp', 'rm', 'mkdir', 'touch',
997
+ 'chmod', 'chown', 'echo', 'cat', 'python', 'python3', 'node', 'export',
998
+ 'curl', 'wget', 'docker', 'make', 'gcc', 'g++', 'javac', 'java',
999
+ 'conda', 'uv', 'poetry', 'nvm', 'rbenv', 'pyenv', 'rustup']
1000
+
1001
+ # Check for lines that start with common command prefixes
1002
+ command_lines = [line.strip() for line in fix_command.split('\n')
1003
+ if any(line.strip().startswith(prefix) for prefix in command_prefixes)]
1004
+
1005
+ if command_lines:
1006
+ # Use the first command line found
1007
+ fix_command = command_lines[0]
1008
+ print(f"āœ… Identified command by prefix: {fix_command}")
1009
+ else:
1010
+ # Try to find lines that look like commands (contain common shell patterns)
1011
+ shell_patterns = [' | ', ' > ', ' >> ', ' && ', ' || ', ' ; ', '$(', '`', ' -y ', ' --yes ']
1012
+ command_lines = [line.strip() for line in fix_command.split('\n')
1013
+ if any(pattern in line for pattern in shell_patterns)]
1014
+
1015
+ if command_lines:
1016
+ # Use the first command line found
1017
+ fix_command = command_lines[0]
1018
+ print(f"āœ… Identified command by shell pattern: {fix_command}")
1019
+ else:
1020
+ # Fall back to the shortest non-empty line as it's likely the command
1021
+ lines = [line.strip() for line in fix_command.split('\n') if line.strip()]
1022
+ if lines:
1023
+ # Exclude very short lines that are likely not commands
1024
+ valid_lines = [line for line in lines if len(line) > 5]
1025
+ if valid_lines:
1026
+ fix_command = min(valid_lines, key=len)
1027
+ else:
1028
+ fix_command = min(lines, key=len)
1029
+ print(f"āœ… Selected shortest line as command: {fix_command}")
1030
+
1031
+ # Clean up the command - remove any trailing periods or quotes
1032
+ fix_command = fix_command.rstrip('.;"\'')
1033
+
1034
+ # Remove common prefixes that LLMs sometimes add
1035
+ prefixes_to_remove = [
1036
+ "Run: ", "Execute: ", "Try: ", "Command: ", "Fix: ", "Solution: ",
1037
+ "You should run: ", "You can run: ", "You need to run: "
1038
+ ]
1039
+ for prefix in prefixes_to_remove:
1040
+ if fix_command.startswith(prefix):
1041
+ fix_command = fix_command[len(prefix):].strip()
1042
+ print(f"āœ… Removed prefix: {prefix}")
1043
+ break
1044
+
1045
+ # If the command is still multi-line or very long, it might not be a valid command
1046
+ if len(fix_command.split('\n')) > 1 or len(fix_command) > 500:
1047
+ print("āš ļø Extracted command appears invalid (multi-line or too long)")
1048
+ print("šŸ” Original response from LLM:")
1049
+ print("-" * 60)
1050
+ print(original_response)
1051
+ print("-" * 60)
1052
+ print("āš ļø Using best guess for command")
1053
+
1054
+ print(f"šŸ”§ Suggested fix: {fix_command}")
1055
+ print(f"šŸ” DEBUG: Returning fix command: {fix_command}")
1056
+ return fix_command
1057
+ except Exception as e:
1058
+ print(f"āŒ Error processing Anthropic response: {e}")
1059
+ print(f"šŸ” DEBUG: Exception type: {type(e).__name__}")
1060
+ print(f"šŸ” DEBUG: Exception details: {str(e)}")
1061
+ return None