KaiWu Cursor commited on
Commit
769eb08
·
1 Parent(s): bb416ab

feat(agent): shorten CAD turns and keep the verification record

Browse files

Default to low effort until a check fails, run each build once, and write the checklist in parallel so a saved run still includes verification.json.

Co-authored-by: Cursor <cursoragent@cursor.com>

agent_core/agent.py CHANGED
@@ -1,10 +1,12 @@
 
 
1
  from agent_core.config import get_client, get_model_id
2
  from agent_core.prompts import SYSTEM
3
  from agent_core.tools.registry import TOOL_HANDLERS, TOOLS, finalize_session
4
 
5
  MAX_TOKENS = 64000
6
  # DeepSeek ignores thinking.budget_tokens; effort is the only knob to shorten reasoning.
7
- TRUNCATION_FALLBACK = {"output_config": {"effort": "low"}}
8
  NO_TOOL = "NO_TOOL"
9
  BUILD_NUDGE = (
10
  "You replied without calling any tool. If this request needs a CAD model, call the tool now instead of "
@@ -40,6 +42,21 @@ def _create(client, **kwargs):
40
  return stream.get_final_message()
41
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  def agent_loop(messages: list) -> dict:
44
  session = {}
45
  try:
@@ -54,7 +71,9 @@ def _run_loop(messages: list, session: dict) -> None:
54
  model = get_model_id()
55
  used_tool = False
56
  nudged = False
57
- truncated = False
 
 
58
 
59
  while True:
60
  response = _create(
@@ -64,12 +83,14 @@ def _run_loop(messages: list, session: dict) -> None:
64
  messages=messages,
65
  tools=TOOLS,
66
  max_tokens=MAX_TOKENS,
67
- **(TRUNCATION_FALLBACK if truncated else {}),
68
  )
 
69
  # A truncated reply may hold a tool_use with partial input; never put it into history.
70
  if response.stop_reason == "max_tokens":
71
- if not truncated:
72
- truncated = True
 
73
  continue
74
  messages.append({"role": "assistant", "content": TRUNCATED_REPLY})
75
  return
@@ -92,6 +113,7 @@ def _run_loop(messages: list, session: dict) -> None:
92
  results = []
93
  for block in tool_uses:
94
  output = _run_tool(block, prompt, session)
 
95
  print(f"> {block.name}: {output[:200]}")
96
  results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
97
  messages.append({"role": "user", "content": results})
 
1
+ import json
2
+
3
  from agent_core.config import get_client, get_model_id
4
  from agent_core.prompts import SYSTEM
5
  from agent_core.tools.registry import TOOL_HANDLERS, TOOLS, finalize_session
6
 
7
  MAX_TOKENS = 64000
8
  # DeepSeek ignores thinking.budget_tokens; effort is the only knob to shorten reasoning.
9
+ # A truncated reply retries once at low so a high-effort rewrite cannot fill the token cap.
10
  NO_TOOL = "NO_TOOL"
11
  BUILD_NUDGE = (
12
  "You replied without calling any tool. If this request needs a CAD model, call the tool now instead of "
 
42
  return stream.get_final_message()
43
 
44
 
45
+ def _next_effort(output: str, effort: str) -> str:
46
+ """Raise effort only after a failed verification, and drop it again once one passes."""
47
+ try:
48
+ payload = json.loads(output)
49
+ except (TypeError, json.JSONDecodeError):
50
+ return effort
51
+ verification = payload.get("verification") if isinstance(payload, dict) else None
52
+ status = verification.get("status") if isinstance(verification, dict) else None
53
+ if status == "failed":
54
+ return "high"
55
+ if status == "passed":
56
+ return "low"
57
+ return effort
58
+
59
+
60
  def agent_loop(messages: list) -> dict:
61
  session = {}
62
  try:
 
71
  model = get_model_id()
72
  used_tool = False
73
  nudged = False
74
+ effort = "low"
75
+ retried_truncation = False
76
+ retry_low = False
77
 
78
  while True:
79
  response = _create(
 
83
  messages=messages,
84
  tools=TOOLS,
85
  max_tokens=MAX_TOKENS,
86
+ output_config={"effort": "low" if retry_low else effort},
87
  )
88
+ retry_low = False
89
  # A truncated reply may hold a tool_use with partial input; never put it into history.
90
  if response.stop_reason == "max_tokens":
91
+ if not retried_truncation:
92
+ retried_truncation = True
93
+ retry_low = True
94
  continue
95
  messages.append({"role": "assistant", "content": TRUNCATED_REPLY})
96
  return
 
113
  results = []
114
  for block in tool_uses:
115
  output = _run_tool(block, prompt, session)
116
+ effort = _next_effort(output, effort)
117
  print(f"> {block.name}: {output[:200]}")
118
  results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
119
  messages.append({"role": "user", "content": results})
agent_core/tools/build123d_tool.py CHANGED
@@ -219,6 +219,63 @@ def run_build123d(code: str, preview_path: Path, step_path: Path | None = None)
219
  return payload
220
 
221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  def save_build123d_run(
223
  code: str,
224
  output_path: str = DEFAULT_BUILD123D_OUTPUT_PATH,
@@ -226,7 +283,7 @@ def save_build123d_run(
226
  verification: dict | None = None,
227
  views_path: Path | None = None,
228
  ) -> dict:
229
- """Re-run code into a new run directory with STEP + STL + manifest (+ verification and views if given)."""
230
  try:
231
  run_dir, output, run_id = resolve_run_output(output_path)
232
  except Exception as exc:
 
219
  return payload
220
 
221
 
222
+ def publish_build123d_run(
223
+ code: str,
224
+ run_dir: Path,
225
+ run_id: str,
226
+ output: Path,
227
+ requested_output_path: str,
228
+ prompt: str | None = None,
229
+ verification: dict | None = None,
230
+ views_path: Path | None = None,
231
+ stdout: str = "",
232
+ stderr: str = "",
233
+ ) -> dict:
234
+ """Record an already executed run: manifest, verification, rendered views, and the latest link. Does not run the code."""
235
+ if verification is not None and views_path and Path(views_path).exists():
236
+ dest = run_dir / "views.png"
237
+ if Path(views_path).resolve() != dest.resolve():
238
+ shutil.copy2(views_path, dest)
239
+ verification = {**verification, "views_path": workspace_relative(dest)}
240
+
241
+ if verification is not None:
242
+ (run_dir / "verification.json").write_text(
243
+ json.dumps(verification, ensure_ascii=False, indent=2), encoding="utf-8"
244
+ )
245
+
246
+ payload = {
247
+ "ok": True,
248
+ "preview_path": str(run_dir / "preview.stl"),
249
+ "stdout": stdout,
250
+ "stderr": stderr,
251
+ }
252
+ manifest_path = write_manifest(
253
+ run_dir=run_dir,
254
+ run_id=run_id,
255
+ requested_output_path=requested_output_path,
256
+ output_path=output,
257
+ code=code,
258
+ prompt=prompt,
259
+ payload=payload,
260
+ generator="build123d",
261
+ verification=verification,
262
+ )
263
+ output_root = run_dir.parent.parent
264
+ latest_warning = update_latest_link(output_root, run_dir)
265
+ result = {
266
+ "ok": True,
267
+ "run_id": run_id,
268
+ "run_dir": workspace_relative(run_dir),
269
+ "output_path": workspace_relative(output),
270
+ "preview_path": workspace_relative(run_dir / "preview.stl"),
271
+ "manifest_path": workspace_relative(manifest_path),
272
+ "latest_path": workspace_relative(output_root / "latest"),
273
+ }
274
+ if latest_warning:
275
+ result["warning"] = latest_warning
276
+ return result
277
+
278
+
279
  def save_build123d_run(
280
  code: str,
281
  output_path: str = DEFAULT_BUILD123D_OUTPUT_PATH,
 
283
  verification: dict | None = None,
284
  views_path: Path | None = None,
285
  ) -> dict:
286
+ """Execute code once into a new run directory with STEP + STL + manifest (+ verification and views if given)."""
287
  try:
288
  run_dir, output, run_id = resolve_run_output(output_path)
289
  except Exception as exc:
agent_core/tools/registry.py CHANGED
@@ -1,30 +1,113 @@
1
  import shutil
2
- import tempfile
3
  from pathlib import Path
4
 
5
  from agent_core.config import DEFAULT_BUILD123D_OUTPUT_PATH, MAX_VERIFY_ROUNDS, VERIFY_ENABLED
 
6
  from agent_core.tools.build123d_tool import PROMPT_SECTION as BUILD123D_PROMPT_SECTION
7
  from agent_core.tools.build123d_tool import TOOL_SCHEMA as BUILD123D_TOOL_SCHEMA
8
- from agent_core.tools.build123d_tool import run_build123d, save_build123d_run
9
  from agent_core.tools.lux3d_tool import PROMPT_SECTION as LUX3D_PROMPT_SECTION
10
  from agent_core.tools.lux3d_tool import TOOL_SCHEMA as LUX3D_TOOL_SCHEMA
11
  from agent_core.tools.lux3d_tool import run_generate_3d_model
12
  from agent_core.utils import json_response
 
13
  from agent_core.verify.run import verify_build123d_run
14
 
15
 
16
  SAVED_KEYS = ("run_id", "run_dir", "output_path", "preview_path", "manifest_path", "latest_path", "warning")
17
-
18
-
19
- def _save_candidate(session: dict, code: str, verification: dict, views_path: Path | None = None) -> dict:
20
- saved = save_build123d_run(
21
- code,
22
- session["output_path"],
23
- session.get("prompt"),
24
- verification={**verification, "checklist": session.get("verify_checklist")},
25
- views_path=views_path,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  )
27
  if saved.get("ok"):
 
28
  session["saved"] = {key: saved[key] for key in SAVED_KEYS if saved.get(key)}
29
  return saved
30
 
@@ -40,29 +123,58 @@ def _execute_build123d_handler(
40
  return json_response(save_build123d_run(code, output_path, prompt))
41
 
42
  session["output_path"], session["prompt"] = output_path, prompt
43
- if "scratch_dir" not in session:
44
- session["scratch_dir"] = tempfile.mkdtemp(prefix="aigc_verify_")
45
- session["candidates"] = session.get("candidates", 0) + 1
46
- payload = run_build123d(code, Path(session["scratch_dir"]) / f"candidate_{session['candidates']}.stl")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  if not payload.get("ok"):
 
 
48
  return json_response(payload)
49
 
 
 
50
  verification = verify_build123d_run(payload, code, prompt, session)
 
51
  for key in ("step_path", "preview_path"):
52
  payload.pop(key, None)
53
 
54
  status = verification["status"]
55
  candidate = None
 
56
  if status == "passed":
57
  candidate = session["verify_candidate"]
58
  elif status == "failed" and verification["round"] >= MAX_VERIFY_ROUNDS:
59
  candidate = session["verify_best"]
60
  elif status == "skipped" and verification["reason"] != "max_rounds_reached" and not session.get("saved"):
61
- # Infra/verify errors already saved once; do not allocate another runs/ dir on retries.
62
- candidate = {"code": code, "verification": verification, "views_path": None}
 
 
 
 
 
 
 
63
 
64
  if candidate:
65
- saved = _save_candidate(session, candidate["code"], candidate["verification"], candidate["views_path"])
 
 
66
  if not saved.get("ok"):
67
  return json_response({**saved, "verification": verification})
68
  payload.update({key: saved[key] for key in SAVED_KEYS if saved.get(key)})
@@ -73,14 +185,12 @@ def _execute_build123d_handler(
73
 
74
 
75
  def finalize_session(session: dict) -> None:
76
- """Save the best candidate if the loop ended before any model was saved, then drop the scratch directory."""
77
  best = session.get("verify_best")
78
- if best and not session.get("saved"):
79
- saved = _save_candidate(session, best["code"], best["verification"], best["views_path"])
 
80
  print(f"> saved best unverified candidate: {saved.get('output_path') or saved.get('error')}")
81
- scratch_dir = session.pop("scratch_dir", None)
82
- if scratch_dir:
83
- shutil.rmtree(scratch_dir, ignore_errors=True)
84
 
85
 
86
  def _generate_3d_model_handler(
 
1
  import shutil
2
+ import threading
3
  from pathlib import Path
4
 
5
  from agent_core.config import DEFAULT_BUILD123D_OUTPUT_PATH, MAX_VERIFY_ROUNDS, VERIFY_ENABLED
6
+ from agent_core.outputs import resolve_run_output
7
  from agent_core.tools.build123d_tool import PROMPT_SECTION as BUILD123D_PROMPT_SECTION
8
  from agent_core.tools.build123d_tool import TOOL_SCHEMA as BUILD123D_TOOL_SCHEMA
9
+ from agent_core.tools.build123d_tool import publish_build123d_run, run_build123d, save_build123d_run
10
  from agent_core.tools.lux3d_tool import PROMPT_SECTION as LUX3D_PROMPT_SECTION
11
  from agent_core.tools.lux3d_tool import TOOL_SCHEMA as LUX3D_TOOL_SCHEMA
12
  from agent_core.tools.lux3d_tool import run_generate_3d_model
13
  from agent_core.utils import json_response
14
+ from agent_core.verify.judge import build_checklist
15
  from agent_core.verify.run import verify_build123d_run
16
 
17
 
18
  SAVED_KEYS = ("run_id", "run_dir", "output_path", "preview_path", "manifest_path", "latest_path", "warning")
19
+ PENDING_STEP = "pending.step"
20
+ PENDING_STL = "pending.stl"
21
+ BEST_VIEWS = "best_views.png"
22
+
23
+
24
+ def _start_checklist(session: dict, prompt: str | None) -> None:
25
+ """Start the acceptance checklist beside geometry. Later rounds in this turn reuse it."""
26
+ if "verify_checklist" in session or session.get("checklist_thread") is not None:
27
+ return
28
+ holder: dict = {}
29
+
30
+ def work() -> None:
31
+ try:
32
+ checklist, usage = build_checklist(prompt or "")
33
+ holder["checklist"] = checklist
34
+ holder["usage"] = usage
35
+ except Exception as exc:
36
+ holder["error"] = exc
37
+
38
+ thread = threading.Thread(target=work, daemon=True)
39
+ thread.start()
40
+ session["checklist_thread"] = thread
41
+ session["checklist_holder"] = holder
42
+
43
+
44
+ def _allocate_run(output_path: str) -> dict:
45
+ run_dir, output, run_id = resolve_run_output(output_path)
46
+ return {
47
+ "run_dir": run_dir,
48
+ "output": output,
49
+ "run_id": run_id,
50
+ "requested_output_path": output_path,
51
+ }
52
+
53
+
54
+ def _discard_uncommitted(run: dict) -> None:
55
+ run_dir = run["run_dir"]
56
+ if run_dir.exists():
57
+ shutil.rmtree(run_dir, ignore_errors=True)
58
+ runs = run_dir.parent
59
+ if runs.name == "runs" and runs.is_dir() and not any(runs.iterdir()):
60
+ runs.rmdir()
61
+
62
+
63
+ def _keep_best_files(session: dict, run: dict, payload: dict, previous_best) -> None:
64
+ """Copy this execution onto model.step and preview.stl only when it becomes the retained best."""
65
+ best = session.get("verify_best")
66
+ if not best or best is previous_best:
67
+ return
68
+ run_dir = run["run_dir"]
69
+ shutil.copy2(run_dir / PENDING_STEP, run["output"])
70
+ shutil.copy2(run_dir / PENDING_STL, run_dir / "preview.stl")
71
+ best["stdout"] = payload.get("stdout", "")
72
+ best["stderr"] = payload.get("stderr", "")
73
+ views = best.get("views_path")
74
+ if views and Path(views).exists():
75
+ stable = run_dir / BEST_VIEWS
76
+ shutil.copy2(views, stable)
77
+ best["views_path"] = stable
78
+ else:
79
+ best["views_path"] = None
80
+
81
+
82
+ def _clear_pending(run_dir: Path) -> None:
83
+ for name in (PENDING_STEP, PENDING_STL, "pending.png", BEST_VIEWS):
84
+ path = run_dir / name
85
+ if path.is_file():
86
+ path.unlink()
87
+
88
+
89
+ def _deliver(session: dict, run: dict, candidate: dict, *, copy_current: bool) -> dict:
90
+ run_dir = run["run_dir"]
91
+ if copy_current:
92
+ shutil.copy2(run_dir / PENDING_STEP, run["output"])
93
+ shutil.copy2(run_dir / PENDING_STL, run_dir / "preview.stl")
94
+ verification = dict(candidate["verification"])
95
+ if session.get("verify_checklist") is not None:
96
+ verification["checklist"] = session["verify_checklist"]
97
+ saved = publish_build123d_run(
98
+ code=candidate["code"],
99
+ run_dir=run_dir,
100
+ run_id=run["run_id"],
101
+ output=run["output"],
102
+ requested_output_path=run["requested_output_path"],
103
+ prompt=session.get("prompt"),
104
+ verification=verification,
105
+ views_path=candidate.get("views_path"),
106
+ stdout=candidate.get("stdout", ""),
107
+ stderr=candidate.get("stderr", ""),
108
  )
109
  if saved.get("ok"):
110
+ _clear_pending(run_dir)
111
  session["saved"] = {key: saved[key] for key in SAVED_KEYS if saved.get(key)}
112
  return saved
113
 
 
123
  return json_response(save_build123d_run(code, output_path, prompt))
124
 
125
  session["output_path"], session["prompt"] = output_path, prompt
126
+ fresh = "run" not in session
127
+ try:
128
+ run = session["run"] if not fresh else _allocate_run(output_path)
129
+ except Exception as exc:
130
+ return json_response({
131
+ "ok": False,
132
+ "stage": "input",
133
+ "error_type": type(exc).__name__,
134
+ "error": str(exc),
135
+ "traceback_tail": "",
136
+ "stdout": "",
137
+ "stderr": "",
138
+ })
139
+
140
+ # Checklist starts with geometry and is not awaited until the bbox check.
141
+ _start_checklist(session, prompt)
142
+ run_dir = run["run_dir"]
143
+ payload = run_build123d(code, run_dir / PENDING_STL, run_dir / PENDING_STEP)
144
  if not payload.get("ok"):
145
+ if fresh:
146
+ _discard_uncommitted(run)
147
  return json_response(payload)
148
 
149
+ session["run"] = run
150
+ previous_best = session.get("verify_best")
151
  verification = verify_build123d_run(payload, code, prompt, session)
152
+ _keep_best_files(session, run, payload, previous_best)
153
  for key in ("step_path", "preview_path"):
154
  payload.pop(key, None)
155
 
156
  status = verification["status"]
157
  candidate = None
158
+ copy_current = False
159
  if status == "passed":
160
  candidate = session["verify_candidate"]
161
  elif status == "failed" and verification["round"] >= MAX_VERIFY_ROUNDS:
162
  candidate = session["verify_best"]
163
  elif status == "skipped" and verification["reason"] != "max_rounds_reached" and not session.get("saved"):
164
+ # Infra/verify errors save this execution once; later retries keep the same runs/ directory.
165
+ candidate = {
166
+ "code": code,
167
+ "verification": verification,
168
+ "views_path": None,
169
+ "stdout": payload.get("stdout", ""),
170
+ "stderr": payload.get("stderr", ""),
171
+ }
172
+ copy_current = True
173
 
174
  if candidate:
175
+ if candidate is not session.get("verify_best"):
176
+ copy_current = True
177
+ saved = _deliver(session, run, candidate, copy_current=copy_current)
178
  if not saved.get("ok"):
179
  return json_response({**saved, "verification": verification})
180
  payload.update({key: saved[key] for key in SAVED_KEYS if saved.get(key)})
 
185
 
186
 
187
  def finalize_session(session: dict) -> None:
188
+ """Deliver the retained best candidate if the loop ended before any model was published."""
189
  best = session.get("verify_best")
190
+ run = session.get("run")
191
+ if best and run and not session.get("saved"):
192
+ saved = _deliver(session, run, best, copy_current=False)
193
  print(f"> saved best unverified candidate: {saved.get('output_path') or saved.get('error')}")
 
 
 
194
 
195
 
196
  def _generate_3d_model_handler(
agent_core/verify/run.py CHANGED
@@ -2,7 +2,7 @@ from pathlib import Path
2
 
3
  from agent_core.config import MAX_VERIFY_ROUNDS
4
  from agent_core.eval.checks import compare_bbox
5
- from agent_core.verify.judge import build_checklist, judge_views
6
  from agent_core.verify.render import render_in_subprocess
7
 
8
 
@@ -36,6 +36,25 @@ def _instruction(passed: bool, round_index: int) -> str:
36
  )
37
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  def verify_build123d_run(payload: dict, code: str, prompt: str | None, session: dict) -> dict:
40
  """Verify a candidate from execute_build123d; records session["verify_candidate"] and session["verify_best"]."""
41
  session.pop("verify_candidate", None)
@@ -49,12 +68,7 @@ def verify_build123d_run(payload: dict, code: str, prompt: str | None, session:
49
  result = {"round": round_index, "max_rounds": MAX_VERIFY_ROUNDS}
50
 
51
  try:
52
- if "verify_checklist" not in session:
53
- checklist, usage = build_checklist(prompt or "")
54
- session["verify_checklist"] = checklist
55
- _add_usage(session, usage)
56
- checklist = session["verify_checklist"]
57
-
58
  dimensions = checklist["overall_dimensions_mm"]
59
  bbox = compare_bbox(payload["bbox_mm"], {"dimensions_mm": dimensions, "mode": "unordered"} if dimensions else None)
60
  result["hard_checks"] = {"bbox": bbox}
 
2
 
3
  from agent_core.config import MAX_VERIFY_ROUNDS
4
  from agent_core.eval.checks import compare_bbox
5
+ from agent_core.verify.judge import judge_views
6
  from agent_core.verify.render import render_in_subprocess
7
 
8
 
 
36
  )
37
 
38
 
39
+ def _load_checklist(session: dict) -> dict:
40
+ """Use this turn's checklist, waiting for the one started beside geometry execution."""
41
+ if "verify_checklist" in session:
42
+ return session["verify_checklist"]
43
+
44
+ thread = session.get("checklist_thread")
45
+ if thread is None:
46
+ raise RuntimeError("checklist was not started")
47
+ thread.join()
48
+ holder = session.pop("checklist_holder", {})
49
+ session.pop("checklist_thread", None)
50
+ error = holder.get("error")
51
+ if error:
52
+ raise error
53
+ session["verify_checklist"] = holder["checklist"]
54
+ _add_usage(session, holder.get("usage") or {})
55
+ return session["verify_checklist"]
56
+
57
+
58
  def verify_build123d_run(payload: dict, code: str, prompt: str | None, session: dict) -> dict:
59
  """Verify a candidate from execute_build123d; records session["verify_candidate"] and session["verify_best"]."""
60
  session.pop("verify_candidate", None)
 
68
  result = {"round": round_index, "max_rounds": MAX_VERIFY_ROUNDS}
69
 
70
  try:
71
+ checklist = _load_checklist(session)
 
 
 
 
 
72
  dimensions = checklist["overall_dimensions_mm"]
73
  bbox = compare_bbox(payload["bbox_mm"], {"dimensions_mm": dimensions, "mode": "unordered"} if dimensions else None)
74
  result["hard_checks"] = {"bbox": bbox}