@tangle-network/agent-bench 0.14.4 → 1.0.2
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.
- package/CHANGELOG.md +46 -0
- package/README.md +2 -3
- package/dist/adapters.d.ts +2 -5
- package/dist/adapters.js +3 -4
- package/dist/benchmarks/_harness.d.ts +17 -20
- package/dist/benchmarks/_harness.js +4 -4
- package/dist/benchmarks/_harness.js.map +1 -1
- package/dist/benchmarks/aec-bench.d.ts +1 -4
- package/dist/benchmarks/aec-bench.js +1 -2
- package/dist/benchmarks/agentbench.d.ts +2 -5
- package/dist/benchmarks/agentbench.js +1 -2
- package/dist/benchmarks/appworld.d.ts +8 -10
- package/dist/benchmarks/appworld.js +23 -23
- package/dist/benchmarks/appworld.js.map +1 -1
- package/dist/benchmarks/bfcl.d.ts +2 -5
- package/dist/benchmarks/bfcl.js +1 -2
- package/dist/benchmarks/cad-design.d.ts +2 -5
- package/dist/benchmarks/cad-design.js +2 -3
- package/dist/benchmarks/cad-design.js.map +1 -1
- package/dist/benchmarks/cadbench.d.ts +1 -4
- package/dist/benchmarks/cadbench.js +1 -2
- package/dist/benchmarks/cadgenbench.d.ts +1 -4
- package/dist/benchmarks/cadgenbench.js +1 -2
- package/dist/benchmarks/commit0.d.ts +2 -5
- package/dist/benchmarks/commit0.js +1 -2
- package/dist/benchmarks/crag.d.ts +1 -4
- package/dist/benchmarks/crag.js +3 -3
- package/dist/benchmarks/crag.js.map +1 -1
- package/dist/benchmarks/dabstep.d.ts +2 -5
- package/dist/benchmarks/dabstep.js +2 -3
- package/dist/benchmarks/dabstep.js.map +1 -1
- package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
- package/dist/benchmarks/enterpriseops-gym.js +1 -2
- package/dist/benchmarks/finresearchbench.d.ts +2 -5
- package/dist/benchmarks/finresearchbench.js +2 -3
- package/dist/benchmarks/finsearchcomp.d.ts +2 -5
- package/dist/benchmarks/finsearchcomp.js +4 -4
- package/dist/benchmarks/finsearchcomp.js.map +1 -1
- package/dist/benchmarks/frames.d.ts +3 -19
- package/dist/benchmarks/frames.js +13 -39
- package/dist/benchmarks/frames.js.map +1 -1
- package/dist/benchmarks/hotpotqa.d.ts +4 -14
- package/dist/benchmarks/hotpotqa.js +12 -32
- package/dist/benchmarks/hotpotqa.js.map +1 -1
- package/dist/benchmarks/humaneval.d.ts +9 -12
- package/dist/benchmarks/humaneval.js +2 -3
- package/dist/benchmarks/humaneval.js.map +1 -1
- package/dist/benchmarks/mcad-bench.d.ts +13 -16
- package/dist/benchmarks/mcad-bench.js +2 -3
- package/dist/benchmarks/mcad-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
- package/dist/benchmarks/mcad-cq-bench.js +2 -3
- package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
- package/dist/benchmarks/mcad-cq-golds.js +1 -2
- package/dist/benchmarks/mcad-golds.d.ts +1 -4
- package/dist/benchmarks/mcad-golds.js +0 -1
- package/dist/benchmarks/mcad-tasks.d.ts +5 -8
- package/dist/benchmarks/mcad-tasks.js +7 -8
- package/dist/benchmarks/mcad-tasks.js.map +1 -1
- package/dist/benchmarks/mind2web.d.ts +3 -5
- package/dist/benchmarks/mind2web.js +2 -3
- package/dist/benchmarks/mind2web.js.map +1 -1
- package/dist/benchmarks/nomiracl.d.ts +1 -4
- package/dist/benchmarks/nomiracl.js +1 -2
- package/dist/benchmarks/open-rag-bench.d.ts +1 -4
- package/dist/benchmarks/open-rag-bench.js +3 -3
- package/dist/benchmarks/open-rag-bench.js.map +1 -1
- package/dist/benchmarks/programbench.d.ts +2 -5
- package/dist/benchmarks/programbench.js +1 -2
- package/dist/benchmarks/rag-shared.d.ts +30 -22
- package/dist/benchmarks/rag-shared.js +8 -2
- package/dist/benchmarks/rag-shared.js.map +1 -1
- package/dist/benchmarks/ragbench.d.ts +1 -4
- package/dist/benchmarks/ragbench.js +3 -3
- package/dist/benchmarks/ragbench.js.map +1 -1
- package/dist/benchmarks/simpleqa.d.ts +2 -18
- package/dist/benchmarks/simpleqa.js +5 -31
- package/dist/benchmarks/simpleqa.js.map +1 -1
- package/dist/benchmarks/swe-bench.d.ts +7 -10
- package/dist/benchmarks/swe-bench.js +4 -4
- package/dist/benchmarks/swe-bench.js.map +1 -1
- package/dist/benchmarks/t2-ragbench.d.ts +1 -4
- package/dist/benchmarks/t2-ragbench.js +3 -3
- package/dist/benchmarks/t2-ragbench.js.map +1 -1
- package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
- package/dist/benchmarks/tau-bench-shared.js +4 -4
- package/dist/benchmarks/tau-bench-shared.js.map +1 -1
- package/dist/benchmarks/tau2-bench.d.ts +2 -5
- package/dist/benchmarks/tau2-bench.js +1 -2
- package/dist/benchmarks/tau3-banking.d.ts +1 -4
- package/dist/benchmarks/tau3-banking.js +1 -2
- package/dist/benchmarks/terminal-bench.d.ts +1 -4
- package/dist/benchmarks/terminal-bench.js +4 -4
- package/dist/benchmarks/terminal-bench.js.map +1 -1
- package/dist/benchmarks/toollm.d.ts +2 -5
- package/dist/benchmarks/toollm.js +1 -2
- package/dist/benchmarks/trata-hedge.d.ts +1 -4
- package/dist/benchmarks/trata-hedge.js +2 -3
- package/dist/benchmarks/types.d.ts +6 -9
- package/dist/benchmarks/webarena-verified.d.ts +2 -5
- package/dist/benchmarks/webarena-verified.js +1 -2
- package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
- package/dist/cadbench-DhAndllg.js.map +1 -0
- package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
- package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
- package/dist/index.d.ts +8 -18
- package/dist/index.js +16 -24
- package/dist/index.js.map +1 -1
- package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
- package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
- package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
- package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
- package/package.json +10 -10
- package/pier_agents/tangle_candidate.py +15 -23
- package/scripts/run-package-tests.mjs +8 -15
- package/src/atom-mcp-e2e.mts +2 -2
- package/src/benchmarks/frames.ts +10 -44
- package/src/benchmarks/hotpotqa.ts +9 -29
- package/src/benchmarks/rag-shared.ts +12 -0
- package/src/benchmarks/simpleqa.ts +2 -36
- package/src/commit0-prereqs.sh +0 -0
- package/src/corpus-replay.mts +8 -8
- package/src/corpus-report.mts +21 -21
- package/src/corpus.test.mts +5 -5
- package/src/corpus.ts +16 -16
- package/src/directives.ts +0 -38
- package/src/examples/lean-verify.ts +1 -1
- package/src/gate.ts +7 -7
- package/src/generate-eval/certify.ts +2 -2
- package/src/index.ts +1 -0
- package/src/refine-loop.ts +5 -5
- package/src/resolve-client.ts +1 -1
- package/src/router-turn.ts +3 -11
- package/src/run-pool.ts +1 -1
- package/src/runtime-hook-recorder.ts +2 -2
- package/src/search-bench/tasks.ts +1 -1
- package/src/selector.test.mts +13 -13
- package/src/selector.ts +19 -19
- package/src/swe-bench-env.ts +4 -12
- package/src/swe-jail.ts +5 -156
- package/src/swe-structural-judge-policy.ts +3 -3
- package/src/swe-structural-policy.ts +3 -3
- package/src/swe-structural-provenance.ts +4 -4
- package/src/terminal-compare.ts +10 -10
- package/src/worker-blender.ts +2 -106
- package/src/worker-build123d.ts +2 -81
- package/tb_agents/opencode_router_agent.py +1 -1
- package/dist/cadbench-BRF-59Mt.js.map +0 -1
- package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
- package/dist/router-turn-uTYO6KQ1.js.map +0 -1
- package/scripts/cadbench_prepare.py +0 -22
- package/scripts/cadgenbench_hard_parts.py +0 -48
- package/scripts/clbench_codebase_judge.py +0 -73
- package/scripts/render-gate-chart.mjs +0 -176
- package/scripts/trata-hedge/README.md +0 -57
- package/scripts/trata-hedge/run.sh +0 -64
- package/src/cloud-loop.mts +0 -156
- package/src/coordination-mcp-container-reach.mts +0 -182
- package/src/fleet.mts +0 -143
- package/src/hev-structural.mts +0 -697
- package/src/humaneval-gate.mts +0 -220
- package/src/mbpp-structural.mts +0 -676
- package/src/mcp-mount-probe.mts +0 -141
- package/src/profiles.ts +0 -128
- package/src/research-gate.mts +0 -132
- package/src/research-shot.ts +0 -144
- package/src/router-executor.ts +0 -51
- package/src/sandbox-run.ts +0 -108
- package/src/search-bench/bridge.ts +0 -182
- package/src/search-bench/export.mts +0 -0
- package/src/search-bench/parametric-check.mts +0 -78
- package/src/search-bench/profiles.ts +0 -113
- package/src/search-bench/run.mts +0 -286
- package/src/search-bench/tasks-fresh.ts +0 -688
- package/src/smoke-structural-rollout.mts +0 -415
- package/src/stats.mts +0 -90
- package/src/swe-code-improve.mts +0 -306
- package/src/swe-improve.mts +0 -284
- package/src/swe-structural.mts +0 -707
- package/src/tb-container-executor.mts +0 -266
- package/src/tb-container-executor.test.mts +0 -134
- package/src/tb-supervisor-sidecar.mts +0 -208
- package/src/trata-gepa.mts +0 -381
- package/src/trata-hedge-solve.mts +0 -81
- package/tb_agents/opencode_refine_agent.py +0 -117
- package/tb_agents/opencode_supervisor_agent.py +0 -239
package/src/worker-blender.ts
CHANGED
|
@@ -20,8 +20,6 @@ import { DEFAULT_BLENDER_DIRECTIVE } from './directives'
|
|
|
20
20
|
import { runRefineLoop } from './refine-loop'
|
|
21
21
|
import { runBenchRouterTurn } from './router-turn'
|
|
22
22
|
|
|
23
|
-
export { DEFAULT_BLENDER_DIRECTIVE } from './directives'
|
|
24
|
-
|
|
25
23
|
const execFileAsync = promisify(execFile)
|
|
26
24
|
|
|
27
25
|
async function runLocal(cmd: string, args: string[], cwd: string, timeoutMs = 180_000): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
@@ -113,7 +111,7 @@ export async function renderBpy(script: string, opts: { views?: number } = {}):
|
|
|
113
111
|
}
|
|
114
112
|
}
|
|
115
113
|
|
|
116
|
-
|
|
114
|
+
interface BlenderLocalConfig {
|
|
117
115
|
routerBaseUrl: string
|
|
118
116
|
routerKey: string
|
|
119
117
|
model: string
|
|
@@ -124,7 +122,7 @@ export interface BlenderLocalConfig {
|
|
|
124
122
|
directive?: string
|
|
125
123
|
}
|
|
126
124
|
|
|
127
|
-
|
|
125
|
+
interface BlenderShot {
|
|
128
126
|
/** The bpy script the agent wrote — the artifact. */
|
|
129
127
|
artifact: string
|
|
130
128
|
/** Rendered view PNGs as data URIs (the images the criteria judge scores). */
|
|
@@ -136,105 +134,3 @@ export interface BlenderShot {
|
|
|
136
134
|
built: boolean
|
|
137
135
|
detail?: string
|
|
138
136
|
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Author a bpy script for the task via the router, execute + render it headless
|
|
142
|
-
* in Blender, refine on execution errors across rounds. Returns the script, the
|
|
143
|
-
* rendered views, a screenshot-rich trace, and real token usage.
|
|
144
|
-
*/
|
|
145
|
-
export async function solveBlenderLocal(task: BenchTask, cfg: BlenderLocalConfig): Promise<BlenderShot> {
|
|
146
|
-
const rounds = Math.max(1, cfg.rounds ?? 2)
|
|
147
|
-
const views = Math.max(1, cfg.views ?? 4)
|
|
148
|
-
const directive = cfg.directive ?? DEFAULT_BLENDER_DIRECTIVE
|
|
149
|
-
const trace: Span[] = []
|
|
150
|
-
const runId = `cadbench-${task.id}`
|
|
151
|
-
let ts = Date.now()
|
|
152
|
-
const tick = () => (ts += 1)
|
|
153
|
-
const usage = { input: 0, output: 0 }
|
|
154
|
-
// Carried across rounds in closures (the round Artifact is the bpy script; the
|
|
155
|
-
// render PNGs + built flag + lastErr persist outside the loop). usage is REAL.
|
|
156
|
-
let renders: string[] = []
|
|
157
|
-
let built = false
|
|
158
|
-
let lastErr = ''
|
|
159
|
-
|
|
160
|
-
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)
|
|
161
|
-
|
|
162
|
-
// Migrated onto runRefineLoop: the mkdtemp dir (with the runner.py written once
|
|
163
|
-
// in setup) is the Ctx; built (RENDER_DONE + ≥1 collected view) is the early-stop,
|
|
164
|
-
// modeled as a judge so default-decide stops the loop. The round-2+ steer carries
|
|
165
|
-
// lastErr + the prior script verbatim.
|
|
166
|
-
const res = await runRefineLoop<string, string>({
|
|
167
|
-
rounds,
|
|
168
|
-
setup: async () => {
|
|
169
|
-
const dir = await mkdtemp(join(tmpdir(), 'blender-'))
|
|
170
|
-
await writeFile(join(dir, 'runner.py'), RUNNER_PY)
|
|
171
|
-
return dir
|
|
172
|
-
},
|
|
173
|
-
prompt: (round, history) =>
|
|
174
|
-
round === 1
|
|
175
|
-
? task.prompt
|
|
176
|
-
: `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}`,
|
|
177
|
-
runShot: async (user, round, dir) => {
|
|
178
|
-
const runnerPath = join(dir, 'runner.py')
|
|
179
|
-
const scriptPath = join(dir, 'model.py')
|
|
180
|
-
const turn = await runBenchRouterTurn(
|
|
181
|
-
{
|
|
182
|
-
routerBaseUrl: cfg.routerBaseUrl,
|
|
183
|
-
routerKey: cfg.routerKey,
|
|
184
|
-
profile: {
|
|
185
|
-
name: 'blender-worker',
|
|
186
|
-
harness: 'cli-base',
|
|
187
|
-
model: {
|
|
188
|
-
provider: 'tangle-router',
|
|
189
|
-
default: cfg.model,
|
|
190
|
-
metadata: { temperature: 0.3 },
|
|
191
|
-
},
|
|
192
|
-
prompt: { systemPrompt: directive },
|
|
193
|
-
},
|
|
194
|
-
},
|
|
195
|
-
user,
|
|
196
|
-
)
|
|
197
|
-
const content = turn.finalText
|
|
198
|
-
if (turn.usage.tokensKnown !== false) {
|
|
199
|
-
usage.input += turn.usage.input
|
|
200
|
-
usage.output += turn.usage.output
|
|
201
|
-
}
|
|
202
|
-
const script = extractPy(content)
|
|
203
|
-
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)
|
|
204
|
-
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)
|
|
205
|
-
|
|
206
|
-
await writeFile(scriptPath, script)
|
|
207
|
-
const run = await runLocal('xvfb-run', ['-a', 'blender', '--background', '--python', runnerPath, '--', scriptPath, dir, String(views)], dir)
|
|
208
|
-
const out = `${run.stdout}\n${run.stderr}`
|
|
209
|
-
built = /RENDER_DONE/.test(out)
|
|
210
|
-
lastErr = built ? '' : (/(AGENT_SCRIPT_ERROR:.*|NO_MESH)/.exec(out)?.[0] ?? out.trim().slice(-800))
|
|
211
|
-
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)
|
|
212
|
-
|
|
213
|
-
if (built) {
|
|
214
|
-
const collected: string[] = []
|
|
215
|
-
for (let v = 0; v < views; v++) {
|
|
216
|
-
const buf = await readFile(join(dir, `view_${v}.png`)).catch(() => undefined)
|
|
217
|
-
if (buf) collected.push(`data:image/png;base64,${buf.toString('base64')}`)
|
|
218
|
-
}
|
|
219
|
-
renders = collected
|
|
220
|
-
// first view carries the screen span (run-capsule reveal)
|
|
221
|
-
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)
|
|
222
|
-
built = collected.length > 0
|
|
223
|
-
}
|
|
224
|
-
return { artifact: script }
|
|
225
|
-
},
|
|
226
|
-
judge: async () => ({ valid: built }),
|
|
227
|
-
teardown: (dir) => rm(dir, { recursive: true, force: true }).then(() => {}, () => {}),
|
|
228
|
-
})
|
|
229
|
-
|
|
230
|
-
const script = res.final.artifact
|
|
231
|
-
return {
|
|
232
|
-
artifact: script,
|
|
233
|
-
renders,
|
|
234
|
-
trace,
|
|
235
|
-
usage,
|
|
236
|
-
ok: script.trim().length > 0,
|
|
237
|
-
built,
|
|
238
|
-
detail: built ? `built + rendered ${renders.length} views` : `did not build in ${rounds} rounds${lastErr ? `; last: ${lastErr.slice(0, 140)}` : ''}`,
|
|
239
|
-
}
|
|
240
|
-
}
|
package/src/worker-build123d.ts
CHANGED
|
@@ -23,8 +23,6 @@ import { DEFAULT_BUILD123D_DIRECTIVE } from './directives'
|
|
|
23
23
|
import { runRefineLoop } from './refine-loop'
|
|
24
24
|
import { runBenchRouterTurn } from './router-turn'
|
|
25
25
|
|
|
26
|
-
export { DEFAULT_BUILD123D_DIRECTIVE } from './directives'
|
|
27
|
-
|
|
28
26
|
const execFileAsync = promisify(execFile)
|
|
29
27
|
|
|
30
28
|
export const CGB_VENV_PY = process.env.CADGENBENCH_VENV ?? '/tmp/cgb-venv/bin/python'
|
|
@@ -53,7 +51,7 @@ function cheatSheet(): string {
|
|
|
53
51
|
return _cheat
|
|
54
52
|
}
|
|
55
53
|
|
|
56
|
-
|
|
54
|
+
interface Build123dConfig {
|
|
57
55
|
routerBaseUrl: string
|
|
58
56
|
routerKey: string
|
|
59
57
|
model: string
|
|
@@ -62,7 +60,7 @@ export interface Build123dConfig {
|
|
|
62
60
|
directive?: string
|
|
63
61
|
}
|
|
64
62
|
|
|
65
|
-
|
|
63
|
+
interface Build123dShot {
|
|
66
64
|
/** The produced STEP text (the artifact the CADGenBench scorer grades). */
|
|
67
65
|
artifact: string
|
|
68
66
|
/** The Python source the agent wrote. */
|
|
@@ -73,80 +71,3 @@ export interface Build123dShot {
|
|
|
73
71
|
built: boolean
|
|
74
72
|
detail?: string
|
|
75
73
|
}
|
|
76
|
-
|
|
77
|
-
/** Author a build123d script via the router, execute it in the CADGenBench venv,
|
|
78
|
-
* read back output.step. Refine on execution error / missing STEP. */
|
|
79
|
-
export async function solveBuild123dLocal(task: BenchTask, cfg: Build123dConfig): Promise<Build123dShot> {
|
|
80
|
-
const rounds = Math.max(1, cfg.rounds ?? 2)
|
|
81
|
-
const directive = cfg.directive ?? DEFAULT_BUILD123D_DIRECTIVE
|
|
82
|
-
const sys = `${directive}\n\nbuild123d API reference:\n${cheatSheet()}`
|
|
83
|
-
const trace: Span[] = []
|
|
84
|
-
const runId = `cadgenbench-${task.id}`
|
|
85
|
-
let ts = Date.now()
|
|
86
|
-
const tick = () => (ts += 1)
|
|
87
|
-
const usage = { input: 0, output: 0 }
|
|
88
|
-
// Carried across rounds in closures (the round Artifact is the Python source; the
|
|
89
|
-
// STEP text + built flag + lastErr persist outside the loop). usage is REAL.
|
|
90
|
-
let step = ''
|
|
91
|
-
let built = false
|
|
92
|
-
let lastErr = ''
|
|
93
|
-
|
|
94
|
-
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)
|
|
95
|
-
|
|
96
|
-
// Migrated onto runRefineLoop: the mkdtemp scratch dir is the Ctx; built (STEP
|
|
97
|
-
// produced) is the early-stop, modeled as a judge so default-decide stops the
|
|
98
|
-
// loop. The round-2+ steer carries lastErr + the prior source verbatim.
|
|
99
|
-
const res = await runRefineLoop<string, string>({
|
|
100
|
-
rounds,
|
|
101
|
-
setup: () => mkdtemp(join(tmpdir(), 'b123d-')),
|
|
102
|
-
prompt: (round, history) =>
|
|
103
|
-
round === 1
|
|
104
|
-
? task.prompt
|
|
105
|
-
: `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}`,
|
|
106
|
-
runShot: async (user, round, dir) => {
|
|
107
|
-
const scriptPath = join(dir, 'build.py')
|
|
108
|
-
const stepPath = join(dir, 'output.step')
|
|
109
|
-
const turn = await runBenchRouterTurn(
|
|
110
|
-
{
|
|
111
|
-
routerBaseUrl: cfg.routerBaseUrl,
|
|
112
|
-
routerKey: cfg.routerKey,
|
|
113
|
-
profile: {
|
|
114
|
-
name: 'build123d-worker',
|
|
115
|
-
model: { provider: 'tangle-router', default: cfg.model },
|
|
116
|
-
prompt: { systemPrompt: sys },
|
|
117
|
-
},
|
|
118
|
-
},
|
|
119
|
-
user,
|
|
120
|
-
)
|
|
121
|
-
const content = turn.finalText
|
|
122
|
-
if (turn.usage.tokensKnown !== false) {
|
|
123
|
-
usage.input += turn.usage.input
|
|
124
|
-
usage.output += turn.usage.output
|
|
125
|
-
}
|
|
126
|
-
const source = extractPy(content)
|
|
127
|
-
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)
|
|
128
|
-
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)
|
|
129
|
-
|
|
130
|
-
await writeFile(scriptPath, source)
|
|
131
|
-
const run = await runLocal(CGB_VENV_PY, [scriptPath], dir)
|
|
132
|
-
const got = existsSync(stepPath) ? await readFile(stepPath, 'utf8').catch(() => '') : ''
|
|
133
|
-
built = got.includes('ISO-10303-21') && got.length > 200
|
|
134
|
-
lastErr = built ? '' : `${run.stdout}\n${run.stderr}`.trim().slice(-800) || 'no output.step written'
|
|
135
|
-
if (built) step = got
|
|
136
|
-
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)
|
|
137
|
-
return { artifact: source }
|
|
138
|
-
},
|
|
139
|
-
judge: async () => ({ valid: built }),
|
|
140
|
-
teardown: (dir) => rm(dir, { recursive: true, force: true }).then(() => {}, () => {}),
|
|
141
|
-
})
|
|
142
|
-
|
|
143
|
-
return {
|
|
144
|
-
artifact: step,
|
|
145
|
-
source: res.final.artifact,
|
|
146
|
-
trace,
|
|
147
|
-
usage,
|
|
148
|
-
ok: res.final.artifact.trim().length > 0,
|
|
149
|
-
built,
|
|
150
|
-
detail: built ? 'exported output.step' : `did not produce a STEP in ${rounds} rounds${lastErr ? `; last: ${lastErr.slice(0, 140)}` : ''}`,
|
|
151
|
-
}
|
|
152
|
-
}
|
|
@@ -162,7 +162,7 @@ class OpenCodeRouterAgent(OpenCodeAgent):
|
|
|
162
162
|
The base `_get_templated_script_path` resolves the template relative to
|
|
163
163
|
`inspect.getfile(self.__class__)` — i.e. next to THIS subclass file, where
|
|
164
164
|
`opencode-setup.sh.j2` does not exist. Resolve it from the stock
|
|
165
|
-
`OpenCodeAgent`'s own directory instead (
|
|
165
|
+
`OpenCodeAgent`'s own directory instead (the canonical template owner).
|
|
166
166
|
"""
|
|
167
167
|
template_path = (
|
|
168
168
|
Path(inspect.getfile(OpenCodeAgent)).parent / "opencode-setup.sh.j2"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cadbench-BRF-59Mt.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 { runBenchRouterTurn } from './router-turn'\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 turn = await runBenchRouterTurn(\n {\n routerBaseUrl: cfg.routerBaseUrl,\n routerKey: cfg.routerKey,\n profile: {\n name: 'blender-worker',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: cfg.model,\n metadata: { temperature: 0.3 },\n },\n prompt: { systemPrompt: directive },\n },\n },\n user,\n )\n const content = turn.finalText\n if (turn.usage.tokensKnown !== false) {\n usage.input += turn.usage.input\n usage.output += turn.usage.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'\nimport { runBenchRouterTurn } from '../router-turn'\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 turn = await runBenchRouterTurn(\n {\n routerBaseUrl: base,\n routerKey: key,\n profile: {\n name: 'cadbench-vision-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: model,\n metadata: {\n temperature: 0,\n maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500),\n },\n },\n },\n },\n { messages: [{ role: 'user', content }] },\n )\n const raw = turn.finalText\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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AS;GACvD,OAAO;IAAE,UAAU,UAAU;IAAG;IAAO,QAAQ;GAAK;EACtD;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cadgenbench-DXtGkuW3.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 { runBenchRouterTurn } from './router-turn'\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 turn = await runBenchRouterTurn(\n {\n routerBaseUrl: cfg.routerBaseUrl,\n routerKey: cfg.routerKey,\n profile: {\n name: 'build123d-worker',\n model: { provider: 'tangle-router', default: cfg.model },\n prompt: { systemPrompt: sys },\n },\n },\n user,\n )\n const content = turn.finalText\n if (turn.usage.tokensKnown !== false) {\n usage.input += turn.usage.input\n usage.output += turn.usage.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;CACvH;AACF;AAEA,SAAgB,2BAA6C;CAC3D,OAAO;EACL,MAAM;EAEN,MAAM,YAAY;GAChB,MAAM,IAAI,MAAM,cAAc,aAAa,CAAC,MAAM,iFAA+E,GAAG,EAAE,SAAS,IAAO,CAAC,CAAC,CAAC,OACtJ,OAAO;IAAE,QAAQ;IAAI,QAAQ,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;GAAE,EAC3E;GACA,IAAI,CAAC,KAAK,KAAK,EAAE,MAAM,GACrB,MAAM,IAAI,MACR,sCAAsC,YAAY,KAAK,EAAE,OAAO,MAAM,GAAG,GAAG,EAAE,8DACf,QAAQ,4EAA4E,SACrJ;EAEJ;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GAGtC,IAAI,QAAQ,aAAa;GACzB,MAAM,OAAO,QAAQ,IAAI;GACzB,IAAI,MAAM;IACR,MAAM,EAAE,aAAa,MAAM,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Q,MAAM,GAAG,GAAG;IAAI;IAC1H,MAAM,IAAI,KAAK,MAAM,EAAE,EAAE;IACzB,MAAM,QAAQ,OAAO,EAAE,cAAc,WAAW,EAAE,YAAY;IAC9D,OAAO;KAAE,UAAU,SAAS;KAAkB;KAAO,QAAQ,aAAa,MAAM,QAAQ,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,KAAK,EAAE,MAAM,KAAK;IAAK;GACnJ,UAAU;IACR,MAAM,GAAG,KAAK;KAAE,WAAW;KAAM,OAAO;IAAK,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;GAChE;EACF;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"router-turn-uTYO6KQ1.js","names":[],"sources":["../src/router-turn.ts"],"sourcesContent":["import {\n type AgentProfile,\n agentProfileSchema,\n type ReasoningEffort,\n} from '@tangle-network/agent-interface'\nimport {\n collectAgentTurn,\n createExecutor,\n streamAgentTurn,\n type AgentTurnInput,\n type CollectedAgentTurn,\n type ToolSpec,\n} from '@tangle-network/agent-runtime/kernel'\n\n/** Bench-local target shorthand; Runtime still executes only the exact profile below. */\nexport interface BenchRouterTarget {\n routerBaseUrl: string\n routerKey: string\n profile: AgentProfile\n}\n\nexport interface BenchRouterTurnConfig extends BenchRouterTarget {\n tools?: ReadonlyArray<ToolSpec>\n timeoutMs?: number\n signal?: AbortSignal\n}\n\nexport interface BenchProfileSettings {\n systemPrompt?: string\n temperature?: number\n maxTokens?: number\n retry?: {\n maxAttempts?: number\n initialBackoffMs?: number\n maxBackoffMs?: number\n jitter?: number\n retryStatuses?: ReadonlyArray<number>\n requestTimeoutMs?: number\n }\n maxTurns?: number\n seed?: number\n reasoningEffort?: ReasoningEffort\n extraBody?: Readonly<Record<string, unknown>>\n toolChoice?: 'auto' | 'required' | 'none'\n}\n\n/** Author an exact direct-Router profile for a benchmark. This is profile construction only;\n * execution still accepts no model or generation fields outside the returned AgentProfile. */\nexport function benchRouterProfile(\n name: string,\n model: string,\n settings: BenchProfileSettings = {},\n): AgentProfile {\n return withBenchProfile(\n {\n name,\n harness: 'cli-base',\n model: { provider: 'tangle-router', default: model },\n },\n settings,\n )\n}\n\n/** Derive another exact profile while preserving all untouched canonical axes. */\nexport function withBenchProfile(\n base: AgentProfile,\n settings: BenchProfileSettings & { name?: string },\n): AgentProfile {\n const metadata = {\n ...(base.model?.metadata ?? {}),\n ...(settings.temperature !== undefined ? { temperature: settings.temperature } : {}),\n ...(settings.retry !== undefined ? { retry: settings.retry } : {}),\n ...(settings.maxTurns !== undefined ? { maxTurns: settings.maxTurns } : {}),\n ...(settings.seed !== undefined ? { seed: settings.seed } : {}),\n ...(settings.extraBody !== undefined ? { extraBody: settings.extraBody } : {}),\n ...(settings.toolChoice !== undefined ? { toolChoice: settings.toolChoice } : {}),\n }\n return agentProfileSchema.parse({\n ...base,\n ...(settings.name ? { name: settings.name } : {}),\n model: {\n ...base.model,\n ...(settings.reasoningEffort !== undefined\n ? { reasoningEffort: settings.reasoningEffort }\n : {}),\n // A bench cap bounds the VISIBLE answer, which the Router lowers as `max_tokens`.\n ...(settings.maxTokens !== undefined\n ? { maxVisibleOutputTokens: settings.maxTokens }\n : {}),\n ...(Object.keys(metadata).length > 0 ? { metadata } : {}),\n },\n ...(settings.systemPrompt !== undefined\n ? { prompt: { ...base.prompt, systemPrompt: settings.systemPrompt } }\n : {}),\n })\n}\n\nexport function benchProfileModel(profile: AgentProfile): string {\n const model = profile.model?.default\n if (typeof model !== 'string' || model.length === 0 || model === 'runtime-selected') {\n throw new Error('benchmark AgentProfile.model.default must be concrete')\n }\n return model\n}\n\n/**\n * The benchmark-side entry to Runtime's canonical one-turn path.\n * It is only an ergonomic composition: Runtime still parses the exact profile,\n * materializes the executor, records identity/usage/result events, and refuses\n * profile axes the direct Router backend cannot carry.\n */\nexport async function runBenchRouterTurn(\n config: BenchRouterTurnConfig,\n input: string | { readonly messages: ReadonlyArray<Readonly<Record<string, unknown>>> },\n): Promise<CollectedAgentTurn> {\n if (!config.profile.model?.default) {\n throw new Error('runBenchRouterTurn: profile.model.default is required')\n }\n const factory = createExecutor({\n backend: 'router',\n routerBaseUrl: config.routerBaseUrl,\n routerKey: config.routerKey,\n ...(config.tools ? { tools: config.tools } : {}),\n })\n const turnInput: AgentTurnInput =\n typeof input === 'string'\n ? { prompt: input }\n : {\n providerOptions: {\n messages: input.messages.map((message) => ({ ...message })),\n },\n }\n const turn = await collectAgentTurn(\n streamAgentTurn(\n { kind: 'executor', factory, profile: config.profile },\n turnInput,\n {\n ...(config.timeoutMs === undefined ? {} : { timeoutMs: config.timeoutMs }),\n ...(config.signal ? { signal: config.signal } : {}),\n },\n ),\n )\n if (turn.status !== 'completed') {\n throw new Error(turn.error?.message ?? `Router turn ended with status ${turn.status}`)\n }\n return turn\n}\n"],"mappings":";;;;;;;;;AA+GA,eAAsB,mBACpB,QACA,OAC6B;CAC7B,IAAI,CAAC,OAAO,QAAQ,OAAO,SACzB,MAAM,IAAI,MAAM,uDAAuD;CAEzE,MAAM,UAAU,eAAe;EAC7B,SAAS;EACT,eAAe,OAAO;EACtB,WAAW,OAAO;EAClB,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;CAChD,CAAC;CACD,MAAM,YACJ,OAAO,UAAU,WACb,EAAE,QAAQ,MAAM,IAChB,EACE,iBAAiB,EACf,UAAU,MAAM,SAAS,KAAK,aAAa,EAAE,GAAG,QAAQ,EAAE,EAC5D,EACF;CACN,MAAM,OAAO,MAAM,iBACjB,gBACE;EAAE,MAAM;EAAY;EAAS,SAAS,OAAO;CAAQ,GACrD,WACA;EACE,GAAI,OAAO,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,OAAO,UAAU;EACxE,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;CACnD,CACF,CACF;CACA,IAAI,KAAK,WAAW,aAClB,MAAM,IAAI,MAAM,KAAK,OAAO,WAAW,iCAAiC,KAAK,QAAQ;CAEvF,OAAO;AACT"}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""Fetch FreedomIntelligence/CADBench + flatten its nested `criteria` into a flat
|
|
3
|
-
bullet list, writing the cleaned JSONL the CADBench adapter reads via CADBENCH_PATH.
|
|
4
|
-
Usage: python3 scripts/cadbench_prepare.py [out.jsonl] (clones the HF dataset to /tmp)"""
|
|
5
|
-
import json, subprocess, sys, os
|
|
6
|
-
OUT = sys.argv[1] if len(sys.argv) > 1 else '/tmp/cadbench_clean.jsonl'
|
|
7
|
-
SRC = '/tmp/cadbench-ds'
|
|
8
|
-
if not os.path.exists(SRC):
|
|
9
|
-
subprocess.run(['git', 'clone', '--depth', '1', 'https://huggingface.co/datasets/FreedomIntelligence/CADBench', SRC], check=True)
|
|
10
|
-
def flatten(x, out):
|
|
11
|
-
if isinstance(x, dict):
|
|
12
|
-
for v in x.values(): flatten(v, out)
|
|
13
|
-
elif isinstance(x, list):
|
|
14
|
-
for v in x: flatten(v, out)
|
|
15
|
-
elif isinstance(x, str): out.append(x)
|
|
16
|
-
rows = [json.loads(l) for l in open(f'{SRC}/CADBench.jsonl', encoding='utf-8-sig') if l.strip()]
|
|
17
|
-
clean = []
|
|
18
|
-
for r in rows:
|
|
19
|
-
b = []; flatten(r['criteria'], b)
|
|
20
|
-
clean.append({'id': r['id'], 'name': r.get('name', ''), 'instruction': r['instruction'], 'type': r.get('type', ''), 'criteria': b})
|
|
21
|
-
open(OUT, 'w').write('\n'.join(json.dumps(c) for c in clean))
|
|
22
|
-
print(f'wrote {len(clean)} tasks -> {OUT}')
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
from build123d import *
|
|
2
|
-
import os, json
|
|
3
|
-
OUT = "/tmp/cgb-hard"; os.makedirs(OUT, exist_ok=True)
|
|
4
|
-
tasks = []
|
|
5
|
-
def save(pid, part, desc):
|
|
6
|
-
p = f"{OUT}/{pid}.step"; export_step(part, p)
|
|
7
|
-
tasks.append({"id": pid, "prompt": desc, "gtStep": p}); print(pid, "OK", round(part.volume,1))
|
|
8
|
-
|
|
9
|
-
# 1. L-bracket: base plate + vertical leg + 4 holes through base
|
|
10
|
-
base = Pos(0,0,4) * Box(60,40,8)
|
|
11
|
-
leg = Pos(-26,0,30) * Box(8,40,52)
|
|
12
|
-
lb = base + leg
|
|
13
|
-
for (x,y) in [(-10,-10),(-10,10),(20,-10),(20,10)]:
|
|
14
|
-
lb -= Pos(x,y,4) * Cylinder(3,12)
|
|
15
|
-
save("l-bracket", lb, "An L-shaped steel mounting bracket. A base plate 60 (X) by 40 (Y) by 8 (Z) units sits flat with its bottom at z=0, centered on X and Y. A vertical leg 8 (X) by 40 (Y) by 52 (Z) units rises from the base's -X edge, forming a right angle (the whole part is ~60 wide, 40 deep, 60 tall). Four vertical through-holes of radius 3 pass through the base plate at X,Y offsets (-10,-10), (-10,10), (20,-10), (20,10) from center.")
|
|
16
|
-
|
|
17
|
-
# 2. Washer: flat annulus
|
|
18
|
-
w = Cylinder(20,4) - Cylinder(10,4)
|
|
19
|
-
save("washer", w, "A flat circular washer: an annular disk of outer radius 20, inner radius 10, and thickness 4 units, centered at the origin.")
|
|
20
|
-
|
|
21
|
-
# 3. Flanged pipe: pipe + flange disk at base + 4 bolt holes in flange
|
|
22
|
-
pipe = Cylinder(12,50, align=(Align.CENTER,Align.CENTER,Align.MIN)) - Cylinder(8,50, align=(Align.CENTER,Align.CENTER,Align.MIN))
|
|
23
|
-
flange = Cylinder(24,6, align=(Align.CENTER,Align.CENTER,Align.MIN)) - Cylinder(8,6, align=(Align.CENTER,Align.CENTER,Align.MIN))
|
|
24
|
-
fp = pipe + flange
|
|
25
|
-
import math
|
|
26
|
-
for i in range(4):
|
|
27
|
-
a = math.radians(45 + i*90); fp -= Pos(18*math.cos(a),18*math.sin(a),3) * Cylinder(2.5,8)
|
|
28
|
-
save("flanged-pipe", fp, "A flanged pipe. A hollow cylindrical pipe of outer radius 12, inner radius 8 (bore), height 50, standing with its base at z=0. At the base is a circular flange disk of radius 24 and thickness 6, sharing the same central bore (radius 8). Four bolt holes of radius 2.5 pass vertically through the flange on a circle of radius 18 from the axis, at 45, 135, 225, 315 degrees.")
|
|
29
|
-
|
|
30
|
-
# 4. Stepped shaft: 3 stacked cylinders, decreasing radius
|
|
31
|
-
s = Cylinder(15,20, align=(Align.CENTER,Align.CENTER,Align.MIN))
|
|
32
|
-
s += Pos(0,0,20) * Cylinder(10,20, align=(Align.CENTER,Align.CENTER,Align.MIN))
|
|
33
|
-
s += Pos(0,0,40) * Cylinder(6,20, align=(Align.CENTER,Align.CENTER,Align.MIN))
|
|
34
|
-
save("stepped-shaft", s, "A stepped cylindrical shaft, coaxial along Z, base at z=0: a bottom section radius 15 height 20, a middle section radius 10 height 20, and a top section radius 6 height 20 (total height 60).")
|
|
35
|
-
|
|
36
|
-
# 5. Mounting plate: plate + 4 corner holes + center hole
|
|
37
|
-
mp = Box(80,60,6)
|
|
38
|
-
for (x,y) in [(-32,-22),(-32,22),(32,-22),(32,22)]:
|
|
39
|
-
mp -= Pos(x,y,0) * Cylinder(3,10)
|
|
40
|
-
mp -= Cylinder(8,10)
|
|
41
|
-
save("mounting-plate", mp, "A rectangular mounting plate 80 (X) by 60 (Y) by 6 (Z) units, centered at the origin. A central through-hole of radius 8, plus four through-holes of radius 3 at the corners, offset (+/-32, +/-22) from center.")
|
|
42
|
-
|
|
43
|
-
# 6. Hex standoff: hexagonal prism with axial hole
|
|
44
|
-
hexp = extrude(RegularPolygon(radius=10, side_count=6), 30) - Cylinder(5,30, align=(Align.CENTER,Align.CENTER,Align.MIN))
|
|
45
|
-
save("hex-standoff", hexp, "A hexagonal standoff: a regular hexagonal prism (circumradius 10, i.e. ~17.3 across flats... actually 20 across corners) extruded 30 units tall from z=0, with a coaxial cylindrical through-hole of radius 5 along its full height.")
|
|
46
|
-
|
|
47
|
-
json.dump(tasks, open(f"{OUT}/tasks.json","w"), indent=2)
|
|
48
|
-
print("WROTE", len(tasks), "tasks")
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
"""Deployable-checker bridge for CL-Bench (Continual) Codebase Adaptation.
|
|
2
|
-
|
|
3
|
-
CL-Bench's `codebase_adaptation` is the ONE domain whose scorer is a deployable
|
|
4
|
-
checker (not an oracle): it applies the instance's provided `test_patch` and runs
|
|
5
|
-
the project's pytest suite inside the instance's Docker image, keying off the exit
|
|
6
|
-
code — exactly the SWE-bench / commit0 regime. This bridge exposes that scorer as a
|
|
7
|
-
standalone (instance_id, patch) -> {success,status} call so our TypeScript gate can
|
|
8
|
-
rank K candidate patches by a verifier the agent could legitimately run itself.
|
|
9
|
-
|
|
10
|
-
Run it with CL-Bench's OWN venv + repo root on the path (its `src.tasks...` package):
|
|
11
|
-
|
|
12
|
-
<clbench>/.venv/bin/python clbench_codebase_judge.py \
|
|
13
|
-
--dataset <clbench>/data/codebase_adaptation/final-dataset.jsonl \
|
|
14
|
-
--instance-id jazzband__tablib-534 --patch-file /tmp/candidate.patch
|
|
15
|
-
# invoked with cwd=<clbench> so `import src.tasks...` resolves
|
|
16
|
-
|
|
17
|
-
Prints one JSON line: {"instance_id","success","status","error"}. Fail loud — a
|
|
18
|
-
Docker/import failure exits non-zero with the message on stderr, never a silent 0.
|
|
19
|
-
"""
|
|
20
|
-
|
|
21
|
-
from __future__ import annotations
|
|
22
|
-
|
|
23
|
-
import argparse
|
|
24
|
-
import json
|
|
25
|
-
import sys
|
|
26
|
-
|
|
27
|
-
from src.tasks.codebase_adaptation.evaluator import evaluate_submission
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def load_instance(dataset_path: str, instance_id: str) -> dict:
|
|
31
|
-
with open(dataset_path, encoding="utf-8") as f:
|
|
32
|
-
for line in f:
|
|
33
|
-
line = line.strip()
|
|
34
|
-
if not line:
|
|
35
|
-
continue
|
|
36
|
-
row = json.loads(line)
|
|
37
|
-
if row.get("instance_id") == instance_id:
|
|
38
|
-
return row
|
|
39
|
-
raise SystemExit(f"instance_id not found in {dataset_path}: {instance_id}")
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def main() -> None:
|
|
43
|
-
ap = argparse.ArgumentParser(description="CL-Bench codebase_adaptation deployable judge")
|
|
44
|
-
ap.add_argument("--dataset", required=True, help="path to final-dataset.jsonl")
|
|
45
|
-
ap.add_argument("--instance-id", required=True)
|
|
46
|
-
ap.add_argument("--patch-file", required=True, help="file holding the candidate unified git diff")
|
|
47
|
-
args = ap.parse_args()
|
|
48
|
-
|
|
49
|
-
instance = load_instance(args.dataset, args.instance_id)
|
|
50
|
-
with open(args.patch_file, encoding="utf-8") as f:
|
|
51
|
-
patch = f.read()
|
|
52
|
-
|
|
53
|
-
# evaluate_submission spins the instance's Docker image, applies test_patch + the
|
|
54
|
-
# candidate, runs pytest, and reports success on a clean exit. A genuine infra
|
|
55
|
-
# failure raises — let it propagate (non-zero exit) so the caller never reads a
|
|
56
|
-
# transport fault as a failed test.
|
|
57
|
-
result = evaluate_submission(patch, instance)
|
|
58
|
-
print(json.dumps({
|
|
59
|
-
"instance_id": args.instance_id,
|
|
60
|
-
"success": bool(result.success),
|
|
61
|
-
"status": result.status,
|
|
62
|
-
"error": (result.error or "")[:500],
|
|
63
|
-
}))
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if __name__ == "__main__":
|
|
67
|
-
try:
|
|
68
|
-
main()
|
|
69
|
-
except SystemExit:
|
|
70
|
-
raise
|
|
71
|
-
except Exception as exc: # infra/import failure — fail loud, do not emit a fake verdict
|
|
72
|
-
print(f"clbench_codebase_judge: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
73
|
-
sys.exit(2)
|