@tangle-network/agent-bench 0.4.1 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/adapters.d.ts +4 -11
  3. package/dist/adapters.js +78 -41
  4. package/dist/adapters.js.map +1 -1
  5. package/dist/benchmarks/_harness.d.ts +48 -66
  6. package/dist/benchmarks/_harness.js +329 -33
  7. package/dist/benchmarks/_harness.js.map +1 -1
  8. package/dist/benchmarks/aec-bench.d.ts +4 -25
  9. package/dist/benchmarks/aec-bench.js +242 -7
  10. package/dist/benchmarks/aec-bench.js.map +1 -1
  11. package/dist/benchmarks/agentbench.d.ts +5 -13
  12. package/dist/benchmarks/agentbench.js +114 -9
  13. package/dist/benchmarks/agentbench.js.map +1 -1
  14. package/dist/benchmarks/appworld.d.ts +9 -29
  15. package/dist/benchmarks/appworld.js +317 -12
  16. package/dist/benchmarks/appworld.js.map +1 -1
  17. package/dist/benchmarks/bfcl.d.ts +5 -15
  18. package/dist/benchmarks/bfcl.js +264 -9
  19. package/dist/benchmarks/bfcl.js.map +1 -1
  20. package/dist/benchmarks/cad-design.d.ts +16 -41
  21. package/dist/benchmarks/cad-design.js +512 -6
  22. package/dist/benchmarks/cad-design.js.map +1 -1
  23. package/dist/benchmarks/cadbench.d.ts +4 -17
  24. package/dist/benchmarks/cadbench.js +2 -8
  25. package/dist/benchmarks/cadgenbench.d.ts +4 -20
  26. package/dist/benchmarks/cadgenbench.js +2 -8
  27. package/dist/benchmarks/commit0.d.ts +5 -27
  28. package/dist/benchmarks/commit0.js +187 -9
  29. package/dist/benchmarks/commit0.js.map +1 -1
  30. package/dist/benchmarks/crag.d.ts +4 -12
  31. package/dist/benchmarks/crag.js +110 -8
  32. package/dist/benchmarks/crag.js.map +1 -1
  33. package/dist/benchmarks/dabstep.d.ts +5 -15
  34. package/dist/benchmarks/dabstep.js +177 -9
  35. package/dist/benchmarks/dabstep.js.map +1 -1
  36. package/dist/benchmarks/enterpriseops-gym.d.ts +5 -34
  37. package/dist/benchmarks/enterpriseops-gym.js +236 -9
  38. package/dist/benchmarks/enterpriseops-gym.js.map +1 -1
  39. package/dist/benchmarks/finresearchbench.d.ts +4 -13
  40. package/dist/benchmarks/finresearchbench.js +218 -7
  41. package/dist/benchmarks/finresearchbench.js.map +1 -1
  42. package/dist/benchmarks/finsearchcomp.d.ts +8 -39
  43. package/dist/benchmarks/finsearchcomp.js +267 -6
  44. package/dist/benchmarks/finsearchcomp.js.map +1 -1
  45. package/dist/benchmarks/frames.d.ts +15 -37
  46. package/dist/benchmarks/frames.js +408 -11
  47. package/dist/benchmarks/frames.js.map +1 -1
  48. package/dist/benchmarks/hotpotqa.d.ts +4 -24
  49. package/dist/benchmarks/hotpotqa.js +250 -14
  50. package/dist/benchmarks/hotpotqa.js.map +1 -1
  51. package/dist/benchmarks/humaneval.d.ts +19 -37
  52. package/dist/benchmarks/humaneval.js +279 -16
  53. package/dist/benchmarks/humaneval.js.map +1 -1
  54. package/dist/benchmarks/mind2web.d.ts +7 -34
  55. package/dist/benchmarks/mind2web.js +257 -8
  56. package/dist/benchmarks/mind2web.js.map +1 -1
  57. package/dist/benchmarks/nomiracl.d.ts +4 -13
  58. package/dist/benchmarks/nomiracl.js +146 -8
  59. package/dist/benchmarks/nomiracl.js.map +1 -1
  60. package/dist/benchmarks/open-rag-bench.d.ts +4 -12
  61. package/dist/benchmarks/open-rag-bench.js +110 -8
  62. package/dist/benchmarks/open-rag-bench.js.map +1 -1
  63. package/dist/benchmarks/programbench.d.ts +5 -29
  64. package/dist/benchmarks/programbench.js +161 -9
  65. package/dist/benchmarks/programbench.js.map +1 -1
  66. package/dist/benchmarks/rag-shared.d.ts +21 -20
  67. package/dist/benchmarks/rag-shared.js +245 -38
  68. package/dist/benchmarks/rag-shared.js.map +1 -1
  69. package/dist/benchmarks/ragbench.d.ts +4 -14
  70. package/dist/benchmarks/ragbench.js +127 -8
  71. package/dist/benchmarks/ragbench.js.map +1 -1
  72. package/dist/benchmarks/simpleqa.d.ts +17 -44
  73. package/dist/benchmarks/simpleqa.js +293 -10
  74. package/dist/benchmarks/simpleqa.js.map +1 -1
  75. package/dist/benchmarks/swe-bench.d.ts +23 -36
  76. package/dist/benchmarks/swe-bench.js +234 -13
  77. package/dist/benchmarks/swe-bench.js.map +1 -1
  78. package/dist/benchmarks/t2-ragbench.d.ts +4 -12
  79. package/dist/benchmarks/t2-ragbench.js +118 -8
  80. package/dist/benchmarks/t2-ragbench.js.map +1 -1
  81. package/dist/benchmarks/tau-bench-shared.d.ts +14 -22
  82. package/dist/benchmarks/tau-bench-shared.js +169 -9
  83. package/dist/benchmarks/tau-bench-shared.js.map +1 -1
  84. package/dist/benchmarks/tau2-bench.d.ts +5 -5
  85. package/dist/benchmarks/tau2-bench.js +28 -10
  86. package/dist/benchmarks/tau2-bench.js.map +1 -1
  87. package/dist/benchmarks/tau3-banking.d.ts +4 -13
  88. package/dist/benchmarks/tau3-banking.js +28 -8
  89. package/dist/benchmarks/tau3-banking.js.map +1 -1
  90. package/dist/benchmarks/terminal-bench.d.ts +4 -22
  91. package/dist/benchmarks/terminal-bench.js +140 -7
  92. package/dist/benchmarks/terminal-bench.js.map +1 -1
  93. package/dist/benchmarks/toollm.d.ts +5 -13
  94. package/dist/benchmarks/toollm.js +184 -9
  95. package/dist/benchmarks/toollm.js.map +1 -1
  96. package/dist/benchmarks/trata-hedge.d.ts +4 -30
  97. package/dist/benchmarks/trata-hedge.js +336 -6
  98. package/dist/benchmarks/trata-hedge.js.map +1 -1
  99. package/dist/benchmarks/types.d.ts +85 -94
  100. package/dist/benchmarks/types.js +1 -1
  101. package/dist/benchmarks/webarena-verified.d.ts +5 -13
  102. package/dist/benchmarks/webarena-verified.js +152 -9
  103. package/dist/benchmarks/webarena-verified.js.map +1 -1
  104. package/dist/cadbench-DpQWZHp4.js +285 -0
  105. package/dist/cadbench-DpQWZHp4.js.map +1 -0
  106. package/dist/cadgenbench-DRhczfsG.js +151 -0
  107. package/dist/cadgenbench-DRhczfsG.js.map +1 -0
  108. package/dist/index.d.ts +245 -293
  109. package/dist/index.js +1669 -1791
  110. package/dist/index.js.map +1 -1
  111. package/package.json +18 -15
  112. package/scripts/verify-packed-consumer.mjs +20 -17
  113. package/src/corpus.test.mts +13 -0
  114. package/src/corpus.ts +4 -0
  115. package/src/pier-trial-controller.test.mts +15 -7
  116. package/src/profile-coordinates.ts +2 -2
  117. package/src/rollout-ledger/backfill-swe-arena.mts +5 -1
  118. package/src/rollout-ledger/settle-capture.mts +7 -1
  119. package/src/search-bench/profiles.ts +1 -1
  120. package/src/skill-sandbox-smoke.mts +2 -1
  121. package/src/swe-arena/gepa-seat.mts +1 -1
  122. package/src/swe-arena/ledger-orphans.test.mts +36 -34
  123. package/dist/benchmarks/cadbench.js.map +0 -1
  124. package/dist/benchmarks/cadgenbench.js.map +0 -1
  125. package/dist/benchmarks/types.js.map +0 -1
  126. package/dist/chunk-53UPUNBZ.js +0 -325
  127. package/dist/chunk-53UPUNBZ.js.map +0 -1
  128. package/dist/chunk-5FEQDSCT.js +0 -211
  129. package/dist/chunk-5FEQDSCT.js.map +0 -1
  130. package/dist/chunk-5H5XV76F.js +0 -240
  131. package/dist/chunk-5H5XV76F.js.map +0 -1
  132. package/dist/chunk-67ACKDCX.js +0 -118
  133. package/dist/chunk-67ACKDCX.js.map +0 -1
  134. package/dist/chunk-7FKBWOQT.js +0 -147
  135. package/dist/chunk-7FKBWOQT.js.map +0 -1
  136. package/dist/chunk-BEN6IF2X.js +0 -221
  137. package/dist/chunk-BEN6IF2X.js.map +0 -1
  138. package/dist/chunk-BZY5QARD.js +0 -120
  139. package/dist/chunk-BZY5QARD.js.map +0 -1
  140. package/dist/chunk-C7T7WEK2.js +0 -103
  141. package/dist/chunk-C7T7WEK2.js.map +0 -1
  142. package/dist/chunk-CLIKAXKH.js +0 -276
  143. package/dist/chunk-CLIKAXKH.js.map +0 -1
  144. package/dist/chunk-CWIOBFSP.js +0 -197
  145. package/dist/chunk-CWIOBFSP.js.map +0 -1
  146. package/dist/chunk-CXDUTWQE.js +0 -318
  147. package/dist/chunk-CXDUTWQE.js.map +0 -1
  148. package/dist/chunk-DWALFME7.js +0 -182
  149. package/dist/chunk-DWALFME7.js.map +0 -1
  150. package/dist/chunk-EEOC6QPJ.js +0 -144
  151. package/dist/chunk-EEOC6QPJ.js.map +0 -1
  152. package/dist/chunk-EIETHPD5.js +0 -321
  153. package/dist/chunk-EIETHPD5.js.map +0 -1
  154. package/dist/chunk-GC2EPS6L.js +0 -130
  155. package/dist/chunk-GC2EPS6L.js.map +0 -1
  156. package/dist/chunk-GCHL6XPM.js +0 -169
  157. package/dist/chunk-GCHL6XPM.js.map +0 -1
  158. package/dist/chunk-HQ5HCCKF.js +0 -142
  159. package/dist/chunk-HQ5HCCKF.js.map +0 -1
  160. package/dist/chunk-HVW25KSX.js +0 -208
  161. package/dist/chunk-HVW25KSX.js.map +0 -1
  162. package/dist/chunk-INNOYXCP.js +0 -387
  163. package/dist/chunk-INNOYXCP.js.map +0 -1
  164. package/dist/chunk-J6BU3NTM.js +0 -251
  165. package/dist/chunk-J6BU3NTM.js.map +0 -1
  166. package/dist/chunk-JSQOUKXS.js +0 -149
  167. package/dist/chunk-JSQOUKXS.js.map +0 -1
  168. package/dist/chunk-JTHWEDEW.js +0 -32
  169. package/dist/chunk-JTHWEDEW.js.map +0 -1
  170. package/dist/chunk-NRMGT25X.js +0 -116
  171. package/dist/chunk-NRMGT25X.js.map +0 -1
  172. package/dist/chunk-PA2ZKHJC.js +0 -230
  173. package/dist/chunk-PA2ZKHJC.js.map +0 -1
  174. package/dist/chunk-PUIRNYI7.js +0 -189
  175. package/dist/chunk-PUIRNYI7.js.map +0 -1
  176. package/dist/chunk-QZZEAHWJ.js +0 -136
  177. package/dist/chunk-QZZEAHWJ.js.map +0 -1
  178. package/dist/chunk-SEVJPLZC.js +0 -260
  179. package/dist/chunk-SEVJPLZC.js.map +0 -1
  180. package/dist/chunk-TBKU5XQI.js +0 -228
  181. package/dist/chunk-TBKU5XQI.js.map +0 -1
  182. package/dist/chunk-UPAMRDX4.js +0 -233
  183. package/dist/chunk-UPAMRDX4.js.map +0 -1
  184. package/dist/chunk-VQRS7VUC.js +0 -342
  185. package/dist/chunk-VQRS7VUC.js.map +0 -1
  186. package/dist/chunk-WG7TM7UV.js +0 -30
  187. package/dist/chunk-WG7TM7UV.js.map +0 -1
  188. package/dist/chunk-X3BTXCJ4.js +0 -262
  189. package/dist/chunk-X3BTXCJ4.js.map +0 -1
  190. package/dist/chunk-XXFF3RRD.js +0 -162
  191. package/dist/chunk-XXFF3RRD.js.map +0 -1
  192. package/dist/chunk-ZFNOM7WR.js +0 -27
  193. package/dist/chunk-ZFNOM7WR.js.map +0 -1
  194. package/dist/chunk-ZNCCYTFG.js +0 -170
  195. package/dist/chunk-ZNCCYTFG.js.map +0 -1
@@ -0,0 +1,285 @@
1
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { tmpdir } from "node:os";
5
+ import { promisify } from "node:util";
6
+ import "@tangle-network/agent-runtime/loops";
7
+ //#region src/worker-blender.ts
8
+ /**
9
+ * BlenderLLM / CADBench worker. The deliverable for a CADBench task is a Blender
10
+ * `bpy` Python script that builds the described 3D model. We author it via the
11
+ * router, execute it headless in Blender (Cycles CPU, no GPU), auto-frame the
12
+ * produced geometry, and render N standardized views — the images the CADBench
13
+ * criteria judge scores. The authoring directive is the GEPA-optimizable surface.
14
+ *
15
+ * Requires `blender` + `xvfb-run` on PATH (apt blender 4.x). No GPU: Cycles CPU
16
+ * with denoising off (the apt build ships without OpenImageDenoise).
17
+ */
18
+ const execFileAsync = promisify(execFile);
19
+ async function runLocal(cmd, args, cwd, timeoutMs = 18e4) {
20
+ try {
21
+ const { stdout, stderr } = await execFileAsync(cmd, args, {
22
+ cwd,
23
+ maxBuffer: 1 << 26,
24
+ timeout: timeoutMs
25
+ });
26
+ return {
27
+ code: 0,
28
+ stdout,
29
+ stderr
30
+ };
31
+ } catch (err) {
32
+ const e = err;
33
+ return {
34
+ code: typeof e.code === "number" ? e.code : 1,
35
+ stdout: e.stdout ?? "",
36
+ stderr: e.stderr ?? e.message ?? String(err)
37
+ };
38
+ }
39
+ }
40
+ /**
41
+ * The standardized Blender runner (written to a temp file per run). It clears the
42
+ * scene, executes the agent's bpy script, auto-frames the produced meshes, sets
43
+ * up neutral lighting, and renders N azimuth views with Cycles CPU.
44
+ */
45
+ const RUNNER_PY = `
46
+ import bpy, sys, math, mathutils, traceback, os
47
+ agent_script, outdir, nviews = sys.argv[-3], sys.argv[-2], int(sys.argv[-1])
48
+ bpy.ops.object.select_all(action='SELECT'); bpy.ops.object.delete()
49
+ ok=True
50
+ try:
51
+ g={'bpy':bpy,'math':math,'mathutils':mathutils,'__name__':'__main__'}
52
+ exec(compile(open(agent_script).read(), agent_script, 'exec'), g)
53
+ except Exception as e:
54
+ traceback.print_exc(); print('AGENT_SCRIPT_ERROR:'+repr(e)); ok=False
55
+ meshes=[o for o in bpy.context.scene.objects if o.type=='MESH']
56
+ if not meshes:
57
+ print('NO_MESH'); sys.exit(0 if ok else 3)
58
+ mn=[1e18]*3; mx=[-1e18]*3
59
+ for o in meshes:
60
+ for c in o.bound_box:
61
+ w=o.matrix_world @ mathutils.Vector(c)
62
+ for i in range(3): mn[i]=min(mn[i],w[i]); mx[i]=max(mx[i],w[i])
63
+ center=mathutils.Vector(((mn[0]+mx[0])/2,(mn[1]+mx[1])/2,(mn[2]+mx[2])/2))
64
+ size=max(mx[i]-mn[i] for i in range(3)) or 1.0
65
+ # standardize: drop any agent-added cameras/lights
66
+ for o in list(bpy.context.scene.objects):
67
+ if o.type in ('CAMERA','LIGHT'): bpy.data.objects.remove(o, do_unlink=True)
68
+ w=bpy.context.scene.world or bpy.data.worlds.new('W'); bpy.context.scene.world=w
69
+ w.use_nodes=True
70
+ try: w.node_tree.nodes['Background'].inputs[1].default_value=0.6
71
+ except Exception: pass
72
+ bpy.ops.object.light_add(type='SUN'); sun=bpy.context.object; sun.data.energy=4.0; sun.rotation_euler=mathutils.Euler((0.6,0.2,0.4))
73
+ bpy.ops.object.camera_add(); cam=bpy.context.object; bpy.context.scene.camera=cam
74
+ sc=bpy.context.scene
75
+ sc.render.engine='CYCLES'; sc.cycles.samples=20; sc.cycles.device='CPU'; sc.cycles.use_denoising=False
76
+ sc.render.resolution_x=640; sc.render.resolution_y=640; sc.render.film_transparent=False
77
+ dist=size*2.4
78
+ el=math.radians(58)
79
+ for v in range(nviews):
80
+ az=math.radians(40 + v*360.0/nviews)
81
+ cam.location=center+mathutils.Vector((math.cos(az)*math.sin(el), math.sin(az)*math.sin(el), math.cos(el)))*dist
82
+ d=(center-cam.location); cam.rotation_euler=d.to_track_quat('-Z','Y').to_euler()
83
+ sc.render.filepath=os.path.join(outdir, 'view_%d.png'%v); bpy.ops.render.render(write_still=True)
84
+ print('RENDER_DONE')
85
+ `.trim();
86
+ /** Execute a bpy script headless + render N standardized views — no authoring.
87
+ * Used by the CADBench judge to render an artifact before vision-scoring it. */
88
+ async function renderBpy(script, opts = {}) {
89
+ const views = Math.max(1, opts.views ?? 4);
90
+ const dir = await mkdtemp(join(tmpdir(), "blender-judge-"));
91
+ const runnerPath = join(dir, "runner.py");
92
+ const scriptPath = join(dir, "model.py");
93
+ try {
94
+ await writeFile(runnerPath, RUNNER_PY);
95
+ await writeFile(scriptPath, script);
96
+ const run = await runLocal("xvfb-run", [
97
+ "-a",
98
+ "blender",
99
+ "--background",
100
+ "--python",
101
+ runnerPath,
102
+ "--",
103
+ scriptPath,
104
+ dir,
105
+ String(views)
106
+ ], dir);
107
+ const out = `${run.stdout}\n${run.stderr}`;
108
+ if (!/RENDER_DONE/.test(out)) return {
109
+ built: false,
110
+ renders: [],
111
+ error: /(AGENT_SCRIPT_ERROR:.*|NO_MESH)/.exec(out)?.[0] ?? out.trim().slice(-400)
112
+ };
113
+ const renders = [];
114
+ for (let v = 0; v < views; v++) {
115
+ const buf = await readFile(join(dir, `view_${v}.png`)).catch(() => void 0);
116
+ if (buf) renders.push(`data:image/png;base64,${buf.toString("base64")}`);
117
+ }
118
+ return {
119
+ built: renders.length > 0,
120
+ renders
121
+ };
122
+ } finally {
123
+ await rm(dir, {
124
+ recursive: true,
125
+ force: true
126
+ }).catch(() => {});
127
+ }
128
+ }
129
+ //#endregion
130
+ //#region src/benchmarks/cadbench.ts
131
+ /**
132
+ * CADBench / BlenderLLM adapter (FreedomIntelligence/CADBench, arXiv:2412.14203).
133
+ * Task = NL instruction → a Blender `bpy` script. Score = the paper's criteria
134
+ * eval: render the produced model to standardized views, then a vision judge
135
+ * (GPT-4o-class) marks each per-task criterion bullet pass/fail against the
136
+ * rendered images + the script text. score = fraction of criteria satisfied.
137
+ *
138
+ * Data: the published dataset's `criteria` flattened to a bullet list (700 tasks,
139
+ * 500 Simulative + 200 Wild). Point CADBENCH_PATH at the cleaned JSONL
140
+ * ({id,name,instruction,type,criteria:string[]} per line). Judge creds from
141
+ * TANGLE_API_KEY / ROUTER_BASE / JUDGE_MODEL (default gpt-4o).
142
+ */
143
+ function must(name) {
144
+ const v = process.env[name];
145
+ if (!v) throw new Error(`env ${name} is required for the CADBench judge`);
146
+ return v;
147
+ }
148
+ /** One batched vision call: rendered views + the bpy script + the numbered
149
+ * criteria → a JSON array of booleans (true = satisfied). Faithful to the
150
+ * paper's combined image+script evaluation. Throws on transport failure (never
151
+ * a silent zero); a parse miss falls back to "all fail" with a note. */
152
+ async function judgeCriteria(instruction, script, criteria, renders) {
153
+ const base = (process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1").replace(/\/$/, "");
154
+ const key = must("TANGLE_API_KEY");
155
+ const model = process.env.JUDGE_MODEL ?? "deepseek-v4-flash";
156
+ const numbered = criteria.map((c, i) => `${i + 1}. ${c}`).join("\n");
157
+ const content = [{
158
+ type: "text",
159
+ text: `You are strictly grading a 3D model that was built by a Blender bpy script for this instruction:\n"${instruction}"\n\nBelow are ${renders.length} rendered views of the produced model, and the script that built it. For EACH numbered criterion, decide whether it is satisfied (judge geometry/shape/proportion/structure from the IMAGES; judge color/size/material reasonableness from the SCRIPT where the images are ambiguous). Return ONLY a JSON array of exactly ${criteria.length} booleans (true=satisfied, false=not), in order, no prose.\n\nCRITERIA:\n${numbered}\n\nSCRIPT:\n\`\`\`python\n${script.slice(0, 6e3)}\n\`\`\``
160
+ }];
161
+ for (const url of renders) content.push({
162
+ type: "image_url",
163
+ image_url: { url }
164
+ });
165
+ const res = await fetch(`${base}/chat/completions`, {
166
+ method: "POST",
167
+ headers: {
168
+ "content-type": "application/json",
169
+ authorization: `Bearer ${key}`
170
+ },
171
+ body: JSON.stringify({
172
+ model,
173
+ max_tokens: 1500,
174
+ temperature: 0,
175
+ messages: [{
176
+ role: "user",
177
+ content
178
+ }]
179
+ })
180
+ });
181
+ if (!res.ok) throw new Error(`judge ${model} ${res.status}: ${(await res.text()).slice(0, 200)}`);
182
+ const raw = (await res.json()).choices?.[0]?.message?.content ?? "";
183
+ const m = /\[\s*(?:true|false)[\s\S]*?\]/i.exec(raw);
184
+ if (!m) return {
185
+ passed: criteria.map(() => false),
186
+ note: `judge returned no parseable verdict: ${raw.slice(0, 80)}`
187
+ };
188
+ let arr;
189
+ try {
190
+ arr = JSON.parse(m[0].toLowerCase());
191
+ } catch {
192
+ return {
193
+ passed: criteria.map(() => false),
194
+ note: "judge verdict not valid JSON"
195
+ };
196
+ }
197
+ const bools = Array.isArray(arr) ? arr.map((x) => x === true) : [];
198
+ const passed = criteria.map((_, i) => bools[i] === true);
199
+ return {
200
+ passed,
201
+ note: `${passed.filter(Boolean).length}/${criteria.length} criteria`
202
+ };
203
+ }
204
+ function createCadBenchAdapter() {
205
+ let cache = null;
206
+ async function load() {
207
+ if (cache) return cache;
208
+ const path = process.env.CADBENCH_PATH;
209
+ if (!path) throw new Error("CADBENCH_PATH must point at the cleaned CADBench JSONL ({id,instruction,type,criteria:[]} per line)");
210
+ cache = (await readFile(path, "utf8")).split("\n").filter((l) => l.trim()).map((l) => {
211
+ const r = JSON.parse(l);
212
+ return {
213
+ id: r.id,
214
+ instruction: r.instruction,
215
+ meta: {
216
+ name: r.name ?? "",
217
+ type: r.type ?? "",
218
+ criteria: r.criteria
219
+ }
220
+ };
221
+ });
222
+ return cache;
223
+ }
224
+ return {
225
+ name: "cadbench",
226
+ async preflight() {
227
+ const { execFile } = await import("node:child_process");
228
+ const { promisify } = await import("node:util");
229
+ const exec = promisify(execFile);
230
+ try {
231
+ await exec("xvfb-run", [
232
+ "-a",
233
+ "blender",
234
+ "--version"
235
+ ], { timeout: 3e4 });
236
+ } catch (err) {
237
+ throw new Error(`cadbench preflight failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}\nFix: install Blender + Xvfb (sudo apt-get install -y blender xvfb). The judge runs \`xvfb-run -a blender --background --python\`.`);
238
+ }
239
+ await load();
240
+ },
241
+ async loadTasks(opts = {}) {
242
+ let rows = await load();
243
+ if (opts.ids) rows = rows.filter((r) => opts.ids.includes(r.id));
244
+ const t = process.env.CADBENCH_TYPE;
245
+ if (t) rows = rows.filter((r) => r.meta.type.toLowerCase() === t.toLowerCase());
246
+ if (opts.limit != null) rows = rows.slice(0, opts.limit);
247
+ return rows.map((r) => ({
248
+ id: r.id,
249
+ prompt: r.instruction,
250
+ metadata: r.meta
251
+ }));
252
+ },
253
+ async goldArtifact() {},
254
+ async judge(task, artifact) {
255
+ const criteria = task.metadata.criteria ?? [];
256
+ if (!artifact.trim()) return {
257
+ resolved: false,
258
+ score: 0,
259
+ detail: "empty artifact"
260
+ };
261
+ if (criteria.length === 0) return {
262
+ resolved: false,
263
+ score: 0,
264
+ detail: "task has no criteria"
265
+ };
266
+ const r = await renderBpy(artifact, { views: 4 });
267
+ if (!r.built) return {
268
+ resolved: false,
269
+ score: 0,
270
+ detail: `did not build/render: ${r.error ?? "no mesh"}`
271
+ };
272
+ const { passed, note } = await judgeCriteria(task.prompt, artifact, criteria, r.renders);
273
+ const score = passed.filter(Boolean).length / criteria.length;
274
+ return {
275
+ resolved: score === 1,
276
+ score,
277
+ detail: note
278
+ };
279
+ }
280
+ };
281
+ }
282
+ //#endregion
283
+ export { createCadBenchAdapter as t };
284
+
285
+ //# sourceMappingURL=cadbench-DpQWZHp4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cadbench-DpQWZHp4.js","names":[],"sources":["../src/worker-blender.ts","../src/benchmarks/cadbench.ts"],"sourcesContent":["/**\n * BlenderLLM / CADBench worker. The deliverable for a CADBench task is a Blender\n * `bpy` Python script that builds the described 3D model. We author it via the\n * router, execute it headless in Blender (Cycles CPU, no GPU), auto-frame the\n * produced geometry, and render N standardized views — the images the CADBench\n * criteria judge scores. The authoring directive is the GEPA-optimizable surface.\n *\n * Requires `blender` + `xvfb-run` on PATH (apt blender 4.x). No GPU: Cycles CPU\n * with denoising off (the apt build ships without OpenImageDenoise).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { Span } from '@tangle-network/agent-eval'\nimport type { BenchTask } from './benchmarks/types'\nimport { DEFAULT_BLENDER_DIRECTIVE } from './directives'\nimport { runRefineLoop } from './refine-loop'\nimport { routerChatWithUsage } from '@tangle-network/agent-runtime/loops'\n\nexport { DEFAULT_BLENDER_DIRECTIVE } from './directives'\n\nconst execFileAsync = promisify(execFile)\n\nasync function runLocal(cmd: string, args: string[], cwd: string, timeoutMs = 180_000): Promise<{ code: number; stdout: string; stderr: string }> {\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, maxBuffer: 1 << 26, timeout: timeoutMs })\n return { code: 0, stdout, stderr }\n } catch (err) {\n const e = err as { code?: number; stdout?: string; stderr?: string; message?: string }\n return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '', stderr: e.stderr ?? e.message ?? String(err) }\n }\n}\n\n\n/** Strip markdown fences so we keep just the Python. */\nfunction extractPy(text: string): string {\n const fence = /```(?:python|py)?\\s*\\n([\\s\\S]*?)```/i.exec(text)\n return (fence ? fence[1] : text).trim()\n}\n\n/**\n * The standardized Blender runner (written to a temp file per run). It clears the\n * scene, executes the agent's bpy script, auto-frames the produced meshes, sets\n * up neutral lighting, and renders N azimuth views with Cycles CPU.\n */\nconst RUNNER_PY = `\nimport bpy, sys, math, mathutils, traceback, os\nagent_script, outdir, nviews = sys.argv[-3], sys.argv[-2], int(sys.argv[-1])\nbpy.ops.object.select_all(action='SELECT'); bpy.ops.object.delete()\nok=True\ntry:\n g={'bpy':bpy,'math':math,'mathutils':mathutils,'__name__':'__main__'}\n exec(compile(open(agent_script).read(), agent_script, 'exec'), g)\nexcept Exception as e:\n traceback.print_exc(); print('AGENT_SCRIPT_ERROR:'+repr(e)); ok=False\nmeshes=[o for o in bpy.context.scene.objects if o.type=='MESH']\nif not meshes:\n print('NO_MESH'); sys.exit(0 if ok else 3)\nmn=[1e18]*3; mx=[-1e18]*3\nfor o in meshes:\n for c in o.bound_box:\n w=o.matrix_world @ mathutils.Vector(c)\n for i in range(3): mn[i]=min(mn[i],w[i]); mx[i]=max(mx[i],w[i])\ncenter=mathutils.Vector(((mn[0]+mx[0])/2,(mn[1]+mx[1])/2,(mn[2]+mx[2])/2))\nsize=max(mx[i]-mn[i] for i in range(3)) or 1.0\n# standardize: drop any agent-added cameras/lights\nfor o in list(bpy.context.scene.objects):\n if o.type in ('CAMERA','LIGHT'): bpy.data.objects.remove(o, do_unlink=True)\nw=bpy.context.scene.world or bpy.data.worlds.new('W'); bpy.context.scene.world=w\nw.use_nodes=True\ntry: w.node_tree.nodes['Background'].inputs[1].default_value=0.6\nexcept Exception: pass\nbpy.ops.object.light_add(type='SUN'); sun=bpy.context.object; sun.data.energy=4.0; sun.rotation_euler=mathutils.Euler((0.6,0.2,0.4))\nbpy.ops.object.camera_add(); cam=bpy.context.object; bpy.context.scene.camera=cam\nsc=bpy.context.scene\nsc.render.engine='CYCLES'; sc.cycles.samples=20; sc.cycles.device='CPU'; sc.cycles.use_denoising=False\nsc.render.resolution_x=640; sc.render.resolution_y=640; sc.render.film_transparent=False\ndist=size*2.4\nel=math.radians(58)\nfor v in range(nviews):\n az=math.radians(40 + v*360.0/nviews)\n cam.location=center+mathutils.Vector((math.cos(az)*math.sin(el), math.sin(az)*math.sin(el), math.cos(el)))*dist\n d=(center-cam.location); cam.rotation_euler=d.to_track_quat('-Z','Y').to_euler()\n sc.render.filepath=os.path.join(outdir, 'view_%d.png'%v); bpy.ops.render.render(write_still=True)\nprint('RENDER_DONE')\n`.trim()\n\n/** Execute a bpy script headless + render N standardized views — no authoring.\n * Used by the CADBench judge to render an artifact before vision-scoring it. */\nexport async function renderBpy(script: string, opts: { views?: number } = {}): Promise<{ built: boolean; renders: string[]; error?: string }> {\n const views = Math.max(1, opts.views ?? 4)\n const dir = await mkdtemp(join(tmpdir(), 'blender-judge-'))\n const runnerPath = join(dir, 'runner.py')\n const scriptPath = join(dir, 'model.py')\n try {\n await writeFile(runnerPath, RUNNER_PY)\n await writeFile(scriptPath, script)\n const run = await runLocal('xvfb-run', ['-a', 'blender', '--background', '--python', runnerPath, '--', scriptPath, dir, String(views)], dir)\n const out = `${run.stdout}\\n${run.stderr}`\n const built = /RENDER_DONE/.test(out)\n if (!built) return { built: false, renders: [], error: (/(AGENT_SCRIPT_ERROR:.*|NO_MESH)/.exec(out)?.[0] ?? out.trim().slice(-400)) }\n const renders: string[] = []\n for (let v = 0; v < views; v++) {\n const buf = await readFile(join(dir, `view_${v}.png`)).catch(() => undefined)\n if (buf) renders.push(`data:image/png;base64,${buf.toString('base64')}`)\n }\n return { built: renders.length > 0, renders }\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {})\n }\n}\n\nexport interface BlenderLocalConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n rounds?: number\n /** N standardized views to render (CADBench uses 4). Default 4. */\n views?: number\n /** The bpy authoring directive — the GEPA-optimizable surface. */\n directive?: string\n}\n\nexport interface BlenderShot {\n /** The bpy script the agent wrote — the artifact. */\n artifact: string\n /** Rendered view PNGs as data URIs (the images the criteria judge scores). */\n renders: string[]\n trace: Span[]\n usage: { input: number; output: number }\n ok: boolean\n /** True if the script executed and produced at least one mesh. */\n built: boolean\n detail?: string\n}\n\n/**\n * Author a bpy script for the task via the router, execute + render it headless\n * in Blender, refine on execution errors across rounds. Returns the script, the\n * rendered views, a screenshot-rich trace, and real token usage.\n */\nexport async function solveBlenderLocal(task: BenchTask, cfg: BlenderLocalConfig): Promise<BlenderShot> {\n const rounds = Math.max(1, cfg.rounds ?? 2)\n const views = Math.max(1, cfg.views ?? 4)\n const directive = cfg.directive ?? DEFAULT_BLENDER_DIRECTIVE\n const trace: Span[] = []\n const runId = `cadbench-${task.id}`\n let ts = Date.now()\n const tick = () => (ts += 1)\n const usage = { input: 0, output: 0 }\n // Carried across rounds in closures (the round Artifact is the bpy script; the\n // render PNGs + built flag + lastErr persist outside the loop). usage is REAL.\n let renders: string[] = []\n let built = false\n let lastErr = ''\n\n trace.push({ spanId: 's-brief', runId, kind: 'llm', name: 'brief', model: cfg.model, messages: [{ role: 'user', content: task.prompt }], startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)\n\n // Migrated onto runRefineLoop: the mkdtemp dir (with the runner.py written once\n // in setup) is the Ctx; built (RENDER_DONE + ≥1 collected view) is the early-stop,\n // modeled as a judge so default-decide stops the loop. The round-2+ steer carries\n // lastErr + the prior script verbatim.\n const res = await runRefineLoop<string, string>({\n rounds,\n setup: async () => {\n const dir = await mkdtemp(join(tmpdir(), 'blender-'))\n await writeFile(join(dir, 'runner.py'), RUNNER_PY)\n return dir\n },\n prompt: (round, history) =>\n round === 1\n ? task.prompt\n : `Your previous bpy script failed:\\n${lastErr}\\n\\nPrevious script:\\n${history[history.length - 1]?.artifact ?? ''}\\n\\nFix it so it runs under \\`blender --background --python\\` and builds the object as mesh(es). Brief:\\n${task.prompt}`,\n runShot: async (user, round, dir) => {\n const runnerPath = join(dir, 'runner.py')\n const scriptPath = join(dir, 'model.py')\n const { content, usage: u } = await routerChatWithUsage(\n cfg,\n [\n { role: 'system', content: directive },\n { role: 'user', content: user },\n ],\n { temperature: 0.3 },\n )\n if (u) {\n usage.input += u.input\n usage.output += u.output\n }\n const script = extractPy(content)\n trace.push({ spanId: `s-author-${round}`, runId, kind: 'llm', name: `author r${round}`, model: cfg.model, messages: [{ role: 'user', content: round === 1 ? task.prompt : 'refine' }], output: content.slice(0, 600), startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)\n trace.push({ spanId: `s-write-${round}`, runId, kind: 'tool', name: 'write_file', toolName: 'create_file', args: { path: 'model.py', content: script }, startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)\n\n await writeFile(scriptPath, script)\n const run = await runLocal('xvfb-run', ['-a', 'blender', '--background', '--python', runnerPath, '--', scriptPath, dir, String(views)], dir)\n const out = `${run.stdout}\\n${run.stderr}`\n built = /RENDER_DONE/.test(out)\n lastErr = built ? '' : (/(AGENT_SCRIPT_ERROR:.*|NO_MESH)/.exec(out)?.[0] ?? out.trim().slice(-800))\n trace.push({ spanId: `s-blender-${round}`, runId, kind: 'tool', name: `blender r${round}`, toolName: 'shell.exec', args: 'blender --background --python runner.py model.py', result: (built ? 'RENDER_DONE' : lastErr).slice(0, 1500), startedAt: tick(), endedAt: tick(), status: built ? 'ok' : 'error', error: built ? undefined : `exit ${run.code}` } as Span)\n\n if (built) {\n const collected: string[] = []\n for (let v = 0; v < views; v++) {\n const buf = await readFile(join(dir, `view_${v}.png`)).catch(() => undefined)\n if (buf) collected.push(`data:image/png;base64,${buf.toString('base64')}`)\n }\n renders = collected\n // first view carries the screen span (run-capsule reveal)\n trace.push({ spanId: `s-render-${round}`, runId, kind: 'tool', name: 'render', toolName: 'render.screenshot', args: { action: 'rendered model', url: 'view_0.png' }, attributes: collected[0] ? { screenshot: collected[0] } : {}, startedAt: tick(), endedAt: tick(), status: collected.length ? 'ok' : 'error', error: collected.length ? undefined : 'render produced no image' } as Span)\n built = collected.length > 0\n }\n return { artifact: script }\n },\n judge: async () => ({ valid: built }),\n teardown: (dir) => rm(dir, { recursive: true, force: true }).then(() => {}, () => {}),\n })\n\n const script = res.final.artifact\n return {\n artifact: script,\n renders,\n trace,\n usage,\n ok: script.trim().length > 0,\n built,\n detail: built ? `built + rendered ${renders.length} views` : `did not build in ${rounds} rounds${lastErr ? `; last: ${lastErr.slice(0, 140)}` : ''}`,\n }\n}\n","/**\n * CADBench / BlenderLLM adapter (FreedomIntelligence/CADBench, arXiv:2412.14203).\n * Task = NL instruction → a Blender `bpy` script. Score = the paper's criteria\n * eval: render the produced model to standardized views, then a vision judge\n * (GPT-4o-class) marks each per-task criterion bullet pass/fail against the\n * rendered images + the script text. score = fraction of criteria satisfied.\n *\n * Data: the published dataset's `criteria` flattened to a bullet list (700 tasks,\n * 500 Simulative + 200 Wild). Point CADBENCH_PATH at the cleaned JSONL\n * ({id,name,instruction,type,criteria:string[]} per line). Judge creds from\n * TANGLE_API_KEY / ROUTER_BASE / JUDGE_MODEL (default gpt-4o).\n */\n\nimport { readFile } from 'node:fs/promises'\nimport type { BenchScore, BenchTask, BenchmarkAdapter, LoadOptions } from './types'\nimport { renderBpy } from '../worker-blender'\n\ninterface CadBenchMeta {\n name: string\n type: string\n criteria: string[]\n}\n\nfunction must(name: string): string {\n const v = process.env[name]\n if (!v) throw new Error(`env ${name} is required for the CADBench judge`)\n return v\n}\n\n/** One batched vision call: rendered views + the bpy script + the numbered\n * criteria → a JSON array of booleans (true = satisfied). Faithful to the\n * paper's combined image+script evaluation. Throws on transport failure (never\n * a silent zero); a parse miss falls back to \"all fail\" with a note. */\nasync function judgeCriteria(\n instruction: string,\n script: string,\n criteria: string[],\n renders: string[],\n): Promise<{ passed: boolean[]; note: string }> {\n const base = (process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1').replace(/\\/$/, '')\n const key = must('TANGLE_API_KEY')\n const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'\n const numbered = criteria.map((c, i) => `${i + 1}. ${c}`).join('\\n')\n const text =\n `You are strictly grading a 3D model that was built by a Blender bpy script for this instruction:\\n\"${instruction}\"\\n\\n` +\n `Below are ${renders.length} rendered views of the produced model, and the script that built it. ` +\n `For EACH numbered criterion, decide whether it is satisfied (judge geometry/shape/proportion/structure from the IMAGES; judge color/size/material reasonableness from the SCRIPT where the images are ambiguous). ` +\n `Return ONLY a JSON array of exactly ${criteria.length} booleans (true=satisfied, false=not), in order, no prose.\\n\\nCRITERIA:\\n${numbered}\\n\\nSCRIPT:\\n\\`\\`\\`python\\n${script.slice(0, 6000)}\\n\\`\\`\\``\n const content: unknown[] = [{ type: 'text', text }]\n for (const url of renders) content.push({ type: 'image_url', image_url: { url } })\n const res = await fetch(`${base}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },\n body: JSON.stringify({ model, max_tokens: 1500, temperature: 0, messages: [{ role: 'user', content }] }),\n })\n if (!res.ok) throw new Error(`judge ${model} ${res.status}: ${(await res.text()).slice(0, 200)}`)\n const data = (await res.json()) as { choices?: Array<{ message?: { content?: string } }> }\n const raw = data.choices?.[0]?.message?.content ?? ''\n const m = /\\[\\s*(?:true|false)[\\s\\S]*?\\]/i.exec(raw)\n if (!m) return { passed: criteria.map(() => false), note: `judge returned no parseable verdict: ${raw.slice(0, 80)}` }\n let arr: unknown\n try {\n arr = JSON.parse(m[0].toLowerCase())\n } catch {\n return { passed: criteria.map(() => false), note: 'judge verdict not valid JSON' }\n }\n const bools = Array.isArray(arr) ? arr.map((x) => x === true) : []\n // Pad/truncate to criteria length (a short array scores the missing as fail).\n const passed = criteria.map((_, i) => bools[i] === true)\n return { passed, note: `${passed.filter(Boolean).length}/${criteria.length} criteria` }\n}\n\nexport function createCadBenchAdapter(): BenchmarkAdapter {\n let cache: Array<{ id: string; instruction: string; meta: CadBenchMeta }> | null = null\n\n async function load(): Promise<typeof cache & object> {\n if (cache) return cache\n const path = process.env.CADBENCH_PATH\n if (!path) throw new Error('CADBENCH_PATH must point at the cleaned CADBench JSONL ({id,instruction,type,criteria:[]} per line)')\n const text = await readFile(path, 'utf8')\n cache = text\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => {\n const r = JSON.parse(l) as { id: string; name?: string; instruction: string; type?: string; criteria: string[] }\n return { id: r.id, instruction: r.instruction, meta: { name: r.name ?? '', type: r.type ?? '', criteria: r.criteria } }\n })\n return cache\n }\n\n return {\n name: 'cadbench',\n\n async preflight() {\n const { execFile } = await import('node:child_process')\n const { promisify } = await import('node:util')\n const exec = promisify(execFile)\n try {\n await exec('xvfb-run', ['-a', 'blender', '--version'], { timeout: 30_000 })\n } catch (err) {\n throw new Error(\n `cadbench preflight failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}\\n` +\n `Fix: install Blender + Xvfb (sudo apt-get install -y blender xvfb). The judge runs \\`xvfb-run -a blender --background --python\\`.`,\n )\n }\n await load()\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let rows = await load()\n if (opts.ids) rows = rows.filter((r) => opts.ids!.includes(r.id))\n // TYPE filter (Simulative|Wild) via env, applied before limit.\n const t = process.env.CADBENCH_TYPE\n if (t) rows = rows.filter((r) => r.meta.type.toLowerCase() === t.toLowerCase())\n if (opts.limit != null) rows = rows.slice(0, opts.limit)\n return rows.map((r): BenchTask => ({ id: r.id, prompt: r.instruction, metadata: r.meta as unknown as Record<string, unknown> }))\n },\n\n async goldArtifact() {\n return undefined // no reference bpy script ships with the benchmark\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = task.metadata as unknown as CadBenchMeta\n const criteria = meta.criteria ?? []\n if (!artifact.trim()) return { resolved: false, score: 0, detail: 'empty artifact' }\n if (criteria.length === 0) return { resolved: false, score: 0, detail: 'task has no criteria' }\n const r = await renderBpy(artifact, { views: 4 })\n if (!r.built) return { resolved: false, score: 0, detail: `did not build/render: ${r.error ?? 'no mesh'}` }\n const { passed, note } = await judgeCriteria(task.prompt, artifact, criteria, r.renders)\n const score = passed.filter(Boolean).length / criteria.length\n return { resolved: score === 1, score, detail: note }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,MAAM,gBAAgB,UAAU,QAAQ;AAExC,eAAe,SAAS,KAAa,MAAgB,KAAa,YAAY,MAAoE;CAChJ,IAAI;EACF,MAAM,EAAE,QAAQ,WAAW,MAAM,cAAc,KAAK,MAAM;GAAE;GAAK,WAAW,KAAK;GAAI,SAAS;EAAU,CAAC;EACzG,OAAO;GAAE,MAAM;GAAG;GAAQ;EAAO;CACnC,SAAS,KAAK;EACZ,MAAM,IAAI;EACV,OAAO;GAAE,MAAM,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO;GAAG,QAAQ,EAAE,UAAU;GAAI,QAAQ,EAAE,UAAU,EAAE,WAAW,OAAO,GAAG;EAAE;CAC/H;AACF;;;;;;AAcA,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwChB,KAAK;;;AAIP,eAAsB,UAAU,QAAgB,OAA2B,CAAC,GAAmE;CAC7I,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,SAAS,CAAC;CACzC,MAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,GAAG,gBAAgB,CAAC;CAC1D,MAAM,aAAa,KAAK,KAAK,WAAW;CACxC,MAAM,aAAa,KAAK,KAAK,UAAU;CACvC,IAAI;EACF,MAAM,UAAU,YAAY,SAAS;EACrC,MAAM,UAAU,YAAY,MAAM;EAClC,MAAM,MAAM,MAAM,SAAS,YAAY;GAAC;GAAM;GAAW;GAAgB;GAAY;GAAY;GAAM;GAAY;GAAK,OAAO,KAAK;EAAC,GAAG,GAAG;EAC3I,MAAM,MAAM,GAAG,IAAI,OAAO,IAAI,IAAI;EAElC,IAAI,CADU,cAAc,K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K,SACI,YAAY,CAAC;GACnC,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;IAAE,UAAU;IAAO,OAAO;IAAG,QAAQ;GAAiB;GACnF,IAAI,SAAS,WAAW,GAAG,OAAO;IAAE,UAAU;IAAO,OAAO;IAAG,QAAQ;GAAuB;GAC9F,MAAM,IAAI,MAAM,UAAU,UAAU,EAAE,OAAO,EAAE,CAAC;GAChD,IAAI,CAAC,EAAE,OAAO,OAAO;IAAE,UAAU;IAAO,OAAO;IAAG,QAAQ,yBAAyB,EAAE,SAAS;GAAY;GAC1G,MAAM,EAAE,QAAQ,SAAS,MAAM,cAAc,KAAK,QAAQ,UAAU,UAAU,EAAE,OAAO;GACvF,MAAM,QAAQ,OAAO,OAAO,OAAO,CAAC,CAAC,SAAS,SAAS;GACvD,OAAO;IAAE,UAAU,UAAU;IAAG;IAAO,QAAQ;GAAK;EACtD;CACF;AACF"}
@@ -0,0 +1,151 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { promisify } from "node:util";
7
+ import "@tangle-network/agent-runtime/loops";
8
+ promisify(execFile);
9
+ const CGB_VENV_PY = process.env.CADGENBENCH_VENV ?? "/tmp/cgb-venv/bin/python";
10
+ const CGB_DIR = process.env.CADGENBENCH_DIR ?? "/tmp/cadgenbench";
11
+ //#endregion
12
+ //#region src/benchmarks/cadgenbench.ts
13
+ /**
14
+ * CADGenBench adapter (huggingface/cadgenbench, Apache-2.0). Task = a part
15
+ * description → a STEP B-rep solid (output.step). Score = the benchmark's OWN
16
+ * deterministic geometric metric (cad_score): validity gate → PCA/ICP align to
17
+ * the ground truth → point-cloud F1 + volume IoU + edge F1 + topology match.
18
+ * NOT an LLM judge, NOT self-defined checks — the published CAD kernel decides.
19
+ *
20
+ * The official task set (private GT, server-side graded) isn't released yet, so
21
+ * tasks here are seeded from the repo's dimension-named geometry fixtures (real
22
+ * GT STEPs scored by the real scorer). When CADGENBENCH_DATA_DIR is set, swap
23
+ * loadTasks to read the published fixtures' description.yaml + ground_truth.step.
24
+ *
25
+ * Requires the CADGenBench venv (CADGENBENCH_VENV) + clone (CADGENBENCH_DIR) +
26
+ * xvfb (the scorer's alignment renders need a display).
27
+ */
28
+ const execFileAsync = promisify(execFile);
29
+ /** Self-contained scorer wrapper (written to a temp file, run in the venv).
30
+ * Scores a candidate STEP against a ground-truth STEP via the benchmark's own
31
+ * evaluate_result, printing the cad_score line. */
32
+ const SCORE_PY = `
33
+ import sys, json, tempfile, shutil
34
+ from pathlib import Path
35
+ from cadgenbench.eval.evaluate import evaluate_result
36
+ cand, gt = Path(sys.argv[1]), Path(sys.argv[2])
37
+ with tempfile.TemporaryDirectory() as rd, tempfile.TemporaryDirectory() as gd:
38
+ rd, gd = Path(rd), Path(gd)
39
+ (rd / 'result.json').write_text('{}')
40
+ shutil.copy(gt, gd / 'ground_truth.step')
41
+ try:
42
+ evaluate_result(rd, gd, candidate_step=cand)
43
+ d = json.loads((rd / 'result.json').read_text())
44
+ print('CGB_SCORE ' + json.dumps({'cad_score': d.get('cad_score', 0.0), 'status': d.get('status', 'unknown')}))
45
+ except Exception as e:
46
+ print('CGB_SCORE ' + json.dumps({'cad_score': 0.0, 'status': 'error', 'error': str(e)[:200]}))
47
+ `.trim();
48
+ /** Fixture-seeded tasks (real GT STEPs from the repo, dim-named so the spec is
49
+ * exact). Replaced by the published dataset when CADGENBENCH_DATA_DIR is set. */
50
+ function fixtureTasks() {
51
+ const g = join(CGB_DIR, "tests/fixtures/geometry");
52
+ return [
53
+ {
54
+ id: "box-10x20x30",
55
+ prompt: "A rectangular solid box, 10 units wide (X), 20 units deep (Y), and 30 units tall (Z).",
56
+ gtStep: join(g, "box_10_20_30.step")
57
+ },
58
+ {
59
+ id: "cube-10",
60
+ prompt: "A cube, 10 units on every side.",
61
+ gtStep: join(g, "box_10_10_10.step")
62
+ },
63
+ {
64
+ id: "sphere-10",
65
+ prompt: "A sphere of radius 10 units, centered at the origin.",
66
+ gtStep: join(g, "sphere_10.step")
67
+ }
68
+ ];
69
+ }
70
+ function createCadGenBenchAdapter() {
71
+ return {
72
+ name: "cadgenbench",
73
+ async preflight() {
74
+ const r = await execFileAsync(CGB_VENV_PY, ["-c", "import cadgenbench.eval.evaluate, build123d, trimesh, manifold3d; print(\"ok\")"], { timeout: 6e4 }).catch((e) => ({
75
+ stdout: "",
76
+ stderr: e instanceof Error ? e.message : String(e)
77
+ }));
78
+ if (!/ok/.test(r.stdout)) throw new Error(`cadgenbench preflight failed (venv=${CGB_VENV_PY}): ${r.stderr.slice(0, 200)}\nFix: git clone https://github.com/huggingface/cadgenbench ${CGB_DIR}; python3 -m venv $CADGENBENCH_VENV; $CADGENBENCH_VENV/bin/pip install -e ${CGB_DIR}`);
79
+ },
80
+ async loadTasks(opts = {}) {
81
+ let tasks = fixtureTasks();
82
+ const hard = process.env.CGB_HARD_DIR;
83
+ if (hard) {
84
+ const { readFile } = await import("node:fs/promises");
85
+ tasks = JSON.parse(await readFile(join(hard, "tasks.json"), "utf8"));
86
+ }
87
+ if (opts.ids) tasks = tasks.filter((t) => opts.ids.includes(t.id));
88
+ if (opts.limit != null) tasks = tasks.slice(0, opts.limit);
89
+ const meta = (gtStep) => ({
90
+ gtStep,
91
+ resolveThreshold: Number(process.env.CGB_RESOLVE_THRESHOLD ?? .9)
92
+ });
93
+ return tasks.map((t) => ({
94
+ id: t.id,
95
+ prompt: t.prompt,
96
+ metadata: meta(t.gtStep)
97
+ }));
98
+ },
99
+ async goldArtifact() {},
100
+ async judge(task, artifact) {
101
+ const { gtStep, resolveThreshold } = task.metadata;
102
+ if (!artifact.includes("ISO-10303-21")) return {
103
+ resolved: false,
104
+ score: 0,
105
+ detail: "artifact is not a STEP file"
106
+ };
107
+ const dir = await mkdtemp(join(tmpdir(), "cgb-judge-"));
108
+ const cand = join(dir, "candidate.step");
109
+ const scorer = join(dir, "score.py");
110
+ try {
111
+ await writeFile(cand, artifact);
112
+ await writeFile(scorer, SCORE_PY);
113
+ const r = await execFileAsync("xvfb-run", [
114
+ "-a",
115
+ CGB_VENV_PY,
116
+ scorer,
117
+ cand,
118
+ gtStep
119
+ ], {
120
+ maxBuffer: 1 << 26,
121
+ timeout: 18e4
122
+ }).catch((e) => ({
123
+ stdout: e.stdout ?? "",
124
+ stderr: e instanceof Error ? e.message : String(e)
125
+ }));
126
+ const m = /CGB_SCORE (\{.*\})/.exec(r.stdout);
127
+ if (!m) return {
128
+ resolved: false,
129
+ score: 0,
130
+ detail: `scorer produced no verdict: ${(r.stderr || r.stdout).slice(0, 160)}`
131
+ };
132
+ const v = JSON.parse(m[1]);
133
+ const score = typeof v.cad_score === "number" ? v.cad_score : 0;
134
+ return {
135
+ resolved: score >= resolveThreshold,
136
+ score,
137
+ detail: `cad_score=${score.toFixed(3)} status=${v.status}${v.error ? ` (${v.error})` : ""}`
138
+ };
139
+ } finally {
140
+ await rm(dir, {
141
+ recursive: true,
142
+ force: true
143
+ }).catch(() => {});
144
+ }
145
+ }
146
+ };
147
+ }
148
+ //#endregion
149
+ export { createCadGenBenchAdapter as t };
150
+
151
+ //# sourceMappingURL=cadgenbench-DRhczfsG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cadgenbench-DRhczfsG.js","names":["execFileAsync"],"sources":["../src/worker-build123d.ts","../src/benchmarks/cadgenbench.ts"],"sourcesContent":["/**\n * CADGenBench worker. The deliverable is a STEP B-rep solid (output.step). We\n * author a build123d (Python on the OpenCascade kernel) script via the router,\n * execute it in the CADGenBench venv, and read back the produced output.step —\n * exactly the reference baseline's contract. The artifact returned IS the STEP\n * text, which the CADGenBench geometric scorer grades against the ground truth.\n *\n * The build123d authoring directive is the GEPA-optimizable surface; the\n * build123d API cheat sheet (shipped in the cadgenbench package) is appended as\n * fixed reference context. Requires the CADGenBench venv (CADGENBENCH_VENV) +\n * its clone (CADGENBENCH_DIR for the cheat sheet).\n */\n\nimport { execFile } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { Span } from '@tangle-network/agent-eval'\nimport type { BenchTask } from './benchmarks/types'\nimport { DEFAULT_BUILD123D_DIRECTIVE } from './directives'\nimport { runRefineLoop } from './refine-loop'\nimport { routerChatWithUsage } from '@tangle-network/agent-runtime/loops'\n\nexport { DEFAULT_BUILD123D_DIRECTIVE } from './directives'\n\nconst execFileAsync = promisify(execFile)\n\nexport const CGB_VENV_PY = process.env.CADGENBENCH_VENV ?? '/tmp/cgb-venv/bin/python'\nexport const CGB_DIR = process.env.CADGENBENCH_DIR ?? '/tmp/cadgenbench'\n\nasync function runLocal(cmd: string, args: string[], cwd: string, timeoutMs = 120_000): Promise<{ code: number; stdout: string; stderr: string }> {\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, maxBuffer: 1 << 26, timeout: timeoutMs })\n return { code: 0, stdout, stderr }\n } catch (err) {\n const e = err as { code?: number; stdout?: string; stderr?: string; message?: string }\n return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '', stderr: e.stderr ?? e.message ?? String(err) }\n }\n}\n\nfunction extractPy(text: string): string {\n const fence = /```(?:python|py)?\\s*\\n([\\s\\S]*?)```/i.exec(text)\n return (fence ? fence[1] : text).trim()\n}\n\nlet _cheat: string | null = null\nfunction cheatSheet(): string {\n if (_cheat != null) return _cheat\n const p = join(CGB_DIR, 'src/cadgenbench/baseline/build123d_cheat_sheet.md')\n _cheat = existsSync(p) ? readFileSync(p, 'utf8').slice(0, 12000) : ''\n return _cheat\n}\n\nexport interface Build123dConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n rounds?: number\n /** The build123d authoring directive — the GEPA-optimizable surface. */\n directive?: string\n}\n\nexport interface Build123dShot {\n /** The produced STEP text (the artifact the CADGenBench scorer grades). */\n artifact: string\n /** The Python source the agent wrote. */\n source: string\n trace: Span[]\n usage: { input: number; output: number }\n ok: boolean\n built: boolean\n detail?: string\n}\n\n/** Author a build123d script via the router, execute it in the CADGenBench venv,\n * read back output.step. Refine on execution error / missing STEP. */\nexport async function solveBuild123dLocal(task: BenchTask, cfg: Build123dConfig): Promise<Build123dShot> {\n const rounds = Math.max(1, cfg.rounds ?? 2)\n const directive = cfg.directive ?? DEFAULT_BUILD123D_DIRECTIVE\n const sys = `${directive}\\n\\nbuild123d API reference:\\n${cheatSheet()}`\n const trace: Span[] = []\n const runId = `cadgenbench-${task.id}`\n let ts = Date.now()\n const tick = () => (ts += 1)\n const usage = { input: 0, output: 0 }\n // Carried across rounds in closures (the round Artifact is the Python source; the\n // STEP text + built flag + lastErr persist outside the loop). usage is REAL.\n let step = ''\n let built = false\n let lastErr = ''\n\n trace.push({ spanId: 's-brief', runId, kind: 'llm', name: 'brief', model: cfg.model, messages: [{ role: 'user', content: task.prompt }], startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)\n\n // Migrated onto runRefineLoop: the mkdtemp scratch dir is the Ctx; built (STEP\n // produced) is the early-stop, modeled as a judge so default-decide stops the\n // loop. The round-2+ steer carries lastErr + the prior source verbatim.\n const res = await runRefineLoop<string, string>({\n rounds,\n setup: () => mkdtemp(join(tmpdir(), 'b123d-')),\n prompt: (round, history) =>\n round === 1\n ? task.prompt\n : `Your previous build123d script failed:\\n${lastErr}\\n\\nPrevious script:\\n${history[history.length - 1]?.artifact ?? ''}\\n\\nFix it so it runs in python and writes a valid output.step. Brief:\\n${task.prompt}`,\n runShot: async (user, round, dir) => {\n const scriptPath = join(dir, 'build.py')\n const stepPath = join(dir, 'output.step')\n const { content, usage: u } = await routerChatWithUsage(cfg, [\n { role: 'system', content: sys },\n { role: 'user', content: user },\n ])\n if (u) {\n usage.input += u.input\n usage.output += u.output\n }\n const source = extractPy(content)\n trace.push({ spanId: `s-author-${round}`, runId, kind: 'llm', name: `author r${round}`, model: cfg.model, messages: [{ role: 'user', content: round === 1 ? task.prompt : 'refine' }], output: content.slice(0, 600), startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)\n trace.push({ spanId: `s-write-${round}`, runId, kind: 'tool', name: 'write_file', toolName: 'create_file', args: { path: 'build.py', content: source }, startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)\n\n await writeFile(scriptPath, source)\n const run = await runLocal(CGB_VENV_PY, [scriptPath], dir)\n const got = existsSync(stepPath) ? await readFile(stepPath, 'utf8').catch(() => '') : ''\n built = got.includes('ISO-10303-21') && got.length > 200\n lastErr = built ? '' : `${run.stdout}\\n${run.stderr}`.trim().slice(-800) || 'no output.step written'\n if (built) step = got\n trace.push({ spanId: `s-exec-${round}`, runId, kind: 'tool', name: `build123d r${round}`, toolName: 'shell.exec', args: 'python build.py', result: (built ? 'wrote output.step' : lastErr).slice(0, 1500), startedAt: tick(), endedAt: tick(), status: built ? 'ok' : 'error', error: built ? undefined : `exit ${run.code}` } as Span)\n return { artifact: source }\n },\n judge: async () => ({ valid: built }),\n teardown: (dir) => rm(dir, { recursive: true, force: true }).then(() => {}, () => {}),\n })\n\n return {\n artifact: step,\n source: res.final.artifact,\n trace,\n usage,\n ok: res.final.artifact.trim().length > 0,\n built,\n detail: built ? 'exported output.step' : `did not produce a STEP in ${rounds} rounds${lastErr ? `; last: ${lastErr.slice(0, 140)}` : ''}`,\n }\n}\n","/**\n * CADGenBench adapter (huggingface/cadgenbench, Apache-2.0). Task = a part\n * description → a STEP B-rep solid (output.step). Score = the benchmark's OWN\n * deterministic geometric metric (cad_score): validity gate → PCA/ICP align to\n * the ground truth → point-cloud F1 + volume IoU + edge F1 + topology match.\n * NOT an LLM judge, NOT self-defined checks — the published CAD kernel decides.\n *\n * The official task set (private GT, server-side graded) isn't released yet, so\n * tasks here are seeded from the repo's dimension-named geometry fixtures (real\n * GT STEPs scored by the real scorer). When CADGENBENCH_DATA_DIR is set, swap\n * loadTasks to read the published fixtures' description.yaml + ground_truth.step.\n *\n * Requires the CADGenBench venv (CADGENBENCH_VENV) + clone (CADGENBENCH_DIR) +\n * xvfb (the scorer's alignment renders need a display).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { BenchScore, BenchTask, BenchmarkAdapter, LoadOptions } from './types'\nimport { CGB_DIR, CGB_VENV_PY } from '../worker-build123d'\n\nconst execFileAsync = promisify(execFile)\n\n/** Self-contained scorer wrapper (written to a temp file, run in the venv).\n * Scores a candidate STEP against a ground-truth STEP via the benchmark's own\n * evaluate_result, printing the cad_score line. */\nconst SCORE_PY = `\nimport sys, json, tempfile, shutil\nfrom pathlib import Path\nfrom cadgenbench.eval.evaluate import evaluate_result\ncand, gt = Path(sys.argv[1]), Path(sys.argv[2])\nwith tempfile.TemporaryDirectory() as rd, tempfile.TemporaryDirectory() as gd:\n rd, gd = Path(rd), Path(gd)\n (rd / 'result.json').write_text('{}')\n shutil.copy(gt, gd / 'ground_truth.step')\n try:\n evaluate_result(rd, gd, candidate_step=cand)\n d = json.loads((rd / 'result.json').read_text())\n print('CGB_SCORE ' + json.dumps({'cad_score': d.get('cad_score', 0.0), 'status': d.get('status', 'unknown')}))\n except Exception as e:\n print('CGB_SCORE ' + json.dumps({'cad_score': 0.0, 'status': 'error', 'error': str(e)[:200]}))\n`.trim()\n\ninterface CgbMeta {\n gtStep: string\n resolveThreshold: number\n}\n\n/** Fixture-seeded tasks (real GT STEPs from the repo, dim-named so the spec is\n * exact). Replaced by the published dataset when CADGENBENCH_DATA_DIR is set. */\nfunction fixtureTasks(): Array<{ id: string; prompt: string; gtStep: string }> {\n const g = join(CGB_DIR, 'tests/fixtures/geometry')\n return [\n { id: 'box-10x20x30', prompt: 'A rectangular solid box, 10 units wide (X), 20 units deep (Y), and 30 units tall (Z).', gtStep: join(g, 'box_10_20_30.step') },\n { id: 'cube-10', prompt: 'A cube, 10 units on every side.', gtStep: join(g, 'box_10_10_10.step') },\n { id: 'sphere-10', prompt: 'A sphere of radius 10 units, centered at the origin.', gtStep: join(g, 'sphere_10.step') },\n ]\n}\n\nexport function createCadGenBenchAdapter(): BenchmarkAdapter {\n return {\n name: 'cadgenbench',\n\n async preflight() {\n const r = await execFileAsync(CGB_VENV_PY, ['-c', 'import cadgenbench.eval.evaluate, build123d, trimesh, manifold3d; print(\"ok\")'], { timeout: 60_000 }).catch(\n (e) => ({ stdout: '', stderr: e instanceof Error ? e.message : String(e) }),\n )\n if (!/ok/.test(r.stdout)) {\n throw new Error(\n `cadgenbench preflight failed (venv=${CGB_VENV_PY}): ${r.stderr.slice(0, 200)}\\n` +\n `Fix: git clone https://github.com/huggingface/cadgenbench ${CGB_DIR}; python3 -m venv $CADGENBENCH_VENV; $CADGENBENCH_VENV/bin/pip install -e ${CGB_DIR}`,\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n // CGB_HARD_DIR (a dir with tasks.json = [{id,prompt,gtStep}]) overrides the\n // trivial fixture primitives with hard multi-feature parts (real headroom).\n let tasks = fixtureTasks()\n const hard = process.env.CGB_HARD_DIR\n if (hard) {\n const { readFile } = await import('node:fs/promises')\n tasks = JSON.parse(await readFile(join(hard, 'tasks.json'), 'utf8')) as Array<{ id: string; prompt: string; gtStep: string }>\n }\n if (opts.ids) tasks = tasks.filter((t) => opts.ids!.includes(t.id))\n if (opts.limit != null) tasks = tasks.slice(0, opts.limit)\n const meta = (gtStep: string): CgbMeta => ({ gtStep, resolveThreshold: Number(process.env.CGB_RESOLVE_THRESHOLD ?? 0.9) })\n return tasks.map((t): BenchTask => ({ id: t.id, prompt: t.prompt, metadata: meta(t.gtStep) as unknown as Record<string, unknown> }))\n },\n\n async goldArtifact() {\n return undefined // GT is a STEP file scored by the kernel, not a returnable artifact\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const { gtStep, resolveThreshold } = task.metadata as unknown as CgbMeta\n if (!artifact.includes('ISO-10303-21')) return { resolved: false, score: 0, detail: 'artifact is not a STEP file' }\n const dir = await mkdtemp(join(tmpdir(), 'cgb-judge-'))\n const cand = join(dir, 'candidate.step')\n const scorer = join(dir, 'score.py')\n try {\n await writeFile(cand, artifact)\n await writeFile(scorer, SCORE_PY)\n // xvfb: the scorer's alignment step renders; needs a display.\n const r = await execFileAsync('xvfb-run', ['-a', CGB_VENV_PY, scorer, cand, gtStep], { maxBuffer: 1 << 26, timeout: 180_000 }).catch(\n (e) => ({ stdout: (e as { stdout?: string }).stdout ?? '', stderr: e instanceof Error ? e.message : String(e) }),\n )\n const m = /CGB_SCORE (\\{.*\\})/.exec(r.stdout)\n if (!m) return { resolved: false, score: 0, detail: `scorer produced no verdict: ${(r.stderr || r.stdout).slice(0, 160)}` }\n const v = JSON.parse(m[1]) as { cad_score: number; status: string; error?: string }\n const score = typeof v.cad_score === 'number' ? v.cad_score : 0\n return { resolved: score >= resolveThreshold, score, detail: `cad_score=${score.toFixed(3)} status=${v.status}${v.error ? ` (${v.error})` : ''}` }\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {})\n }\n },\n }\n}\n"],"mappings":";;;;;;;AA2BsB,UAAU,QAAQ;AAExC,MAAa,cAAc,QAAQ,IAAI,oBAAoB;AAC3D,MAAa,UAAU,QAAQ,IAAI,mBAAmB;;;;;;;;;;;;;;;;;;ACNtD,MAAM,gBAAgB,UAAU,QAAQ;;;;AAKxC,MAAM,WAAW;;;;;;;;;;;;;;;EAef,KAAK;;;AASP,SAAS,eAAsE;CAC7E,MAAM,IAAI,KAAK,SAAS,yBAAyB;CACjD,OAAO;EACL;GAAE,IAAI;GAAgB,QAAQ;GAAyF,QAAQ,KAAK,GAAG,mBAAmB;EAAE;EAC5J;GAAE,IAAI;GAAW,QAAQ;GAAmC,QAAQ,KAAK,GAAG,mBAAmB;EAAE;EACjG;GAAE,IAAI;GAAa,QAAQ;GAAwD,QAAQ,KAAK,GAAG,gBAAgB;EAAE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