Files
Mark-LIV/actions/dev_agent.py
T

518 lines
17 KiB
Python
Raw Normal View History

2026-03-02 04:30:10 +03:00
import subprocess
import sys
import json
import re
import time
from pathlib import Path
2026-04-19 15:22:49 +03:00
2026-03-02 04:30:10 +03:00
def get_base_dir():
if getattr(sys, "frozen", False):
return Path(sys.executable).parent
return Path(__file__).resolve().parent.parent
2026-04-19 15:22:49 +03:00
BASE_DIR = get_base_dir()
PROJECTS_DIR = Path.home() / "Desktop" / "JarvisProjects"
MAX_FIX_ATTEMPTS = 5
2026-03-02 04:30:10 +03:00
2026-06-06 17:41:38 +03:00
from core.llm_client import call_llm_text as _llm
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
def _strip_fences(text: str) -> str:
2026-03-02 04:30:10 +03:00
text = text.strip()
2026-04-19 15:22:49 +03:00
text = re.sub(r"^```[a-zA-Z]*\r?\n?", "", text)
text = re.sub(r"\r?\n?```\s*$", "", text)
2026-03-02 04:30:10 +03:00
return text.strip()
2026-04-19 15:22:49 +03:00
def _is_rate_limit(error: Exception) -> bool:
msg = str(error).lower()
return "429" in msg or "quota" in msg or "resource_exhausted" in msg
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
def _parse_traceback(output: str, project_files: list[str]) -> tuple[str | None, int | None]:
pattern = re.compile(r'File ["\']([^"\']+\.py)["\'],\s+line\s+(\d+)', re.IGNORECASE)
matches = pattern.findall(output)
for raw_path, line_str in reversed(matches):
raw_name = Path(raw_path).name
for pf in project_files:
if Path(pf).name == raw_name or pf == raw_path or raw_path.endswith(pf):
return pf, int(line_str)
return None, None
def _classify_error(output: str) -> str:
low = output.lower()
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
if any(x in low for x in ("no module named", "modulenotfounderror", "importerror")):
return "dependency_error"
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
if "syntaxerror" in low or "invalid syntax" in low:
return "syntax_error"
if "cannot import" in low or "importerror" in low:
return "import_error"
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
if any(x in low for x in (
"traceback", "exception", "error:", "nameerror", "typeerror",
"attributeerror", "valueerror", "keyerror", "indexerror",
"zerodivisionerror", "filenotfounderror", "permissionerror",
)):
return "runtime_error"
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
return "none"
def _has_error(output: str, run_command: str) -> bool:
low = output.lower()
if "timed out" in low:
2026-03-02 04:30:10 +03:00
return False
2026-04-19 15:22:49 +03:00
if not output.strip():
return False
error_type = _classify_error(output)
return error_type != "none"
class RateLimitError(Exception):
pass
2026-03-02 04:30:10 +03:00
def _plan_project(description: str, language: str) -> dict:
2026-06-06 17:41:38 +03:00
system = (
"You are a senior software architect. "
"Return ONLY valid JSON — no markdown, no explanation."
)
prompt = f"""Create a minimal, complete file plan for this project.
2026-03-02 04:30:10 +03:00
Language: {language}
Description: {description}
2026-06-06 17:41:38 +03:00
Return ONLY valid JSON:
2026-03-02 04:30:10 +03:00
{{
2026-04-19 15:22:49 +03:00
"project_name": "snake_case_name",
2026-03-02 04:30:10 +03:00
"entry_point": "main.py",
"files": [
2026-04-19 15:22:49 +03:00
{{
"path": "main.py",
2026-06-06 17:41:38 +03:00
"description": "Entry point",
"imports": ["utils.helpers"]
2026-04-19 15:22:49 +03:00
}},
{{
"path": "utils/helpers.py",
2026-06-06 17:41:38 +03:00
"description": "Helpers",
2026-04-19 15:22:49 +03:00
"imports": []
}}
2026-03-02 04:30:10 +03:00
],
"run_command": "python main.py",
2026-04-19 15:22:49 +03:00
"dependencies": ["requests"]
2026-03-02 04:30:10 +03:00
}}
2026-06-06 17:41:38 +03:00
Rules: dependency order, relative paths, entry point last, stdlib NOT in dependencies.
2026-03-02 04:30:10 +03:00
JSON:"""
try:
2026-06-06 17:41:38 +03:00
raw = _strip_fences(_llm(prompt, system=system))
2026-03-02 04:30:10 +03:00
return json.loads(raw)
except json.JSONDecodeError as e:
2026-06-06 17:41:38 +03:00
raise ValueError(f"Planner returned invalid JSON: {e}")
2026-04-19 15:22:49 +03:00
except Exception as e:
raise
2026-03-02 04:30:10 +03:00
def _write_file(
2026-04-19 15:22:49 +03:00
file_info: dict,
2026-03-02 04:30:10 +03:00
project_description: str,
all_files: list[dict],
language: str,
2026-04-19 15:22:49 +03:00
project_dir: Path,
already_written: dict[str, str],
2026-03-02 04:30:10 +03:00
) -> str:
2026-06-06 17:41:38 +03:00
file_path = file_info["path"]
file_desc = file_info.get("description", "")
2026-04-19 15:22:49 +03:00
file_imports = file_info.get("imports", [])
2026-03-02 04:30:10 +03:00
file_list = "\n".join(
2026-04-19 15:22:49 +03:00
f" [{i+1}] {f['path']}: {f.get('description', '')}"
for i, f in enumerate(all_files)
2026-03-02 04:30:10 +03:00
)
2026-06-06 17:41:38 +03:00
dep_ctx = ""
2026-04-19 15:22:49 +03:00
for dep_dotted in file_imports:
dep_path = dep_dotted.replace(".", "/") + ".py"
if dep_path in already_written:
2026-06-06 17:41:38 +03:00
dep_ctx += f"\n\n--- {dep_path} ---\n{already_written[dep_path][:2000]}"
2026-03-02 04:30:10 +03:00
2026-06-06 17:41:38 +03:00
system = (
f"You are a senior {language} developer. "
"Output ONLY raw code — no explanation, no markdown, no backticks."
)
prompt = (
f"Project goal: {project_description}\n\n"
f"Files (dependency order):\n{file_list}\n"
f"{dep_ctx}\n\n"
f"Write complete code for: {file_path}\n"
f"Purpose: {file_desc}\n"
f"{'Imports from: ' + ', '.join(file_imports) if file_imports else 'No project-internal imports.'}\n\n"
f"Rules: COMPLETE & RUNNABLE code, no placeholders, match import paths exactly.\n\n"
f"Code for {file_path}:"
)
2026-03-02 04:30:10 +03:00
2026-06-06 17:41:38 +03:00
try:
code = _strip_fences(_llm(prompt, system=system))
2026-03-02 04:30:10 +03:00
full_path = project_dir / file_path
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(code, encoding="utf-8")
2026-04-19 15:22:49 +03:00
print(f"[DevAgent] ✅ Written: {file_path} ({len(code)} chars)")
2026-03-02 04:30:10 +03:00
return code
except Exception as e:
raise
def _install_dependencies(dependencies: list[str], project_dir: Path) -> str:
if not dependencies:
2026-04-19 15:22:49 +03:00
return "No external dependencies."
to_install = []
for dep in dependencies:
pkg_name = re.split(r"[>=<!]", dep)[0].strip()
result = subprocess.run(
[sys.executable, "-m", "pip", "show", pkg_name],
capture_output=True, text=True
)
if result.returncode != 0:
to_install.append(dep)
else:
print(f"[DevAgent] ✓ Already installed: {pkg_name}")
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
if not to_install:
return f"All dependencies already installed: {', '.join(dependencies)}"
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
print(f"[DevAgent] 📦 Installing: {to_install}")
2026-03-02 04:30:10 +03:00
try:
result = subprocess.run(
2026-04-19 15:22:49 +03:00
[sys.executable, "-m", "pip", "install"] + to_install,
2026-03-02 04:30:10 +03:00
capture_output=True, text=True,
encoding="utf-8", errors="replace",
timeout=120, cwd=str(project_dir)
)
if result.returncode == 0:
2026-04-19 15:22:49 +03:00
return f"Installed: {', '.join(to_install)}"
return f"Install warning (non-fatal): {result.stderr[:200]}"
2026-03-02 04:30:10 +03:00
except subprocess.TimeoutExpired:
2026-04-19 15:22:49 +03:00
return "Dependency install timed out (non-fatal)."
2026-03-02 04:30:10 +03:00
except Exception as e:
2026-04-19 15:22:49 +03:00
return f"Install error (non-fatal): {e}"
2026-03-02 04:30:10 +03:00
def _open_vscode(project_dir: Path) -> bool:
2026-04-19 15:22:49 +03:00
vscode_candidates = [
2026-03-02 04:30:10 +03:00
"code",
2026-04-19 15:22:49 +03:00
rf"C:\Users\{Path.home().name}\AppData\Local\Programs\Microsoft VS Code\bin\code.cmd",
r"C:\Program Files\Microsoft VS Code\bin\code.cmd",
2026-03-02 04:30:10 +03:00
]
2026-04-19 15:22:49 +03:00
for cmd in vscode_candidates:
2026-03-02 04:30:10 +03:00
try:
subprocess.Popen(
[cmd, str(project_dir)],
2026-04-19 15:22:49 +03:00
shell=True,
2026-03-02 04:30:10 +03:00
stdout=subprocess.DEVNULL,
2026-04-19 15:22:49 +03:00
stderr=subprocess.DEVNULL
2026-03-02 04:30:10 +03:00
)
2026-04-19 15:22:49 +03:00
time.sleep(1.5)
2026-03-02 04:30:10 +03:00
print(f"[DevAgent] 💻 VSCode opened: {project_dir}")
return True
except Exception:
continue
return False
def _run_project(run_command: str, project_dir: Path, timeout: int = 30) -> str:
print(f"[DevAgent] 🚀 Running: {run_command}")
try:
parts = run_command.split()
2026-04-19 15:22:49 +03:00
if parts[0].lower() == "python":
2026-03-02 04:30:10 +03:00
parts[0] = sys.executable
result = subprocess.run(
parts,
capture_output=True, text=True,
encoding="utf-8", errors="replace",
2026-04-19 15:22:49 +03:00
timeout=timeout,
cwd=str(project_dir)
2026-03-02 04:30:10 +03:00
)
2026-04-19 15:22:49 +03:00
stdout = result.stdout.strip()
stderr = result.stderr.strip()
combined_parts = []
if stdout:
combined_parts.append(f"STDOUT:\n{stdout}")
if stderr:
combined_parts.append(f"STDERR:\n{stderr}")
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
return "\n\n".join(combined_parts) if combined_parts else "Ran with no output."
2026-03-02 04:30:10 +03:00
except subprocess.TimeoutExpired:
2026-04-19 15:22:49 +03:00
return f"Timed out after {timeout}s — long-running app (server/GUI) is likely working."
2026-03-02 04:30:10 +03:00
except FileNotFoundError as e:
return f"Command not found: {e}"
except Exception as e:
return f"Run error: {e}"
2026-04-19 15:22:49 +03:00
def _try_auto_install(error_output: str, project_dir: Path) -> bool:
"""ModuleNotFoundError varsa eksik paketi otomatik kurmaya çalışır."""
pattern = re.compile(
r"No module named ['\"]([a-zA-Z0-9_\-\.]+)['\"]", re.IGNORECASE
)
match = pattern.search(error_output)
if not match:
return False
pkg = match.group(1).replace("_", "-").split(".")[0]
print(f"[DevAgent] 🔧 Auto-installing missing package: {pkg}")
try:
result = subprocess.run(
[sys.executable, "-m", "pip", "install", pkg],
capture_output=True, text=True,
encoding="utf-8", errors="replace",
timeout=60, cwd=str(project_dir)
)
return result.returncode == 0
except Exception:
return False
def _fix_files(
2026-03-02 04:30:10 +03:00
error_output: str,
project_description: str,
all_files: list[dict],
2026-04-19 15:22:49 +03:00
file_codes: dict[str, str],
2026-03-02 04:30:10 +03:00
language: str,
2026-04-19 15:22:49 +03:00
project_dir: Path,
entry_point: str,
) -> dict[str, str]:
error_file, error_line = _parse_traceback(error_output, list(file_codes.keys()))
error_type = _classify_error(error_output)
files_to_fix: list[str] = []
if error_file:
files_to_fix.append(error_file)
if error_type == "import_error":
for fi in all_files:
if error_file.replace("/", ".").replace(".py", "") in fi.get("imports", []):
p = fi["path"]
if p not in files_to_fix:
files_to_fix.append(p)
else:
files_to_fix.append(entry_point)
updated_codes: dict[str, str] = {}
2026-03-02 04:30:10 +03:00
2026-06-06 17:41:38 +03:00
system = f"You are an expert {language} debugger. Return ONLY the complete fixed code — no explanation, no markdown, no backticks."
2026-04-19 15:22:49 +03:00
for fix_path in files_to_fix:
current_code = file_codes.get(fix_path, "")
other_ctx = ""
for fp, code in file_codes.items():
if fp != fix_path and code:
2026-06-06 17:41:38 +03:00
other_ctx += f"\n--- {fp} ---\n{code[:1500]}\n"
2026-03-02 04:30:10 +03:00
2026-06-06 17:41:38 +03:00
line_hint = (
f"\nError near line {error_line} in this file."
if error_line and fix_path == error_file else ""
)
2026-03-02 04:30:10 +03:00
2026-06-06 17:41:38 +03:00
prompt = (
f"Project goal: {project_description}\n\n"
f"All files:\n"
+ "\n".join(f" - {f['path']}: {f.get('description', '')}" for f in all_files)
+ f"\n\nOther files (context):\n{other_ctx[:3500]}\n\n"
f"File to fix: {fix_path}{line_hint}\n"
f"Error type: {error_type}\n\n"
f"Error output:\n{error_output[:2500]}\n\n"
f"Current code:\n{current_code}\n\n"
f"Fixed code for {fix_path}:"
)
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
try:
2026-06-06 17:41:38 +03:00
fixed = _strip_fences(_llm(prompt, system=system))
2026-04-19 15:22:49 +03:00
full_path = project_dir / fix_path
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(fixed, encoding="utf-8")
updated_codes[fix_path] = fixed
print(f"[DevAgent] 🔧 Fixed: {fix_path}")
except Exception as e:
print(f"[DevAgent] ⚠️ Could not fix {fix_path}: {e}")
return updated_codes
2026-03-02 04:30:10 +03:00
def _build_project(
description: str,
language: str,
project_name: str,
timeout: int,
speak=None,
2026-04-19 15:22:49 +03:00
player=None,
2026-03-02 04:30:10 +03:00
) -> str:
def log(msg: str):
print(f"[DevAgent] {msg}")
if player:
player.write_log(f"[DevAgent] {msg}")
log("Planning project structure...")
try:
plan = _plan_project(description, language)
except RateLimitError:
2026-04-19 15:22:49 +03:00
msg = "Rate limit reached, sir. Please try again in a moment."
2026-03-02 04:30:10 +03:00
if speak: speak(msg)
return msg
except ValueError as e:
msg = f"Planning failed: {e}"
if speak: speak(msg)
return msg
2026-04-19 15:22:49 +03:00
proj_name = project_name or plan.get("project_name", "jarvis_project")
proj_name = re.sub(r"[^\w\-]", "_", proj_name)
project_dir = PROJECTS_DIR / proj_name
2026-03-02 04:30:10 +03:00
project_dir.mkdir(parents=True, exist_ok=True)
2026-04-19 15:22:49 +03:00
files = plan.get("files", [])
entry_point = plan.get("entry_point", "main.py")
run_command = plan.get("run_command", f"python {entry_point}")
2026-03-02 04:30:10 +03:00
dependencies = plan.get("dependencies", [])
log(f"Project: {proj_name} | Files: {len(files)} | Entry: {entry_point}")
2026-04-19 15:22:49 +03:00
def _dep_sort_key(fi: dict) -> int:
return len(fi.get("imports", []))
sorted_files = sorted(files, key=_dep_sort_key)
2026-03-02 04:30:10 +03:00
file_codes: dict[str, str] = {}
2026-04-19 15:22:49 +03:00
for file_info in sorted_files:
2026-03-02 04:30:10 +03:00
file_path = file_info.get("path", "")
if not file_path:
continue
log(f"Writing {file_path}...")
2026-04-19 15:22:49 +03:00
for attempt in range(2):
try:
code = _write_file(
file_info=file_info,
project_description=description,
all_files=files,
language=language,
project_dir=project_dir,
already_written=file_codes,
)
file_codes[file_path] = code
time.sleep(0.4)
break
except RateLimitError:
if attempt == 0:
log("Rate limit — waiting 20s...")
time.sleep(20)
else:
log(f"Rate limit retry failed for {file_path}, skipping.")
except Exception as e:
log(f"Failed to write {file_path}: {e}")
break
2026-03-02 04:30:10 +03:00
if not file_codes:
2026-04-19 15:22:49 +03:00
msg = "I could not write any project files, sir."
2026-03-02 04:30:10 +03:00
if speak: speak(msg)
return msg
if dependencies:
2026-04-19 15:22:49 +03:00
install_result = _install_dependencies(dependencies, project_dir)
log(install_result)
2026-03-02 04:30:10 +03:00
_open_vscode(project_dir)
2026-04-19 15:22:49 +03:00
last_output = ""
auto_installs = 0
2026-03-02 04:30:10 +03:00
for attempt in range(1, MAX_FIX_ATTEMPTS + 1):
log(f"Running project (attempt {attempt}/{MAX_FIX_ATTEMPTS})...")
last_output = _run_project(run_command, project_dir, timeout)
2026-04-19 15:22:49 +03:00
log(f"Output preview: {last_output[:150]}")
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
if not _has_error(last_output, run_command):
2026-03-02 04:30:10 +03:00
msg = (
f"Project '{proj_name}' is working, sir. "
f"Built in {attempt} attempt{'s' if attempt > 1 else ''}. "
2026-04-19 15:22:49 +03:00
f"Saved to: {project_dir}"
2026-03-02 04:30:10 +03:00
)
if speak: speak(msg)
return f"{msg}\n\nOutput:\n{last_output}"
if attempt == MAX_FIX_ATTEMPTS:
break
2026-04-19 15:22:49 +03:00
error_type = _classify_error(last_output)
if error_type == "dependency_error" and auto_installs < 3:
installed = _try_auto_install(last_output, project_dir)
if installed:
auto_installs += 1
log("Missing dependency installed, retrying...")
time.sleep(1)
continue
2026-03-02 04:30:10 +03:00
2026-04-19 15:22:49 +03:00
log(f"Fixing errors (type: {error_type})...")
2026-03-02 04:30:10 +03:00
try:
2026-04-19 15:22:49 +03:00
updated = _fix_files(
error_output=last_output,
project_description=description,
all_files=files,
file_codes=file_codes,
language=language,
project_dir=project_dir,
entry_point=entry_point,
2026-03-02 04:30:10 +03:00
)
2026-04-19 15:22:49 +03:00
file_codes.update(updated)
time.sleep(1)
2026-03-02 04:30:10 +03:00
except RateLimitError:
2026-04-19 15:22:49 +03:00
msg = "Rate limit reached during fix. Project saved, check it manually in VSCode."
2026-03-02 04:30:10 +03:00
if speak: speak(msg)
return msg
except Exception as e:
2026-04-19 15:22:49 +03:00
log(f"Fix step failed: {e}")
2026-03-02 04:30:10 +03:00
msg = (
2026-04-19 15:22:49 +03:00
f"I couldn't fully fix '{proj_name}' after {MAX_FIX_ATTEMPTS} attempts, sir. "
f"Project is saved at {project_dir} — open it in VSCode and check manually."
2026-03-02 04:30:10 +03:00
)
if speak: speak(msg)
2026-04-19 15:22:49 +03:00
return f"{msg}\n\nLast error:\n{last_output[:600]}"
2026-03-02 04:30:10 +03:00
def dev_agent(
parameters: dict,
response=None,
player=None,
session_memory=None,
2026-04-19 15:22:49 +03:00
speak=None,
2026-03-02 04:30:10 +03:00
) -> str:
p = parameters or {}
description = p.get("description", "").strip()
language = p.get("language", "python").strip()
project_name = p.get("project_name", "").strip()
timeout = int(p.get("timeout", 30))
if not description:
return "Please describe the project you want me to build, sir."
return _build_project(
description = description,
language = language,
project_name = project_name,
timeout = timeout,
speak = speak,
2026-04-19 15:22:49 +03:00
player = player,
2026-03-02 04:30:10 +03:00
)