@tangle-network/agent-bench 0.14.2 → 1.0.0

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 (218) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +2 -3
  3. package/dist/adapters.d.ts +2 -5
  4. package/dist/adapters.js +3 -4
  5. package/dist/benchmarks/_harness.d.ts +17 -20
  6. package/dist/benchmarks/_harness.js +4 -4
  7. package/dist/benchmarks/_harness.js.map +1 -1
  8. package/dist/benchmarks/aec-bench.d.ts +1 -4
  9. package/dist/benchmarks/aec-bench.js +1 -2
  10. package/dist/benchmarks/agentbench.d.ts +2 -5
  11. package/dist/benchmarks/agentbench.js +1 -2
  12. package/dist/benchmarks/appworld.d.ts +8 -10
  13. package/dist/benchmarks/appworld.js +23 -23
  14. package/dist/benchmarks/appworld.js.map +1 -1
  15. package/dist/benchmarks/bfcl.d.ts +2 -5
  16. package/dist/benchmarks/bfcl.js +1 -2
  17. package/dist/benchmarks/cad-design.d.ts +2 -5
  18. package/dist/benchmarks/cad-design.js +2 -3
  19. package/dist/benchmarks/cad-design.js.map +1 -1
  20. package/dist/benchmarks/cadbench.d.ts +1 -4
  21. package/dist/benchmarks/cadbench.js +1 -2
  22. package/dist/benchmarks/cadgenbench.d.ts +1 -4
  23. package/dist/benchmarks/cadgenbench.js +1 -2
  24. package/dist/benchmarks/commit0.d.ts +2 -5
  25. package/dist/benchmarks/commit0.js +1 -2
  26. package/dist/benchmarks/crag.d.ts +1 -4
  27. package/dist/benchmarks/crag.js +3 -3
  28. package/dist/benchmarks/crag.js.map +1 -1
  29. package/dist/benchmarks/dabstep.d.ts +2 -5
  30. package/dist/benchmarks/dabstep.js +2 -3
  31. package/dist/benchmarks/dabstep.js.map +1 -1
  32. package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
  33. package/dist/benchmarks/enterpriseops-gym.js +1 -2
  34. package/dist/benchmarks/finresearchbench.d.ts +2 -5
  35. package/dist/benchmarks/finresearchbench.js +2 -3
  36. package/dist/benchmarks/finsearchcomp.d.ts +2 -5
  37. package/dist/benchmarks/finsearchcomp.js +4 -4
  38. package/dist/benchmarks/finsearchcomp.js.map +1 -1
  39. package/dist/benchmarks/frames.d.ts +3 -19
  40. package/dist/benchmarks/frames.js +13 -39
  41. package/dist/benchmarks/frames.js.map +1 -1
  42. package/dist/benchmarks/hotpotqa.d.ts +4 -14
  43. package/dist/benchmarks/hotpotqa.js +12 -32
  44. package/dist/benchmarks/hotpotqa.js.map +1 -1
  45. package/dist/benchmarks/humaneval.d.ts +9 -12
  46. package/dist/benchmarks/humaneval.js +2 -3
  47. package/dist/benchmarks/humaneval.js.map +1 -1
  48. package/dist/benchmarks/mcad-bench.d.ts +13 -16
  49. package/dist/benchmarks/mcad-bench.js +2 -3
  50. package/dist/benchmarks/mcad-bench.js.map +1 -1
  51. package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
  52. package/dist/benchmarks/mcad-cq-bench.js +2 -3
  53. package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
  54. package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
  55. package/dist/benchmarks/mcad-cq-golds.js +1 -2
  56. package/dist/benchmarks/mcad-golds.d.ts +1 -4
  57. package/dist/benchmarks/mcad-golds.js +0 -1
  58. package/dist/benchmarks/mcad-tasks.d.ts +5 -8
  59. package/dist/benchmarks/mcad-tasks.js +7 -8
  60. package/dist/benchmarks/mcad-tasks.js.map +1 -1
  61. package/dist/benchmarks/mind2web.d.ts +3 -5
  62. package/dist/benchmarks/mind2web.js +2 -3
  63. package/dist/benchmarks/mind2web.js.map +1 -1
  64. package/dist/benchmarks/nomiracl.d.ts +1 -4
  65. package/dist/benchmarks/nomiracl.js +1 -2
  66. package/dist/benchmarks/open-rag-bench.d.ts +1 -4
  67. package/dist/benchmarks/open-rag-bench.js +3 -3
  68. package/dist/benchmarks/open-rag-bench.js.map +1 -1
  69. package/dist/benchmarks/programbench.d.ts +2 -5
  70. package/dist/benchmarks/programbench.js +1 -2
  71. package/dist/benchmarks/rag-shared.d.ts +30 -22
  72. package/dist/benchmarks/rag-shared.js +8 -2
  73. package/dist/benchmarks/rag-shared.js.map +1 -1
  74. package/dist/benchmarks/ragbench.d.ts +1 -4
  75. package/dist/benchmarks/ragbench.js +3 -3
  76. package/dist/benchmarks/ragbench.js.map +1 -1
  77. package/dist/benchmarks/simpleqa.d.ts +2 -18
  78. package/dist/benchmarks/simpleqa.js +5 -31
  79. package/dist/benchmarks/simpleqa.js.map +1 -1
  80. package/dist/benchmarks/swe-bench.d.ts +7 -10
  81. package/dist/benchmarks/swe-bench.js +4 -4
  82. package/dist/benchmarks/swe-bench.js.map +1 -1
  83. package/dist/benchmarks/t2-ragbench.d.ts +1 -4
  84. package/dist/benchmarks/t2-ragbench.js +3 -3
  85. package/dist/benchmarks/t2-ragbench.js.map +1 -1
  86. package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
  87. package/dist/benchmarks/tau-bench-shared.js +4 -4
  88. package/dist/benchmarks/tau-bench-shared.js.map +1 -1
  89. package/dist/benchmarks/tau2-bench.d.ts +2 -5
  90. package/dist/benchmarks/tau2-bench.js +1 -2
  91. package/dist/benchmarks/tau3-banking.d.ts +1 -4
  92. package/dist/benchmarks/tau3-banking.js +1 -2
  93. package/dist/benchmarks/terminal-bench.d.ts +1 -4
  94. package/dist/benchmarks/terminal-bench.js +4 -4
  95. package/dist/benchmarks/terminal-bench.js.map +1 -1
  96. package/dist/benchmarks/toollm.d.ts +2 -5
  97. package/dist/benchmarks/toollm.js +1 -2
  98. package/dist/benchmarks/trata-hedge.d.ts +1 -4
  99. package/dist/benchmarks/trata-hedge.js +2 -3
  100. package/dist/benchmarks/types.d.ts +6 -9
  101. package/dist/benchmarks/webarena-verified.d.ts +2 -5
  102. package/dist/benchmarks/webarena-verified.js +1 -2
  103. package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
  104. package/dist/cadbench-DhAndllg.js.map +1 -0
  105. package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
  106. package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
  107. package/dist/index.d.ts +8 -18
  108. package/dist/index.js +16 -24
  109. package/dist/index.js.map +1 -1
  110. package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
  111. package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
  112. package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
  113. package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
  114. package/package.json +10 -10
  115. package/pier_agents/tangle_candidate.py +15 -23
  116. package/scripts/run-package-tests.mjs +8 -15
  117. package/scripts/verify-packed-consumer.mjs +0 -1
  118. package/src/atom-mcp-e2e.mts +16 -4
  119. package/src/benchmarks/frames.ts +10 -44
  120. package/src/benchmarks/hotpotqa.ts +9 -29
  121. package/src/benchmarks/rag-shared.ts +12 -0
  122. package/src/benchmarks/simpleqa.ts +2 -36
  123. package/src/commit0-prereqs.sh +0 -0
  124. package/src/corpus-replay.mts +8 -8
  125. package/src/corpus-report.mts +21 -21
  126. package/src/corpus.test.mts +5 -5
  127. package/src/corpus.ts +16 -16
  128. package/src/directives.ts +0 -38
  129. package/src/examples/lean-verify.ts +1 -1
  130. package/src/gate.ts +8 -8
  131. package/src/generate-eval/certify.ts +2 -2
  132. package/src/index.ts +1 -0
  133. package/src/refine-loop.ts +5 -5
  134. package/src/resolve-client.ts +1 -1
  135. package/src/router-turn.ts +3 -11
  136. package/src/run-benchmarks.test.mts +0 -4
  137. package/src/run-pool.ts +1 -1
  138. package/src/runtime-hook-recorder.ts +2 -2
  139. package/src/search-bench/tasks.ts +1 -1
  140. package/src/selector.test.mts +13 -13
  141. package/src/selector.ts +19 -19
  142. package/src/swe-bench-env.ts +4 -12
  143. package/src/swe-jail.ts +5 -156
  144. package/src/swe-structural-judge-policy.ts +3 -3
  145. package/src/swe-structural-policy.ts +3 -3
  146. package/src/swe-structural-provenance.ts +4 -4
  147. package/src/terminal-compare.ts +10 -10
  148. package/src/worker-blender.ts +2 -106
  149. package/src/worker-build123d.ts +2 -81
  150. package/tb_agents/opencode_router_agent.py +1 -1
  151. package/dist/cadbench-BRF-59Mt.js.map +0 -1
  152. package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
  153. package/dist/router-turn-uTYO6KQ1.js.map +0 -1
  154. package/scripts/cadbench_prepare.py +0 -22
  155. package/scripts/cadgenbench_hard_parts.py +0 -48
  156. package/scripts/clbench_codebase_judge.py +0 -73
  157. package/scripts/render-gate-chart.mjs +0 -176
  158. package/scripts/trata-hedge/README.md +0 -57
  159. package/scripts/trata-hedge/run.sh +0 -64
  160. package/src/browser/adapters/bad-design-audit.ts +0 -153
  161. package/src/browser/adapters/bad-design-audit.verify.ts +0 -85
  162. package/src/browser/adapters/bad.ts +0 -165
  163. package/src/browser/agent-adapter.ts +0 -145
  164. package/src/browser/process-adapter.ts +0 -146
  165. package/src/browser/run-to-spans.ts +0 -105
  166. package/src/browser/run-to-spans.verify.ts +0 -89
  167. package/src/browser/ui-reviewer.ts +0 -200
  168. package/src/browser/ui-reviewer.verify.ts +0 -94
  169. package/src/browser/verify.ts +0 -96
  170. package/src/clbench-codebase-gate.mts +0 -314
  171. package/src/clbench-context-gate.mts +0 -341
  172. package/src/cloud-loop.mts +0 -156
  173. package/src/commit0-env-run.mts +0 -62
  174. package/src/commit0-env.ts +0 -172
  175. package/src/commit0-gate.mts +0 -558
  176. package/src/coordination-mcp-container-reach.mts +0 -182
  177. package/src/egress-probe.mts +0 -26
  178. package/src/fleet.mts +0 -143
  179. package/src/hev-structural.mts +0 -697
  180. package/src/humaneval-gate.mts +0 -220
  181. package/src/humaneval-repair-gate.mts +0 -182
  182. package/src/mbpp-structural.mts +0 -676
  183. package/src/mcp-mount-probe.mts +0 -139
  184. package/src/profile-coordinates.ts +0 -134
  185. package/src/profiles.ts +0 -128
  186. package/src/research-gate.mts +0 -132
  187. package/src/research-shot.ts +0 -144
  188. package/src/router-executor.ts +0 -51
  189. package/src/run-benchmarks-report.ts +0 -66
  190. package/src/sandbox-run.ts +0 -108
  191. package/src/search-bench/bridge.ts +0 -182
  192. package/src/search-bench/export.mts +0 -0
  193. package/src/search-bench/parametric-check.mts +0 -78
  194. package/src/search-bench/profiles.ts +0 -113
  195. package/src/search-bench/run.mts +0 -286
  196. package/src/search-bench/tasks-fresh.ts +0 -688
  197. package/src/skill-sandbox-smoke.mts +0 -101
  198. package/src/smoke-structural-rollout.mts +0 -415
  199. package/src/stats.mts +0 -90
  200. package/src/supervisor-arena.mts +0 -825
  201. package/src/swe-code-improve.mts +0 -306
  202. package/src/swe-emit-patch.mts +0 -125
  203. package/src/swe-improve.mts +0 -284
  204. package/src/swe-local-proof.mts +0 -265
  205. package/src/swe-repro-calibrate.mts +0 -451
  206. package/src/swe-stream.mts +0 -1561
  207. package/src/swe-structural.mts +0 -707
  208. package/src/tb-container-executor.mts +0 -266
  209. package/src/tb-container-executor.test.mts +0 -134
  210. package/src/tb-supervisor-sidecar.mts +0 -208
  211. package/src/trajectory-assemble.mjs +0 -130
  212. package/src/trata-gepa.mts +0 -381
  213. package/src/trata-hedge-solve.mts +0 -81
  214. package/src/worker-browser.ts +0 -115
  215. package/src/worker-cad.ts +0 -470
  216. package/src/workspace-loop.mts +0 -133
  217. package/tb_agents/opencode_refine_agent.py +0 -117
  218. package/tb_agents/opencode_supervisor_agent.py +0 -239
@@ -1,115 +0,0 @@
1
- /**
2
- * Mind2Web browser worker: one shot = the model, under the candidate authoring
3
- * DIRECTIVE, reads the task + candidate elements and commits to a single next
4
- * action (ELEMENT / ACTION / VALUE). The artifact is scored by the deterministic
5
- * mind2web judge (element-match + op/value match); the produced trace carries the
6
- * step's REAL page screenshot so run-capsule's screen capsule turns the run into a
7
- * film — the actual page the agent acted on, not a re-rendered DOM.
8
- *
9
- * `directive` is the GEPA-optimizable surface: a minimal element-selection
10
- * instruction with headroom for the optimizer to learn the discrimination moves
11
- * (prefer the element whose role/label matches the goal step, disambiguate
12
- * look-alikes) that move the deterministic Step-SR gate.
13
- *
14
- * Reports REAL token usage so the campaign's backend-integrity guard sees a real
15
- * backend, never a fabricated zero.
16
- */
17
-
18
- import { readFile } from 'node:fs/promises'
19
- import type { Span } from '@tangle-network/agent-eval'
20
- import type { BenchTask } from './benchmarks/types'
21
- import { runBenchRouterTurn } from './router-turn'
22
-
23
- export interface BrowserLocalConfig {
24
- routerBaseUrl: string
25
- routerKey: string
26
- model: string
27
- /** The element-selection directive (system prompt) — the GEPA-optimizable surface. */
28
- directive?: string
29
- }
30
-
31
- export interface BrowserShot {
32
- /** The ELEMENT/ACTION/VALUE the model produced — the artifact the judge scores. */
33
- artifact: string
34
- trace: Span[]
35
- usage?: { input: number; output: number }
36
- ok: boolean
37
- detail?: string
38
- }
39
-
40
- /**
41
- * The hand-written baseline element-selection directive — the SURFACE the GEPA
42
- * loop optimizes. Deliberately minimal: states the job and the output contract,
43
- * not HOW to discriminate the right element, leaving headroom for the optimizer.
44
- */
45
- export const DEFAULT_MIND2WEB_DIRECTIVE =
46
- 'You are a web agent choosing the NEXT UI action toward the task goal. Read the task and the candidate elements, then pick the single element that makes progress and the correct action (CLICK, or TYPE/SELECT with a value). Respond with ONLY the three required lines.'
47
-
48
- interface Mind2WebMetaView {
49
- task?: string
50
- website?: string
51
- screenshotPath?: string
52
- }
53
-
54
- /**
55
- * One element-selection shot under `directive`. Returns the artifact, REAL token
56
- * usage, and a screenshot-rich trace (task → chosen action → a browser.<op> span
57
- * carrying the page screenshot) for run-capsule.
58
- */
59
- export async function solveBrowserLocal(task: BenchTask, cfg: BrowserLocalConfig): Promise<BrowserShot> {
60
- const directive = cfg.directive ?? DEFAULT_MIND2WEB_DIRECTIVE
61
- const meta = (task.metadata ?? {}) as Mind2WebMetaView
62
- const runId = `m2w-${task.id}`
63
- let ts = Date.now()
64
- const tick = () => (ts += 1)
65
- const trace: Span[] = []
66
- const goal = meta.task ?? task.prompt
67
-
68
- trace.push({ spanId: 's-task', runId, kind: 'llm', name: 'web task', model: cfg.model, messages: [{ role: 'user', content: goal }], startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)
69
-
70
- const turn = await runBenchRouterTurn(
71
- {
72
- routerBaseUrl: cfg.routerBaseUrl,
73
- routerKey: cfg.routerKey,
74
- profile: {
75
- name: 'browser-local-worker',
76
- model: { provider: 'tangle-router', default: cfg.model },
77
- prompt: { systemPrompt: directive },
78
- },
79
- },
80
- task.prompt,
81
- )
82
- const content = turn.finalText
83
- const usage =
84
- turn.usage.tokensKnown === false
85
- ? undefined
86
- : { input: turn.usage.input, output: turn.usage.output }
87
- const artifact = content.trim()
88
-
89
- const elementId = /ELEMENT:\s*\[?(\d+)\]?/i.exec(artifact)?.[1] ?? ''
90
- const op = (/ACTION:\s*(CLICK|TYPE|SELECT)/i.exec(artifact)?.[1] ?? 'CLICK').toUpperCase()
91
- const value = (/VALUE:\s*(.*)/i.exec(artifact)?.[1] ?? '').trim()
92
-
93
- trace.push({ spanId: 's-reply', runId, kind: 'llm', name: 'choose action', model: cfg.model, messages: [{ role: 'user', content: goal }], output: artifact.slice(0, 400), startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)
94
-
95
- let screenshot: string | undefined
96
- if (typeof meta.screenshotPath === 'string' && meta.screenshotPath) {
97
- const buf = await readFile(meta.screenshotPath).catch(() => undefined)
98
- if (buf) screenshot = `data:image/jpeg;base64,${buf.toString('base64')}`
99
- }
100
- const label = `${op}${value ? ` "${value.slice(0, 40)}"` : ''} element #${elementId}`
101
- trace.push({
102
- spanId: 's-act',
103
- runId,
104
- kind: 'tool',
105
- name: `browser ${op.toLowerCase()}`,
106
- toolName: `browser.${op.toLowerCase()}`,
107
- args: { action: label, url: meta.website ? `https://${meta.website}` : undefined, selector: `[backend_node_id="${elementId}"]` },
108
- attributes: screenshot ? { screenshot } : {},
109
- startedAt: tick(),
110
- endedAt: tick(),
111
- status: 'ok',
112
- } as Span)
113
-
114
- return { artifact, trace, usage, ok: artifact.length > 0, detail: label }
115
- }
package/src/worker-cad.ts DELETED
@@ -1,470 +0,0 @@
1
- /**
2
- * CAD sandbox worker: one shot = a fresh 'universal' Tangle sandbox where a
3
- * coding agent authors OpenSCAD source for the task's brief. The sandbox's OWN
4
- * Nix-profile toolchain is the gate — `openscad` compiles + exports the STL and
5
- * renders a PNG inside the box; we read both back. The artifact (the `.scad`) is
6
- * scored by the cad-design judge; the produced trace (brief → code → compile →
7
- * render screenshot) drives run-capsule's conversation/code/terminal/screen
8
- * capsules.
9
- *
10
- * This is the "full rounded run": real sandbox, the real CAD kernel as the
11
- * verifiable reward, real geometry, and a screenshot-rich trace for the video.
12
- * Requires `openscad` + `xvfb-run` in the sandbox profile (universal has both).
13
- */
14
-
15
- import { execFile } from 'node:child_process'
16
- import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
17
- import { tmpdir } from 'node:os'
18
- import { join } from 'node:path'
19
- import { promisify } from 'node:util'
20
- import { acquireSandbox } from '@tangle-network/agent-runtime/kernel'
21
- import { Sandbox } from '@tangle-network/sandbox'
22
- import type { Span } from '@tangle-network/agent-eval'
23
- import type { BenchTask } from './benchmarks/types'
24
- import { DEFAULT_CAD_DIRECTIVE, DEFAULT_CAD_SANDBOX_DIRECTIVE } from './directives'
25
- import { runRefineLoop } from './refine-loop'
26
- import { runBenchRouterTurn } from './router-turn'
27
-
28
- export { DEFAULT_CAD_DIRECTIVE } from './directives'
29
-
30
- export interface CadWorkerConfig {
31
- sandboxBaseUrl: string
32
- sandboxKey: string
33
- routerBaseUrl: string
34
- routerKey: string
35
- model: string
36
- provider?: string
37
- timeoutMs?: number
38
- }
39
-
40
- export interface CadShotResult {
41
- /** The OpenSCAD source the agent wrote — the artifact the judge scores. */
42
- artifact: string
43
- /** Trace of the run for run-capsule: brief → code → compile → render. */
44
- trace: Span[]
45
- ok: boolean
46
- detail?: string
47
- }
48
-
49
- const SCAD_PATH = '/work/model.scad'
50
- const STL_PATH = '/work/model.stl'
51
- const PNG_PATH = '/work/model.png'
52
-
53
- /** The acquired sandbox instance — the per-task execution Ctx for solveCadRefine. */
54
- type SandboxBox = Awaited<ReturnType<typeof acquireSandbox>>
55
-
56
- const randomSuffix = () => Math.random().toString(36).slice(2, 10)
57
-
58
- /** Strip markdown fences / prose so we keep just the OpenSCAD source. */
59
- function extractScad(text: string): string {
60
- const fence = /```(?:openscad|scad|c|cpp)?\s*\n([\s\S]*?)```/i.exec(text)
61
- return (fence ? fence[1] : text).trim()
62
- }
63
-
64
- const execFileAsync = promisify(execFile)
65
-
66
- /** Run a local command, returning exit code + streams (never throws on nonzero —
67
- * the geometry gate is the arbiter, so a failed compile still yields its error). */
68
- async function runLocal(
69
- cmd: string,
70
- args: string[],
71
- cwd: string,
72
- ): Promise<{ code: number; stdout: string; stderr: string }> {
73
- try {
74
- const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, maxBuffer: 1 << 26, timeout: 120_000 })
75
- return { code: 0, stdout, stderr }
76
- } catch (err) {
77
- const e = err as { code?: number; stdout?: string; stderr?: string; message?: string }
78
- return { code: e.code ?? 1, stdout: e.stdout ?? '', stderr: e.stderr ?? e.message ?? String(err) }
79
- }
80
- }
81
-
82
- export interface CadLocalConfig {
83
- routerBaseUrl: string
84
- routerKey: string
85
- model: string
86
- rounds?: number
87
- /** The authoring directive (system prompt) — the GEPA-optimizable surface. */
88
- directive?: string
89
- }
90
-
91
- export interface CadLocalShot {
92
- /** Final OpenSCAD source — the artifact the judge scores. */
93
- artifact: string
94
- /** First-round source (the blind shot, before any refine). */
95
- round1Artifact: string
96
- trace: Span[]
97
- /** Per-compiling-round render PNGs as data URIs (run-capsule reveal/orbit). */
98
- renders: string[]
99
- usage: { input: number; output: number }
100
- ok: boolean
101
- detail?: string
102
- }
103
-
104
- /**
105
- * LOCAL CAD refine loop — the staging-independent twin of `solveCadRefine`. The
106
- * model authors the `.scad` via the router under `directive`, the LOCAL openscad
107
- * kernel (`xvfb-run -a openscad`) gates + renders each round, and compiler
108
- * feedback drives the next round. Returns the final source, per-round renders, a
109
- * screenshot-rich trace, and REAL token usage. This is the seam the GEPA loop
110
- * drives: `directive` is the surface, the deterministic geometry gate is the reward.
111
- */
112
- export async function solveCadRefineLocal(task: BenchTask, cfg: CadLocalConfig): Promise<CadLocalShot> {
113
- const rounds = Math.max(1, cfg.rounds ?? 3)
114
- const directive = cfg.directive ?? DEFAULT_CAD_DIRECTIVE
115
- const trace: Span[] = []
116
- const renders: string[] = []
117
- const runId = `cad-${task.id}`
118
- let ts = Date.now()
119
- const tick = () => (ts += 1)
120
- const usage = { input: 0, output: 0 }
121
- // Carried across rounds in closures (the round Artifact is the .scad source; the
122
- // lastErr steer + resolved early-stop persist outside the loop). usage is REAL.
123
- let lastErr = ''
124
- let resolved = false
125
-
126
- 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)
127
-
128
- // Migrated onto runRefineLoop: the mkdtemp dir is the Ctx; resolved (compiles AND
129
- // has geometry) is the early-stop, modeled as a judge so default-decide stops the
130
- // loop. The round-2+ steer carries lastErr + the prior source verbatim.
131
- const res = await runRefineLoop<string, string>({
132
- rounds,
133
- setup: () => mkdtemp(join(tmpdir(), 'cad-local-')),
134
- prompt: (round, history) =>
135
- round === 1
136
- ? task.prompt
137
- : `Your previous OpenSCAD had this problem:\n${lastErr}\n\nHere is the previous source:\n${history[history.length - 1]?.artifact ?? ''}\n\nFix it so it compiles AND better matches the brief:\n${task.prompt}`,
138
- runShot: async (user, round, dir) => {
139
- const scadPath = join(dir, 'model.scad')
140
- const stlPath = join(dir, 'model.stl')
141
- const pngPath = join(dir, 'model.png')
142
- const turn = await runBenchRouterTurn(
143
- {
144
- routerBaseUrl: cfg.routerBaseUrl,
145
- routerKey: cfg.routerKey,
146
- profile: {
147
- name: 'cad-local-worker',
148
- model: { provider: 'tangle-router', default: cfg.model },
149
- prompt: { systemPrompt: directive },
150
- },
151
- },
152
- user,
153
- )
154
- const content = turn.finalText
155
- if (turn.usage.tokensKnown !== false) {
156
- usage.input += turn.usage.input
157
- usage.output += turn.usage.output
158
- }
159
- const scad = extractScad(content)
160
- trace.push({ spanId: `s-reply-${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)
161
- trace.push({ spanId: `s-write-${round}`, runId, kind: 'tool', name: 'write_file', toolName: 'create_file', args: { path: 'model.scad', content: scad }, startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)
162
-
163
- await writeFile(scadPath, scad)
164
- const compile = await runLocal('xvfb-run', ['-a', 'openscad', '-o', stlPath, scadPath], dir)
165
- const compileOk = compile.code === 0
166
- lastErr = compileOk ? '' : `${compile.stdout}\n${compile.stderr}`.trim().slice(0, 800)
167
- trace.push({ spanId: `s-compile-${round}`, runId, kind: 'tool', name: `openscad r${round}`, toolName: 'shell.exec', args: 'openscad -o model.stl model.scad', result: (compileOk ? compile.stderr : lastErr).slice(0, 1500) || 'ok', startedAt: tick(), endedAt: tick(), status: compileOk ? 'ok' : 'error', error: compileOk ? undefined : `exit ${compile.code}` } as Span)
168
-
169
- let screenshot: string | undefined
170
- if (compileOk) {
171
- // Full CGAL --render (not preview): clean coplanar faces, no z-fighting
172
- // speckle on the window/door cutouts. Dark Tomorrow-Night palette to match
173
- // the film; --autocenter --viewall frames any model regardless of its
174
- // dimensions (so the same command flatters every task in the set).
175
- const render = await runLocal('xvfb-run', ['-a', 'openscad', '-o', pngPath, '--render', '--imgsize=1280,960', '--colorscheme=Tomorrow Night', '--projection=perspective', '--autocenter', '--viewall', '--camera=0,0,0,60,0,25,0', scadPath], dir)
176
- if (render.code === 0) {
177
- const buf = await readFile(pngPath).catch(() => undefined)
178
- if (buf) {
179
- screenshot = `data:image/png;base64,${buf.toString('base64')}`
180
- renders.push(screenshot)
181
- }
182
- }
183
- const stl = await readFile(stlPath, 'utf8').catch(() => '')
184
- resolved = stl.length > 0 && /facet normal/.test(stl)
185
- }
186
- trace.push({ spanId: `s-render-${round}`, runId, kind: 'tool', name: `render r${round}`, toolName: 'render.screenshot', args: { action: `rendered round ${round}`, url: 'model.png' }, attributes: screenshot ? { screenshot } : {}, startedAt: tick(), endedAt: tick(), status: screenshot ? 'ok' : 'error', error: screenshot ? undefined : (compileOk ? 'render produced no image' : 'skipped — did not compile') } as Span)
187
- return { artifact: scad }
188
- },
189
- judge: async () => ({ valid: resolved }),
190
- teardown: (dir) => rm(dir, { recursive: true, force: true }).then(() => {}, () => {}),
191
- })
192
-
193
- return {
194
- artifact: res.final.artifact,
195
- round1Artifact: res.blind.artifact,
196
- trace,
197
- renders,
198
- usage,
199
- ok: res.final.artifact.trim().length > 0,
200
- detail: resolved ? `compiled in ≤${rounds} rounds` : `did not compile cleanly in ${rounds} rounds${lastErr ? `; last: ${lastErr.slice(0, 120)}` : ''}`,
201
- }
202
- }
203
-
204
- export interface CadRefineConfig extends CadWorkerConfig {
205
- /** Max author→gate→refine rounds. Default 3. */
206
- rounds?: number
207
- }
208
-
209
- /**
210
- * Orchestrated CAD refine loop: a BARE universal sandbox is the CAD compute +
211
- * render environment (reliable to provision); the model authors the `.scad` via
212
- * the router, the box's own openscad gates + renders each round, and the
213
- * compiler/geometry feedback drives the next round until it passes or rounds run
214
- * out. This is the "design in a loop" path — every round's render is captured,
215
- * so the trace shows the model improving the house across attempts.
216
- */
217
- export async function solveCadRefine(task: BenchTask, cfg: CadRefineConfig): Promise<CadShotResult> {
218
- const rounds = cfg.rounds ?? 3
219
- const client = new Sandbox({ baseUrl: cfg.sandboxBaseUrl, apiKey: cfg.sandboxKey })
220
- const t0 = Date.now()
221
- const trace: Span[] = []
222
- const runId = `cad-${task.id}`
223
- let ts = t0
224
- const tick = () => (ts += 1)
225
- // The authoring system prompt for the orchestrated sandbox path — kept verbatim,
226
- // distinct from DEFAULT_CAD_DIRECTIVE (the local path's GEPA surface).
227
- const sys = DEFAULT_CAD_SANDBOX_DIRECTIVE
228
- // Carried across rounds in closures (the round Artifact is the .scad source; the
229
- // lastErr steer + resolved early-stop persist outside the loop).
230
- let lastErr = ''
231
- let resolved = false
232
-
233
- // Migrated onto runRefineLoop: the universal sandbox box is the Ctx (acquired once,
234
- // /work created in setup, torn down in teardown). resolved (compiles AND has
235
- // geometry) is the early-stop, modeled as a judge so default-decide stops the loop.
236
- // The round-2+ steer carries lastErr + the prior source verbatim.
237
- const res = await runRefineLoop<string, SandboxBox>({
238
- rounds,
239
- setup: async () => {
240
- const box = await acquireSandbox(client, {
241
- name: `cad-${task.id}-${randomSuffix()}`.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 60),
242
- environment: 'universal',
243
- })
244
- // If init fails AFTER acquire, reap the box here — setup throwing before it
245
- // returns the Ctx means runRefineLoop's teardown never runs, so an unguarded
246
- // mkdir failure would leak the sandbox (the pre-migration finally deleted it).
247
- try {
248
- await box.exec('mkdir -p /work', { timeoutMs: 30_000 })
249
- // The brief frames the title card (understood_task).
250
- 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)
251
- return box
252
- } catch (err) {
253
- try {
254
- await box.delete?.()
255
- } catch {
256
- // platform reaps on expiry
257
- }
258
- throw err
259
- }
260
- },
261
- prompt: (round, history) =>
262
- round === 1
263
- ? task.prompt
264
- : `Your previous OpenSCAD had this problem:\n${lastErr}\n\nHere is the previous source:\n${history[history.length - 1]?.artifact ?? ''}\n\nFix it so it compiles AND better matches the brief:\n${task.prompt}`,
265
- runShot: async (user, round, box) => {
266
- const turn = await runBenchRouterTurn(
267
- {
268
- routerBaseUrl: cfg.routerBaseUrl,
269
- routerKey: cfg.routerKey,
270
- profile: {
271
- name: 'cad-sandbox-worker',
272
- model: { provider: 'tangle-router', default: cfg.model },
273
- prompt: { systemPrompt: sys },
274
- },
275
- },
276
- user,
277
- )
278
- const reply = turn.finalText
279
- const scad = extractScad(reply)
280
- trace.push({ spanId: `s-reply-${round}`, runId, kind: 'llm', name: `author r${round}`, model: cfg.model, messages: [{ role: 'user', content: round === 1 ? task.prompt : 'refine' }], output: reply.slice(0, 600), startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)
281
- trace.push({ spanId: `s-write-${round}`, runId, kind: 'tool', name: 'write_file', toolName: 'create_file', args: { path: 'model.scad', content: scad }, startedAt: tick(), endedAt: tick(), status: 'ok' } as Span)
282
-
283
- await box.fs.write(SCAD_PATH, scad)
284
- const compile = await box.exec(`xvfb-run -a openscad -o ${STL_PATH} ${SCAD_PATH}`, { timeoutMs: 120_000 })
285
- const compileOk = compile.exitCode === 0
286
- lastErr = compileOk ? '' : `${compile.stdout}\n${compile.stderr}`.trim().slice(0, 800)
287
- trace.push({ spanId: `s-compile-${round}`, runId, kind: 'tool', name: `openscad r${round}`, toolName: 'shell.exec', args: 'openscad -o model.stl model.scad', result: (compileOk ? compile.stderr : lastErr).slice(0, 1500) || 'ok', startedAt: tick(), endedAt: tick(), status: compileOk ? 'ok' : 'error', error: compileOk ? undefined : `exit ${compile.exitCode}` } as Span)
288
-
289
- let screenshot: string | undefined
290
- if (compileOk) {
291
- const render = await box.exec(`xvfb-run -a openscad -o ${PNG_PATH} --imgsize=1100,850 --camera=40,30,40,55,0,25,260 --colorscheme=Tomorrow ${SCAD_PATH}`, { timeoutMs: 120_000 })
292
- if (render.exitCode === 0) {
293
- const localPng = join(tmpdir(), `cad-${task.id}-r${round}-${randomSuffix()}.png`)
294
- await box.fs.download(PNG_PATH, localPng).catch(() => undefined)
295
- const buf = await readFile(localPng).catch(() => undefined)
296
- if (buf) screenshot = `data:image/png;base64,${buf.toString('base64')}`
297
- }
298
- // Geometry gate: read STL back + check it's non-trivial (the adapter judge
299
- // does the full spec scoring; here we just decide whether to stop refining).
300
- const stl = await box.fs.read(STL_PATH).catch(() => '')
301
- resolved = stl.length > 0 && /facet normal/.test(stl)
302
- }
303
- trace.push({ spanId: `s-render-${round}`, runId, kind: 'tool', name: `render r${round}`, toolName: 'render.screenshot', args: { action: `rendered round ${round}`, url: 'model.png' }, attributes: screenshot ? { screenshot } : {}, startedAt: tick(), endedAt: tick(), status: screenshot ? 'ok' : 'error', error: screenshot ? undefined : (compileOk ? 'render produced no image' : 'skipped — did not compile') } as Span)
304
- return { artifact: scad }
305
- },
306
- judge: async () => ({ valid: resolved }),
307
- teardown: async (box) => {
308
- try {
309
- await box.delete()
310
- } catch {
311
- // staging reaps on expiry
312
- }
313
- },
314
- })
315
-
316
- const artifact = res.final.artifact
317
- return { artifact, trace, ok: artifact.trim().length > 0, detail: resolved ? `resolved in ≤${rounds} rounds` : `did not fully resolve in ${rounds} rounds${lastErr ? `; last: ${lastErr.slice(0, 120)}` : ''}` }
318
- }
319
-
320
- /** Run one CAD authoring shot in a real sandbox, gating with the box's own
321
- * openscad and capturing a screenshot-rich trace. */
322
- export async function solveCadShot(task: BenchTask, cfg: CadWorkerConfig): Promise<CadShotResult> {
323
- const client = new Sandbox({ baseUrl: cfg.sandboxBaseUrl, apiKey: cfg.sandboxKey })
324
- const box = await acquireSandbox(client, {
325
- name: `cad-${task.id}-${randomSuffix()}`.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 60),
326
- environment: 'universal',
327
- backend: {
328
- type: 'opencode',
329
- // provider/model/baseUrl pinning only — in-box model auth is the box-provisioned
330
- // OPENCODE_MODEL_API_KEY (foreign keys are 403'd at egress).
331
- model: {
332
- provider: cfg.provider ?? 'openai',
333
- model: cfg.model,
334
- baseUrl: cfg.routerBaseUrl,
335
- },
336
- },
337
- })
338
-
339
- const t0 = Date.now()
340
- const trace: Span[] = []
341
- const runId = `cad-${task.id}`
342
-
343
- try {
344
- const prompt = [
345
- task.prompt,
346
- '',
347
- `Write the OpenSCAD source to ${SCAD_PATH} (create the /work directory if needed).`,
348
- `Then verify it compiles by running: xvfb-run -a openscad -o ${STL_PATH} ${SCAD_PATH}`,
349
- `Fix any errors until it compiles cleanly and the geometry matches the brief. Then stop.`,
350
- `The file at ${SCAD_PATH} is the deliverable.`,
351
- ].join('\n')
352
-
353
- // Conversation: the brief (understood_task) + the agent's reply.
354
- trace.push({
355
- spanId: 's-brief',
356
- runId,
357
- kind: 'llm',
358
- name: 'brief',
359
- model: cfg.model,
360
- messages: [{ role: 'user', content: task.prompt }],
361
- startedAt: t0,
362
- endedAt: t0,
363
- status: 'ok',
364
- } as Span)
365
-
366
- const signal = cfg.timeoutMs ? AbortSignal.timeout(cfg.timeoutMs) : undefined
367
- let lastErr: string | undefined
368
- let agentText = ''
369
- for await (const ev of box.streamPrompt(prompt, signal ? { signal } : {})) {
370
- if (ev?.type === 'error') lastErr = JSON.stringify(ev.data).slice(0, 300)
371
- const text = typeof (ev as { text?: unknown })?.text === 'string' ? (ev as unknown as { text: string }).text : ''
372
- if (text) agentText += text
373
- }
374
-
375
- const artifact = await box.fs.read(SCAD_PATH).catch(() => '')
376
- if (artifact.trim()) {
377
- trace.push({
378
- spanId: 's-write',
379
- runId,
380
- kind: 'tool',
381
- name: 'write_file',
382
- toolName: 'create_file',
383
- args: { path: 'model.scad', content: artifact },
384
- startedAt: t0 + 1,
385
- endedAt: t0 + 2,
386
- status: 'ok',
387
- } as Span)
388
- }
389
-
390
- // GATE + RENDER in the sandbox itself (the box's own openscad/xvfb).
391
- const compile = await box.exec(`xvfb-run -a openscad -o ${STL_PATH} ${SCAD_PATH}`, {
392
- timeoutMs: 120_000,
393
- })
394
- trace.push({
395
- spanId: 's-compile',
396
- runId,
397
- kind: 'tool',
398
- name: 'openscad compile',
399
- toolName: 'shell.exec',
400
- args: `openscad -o model.stl model.scad`,
401
- result: `${compile.stdout}\n${compile.stderr}`.trim().slice(0, 2000),
402
- startedAt: t0 + 3,
403
- endedAt: t0 + 4,
404
- status: compile.exitCode === 0 ? 'ok' : 'error',
405
- error: compile.exitCode === 0 ? undefined : `openscad exit ${compile.exitCode}`,
406
- } as Span)
407
-
408
- let screenshot: string | undefined
409
- if (compile.exitCode === 0) {
410
- const render = await box.exec(
411
- `xvfb-run -a openscad -o ${PNG_PATH} --imgsize=1100,850 --camera=40,30,40,55,0,25,260 --colorscheme=Tomorrow ${SCAD_PATH}`,
412
- { timeoutMs: 120_000 },
413
- )
414
- if (render.exitCode === 0) {
415
- const localPng = join(tmpdir(), `cad-${task.id}-${randomSuffix()}.png`)
416
- await box.fs.download(PNG_PATH, localPng).catch(() => undefined)
417
- const buf = await readFile(localPng).catch(() => undefined)
418
- if (buf) screenshot = `data:image/png;base64,${buf.toString('base64')}`
419
- }
420
- }
421
- // Screen span carrying the render — drives run-capsule's screen capsule.
422
- trace.push({
423
- spanId: 's-render',
424
- runId,
425
- kind: 'tool',
426
- name: 'render',
427
- toolName: 'render.screenshot',
428
- args: { action: 'rendered model.scad', url: 'model.png' },
429
- attributes: screenshot ? { screenshot } : {},
430
- startedAt: t0 + 5,
431
- endedAt: t0 + 6,
432
- status: screenshot ? 'ok' : 'error',
433
- error: screenshot ? undefined : 'render produced no image',
434
- } as Span)
435
-
436
- // Agent's closing reply (conversation capsule).
437
- if (agentText.trim()) {
438
- trace.push({
439
- spanId: 's-reply',
440
- runId,
441
- kind: 'llm',
442
- name: 'reply',
443
- model: cfg.model,
444
- messages: [{ role: 'user', content: task.prompt }],
445
- output: agentText.trim().slice(0, 600),
446
- startedAt: t0 + 7,
447
- endedAt: t0 + 8,
448
- status: 'ok',
449
- } as Span)
450
- }
451
-
452
- return {
453
- artifact,
454
- trace,
455
- ok: artifact.trim().length > 0 && compile.exitCode === 0,
456
- detail:
457
- artifact.trim().length === 0
458
- ? `no .scad written${lastErr ? `; lastError=${lastErr}` : ''}`
459
- : compile.exitCode === 0
460
- ? undefined
461
- : `compiled with exit ${compile.exitCode}`,
462
- }
463
- } finally {
464
- try {
465
- await box.delete()
466
- } catch {
467
- /* staging reaps on expiry */
468
- }
469
- }
470
- }