File size: 13,389 Bytes
77be2f6
d4c2386
77be2f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c2386
77be2f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c2386
 
77be2f6
 
 
 
 
d4c2386
 
 
77be2f6
 
 
d4c2386
 
77be2f6
 
 
 
d4c2386
 
 
77be2f6
 
 
 
 
 
 
d4c2386
 
 
 
 
 
 
 
 
 
77be2f6
d4c2386
 
 
 
 
77be2f6
 
 
d4c2386
 
77be2f6
 
 
 
 
 
 
 
 
 
 
 
d4c2386
77be2f6
 
 
 
 
 
 
d4c2386
77be2f6
d4c2386
77be2f6
 
 
 
 
 
 
d4c2386
77be2f6
 
 
d4c2386
77be2f6
 
 
 
 
 
 
d4c2386
77be2f6
 
 
 
d4c2386
77be2f6
 
 
 
 
 
 
d4c2386
77be2f6
 
 
 
 
 
 
 
 
 
 
 
d4c2386
 
 
769eb08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c2386
 
 
 
 
 
 
769eb08
d4c2386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77be2f6
 
d4c2386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77be2f6
d4c2386
 
 
 
 
 
77be2f6
 
 
 
 
d4c2386
77be2f6
 
d4c2386
77be2f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4c2386
 
77be2f6
2d40989
 
 
77be2f6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import json
import shutil
import subprocess
import sys
import textwrap
from pathlib import Path

from agent_core.config import DEFAULT_BUILD123D_OUTPUT_PATH, WORKDIR
from agent_core.outputs import resolve_run_output, update_latest_link, workspace_relative, write_manifest
from agent_core.utils import json_response


BUILD123D_RUNNER = r"""
import contextlib
import io
import json
import sys
import traceback
from pathlib import Path

stdout_buffer = io.StringIO()
stderr_buffer = io.StringIO()


def tail(text, limit=4000):
    if not text:
        return ""
    return text[-limit:]


def fail(stage, exc=None, error_type=None, error=None):
    payload = {
        "ok": False,
        "stage": stage,
        "error_type": error_type or (type(exc).__name__ if exc else "Error"),
        "error": error or (str(exc) if exc else ""),
        "traceback_tail": tail(traceback.format_exc() if exc else ""),
        "stdout": tail(stdout_buffer.getvalue()),
        "stderr": tail(stderr_buffer.getvalue()),
    }
    print(json.dumps(payload, ensure_ascii=False))


def unwrap_result(value):
    for attr in ("part", "sketch", "line"):
        try:
            unwrapped = getattr(value, attr)
        except Exception:
            continue
        if unwrapped is not None:
            return unwrapped
    return value


try:
    request = json.loads(sys.stdin.read())
    code = request["code"]
    preview_path = Path(request["preview_path"])
    step_path = Path(request["step_path"]) if request.get("step_path") else None
except Exception as exc:
    fail("input", exc)
    sys.exit(0)

try:
    import build123d as bd
    from build123d import *  # noqa: F403
except Exception as exc:
    fail("import", exc)
    sys.exit(0)

try:
    compiled = compile(code, "<build123d_code>", "exec")
except Exception as exc:
    fail("syntax", exc)
    sys.exit(0)

namespace = {
    "__name__": "__build123d_user_code__",
    "bd": bd,
}
namespace.update({name: getattr(bd, name) for name in dir(bd) if not name.startswith("_")})

try:
    with contextlib.redirect_stdout(stdout_buffer), contextlib.redirect_stderr(stderr_buffer):
        exec(compiled, namespace)
except Exception as exc:
    fail("execution", exc)
    sys.exit(0)

if "result" not in namespace:
    fail("result", error_type="MissingResult", error="build123d code must assign the final model to variable 'result'.")
    sys.exit(0)

result = namespace["result"]
if result is None:
    fail("result", error_type="InvalidResult", error="'result' is None.")
    sys.exit(0)

try:
    exportable = unwrap_result(result)
    size = exportable.bounding_box().size
    bbox_mm = {"x": float(size.X), "y": float(size.Y), "z": float(size.Z)}
except Exception as exc:
    fail("result", exc)
    sys.exit(0)

try:
    if step_path:
        step_path.parent.mkdir(parents=True, exist_ok=True)
        export_step(exportable, step_path)  # noqa: F405
    preview_path.parent.mkdir(parents=True, exist_ok=True)
    export_stl(exportable, preview_path)  # noqa: F405
except Exception as exc:
    fail("export", exc)
    sys.exit(0)

payload = {
    "ok": True,
    "stage": "done",
    "step_path": str(step_path) if step_path else None,
    "preview_path": str(preview_path),
    "bbox_mm": bbox_mm,
    "stdout": tail(stdout_buffer.getvalue()),
    "stderr": tail(stderr_buffer.getvalue()),
}
print(json.dumps(payload, ensure_ascii=False))
"""


def _input_error(error_type: str, error: str) -> dict:
    return {
        "ok": False,
        "stage": "input",
        "error_type": error_type,
        "error": error,
        "traceback_tail": "",
        "stdout": "",
        "stderr": "",
    }


def run_build123d(code: str, preview_path: Path, step_path: Path | None = None) -> dict:
    """Execute build123d code in a subprocess; always export an STL, export STEP only when step_path is given."""
    if not code or not code.strip():
        return _input_error("EmptyCode", "execute_build123d requires non-empty build123d code.")

    request = {
        "code": code,
        "preview_path": str(preview_path),
        "step_path": str(step_path) if step_path else None,
    }

    try:
        process = subprocess.run(
            [sys.executable, "-c", BUILD123D_RUNNER],
            input=json.dumps(request, ensure_ascii=False),
            cwd=WORKDIR,
            capture_output=True,
            text=True,
            timeout=120,
        )
    except subprocess.TimeoutExpired as exc:
        return {
            "ok": False,
            "stage": "execution",
            "error_type": "TimeoutExpired",
            "error": "build123d execution timed out after 120 seconds.",
            "traceback_tail": "",
            "stdout": exc.stdout[-4000:] if exc.stdout else "",
            "stderr": exc.stderr[-4000:] if exc.stderr else "",
        }
    except Exception as exc:
        return {
            "ok": False,
            "stage": "subprocess",
            "error_type": type(exc).__name__,
            "error": str(exc),
            "traceback_tail": "",
            "stdout": "",
            "stderr": "",
        }

    raw_output = process.stdout.strip()
    if not raw_output:
        return {
            "ok": False,
            "stage": "subprocess",
            "error_type": "NoRunnerOutput",
            "error": "build123d runner returned no JSON output.",
            "traceback_tail": "",
            "stdout": "",
            "stderr": process.stderr[-4000:],
        }

    try:
        payload = json.loads(raw_output.splitlines()[-1])
    except Exception as exc:
        return {
            "ok": False,
            "stage": "subprocess",
            "error_type": type(exc).__name__,
            "error": f"Failed to parse build123d runner output: {exc}",
            "traceback_tail": "",
            "stdout": raw_output[-4000:],
            "stderr": process.stderr[-4000:],
        }

    if process.returncode != 0 and payload.get("ok") is not False:
        payload = {
            "ok": False,
            "stage": "subprocess",
            "error_type": "RunnerFailed",
            "error": f"build123d runner exited with code {process.returncode}.",
            "traceback_tail": "",
            "stdout": raw_output[-4000:],
            "stderr": process.stderr[-4000:],
        }

    return payload


def publish_build123d_run(
    code: str,
    run_dir: Path,
    run_id: str,
    output: Path,
    requested_output_path: str,
    prompt: str | None = None,
    verification: dict | None = None,
    views_path: Path | None = None,
    stdout: str = "",
    stderr: str = "",
) -> dict:
    """Record an already executed run: manifest, verification, rendered views, and the latest link. Does not run the code."""
    if verification is not None and views_path and Path(views_path).exists():
        dest = run_dir / "views.png"
        if Path(views_path).resolve() != dest.resolve():
            shutil.copy2(views_path, dest)
        verification = {**verification, "views_path": workspace_relative(dest)}

    if verification is not None:
        (run_dir / "verification.json").write_text(
            json.dumps(verification, ensure_ascii=False, indent=2), encoding="utf-8"
        )

    payload = {
        "ok": True,
        "preview_path": str(run_dir / "preview.stl"),
        "stdout": stdout,
        "stderr": stderr,
    }
    manifest_path = write_manifest(
        run_dir=run_dir,
        run_id=run_id,
        requested_output_path=requested_output_path,
        output_path=output,
        code=code,
        prompt=prompt,
        payload=payload,
        generator="build123d",
        verification=verification,
    )
    output_root = run_dir.parent.parent
    latest_warning = update_latest_link(output_root, run_dir)
    result = {
        "ok": True,
        "run_id": run_id,
        "run_dir": workspace_relative(run_dir),
        "output_path": workspace_relative(output),
        "preview_path": workspace_relative(run_dir / "preview.stl"),
        "manifest_path": workspace_relative(manifest_path),
        "latest_path": workspace_relative(output_root / "latest"),
    }
    if latest_warning:
        result["warning"] = latest_warning
    return result


def save_build123d_run(
    code: str,
    output_path: str = DEFAULT_BUILD123D_OUTPUT_PATH,
    prompt: str | None = None,
    verification: dict | None = None,
    views_path: Path | None = None,
) -> dict:
    """Execute code once into a new run directory with STEP + STL + manifest (+ verification and views if given)."""
    try:
        run_dir, output, run_id = resolve_run_output(output_path)
    except Exception as exc:
        return _input_error(type(exc).__name__, str(exc))

    payload = run_build123d(code, run_dir / "preview.stl", output)
    if not payload.get("ok"):
        return payload

    if verification is not None:
        if views_path:
            shutil.copy2(views_path, run_dir / "views.png")
            verification = {**verification, "views_path": workspace_relative(run_dir / "views.png")}
        (run_dir / "verification.json").write_text(
            json.dumps(verification, ensure_ascii=False, indent=2), encoding="utf-8"
        )

    payload.pop("step_path", None)
    manifest_path = write_manifest(
        run_dir=run_dir,
        run_id=run_id,
        requested_output_path=output_path,
        output_path=output,
        code=code,
        prompt=prompt,
        payload=payload,
        generator="build123d",
        verification=verification,
    )
    output_root = run_dir.parent.parent
    latest_warning = update_latest_link(output_root, run_dir)

    payload["run_id"] = run_id
    payload["run_dir"] = workspace_relative(run_dir)
    payload["output_path"] = workspace_relative(output)
    payload["preview_path"] = workspace_relative(Path(payload["preview_path"]))
    payload["manifest_path"] = workspace_relative(manifest_path)
    payload["latest_path"] = workspace_relative(output_root / "latest")
    if latest_warning:
        payload["warning"] = latest_warning
    return payload


def run_execute_build123d(
    code: str,
    output_path: str = DEFAULT_BUILD123D_OUTPUT_PATH,
    prompt: str | None = None,
) -> str:
    return json_response(save_build123d_run(code, output_path, prompt))


TOOL_SCHEMA = {
    "name": "execute_build123d",
    "description": textwrap.dedent("""
        Execute build123d Python code, verify the model from rendered views, and save it as STEP + STL once accepted.
        The code must assign the final build123d model to a variable named result.
        build123d public symbols are pre-imported, and build123d is also available as bd.
        A model is saved only when the result contains output_path; candidates that fail verification are not saved.
        Do NOT supply output_path in normal usage. The tool automatically writes files to the configured artifact directory under a unique run directory. Only set output_path if the user explicitly requests a different location.
    """).strip(),
    "input_schema": {
        "type": "object",
        "properties": {
            "code": {
                "type": "string",
                "description": "build123d Python code. It must assign the final model to variable 'result'.",
            },
            "output_path": {
                "type": "string",
                "description": "Advanced: custom STEP file path or output directory. Omit this field to use the configured artifact directory (recommended).",
            },
        },
        "required": ["code"],
    },
}


PROMPT_SECTION = """
For precise CAD tasks:
- Use execute_build123d for dimensioned parts, parametric geometry, engineering models, and STEP/CAD output.
- Write build123d Python code.
- The code must assign the final model to a variable named result.
- build123d public symbols are pre-imported, and build123d is also available as bd.
- BuildPart, BuildSketch, and BuildLine builder objects are accepted; the tool will unwrap their .part, .sketch, or .line result.
- Call execute_build123d with just the code; do NOT pass output_path. The tool writes outputs into the configured artifact directory under a unique run directory automatically.
- If execute_build123d returns ok=false, inspect the structured error, fix the code, and call execute_build123d again.
- When ok=true, the result may include a verification object produced by an independent reviewer from rendered views. Follow verification.instruction. If it failed, fix the failed checklist items and hard_checks problems by editing your previous code rather than starting over.
- The model is saved only when the result contains output_path. Without output_path nothing was saved yet, so do not report any file path.
- CadQuery is not enabled in the current runtime. If the user explicitly asks for CadQuery, say that the active CAD tool is build123d.
- When the user message includes an image, use the image for shape and structure. If text and image conflict, follow the text for dimensions and the image for shape. If a dimension is unclear, estimate it and state the estimate in the reply.
- If the text already specifies what to build, build that even when the image is blurry.
- If the image is blank, unrelated, or unrecognizable, or the shape and structure cannot be determined, and the text does not specify an object, do not call execute_build123d.
""".strip()