Clears the workspace, saves code from the payload, runs main.py, and returns code + result. The payload format is expected to be: FILENAME ```python CODE ``` Repeated for multiple files.
(data: str, _context: Dict[str, Any])
| 13 | return (data or "").upper() |
| 14 | |
| 15 | def code_save_and_run(data: str, _context: Dict[str, Any]) -> str: |
| 16 | """ |
| 17 | Clears the workspace, saves code from the payload, runs main.py, and returns code + result. |
| 18 | |
| 19 | The payload format is expected to be: |
| 20 | FILENAME |
| 21 | ```python |
| 22 | CODE |
| 23 | ``` |
| 24 | Repeated for multiple files. |
| 25 | """ |
| 26 | # Parse matches first |
| 27 | pattern = re.compile(r"(?P<filename>[^\n]+)\n```(?:python)?\n(?P<code>.*?)\n```", re.DOTALL) |
| 28 | matches = list(pattern.finditer(data)) |
| 29 | |
| 30 | if not matches: |
| 31 | return data |
| 32 | |
| 33 | ctx = FileToolContext(_context) |
| 34 | workspace_root = ctx.workspace_root |
| 35 | |
| 36 | # 1. Clear workspace |
| 37 | if workspace_root.exists(): |
| 38 | for item in workspace_root.iterdir(): |
| 39 | if item.name == "attachments": |
| 40 | continue |
| 41 | |
| 42 | if item.is_dir(): |
| 43 | shutil.rmtree(item) |
| 44 | else: |
| 45 | item.unlink() |
| 46 | |
| 47 | saved_code_blocks = [] |
| 48 | for match in matches: |
| 49 | filename = match.group("filename").strip() |
| 50 | code = match.group("code") |
| 51 | |
| 52 | # Save to file |
| 53 | file_path = workspace_root / filename |
| 54 | # Ensure parent dirs exist if filename contains path separators |
| 55 | file_path.parent.mkdir(parents=True, exist_ok=True) |
| 56 | file_path.write_text(code, encoding="utf-8") |
| 57 | |
| 58 | saved_code_blocks.append(f"{filename}\n```python\n{code}\n```") |
| 59 | |
| 60 | cleaned_code_str = "\n".join(saved_code_blocks) |
| 61 | |
| 62 | # 3. Execute main.py |
| 63 | success_info = "The software run successfully without errors." |
| 64 | execution_result = "" |
| 65 | |
| 66 | try: |
| 67 | env = os.environ.copy() |
| 68 | env["PYTHONUNBUFFERED"] = "1" |
| 69 | |
| 70 | if os.name == 'nt': |
| 71 | command = f"cd {workspace_root} && dir && uv run main.py" |
| 72 | process = subprocess.Popen( |
nothing calls this directly
no test coverage detected