import shutil import threading from pathlib import Path from agent_core.config import DEFAULT_BUILD123D_OUTPUT_PATH, MAX_VERIFY_ROUNDS, VERIFY_ENABLED from agent_core.outputs import resolve_run_output from agent_core.tools.build123d_tool import PROMPT_SECTION as BUILD123D_PROMPT_SECTION from agent_core.tools.build123d_tool import TOOL_SCHEMA as BUILD123D_TOOL_SCHEMA from agent_core.tools.build123d_tool import publish_build123d_run, run_build123d, save_build123d_run from agent_core.utils import json_response from agent_core.verify.judge import build_checklist from agent_core.verify.run import verify_build123d_run SAVED_KEYS = ("run_id", "run_dir", "output_path", "preview_path", "manifest_path", "latest_path", "warning") PENDING_STEP = "pending.step" PENDING_STL = "pending.stl" BEST_VIEWS = "best_views.png" def _start_checklist(session: dict, prompt: str | None) -> None: """Start the acceptance checklist beside geometry. Later rounds in this turn reuse it.""" if "verify_checklist" in session or session.get("checklist_thread") is not None: return holder: dict = {} def work() -> None: try: checklist, usage = build_checklist(prompt or "") holder["checklist"] = checklist holder["usage"] = usage except Exception as exc: holder["error"] = exc thread = threading.Thread(target=work, daemon=True) thread.start() session["checklist_thread"] = thread session["checklist_holder"] = holder def _allocate_run(output_path: str) -> dict: run_dir, output, run_id = resolve_run_output(output_path) return { "run_dir": run_dir, "output": output, "run_id": run_id, "requested_output_path": output_path, } def _discard_uncommitted(run: dict) -> None: run_dir = run["run_dir"] if run_dir.exists(): shutil.rmtree(run_dir, ignore_errors=True) runs = run_dir.parent if runs.name == "runs" and runs.is_dir() and not any(runs.iterdir()): runs.rmdir() def _keep_best_files(session: dict, run: dict, payload: dict, previous_best) -> None: """Copy this execution onto model.step and preview.stl only when it becomes the retained best.""" best = session.get("verify_best") if not best or best is previous_best: return run_dir = run["run_dir"] shutil.copy2(run_dir / PENDING_STEP, run["output"]) shutil.copy2(run_dir / PENDING_STL, run_dir / "preview.stl") best["stdout"] = payload.get("stdout", "") best["stderr"] = payload.get("stderr", "") views = best.get("views_path") if views and Path(views).exists(): stable = run_dir / BEST_VIEWS shutil.copy2(views, stable) best["views_path"] = stable else: best["views_path"] = None def _clear_pending(run_dir: Path) -> None: for name in (PENDING_STEP, PENDING_STL, "pending.png", BEST_VIEWS): path = run_dir / name if path.is_file(): path.unlink() def _deliver(session: dict, run: dict, candidate: dict, *, copy_current: bool) -> dict: run_dir = run["run_dir"] if copy_current: shutil.copy2(run_dir / PENDING_STEP, run["output"]) shutil.copy2(run_dir / PENDING_STL, run_dir / "preview.stl") verification = dict(candidate["verification"]) if session.get("verify_checklist") is not None: verification["checklist"] = session["verify_checklist"] saved = publish_build123d_run( code=candidate["code"], run_dir=run_dir, run_id=run["run_id"], output=run["output"], requested_output_path=run["requested_output_path"], prompt=session.get("prompt"), verification=verification, views_path=candidate.get("views_path"), stdout=candidate.get("stdout", ""), stderr=candidate.get("stderr", ""), ) if saved.get("ok"): _clear_pending(run_dir) session["saved"] = {key: saved[key] for key in SAVED_KEYS if saved.get(key)} return saved def _execute_build123d_handler( code: str, output_path: str | None = None, prompt: str | None = None, session: dict | None = None, ) -> str: output_path = output_path or DEFAULT_BUILD123D_OUTPUT_PATH if not VERIFY_ENABLED or session is None: return json_response(save_build123d_run(code, output_path, prompt)) session["output_path"], session["prompt"] = output_path, prompt fresh = "run" not in session try: run = session["run"] if not fresh else _allocate_run(output_path) except Exception as exc: return json_response({ "ok": False, "stage": "input", "error_type": type(exc).__name__, "error": str(exc), "traceback_tail": "", "stdout": "", "stderr": "", }) # Checklist starts with geometry and is not awaited until the bbox check. _start_checklist(session, prompt) run_dir = run["run_dir"] payload = run_build123d(code, run_dir / PENDING_STL, run_dir / PENDING_STEP) if not payload.get("ok"): if fresh: _discard_uncommitted(run) return json_response(payload) session["run"] = run previous_best = session.get("verify_best") verification = verify_build123d_run(payload, code, prompt, session) _keep_best_files(session, run, payload, previous_best) for key in ("step_path", "preview_path"): payload.pop(key, None) status = verification["status"] candidate = None copy_current = False if status == "passed": candidate = session["verify_candidate"] elif status == "failed" and verification["round"] >= MAX_VERIFY_ROUNDS: candidate = session["verify_best"] elif status == "skipped" and verification["reason"] != "max_rounds_reached" and not session.get("saved"): # Infra/verify errors save this execution once; later retries keep the same runs/ directory. candidate = { "code": code, "verification": verification, "views_path": None, "stdout": payload.get("stdout", ""), "stderr": payload.get("stderr", ""), } copy_current = True if candidate: if candidate is not session.get("verify_best"): copy_current = True saved = _deliver(session, run, candidate, copy_current=copy_current) if not saved.get("ok"): return json_response({**saved, "verification": verification}) payload.update({key: saved[key] for key in SAVED_KEYS if saved.get(key)}) elif session.get("saved") and status == "skipped": payload.update({key: session["saved"][key] for key in SAVED_KEYS if session["saved"].get(key)}) payload["verification"] = verification return json_response(payload) def finalize_session(session: dict) -> None: """Deliver the retained best candidate if the loop ended before any model was published.""" best = session.get("verify_best") run = session.get("run") if best and run and not session.get("saved"): saved = _deliver(session, run, best, copy_current=False) print(f"> saved best unverified candidate: {saved.get('output_path') or saved.get('error')}") ACTIVE_TOOLS = [ { "name": "execute_build123d", "schema": BUILD123D_TOOL_SCHEMA, "handler": _execute_build123d_handler, "prompt_section": BUILD123D_PROMPT_SECTION, }, ] TOOLS = [tool["schema"] for tool in ACTIVE_TOOLS] TOOL_HANDLERS = {tool["name"]: tool["handler"] for tool in ACTIVE_TOOLS} TOOL_PROMPT_SECTIONS = [tool["prompt_section"] for tool in ACTIVE_TOOLS]