@tangle-network/agent-bench 1.0.2 → 3.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 (222) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +24 -2
  3. package/dist/adapters.d.ts +3 -3
  4. package/dist/adapters.js +3 -5
  5. package/dist/adapters.js.map +1 -1
  6. package/dist/benchmarks/_harness.d.ts +4 -4
  7. package/dist/benchmarks/_harness.js +5 -2
  8. package/dist/benchmarks/_harness.js.map +1 -1
  9. package/dist/benchmarks/aec-bench.d.ts +2 -2
  10. package/dist/benchmarks/aec-bench.js +49 -42
  11. package/dist/benchmarks/aec-bench.js.map +1 -1
  12. package/dist/benchmarks/agentbench.d.ts +2 -2
  13. package/dist/benchmarks/agentbench.js +41 -34
  14. package/dist/benchmarks/agentbench.js.map +1 -1
  15. package/dist/benchmarks/appworld.d.ts +4 -4
  16. package/dist/benchmarks/appworld.js +67 -53
  17. package/dist/benchmarks/appworld.js.map +1 -1
  18. package/dist/benchmarks/bfcl.d.ts +2 -2
  19. package/dist/benchmarks/bfcl.js +52 -44
  20. package/dist/benchmarks/bfcl.js.map +1 -1
  21. package/dist/benchmarks/cad-design.d.ts +2 -2
  22. package/dist/benchmarks/cad-design.js +53 -44
  23. package/dist/benchmarks/cad-design.js.map +1 -1
  24. package/dist/benchmarks/cadbench.d.ts +2 -2
  25. package/dist/benchmarks/cadbench.js +1 -1
  26. package/dist/benchmarks/cadgenbench.d.ts +2 -2
  27. package/dist/benchmarks/cadgenbench.js +1 -1
  28. package/dist/benchmarks/commit0.d.ts +2 -2
  29. package/dist/benchmarks/commit0.js +38 -31
  30. package/dist/benchmarks/commit0.js.map +1 -1
  31. package/dist/benchmarks/crag.d.ts +2 -2
  32. package/dist/benchmarks/crag.js +37 -32
  33. package/dist/benchmarks/crag.js.map +1 -1
  34. package/dist/benchmarks/dabstep.d.ts +2 -2
  35. package/dist/benchmarks/dabstep.js +41 -34
  36. package/dist/benchmarks/dabstep.js.map +1 -1
  37. package/dist/benchmarks/finresearchbench.d.ts +4 -4
  38. package/dist/benchmarks/finresearchbench.js +63 -50
  39. package/dist/benchmarks/finresearchbench.js.map +1 -1
  40. package/dist/benchmarks/finsearchcomp.d.ts +3 -3
  41. package/dist/benchmarks/finsearchcomp.js +55 -44
  42. package/dist/benchmarks/finsearchcomp.js.map +1 -1
  43. package/dist/benchmarks/frames.d.ts +2 -2
  44. package/dist/benchmarks/frames.js +66 -51
  45. package/dist/benchmarks/frames.js.map +1 -1
  46. package/dist/benchmarks/hotpotqa.d.ts +2 -2
  47. package/dist/benchmarks/hotpotqa.js +59 -47
  48. package/dist/benchmarks/hotpotqa.js.map +1 -1
  49. package/dist/benchmarks/humaneval.d.ts +3 -3
  50. package/dist/benchmarks/humaneval.js +39 -35
  51. package/dist/benchmarks/humaneval.js.map +1 -1
  52. package/dist/benchmarks/mcad-bench.d.ts +2 -2
  53. package/dist/benchmarks/mcad-bench.js +68 -56
  54. package/dist/benchmarks/mcad-bench.js.map +1 -1
  55. package/dist/benchmarks/mcad-cq-bench.d.ts +3 -3
  56. package/dist/benchmarks/mcad-cq-bench.js +70 -58
  57. package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
  58. package/dist/benchmarks/mcad-cq-golds.d.ts +1 -1
  59. package/dist/benchmarks/mcad-cq-golds.js +1 -1
  60. package/dist/benchmarks/mcad-cq-golds.js.map +1 -1
  61. package/dist/benchmarks/mcad-golds.d.ts +1 -1
  62. package/dist/benchmarks/mcad-golds.js.map +1 -1
  63. package/dist/benchmarks/mind2web.d.ts +3 -3
  64. package/dist/benchmarks/mind2web.js +62 -49
  65. package/dist/benchmarks/mind2web.js.map +1 -1
  66. package/dist/benchmarks/nomiracl.d.ts +2 -2
  67. package/dist/benchmarks/nomiracl.js +43 -36
  68. package/dist/benchmarks/nomiracl.js.map +1 -1
  69. package/dist/benchmarks/open-rag-bench.d.ts +2 -2
  70. package/dist/benchmarks/open-rag-bench.js +37 -32
  71. package/dist/benchmarks/open-rag-bench.js.map +1 -1
  72. package/dist/benchmarks/programbench.d.ts +2 -2
  73. package/dist/benchmarks/programbench.js +28 -23
  74. package/dist/benchmarks/programbench.js.map +1 -1
  75. package/dist/benchmarks/rag-shared.d.ts +2 -2
  76. package/dist/benchmarks/rag-shared.js +15 -13
  77. package/dist/benchmarks/rag-shared.js.map +1 -1
  78. package/dist/benchmarks/ragbench.d.ts +2 -2
  79. package/dist/benchmarks/ragbench.js +34 -29
  80. package/dist/benchmarks/ragbench.js.map +1 -1
  81. package/dist/benchmarks/simpleqa.d.ts +2 -2
  82. package/dist/benchmarks/simpleqa.js +63 -52
  83. package/dist/benchmarks/simpleqa.js.map +1 -1
  84. package/dist/benchmarks/swe-bench.d.ts +4 -4
  85. package/dist/benchmarks/swe-bench.js +47 -41
  86. package/dist/benchmarks/swe-bench.js.map +1 -1
  87. package/dist/benchmarks/t2-ragbench.d.ts +2 -2
  88. package/dist/benchmarks/t2-ragbench.js +37 -32
  89. package/dist/benchmarks/t2-ragbench.js.map +1 -1
  90. package/dist/benchmarks/tau-bench-shared.d.ts +2 -2
  91. package/dist/benchmarks/tau-bench-shared.js +43 -36
  92. package/dist/benchmarks/tau-bench-shared.js.map +1 -1
  93. package/dist/benchmarks/tau2-bench.d.ts +2 -2
  94. package/dist/benchmarks/tau2-bench.js.map +1 -1
  95. package/dist/benchmarks/tau3-banking.d.ts +2 -2
  96. package/dist/benchmarks/tau3-banking.js.map +1 -1
  97. package/dist/benchmarks/terminal-bench.d.ts +2 -2
  98. package/dist/benchmarks/terminal-bench.js +29 -23
  99. package/dist/benchmarks/terminal-bench.js.map +1 -1
  100. package/dist/benchmarks/toollm.d.ts +2 -2
  101. package/dist/benchmarks/toollm.js +40 -34
  102. package/dist/benchmarks/toollm.js.map +1 -1
  103. package/dist/benchmarks/trata-hedge.d.ts +2 -2
  104. package/dist/benchmarks/trata-hedge.js +49 -43
  105. package/dist/benchmarks/trata-hedge.js.map +1 -1
  106. package/dist/benchmarks/types.d.ts +33 -63
  107. package/dist/benchmarks/types.js +36 -1
  108. package/dist/benchmarks/types.js.map +1 -0
  109. package/dist/benchmarks/webarena-verified.d.ts +2 -2
  110. package/dist/benchmarks/webarena-verified.js +29 -24
  111. package/dist/benchmarks/webarena-verified.js.map +1 -1
  112. package/dist/{cadbench-DhAndllg.js → cadbench-htzAmMaI.js} +41 -36
  113. package/dist/cadbench-htzAmMaI.js.map +1 -0
  114. package/dist/{cadgenbench-Tvk16YKT.js → cadgenbench-BLvEtnxU.js} +28 -22
  115. package/dist/cadgenbench-BLvEtnxU.js.map +1 -0
  116. package/dist/cli.d.ts +1 -0
  117. package/dist/cli.js +667 -0
  118. package/dist/cli.js.map +1 -0
  119. package/dist/index.d.ts +11 -10
  120. package/dist/index.js +64 -59
  121. package/dist/index.js.map +1 -1
  122. package/package.json +9 -6
  123. package/scripts/enterpriseops-gym-run.sh +82 -0
  124. package/scripts/grade-recorded-evidence.mjs +50 -0
  125. package/scripts/harvey-lab-judge.py +50 -0
  126. package/scripts/harvey-lab-run.sh +53 -0
  127. package/scripts/harvey-lab-sandbox.sh +21 -0
  128. package/scripts/healthbench-professional-run.sh +30 -0
  129. package/scripts/healthbench_professional_run.py +112 -0
  130. package/scripts/mlcr-run.sh +17 -0
  131. package/scripts/mlcr_run.py +133 -0
  132. package/scripts/prbench-run.sh +39 -0
  133. package/scripts/prbench_run.py +53 -0
  134. package/scripts/verify-packed-consumer.mjs +32 -27
  135. package/src/adapters.ts +5 -7
  136. package/src/atom-mcp-e2e.mts +2 -2
  137. package/src/benchmarks/_harness.test.mts +18 -1
  138. package/src/benchmarks/_harness.ts +12 -7
  139. package/src/benchmarks/aec-bench.test.mts +14 -14
  140. package/src/benchmarks/aec-bench.ts +62 -56
  141. package/src/benchmarks/agent-eval-contract.test.mts +38 -0
  142. package/src/benchmarks/agentbench.ts +44 -37
  143. package/src/benchmarks/appworld.test.mts +7 -7
  144. package/src/benchmarks/appworld.ts +88 -75
  145. package/src/benchmarks/bfcl.ts +60 -53
  146. package/src/benchmarks/cad-design.ts +34 -32
  147. package/src/benchmarks/cadbench.ts +36 -36
  148. package/src/benchmarks/cadgenbench.ts +30 -28
  149. package/src/benchmarks/commit0.test.mts +9 -9
  150. package/src/benchmarks/commit0.ts +50 -43
  151. package/src/benchmarks/crag.ts +45 -40
  152. package/src/benchmarks/dabstep-official.test.mts +8 -8
  153. package/src/benchmarks/dabstep.test.mts +11 -11
  154. package/src/benchmarks/dabstep.ts +47 -40
  155. package/src/benchmarks/external-adapters.test.mts +43 -44
  156. package/src/benchmarks/finresearchbench.ts +58 -48
  157. package/src/benchmarks/finsearchcomp.ts +73 -68
  158. package/src/benchmarks/frames.ts +76 -69
  159. package/src/benchmarks/hotpotqa.ts +69 -64
  160. package/src/benchmarks/humaneval.ts +37 -35
  161. package/src/benchmarks/mcad-bench.test.mts +30 -30
  162. package/src/benchmarks/mcad-bench.ts +66 -60
  163. package/src/benchmarks/mcad-cq-bench.ts +69 -63
  164. package/src/benchmarks/mcad-cq-golds.ts +1 -1
  165. package/src/benchmarks/mcad-cq.test.mts +40 -40
  166. package/src/benchmarks/mcad-golds.ts +1 -1
  167. package/src/benchmarks/mind2web.ts +66 -58
  168. package/src/benchmarks/nomiracl.ts +53 -46
  169. package/src/benchmarks/open-rag-bench.ts +47 -42
  170. package/src/benchmarks/programbench.test.mts +10 -10
  171. package/src/benchmarks/programbench.ts +38 -33
  172. package/src/benchmarks/rag-benchmarks.test.mts +31 -31
  173. package/src/benchmarks/rag-shared.ts +13 -16
  174. package/src/benchmarks/ragbench.ts +44 -39
  175. package/src/benchmarks/simpleqa.ts +79 -74
  176. package/src/benchmarks/swe-bench.test.mts +3 -3
  177. package/src/benchmarks/swe-bench.ts +66 -61
  178. package/src/benchmarks/t2-ragbench.ts +47 -42
  179. package/src/benchmarks/tau-bench-shared.ts +51 -44
  180. package/src/benchmarks/tau-pin.test.mts +1 -1
  181. package/src/benchmarks/tau2-bench.ts +2 -2
  182. package/src/benchmarks/tau3-banking.ts +2 -2
  183. package/src/benchmarks/terminal-bench.test.mts +3 -3
  184. package/src/benchmarks/terminal-bench.ts +41 -36
  185. package/src/benchmarks/toollm.ts +54 -47
  186. package/src/benchmarks/trata-hedge.ts +61 -58
  187. package/src/benchmarks/types.ts +70 -59
  188. package/src/benchmarks/webarena-verified.ts +49 -42
  189. package/src/cli.ts +74 -0
  190. package/src/corpus-replay.mts +9 -9
  191. package/src/examples/benchmark-matrix.mts +19 -16
  192. package/src/examples/lean-proof-gate.mts +1 -1
  193. package/src/examples/math-demo.mts +2 -2
  194. package/src/examples/strategy-demo.mts +1 -1
  195. package/src/gate-cli.mts +6 -6
  196. package/src/gate.test.mts +14 -12
  197. package/src/gate.ts +23 -22
  198. package/src/generate-eval/certify.ts +4 -4
  199. package/src/index.ts +17 -11
  200. package/src/published.test.mts +534 -0
  201. package/src/published.ts +524 -0
  202. package/src/run-benchmarks-cli.mts +3 -3
  203. package/src/run-benchmarks.test.mts +58 -48
  204. package/src/run-benchmarks.ts +64 -57
  205. package/src/swe-bench-env.ts +6 -6
  206. package/src/swe-self-improve.mts +3 -3
  207. package/src/terminal-compare.ts +1 -1
  208. package/src/worker.ts +1 -1
  209. package/dist/benchmarks/enterpriseops-gym.d.ts +0 -6
  210. package/dist/benchmarks/enterpriseops-gym.js +0 -236
  211. package/dist/benchmarks/enterpriseops-gym.js.map +0 -1
  212. package/dist/cadbench-DhAndllg.js.map +0 -1
  213. package/dist/cadgenbench-Tvk16YKT.js.map +0 -1
  214. package/fixtures/enterpriseops-gym.json +0 -103
  215. package/scripts/enterpriseops_gym_judge.py +0 -281
  216. package/src/benchmarks/enterpriseops-gym.test.mts +0 -77
  217. package/src/benchmarks/enterpriseops-gym.ts +0 -343
  218. package/src/eops-skills/address-every-subtask.md +0 -5
  219. package/src/eops-skills/exact-tools-and-args.md +0 -5
  220. package/src/eops-skills/full-sequence-to-goal.md +0 -5
  221. package/src/eops-skills/ground-every-value.md +0 -5
  222. package/src/eops-skills/honor-the-policies.md +0 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.0.0
4
+
5
+ Breaking: every adapter is now agent-eval's `BenchmarkAdapter` (agent-eval `^2.0.11`), the one benchmark contract, and agent-bench's own `BenchmarkAdapter`, `BenchScore` and the old `BenchTask` shape are gone.
6
+ An adapter is a `RuntimeBenchmark`, built with `runtimeBenchmark({ id, loadAll, evaluate, runtime })`:
7
+ - `name` is `id`.
8
+ - `loadTasks` is `loadAll`, and its `split` option is `subset` (the publisher's domain, category, language or dataset split).
9
+ - `judge` is `evaluate`, returning agent-eval's verdict `{ passed, score, notes, raw }` plus `judgeArtifacts` and `judgeUsage` (`resolved` is `passed`, `detail` is `notes`).
10
+ - `preflight`, `goldArtifact` and `output` move under `runtime`; `boxSetup`, `boxExtract` and `leafClient` are `runtime.workspaceSetup`, `runtime.workspaceExtract` and `runtime.worker`.
11
+ - A task is agent-eval's `BenchmarkDatasetItem`: the prompt is `payload.prompt` (read it with `runtime.prompt(task)`), and the publisher's subset is `payload.subset`.
12
+ - `loadDataset(split)` and `assignSplit` serve the same tasks by agent-eval's `deterministicSplit`, so agent-eval's benchmark runners take any adapter as is.
13
+
14
+ `answerScoreToBenchScore` is `answerScoreToEvaluation`.
15
+ `runBenchmarks` and `runGate` take `subset` for `split`, and the CLIs read `SUBSET` for `SPLIT`; `gate-cli` requires `BENCH`.
16
+ `agent-bench run` task scores and RunRecords say `passed` and `notes` for `resolved` and `detail`.
17
+ The reimplemented EnterpriseOps-Gym adapter is deleted: `agent-bench run enterpriseops-gym` runs ServiceNow's own runner and grader.
18
+
19
+ `agent-bench run healthbench-professional` runs openai/simple-evals' HealthBenchEval with its HealthBench Professional settings (GPT-5.4 low grader, length adjustment) on the openai/healthbench-professional release, fetched at a pinned revision at run time and never committed. OpenAI releases no official implementation, so these runs are never official; a registry entry's new `unofficial` names why.
20
+
21
+ `agent-bench run mlcr` runs MLCR v1.1 with its publisher's own runner and scorer: an OpenAI-compatible endpoint is a registered provider, the experiment is the publisher's smoke experiment, and the jury is the publisher's three judges or one substituted judge. The Wisedocs/mlcr-dataset release carries no license, so it is fetched at a pinned revision into the publisher checkout at run time and never committed.
22
+
23
+ ## 2.0.0
24
+
25
+ Breaking: the public types now come from `@tangle-network/agent-runtime` `^9.0.3` (was `^8.0.1`); consumers move to agent-runtime 9 with it. 1.0.3 to 1.0.5 were tagged, never published, and their changes ship here. Recorded runs are graded with a fresh terminal-bench cache (#2550). Default judge and worker models move to the newest Router model in their tier: `deepseek/deepseek-v4.1-flash` for `deepseek-v4-flash` (bare `deepseek-v4.1-flash` where a slash would select a harness), `gemini-3.1-pro-preview` for the Trata hedge judge's `gemini-2.5-pro`, and `opencode/zai-coding-plan/glm-5.3` for atom-mcp-e2e's `glm-5-turbo`, which the bridge no longer serves. The Trata hedge and CADBench judges and the generated-eval discrimination gate now build profiles Runtime accepts (`maxVisibleOutputTokens`, `harness: 'cli-base'`); before, each was refused before any model call.
26
+
27
+ ## 1.0.3
28
+
29
+ Release qualification grades the three recorded 2026-09-24 agent outputs (Terminal-Bench `hello-world` and `fix-permissions`, SWE-bench Verified `astropy__astropy-12907`) with their official judges through the packed archive, and refuses unless each grade matches its recorded verdict.
30
+ `scripts/grade-recorded-evidence.mjs` runs it; no model is called. The stray compiled `script_agent` bytecode is removed from the source tree.
31
+
3
32
  ## 1.0.2
4
33
 
5
34
  Follows `@tangle-network/agent-runtime` 8.0.1 (`^8.0.1`). No code change.
package/README.md CHANGED
@@ -27,8 +27,30 @@ pnpm add -D @tangle-network/agent-bench
27
27
  import { resolveAdapter } from '@tangle-network/agent-bench'
28
28
 
29
29
  const crag = resolveAdapter('crag')
30
+ const [task] = await crag.loadAll({ limit: 1 })
31
+ const verdict = await crag.evaluate(task, artifact) // { passed, score, notes, raw }
30
32
  ```
31
33
 
34
+ Every adapter is an agent-eval `BenchmarkAdapter` (`RuntimeBenchmark`), so agent-eval's benchmark runners take it as is.
35
+ Its `runtime` hooks are what an agent-runtime worker needs: `prompt`, `preflight`, the deliverable parser `output`, `workspaceSetup` and `workspaceExtract` in the box, and `worker` where the benchmark's own protocol is the worker.
36
+ `loadAll` returns every task in the publisher's order (`limit`, `ids`, and the publisher's `subset`: a domain, category or language), ignoring agent-eval's search/dev/holdout splits; `loadDataset(split)` serves the same tasks by agent-eval's `deterministicSplit`.
37
+ Build a new one with `runtimeBenchmark({ id, loadAll, evaluate, runtime })`.
38
+
39
+ ## Published benchmarks through their own runners
40
+
41
+ `agent-bench run <benchmark> --target <target>` runs a published benchmark with its publisher's own runner and grader, unmodified, at the commit `src/published.ts` pins, and prints the publisher's score with what it measured:
42
+
43
+ ```bash
44
+ TANGLE_API_KEY=... agent-bench run automationbench --target model:<router model> --tasks 5
45
+ agent-bench list
46
+ ```
47
+
48
+ - `model:<router model>` calls the Tangle Router; a `:free` model takes its free test lane.
49
+ - `profile:<harness/model>` runs that harness with its own loop and tools through a CLI Bridge (`AGENT_BENCH_BRIDGE_URL`, default `http://127.0.0.1:3344/v1`, key in `AGENT_BENCH_BRIDGE_KEY`); the benchmark's tools reach it as caller-executed MCP tools, so the run measures `own-loop`.
50
+ - `app:<app>@<harness/model>` runs an agent app's executable profile on that harness through the same CLI Bridge, with the app's production model replaced by the harness model; the run records both.
51
+ - Each run records `measured` (`model-shaped`: the target as a model calling the benchmark's tools; `own-loop`: the agent with its own loop and tools), the judge, and `official: false` whenever a judge was substituted.
52
+ - Arguments after `--` go to the publisher's runner unchanged. Publisher checkouts are cached in `~/.cache/agent-bench/published`.
53
+
32
54
  ## SWE-bench judge setup (the one block not in HARNESS.md)
33
55
 
34
56
  ```bash
@@ -51,7 +73,7 @@ const adapter = createSweBenchAdapter({
51
73
  destination: path.join(runDirectory, taskId, String(attemptSequence)),
52
74
  }),
53
75
  })
54
- const score = await adapter.judge(task, patch)
76
+ const score = await adapter.evaluate(task, patch)
55
77
  console.log(score.judgeArtifacts?.manifestPath)
56
78
  ```
57
79
 
@@ -84,7 +106,7 @@ The public [adyen/DABstep](https://huggingface.co/datasets/adyen/DABstep) releas
84
106
  Point `DABSTEP_DATASET_CSV` at an absolute row-file path when the checkout and the rows live apart.
85
107
 
86
108
  **FinResearchBench.**
87
- The judge is a model call, so its score records the exact judge turn usage on `BenchScore.judgeUsage` (tokens, cost, model).
109
+ The judge is a model call, so its score records the exact judge turn usage on `BenchEvaluation.judgeUsage` (tokens, cost, model).
88
110
  `tokensKnown: false` and `usdKnown: false` survive verbatim; an unknown judge cost never reads as zero spend.
89
111
  `FINRESEARCHBENCH_JUDGE_MODEL` (or `JUDGE_MODEL`) selects the judge; `FINRESEARCHBENCH_PASS_THRESHOLD` moves the resolve bar from 0.8.
90
112
 
@@ -1,5 +1,5 @@
1
- import { BenchmarkAdapter } from "./benchmarks/types.js";
2
- export declare const ADAPTERS: Record<string, () => BenchmarkAdapter>;
1
+ import { RuntimeBenchmark } from "./benchmarks/types.js";
2
+ export declare const ADAPTERS: Record<string, () => RuntimeBenchmark>;
3
3
  /** Resolve a benchmark key to its adapter, failing loud with the known keys. */
4
- export declare function resolveAdapter(key: string): BenchmarkAdapter;
4
+ export declare function resolveAdapter(key: string): RuntimeBenchmark;
5
5
  //# sourceMappingURL=adapters.d.ts.map
package/dist/adapters.js CHANGED
@@ -2,13 +2,12 @@ import { createAecBenchAdapter } from "./benchmarks/aec-bench.js";
2
2
  import { createAgentBenchAdapter } from "./benchmarks/agentbench.js";
3
3
  import { createAppWorldAdapter, createAppWorldReactAdapter } from "./benchmarks/appworld.js";
4
4
  import { createBfclAdapter } from "./benchmarks/bfcl.js";
5
- import { t as createCadBenchAdapter } from "./cadbench-DhAndllg.js";
5
+ import { t as createCadBenchAdapter } from "./cadbench-htzAmMaI.js";
6
6
  import { createCadDesignAdapter } from "./benchmarks/cad-design.js";
7
- import { t as createCadGenBenchAdapter } from "./cadgenbench-Tvk16YKT.js";
7
+ import { t as createCadGenBenchAdapter } from "./cadgenbench-BLvEtnxU.js";
8
8
  import { createCommit0Adapter } from "./benchmarks/commit0.js";
9
9
  import { createCragAdapter } from "./benchmarks/crag.js";
10
10
  import { createDabstepAdapter } from "./benchmarks/dabstep.js";
11
- import { createEnterpriseOpsGymAdapter } from "./benchmarks/enterpriseops-gym.js";
12
11
  import { createFinResearchBenchAdapter } from "./benchmarks/finresearchbench.js";
13
12
  import { createFinsearchcompAdapter } from "./benchmarks/finsearchcomp.js";
14
13
  import { createFramesAdapter } from "./benchmarks/frames.js";
@@ -33,7 +32,7 @@ import { createWebArenaVerifiedAdapter } from "./benchmarks/webarena-verified.js
33
32
  // src/adapters.ts
34
33
  /**
35
34
  * The benchmark registry — the single source of truth for every wired benchmark.
36
- * One key per benchmark; the value is its `BenchmarkAdapter` factory. `runBenchmarks`
35
+ * One key per benchmark; the value is its `RuntimeBenchmark` factory (an agent-eval `BenchmarkAdapter`). `runBenchmarks`
37
36
  * (the unifier) maps over this; `run.ts`, `rsi.ts`, and `corpus-replay.mts` all read it
38
37
  * here rather than each keeping their own copy.
39
38
  */
@@ -52,7 +51,6 @@ const ADAPTERS = {
52
51
  toollm: createToolLlmAdapter,
53
52
  appworld: createAppWorldAdapter,
54
53
  "appworld-react": createAppWorldReactAdapter,
55
- "enterpriseops-gym": createEnterpriseOpsGymAdapter,
56
54
  "cad-design": createCadDesignAdapter,
57
55
  mcad: createMcadBenchAdapter,
58
56
  "mcad-cq": createMcadCqAdapter,
@@ -1 +1 @@
1
- {"version":3,"file":"adapters.js","names":[],"sources":["../src/adapters.ts"],"sourcesContent":["/**\n * The benchmark registry — the single source of truth for every wired benchmark.\n * One key per benchmark; the value is its `BenchmarkAdapter` factory. `runBenchmarks`\n * (the unifier) maps over this; `run.ts`, `rsi.ts`, and `corpus-replay.mts` all read it\n * here rather than each keeping their own copy.\n */\n\nimport { createAecBenchAdapter } from './benchmarks/aec-bench'\nimport { createAgentBenchAdapter } from './benchmarks/agentbench'\nimport { createAppWorldAdapter, createAppWorldReactAdapter } from './benchmarks/appworld'\nimport { createBfclAdapter } from './benchmarks/bfcl'\nimport { createCadBenchAdapter } from './benchmarks/cadbench'\nimport { createCadDesignAdapter } from './benchmarks/cad-design'\nimport { createCadGenBenchAdapter } from './benchmarks/cadgenbench'\nimport { createCommit0Adapter } from './benchmarks/commit0'\nimport { createCragAdapter } from './benchmarks/crag'\nimport { createDabstepAdapter } from './benchmarks/dabstep'\nimport { createEnterpriseOpsGymAdapter } from './benchmarks/enterpriseops-gym'\nimport { createFinResearchBenchAdapter } from './benchmarks/finresearchbench'\nimport { createFinsearchcompAdapter } from './benchmarks/finsearchcomp'\nimport { createFramesAdapter } from './benchmarks/frames'\nimport { createHotpotqaAdapter } from './benchmarks/hotpotqa'\nimport { createHumanEvalAdapter } from './benchmarks/humaneval'\nimport { createMcadBenchAdapter } from './benchmarks/mcad-bench'\nimport { createMcadCqAdapter } from './benchmarks/mcad-cq-bench'\nimport { createMind2WebAdapter } from './benchmarks/mind2web'\nimport { createNoMiraclAdapter } from './benchmarks/nomiracl'\nimport { createOpenRagBenchAdapter } from './benchmarks/open-rag-bench'\nimport { createProgrambenchAdapter } from './benchmarks/programbench'\nimport { createRagBenchAdapter } from './benchmarks/ragbench'\nimport { createSimpleQaAdapter } from './benchmarks/simpleqa'\nimport { createSweBenchAdapter } from './benchmarks/swe-bench'\nimport { createT2RagBenchAdapter } from './benchmarks/t2-ragbench'\nimport { createTau2BenchAdapter } from './benchmarks/tau2-bench'\nimport { createTau3BankingAdapter } from './benchmarks/tau3-banking'\nimport { createTerminalBenchAdapter } from './benchmarks/terminal-bench'\nimport { createToolLlmAdapter } from './benchmarks/toollm'\nimport { createTrataHedgeAdapter } from './benchmarks/trata-hedge'\nimport { createWebArenaVerifiedAdapter } from './benchmarks/webarena-verified'\nimport type { BenchmarkAdapter } from './benchmarks/types'\n\nexport const ADAPTERS: Record<string, () => BenchmarkAdapter> = {\n 'swe-bench': createSweBenchAdapter,\n 'terminal-bench': createTerminalBenchAdapter,\n // Code-benches sharing ./benchmarks/_harness (stage → external evaluator → report).\n // loadTasks fetches the REAL dataset (committed fixtures fallback offline); judge\n // delegates to the benchmark's own harness and fails loud when it/Docker is absent.\n 'aec-bench': createAecBenchAdapter,\n commit0: createCommit0Adapter,\n dabstep: createDabstepAdapter,\n programbench: createProgrambenchAdapter,\n 'webarena-verified': createWebArenaVerifiedAdapter,\n 'tau2-bench': createTau2BenchAdapter,\n 'tau3-banking': createTau3BankingAdapter,\n agentbench: createAgentBenchAdapter,\n bfcl: createBfclAdapter,\n toollm: createToolLlmAdapter,\n appworld: createAppWorldAdapter,\n // AppWorld's native interactive protocol — the worker is the in-engine ReAct\n // episode (execution feedback every turn), the mode published baselines use.\n 'appworld-react': createAppWorldReactAdapter,\n 'enterpriseops-gym': createEnterpriseOpsGymAdapter,\n 'cad-design': createCadDesignAdapter,\n // Dimensioned mechanical parts: same OpenSCAD+xvfb judge deps as cad-design, but\n // the spec is metric (bbox / volume / body count / point-in-solid hole probes)\n // rather than qualitative, and every task carries a verified gold.\n mcad: createMcadBenchAdapter,\n // The same 10 parts and the same spec assertions, but the worker writes a Python\n // CadQuery script that must export STEP as well as the ASCII STL — which closes\n // the format deviation `mcad-tasks.ts` documents (upstream asks for STEP;\n // OpenSCAD cannot emit it). STEP delivery is one extra SCORED check.\n 'mcad-cq': createMcadCqAdapter,\n cadbench: createCadBenchAdapter,\n cadgenbench: createCadGenBenchAdapter,\n frames: createFramesAdapter,\n ragbench: createRagBenchAdapter,\n crag: createCragAdapter,\n nomiracl: createNoMiraclAdapter,\n 'open-rag-bench': createOpenRagBenchAdapter,\n 't2-ragbench': createT2RagBenchAdapter,\n finresearchbench: createFinResearchBenchAdapter,\n finsearchcomp: createFinsearchcompAdapter,\n simpleqa: createSimpleQaAdapter,\n hotpotqa: createHotpotqaAdapter,\n // Deployable-checker code domain: worker = router completion, judge = Docker test\n // run (--network=none). The steering A/B counterpart to humaneval-gate.mts (selection).\n humaneval: createHumanEvalAdapter,\n mind2web: createMind2WebAdapter,\n 'trata-hedge': createTrataHedgeAdapter,\n}\n\n/** Resolve a benchmark key to its adapter, failing loud with the known keys. */\nexport function resolveAdapter(key: string): BenchmarkAdapter {\n const make = ADAPTERS[key]\n if (!make) throw new Error(`unknown benchmark ${JSON.stringify(key)} (have: ${Object.keys(ADAPTERS).join(', ')})`)\n return make()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,WAAmD;CAC9D,aAAa;CACb,kBAAkB;CAIlB,aAAa;CACb,SAAS;CACT,SAAS;CACT,cAAc;CACd,qBAAqB;CACrB,cAAc;CACd,gBAAgB;CAChB,YAAY;CACZ,MAAM;CACN,QAAQ;CACR,UAAU;CAGV,kBAAkB;CAClB,qBAAqB;CACrB,cAAc;CAId,MAAM;CAKN,WAAW;CACX,UAAU;CACV,aAAa;CACb,QAAQ;CACR,UAAU;CACV,MAAM;CACN,UAAU;CACV,kBAAkB;CAClB,eAAe;CACf,kBAAkB;CAClB,eAAe;CACf,UAAU;CACV,UAAU;CAGV,WAAW;CACX,UAAU;CACV,eAAe;AACjB;;AAGA,SAAgB,eAAe,KAA+B;CAC5D,MAAM,OAAO,SAAS;CACtB,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,qBAAqB,KAAK,UAAU,GAAG,EAAE,UAAU,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,EAAE;CACjH,OAAO,KAAK;AACd"}
1
+ {"version":3,"file":"adapters.js","names":[],"sources":["../src/adapters.ts"],"sourcesContent":["/**\n * The benchmark registry — the single source of truth for every wired benchmark.\n * One key per benchmark; the value is its `RuntimeBenchmark` factory (an agent-eval `BenchmarkAdapter`). `runBenchmarks`\n * (the unifier) maps over this; `run.ts`, `rsi.ts`, and `corpus-replay.mts` all read it\n * here rather than each keeping their own copy.\n */\n\nimport { createAecBenchAdapter } from './benchmarks/aec-bench'\nimport { createAgentBenchAdapter } from './benchmarks/agentbench'\nimport { createAppWorldAdapter, createAppWorldReactAdapter } from './benchmarks/appworld'\nimport { createBfclAdapter } from './benchmarks/bfcl'\nimport { createCadBenchAdapter } from './benchmarks/cadbench'\nimport { createCadDesignAdapter } from './benchmarks/cad-design'\nimport { createCadGenBenchAdapter } from './benchmarks/cadgenbench'\nimport { createCommit0Adapter } from './benchmarks/commit0'\nimport { createCragAdapter } from './benchmarks/crag'\nimport { createDabstepAdapter } from './benchmarks/dabstep'\nimport { createFinResearchBenchAdapter } from './benchmarks/finresearchbench'\nimport { createFinsearchcompAdapter } from './benchmarks/finsearchcomp'\nimport { createFramesAdapter } from './benchmarks/frames'\nimport { createHotpotqaAdapter } from './benchmarks/hotpotqa'\nimport { createHumanEvalAdapter } from './benchmarks/humaneval'\nimport { createMcadBenchAdapter } from './benchmarks/mcad-bench'\nimport { createMcadCqAdapter } from './benchmarks/mcad-cq-bench'\nimport { createMind2WebAdapter } from './benchmarks/mind2web'\nimport { createNoMiraclAdapter } from './benchmarks/nomiracl'\nimport { createOpenRagBenchAdapter } from './benchmarks/open-rag-bench'\nimport { createProgrambenchAdapter } from './benchmarks/programbench'\nimport { createRagBenchAdapter } from './benchmarks/ragbench'\nimport { createSimpleQaAdapter } from './benchmarks/simpleqa'\nimport { createSweBenchAdapter } from './benchmarks/swe-bench'\nimport { createT2RagBenchAdapter } from './benchmarks/t2-ragbench'\nimport { createTau2BenchAdapter } from './benchmarks/tau2-bench'\nimport { createTau3BankingAdapter } from './benchmarks/tau3-banking'\nimport { createTerminalBenchAdapter } from './benchmarks/terminal-bench'\nimport { createToolLlmAdapter } from './benchmarks/toollm'\nimport { createTrataHedgeAdapter } from './benchmarks/trata-hedge'\nimport { createWebArenaVerifiedAdapter } from './benchmarks/webarena-verified'\nimport type { RuntimeBenchmark } from './benchmarks/types'\n\nexport const ADAPTERS: Record<string, () => RuntimeBenchmark> = {\n 'swe-bench': createSweBenchAdapter,\n 'terminal-bench': createTerminalBenchAdapter,\n // Code-benches sharing ./benchmarks/_harness (stage → external evaluator → report).\n // loadAll fetches the REAL dataset (committed fixtures fallback offline); evaluate\n // delegates to the benchmark's own harness and fails loud when it/Docker is absent.\n 'aec-bench': createAecBenchAdapter,\n commit0: createCommit0Adapter,\n dabstep: createDabstepAdapter,\n programbench: createProgrambenchAdapter,\n 'webarena-verified': createWebArenaVerifiedAdapter,\n 'tau2-bench': createTau2BenchAdapter,\n 'tau3-banking': createTau3BankingAdapter,\n agentbench: createAgentBenchAdapter,\n bfcl: createBfclAdapter,\n toollm: createToolLlmAdapter,\n appworld: createAppWorldAdapter,\n // AppWorld's native interactive protocol — the worker is the in-engine ReAct\n // episode (execution feedback every turn), the mode published baselines use.\n 'appworld-react': createAppWorldReactAdapter,\n 'cad-design': createCadDesignAdapter,\n // Dimensioned mechanical parts: same OpenSCAD+xvfb judge deps as cad-design, but\n // the spec is metric (bbox / volume / body count / point-in-solid hole probes)\n // rather than qualitative, and every task carries a verified gold.\n mcad: createMcadBenchAdapter,\n // The same 10 parts and the same spec assertions, but the worker writes a Python\n // CadQuery script that must export STEP as well as the ASCII STL — which closes\n // the format deviation `mcad-tasks.ts` documents (upstream asks for STEP;\n // OpenSCAD cannot emit it). STEP delivery is one extra SCORED check.\n 'mcad-cq': createMcadCqAdapter,\n cadbench: createCadBenchAdapter,\n cadgenbench: createCadGenBenchAdapter,\n frames: createFramesAdapter,\n ragbench: createRagBenchAdapter,\n crag: createCragAdapter,\n nomiracl: createNoMiraclAdapter,\n 'open-rag-bench': createOpenRagBenchAdapter,\n 't2-ragbench': createT2RagBenchAdapter,\n finresearchbench: createFinResearchBenchAdapter,\n finsearchcomp: createFinsearchcompAdapter,\n simpleqa: createSimpleQaAdapter,\n hotpotqa: createHotpotqaAdapter,\n // Deployable-checker code domain: worker = router completion, judge = Docker test\n // run (--network=none). The steering A/B counterpart to humaneval-gate.mts (selection).\n humaneval: createHumanEvalAdapter,\n mind2web: createMind2WebAdapter,\n 'trata-hedge': createTrataHedgeAdapter,\n}\n\n/** Resolve a benchmark key to its adapter, failing loud with the known keys. */\nexport function resolveAdapter(key: string): RuntimeBenchmark {\n const make = ADAPTERS[key]\n if (!make) throw new Error(`unknown benchmark ${JSON.stringify(key)} (have: ${Object.keys(ADAPTERS).join(', ')})`)\n return make()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,WAAmD;CAC9D,aAAa;CACb,kBAAkB;CAIlB,aAAa;CACb,SAAS;CACT,SAAS;CACT,cAAc;CACd,qBAAqB;CACrB,cAAc;CACd,gBAAgB;CAChB,YAAY;CACZ,MAAM;CACN,QAAQ;CACR,UAAU;CAGV,kBAAkB;CAClB,cAAc;CAId,MAAM;CAKN,WAAW;CACX,UAAU;CACV,aAAa;CACb,QAAQ;CACR,UAAU;CACV,MAAM;CACN,UAAU;CACV,kBAAkB;CAClB,eAAe;CACf,kBAAkB;CAClB,eAAe;CACf,UAAU;CACV,UAAU;CAGV,WAAW;CACX,UAAU;CACV,eAAe;AACjB;;AAGA,SAAgB,eAAe,KAA+B;CAC5D,MAAM,OAAO,SAAS;CACtB,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,qBAAqB,KAAK,UAAU,GAAG,EAAE,UAAU,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,EAAE;CACjH,OAAO,KAAK;AACd"}
@@ -1,4 +1,4 @@
1
- import { BenchScore, JudgeArtifactReceipt } from "./types.js";
1
+ import { BenchEvaluation, JudgeArtifactReceipt } from "./types.js";
2
2
  /** Package root for agent-bench, so `.venv`, scripts, and fixtures resolve. */
3
3
  export declare const benchRoot: string;
4
4
  /** Resolve the shared interpreter without requiring an installed package to contain a venv. */
@@ -71,10 +71,10 @@ export interface StagedRunSpec {
71
71
  /** Hard timeout for the evaluator (ms); 0 = none. */
72
72
  timeoutMs?: number;
73
73
  /**
74
- * Read the evaluator's report(s) out of `dir` and map to a BenchScore. Throws
74
+ * Read the evaluator's report(s) out of `dir` and map to a BenchEvaluation. Throws
75
75
  * if the expected report is absent/malformed (fail loud — no default score).
76
76
  */
77
- parseReport(dir: string): Promise<BenchScore>;
77
+ parseReport(dir: string): Promise<BenchEvaluation>;
78
78
  /**
79
79
  * Copy the complete evaluator directory plus raw process stdout/stderr to this
80
80
  * caller-owned directory before cleanup. The destination must not exist.
@@ -97,7 +97,7 @@ export declare class StagedJudgeError extends Error {
97
97
  * cleanup. The evaluator's stdout/stderr is surfaced on failure; the temp dir is
98
98
  * always removed in `finally` unless `keepTmp`.
99
99
  */
100
- export declare function runStagedJudge(spec: StagedRunSpec): Promise<BenchScore>;
100
+ export declare function runStagedJudge(spec: StagedRunSpec): Promise<BenchEvaluation>;
101
101
  /** Read + JSON.parse a report file from a staged run; throws with the path on failure. */
102
102
  export declare function readJsonReport<T>(path: string): Promise<T>;
103
103
  /** Write a UTF-8 file into a staged dir (artifact / preds.json / attempt.sh / …). */
@@ -10,13 +10,13 @@ import { promisify } from "node:util";
10
10
  /**
11
11
  * Shared code-bench harness. The "stage the artifact → run the benchmark's own
12
12
  * evaluator in an external process (mkdtemp / execFile / .venv python / Docker)
13
- * → read its JSON report → { resolved, score }" spine that swe-bench,
13
+ * → read its JSON report → { passed, score }" spine that swe-bench,
14
14
  * terminal-bench, commit0, programbench and aec-bench all need. Factored out so
15
15
  * the Docker/venv/report-reading logic lives in ONE place instead of being
16
16
  * copy-pasted per adapter.
17
17
  *
18
18
  * It owns NO benchmark policy: each adapter passes the argv for its evaluator
19
- * and a `parseReport` that maps that evaluator's report JSON → a BenchScore. The
19
+ * and a `parseReport` that maps that evaluator's report JSON → a BenchEvaluation. The
20
20
  * harness owns process spawning, temp-dir lifecycle, large-buffer/timeout config
21
21
  * and fail-loud diagnostics.
22
22
  *
@@ -123,6 +123,9 @@ function runVenvScriptStdin(scriptPath, args, input, opts = {}) {
123
123
  stderr += c.toString("utf8");
124
124
  });
125
125
  child.on("error", (err) => reject(err));
126
+ child.stdin.on("error", (err) => {
127
+ if (err.code !== "EPIPE") reject(err);
128
+ });
126
129
  child.on("close", (code) => {
127
130
  if (code === 0) resolve(stdout);
128
131
  else reject(new Error((stderr || stdout || `exit ${code}`).slice(0, 1500)));
@@ -1 +1 @@
1
- {"version":3,"file":"_harness.js","names":[],"sources":["../../src/benchmarks/_harness.ts"],"sourcesContent":["/**\n * Shared code-bench harness. The \"stage the artifact → run the benchmark's own\n * evaluator in an external process (mkdtemp / execFile / .venv python / Docker)\n * → read its JSON report → { resolved, score }\" spine that swe-bench,\n * terminal-bench, commit0, programbench and aec-bench all need. Factored out so\n * the Docker/venv/report-reading logic lives in ONE place instead of being\n * copy-pasted per adapter.\n *\n * It owns NO benchmark policy: each adapter passes the argv for its evaluator\n * and a `parseReport` that maps that evaluator's report JSON → a BenchScore. The\n * harness owns process spawning, temp-dir lifecycle, large-buffer/timeout config\n * and fail-loud diagnostics.\n *\n * Fail-loud: an absent .venv / harness / Docker daemon THROWS from `preflight`\n * (the adapter passes the import line + the exact fix). A staged run that exits\n * nonzero throws with the captured stderr — never a fabricated score.\n */\n\nimport { execFile, spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport {\n cp,\n lstat,\n mkdir,\n mkdtemp,\n readFile,\n readlink,\n readdir,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\nimport type {\n BenchScore,\n JudgeArtifactFileReceipt,\n JudgeArtifactReceipt,\n} from './types'\n\nconst execFileAsync = promisify(execFile)\n\n/** Locate the package by identity because source files and compiled chunks have different depths. */\nfunction resolveBenchRoot(moduleUrl: string): string {\n let current = dirname(fileURLToPath(moduleUrl))\n while (true) {\n const manifestPath = join(current, 'package.json')\n if (existsSync(manifestPath)) {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { name?: unknown }\n if (manifest.name === '@tangle-network/agent-bench') return current\n }\n const parent = dirname(current)\n if (parent === current) {\n throw new Error(`Unable to locate @tangle-network/agent-bench from ${moduleUrl}`)\n }\n current = parent\n }\n}\n\n/** Package root for agent-bench, so `.venv`, scripts, and fixtures resolve. */\nexport const benchRoot = resolveBenchRoot(import.meta.url)\n\n/** Resolve the shared interpreter without requiring an installed package to contain a venv. */\nexport function resolveBenchPython(\n env: Readonly<{ AGENT_BENCH_PYTHON?: string }> = process.env,\n root: string = benchRoot,\n): string {\n const configured = env.AGENT_BENCH_PYTHON\n if (configured === undefined) return join(root, '.venv', 'bin', 'python')\n if (!isAbsolute(configured)) {\n throw new Error('AGENT_BENCH_PYTHON must be an absolute path')\n }\n return configured\n}\n\n/** The shared interpreter every Python-backed evaluator runs through. */\nexport const venvPython = resolveBenchPython()\n\n/** Interpreter for a NAMED isolated venv (e.g. `.venv-commit0`). Benches whose pip\n * deps conflict with the shared `.venv` (commit0 downgrades pydantic/sqlalchemy)\n * get their own venv and pass its python explicitly — keeping the shared one clean. */\nexport const venvPythonAt = (venvDir: string): string => venvBinAt(venvDir, 'python')\n\n/** Resolve an executable in an isolated venv. Relative venv paths are package-owned;\n * absolute paths allow installed consumers to keep large environments elsewhere. */\nexport function venvBinAt(venvDir: string, name: string): string {\n return join(resolve(benchRoot, venvDir), 'bin', name)\n}\n\n/** Report/transcript reads are large; 256 MiB matches the SWE harness budget. */\nexport const bigBuffer = 1024 * 1024 * 256\n\n/** Path to a named executable inside the bench venv (e.g. `venvBin('tb')`). */\nexport function venvBin(name: string): string {\n return venvBinAt('.venv', name)\n}\n\n/**\n * Run the bench venv python with an inline script (`-c`); return stdout. Throws\n * (with stderr) on a nonzero exit — the loaders rely on this to fail loud rather\n * than parse a partial dump.\n */\nexport async function runVenvPython(\n script: string,\n args: string[] = [],\n timeoutMs = 0,\n python: string = venvPython,\n): Promise<string> {\n const { stdout } = await execFileAsync(python, ['-c', script, ...args], {\n maxBuffer: bigBuffer,\n timeout: timeoutMs,\n })\n return stdout\n}\n\n/**\n * Preflight a python-backed harness: import the module(s) and (optionally) ping\n * Docker, all inside the bench venv. On failure THROWS the captured error joined\n * to the adapter's `fix` guidance — the contract every code-bench preflight wants.\n */\nexport async function preflightVenvImports(opts: {\n /** Module names to `import` (e.g. ['swebench']); '' entries are ignored. */\n modules: string[]\n /** Also `docker.from_env().ping()` — true for Docker-backed evaluators. */\n requireDocker?: boolean\n /** Actionable remediation appended to the thrown message. */\n fix: string\n /** Override the interpreter (e.g. an isolated `.venv-commit0`). Default: shared `.venv`. */\n python?: string\n}): Promise<void> {\n const imports = opts.modules.filter((m) => m.length > 0)\n const lines = [...imports.map((m) => `import ${m}`)]\n if (opts.requireDocker) lines.push('import docker', 'docker.from_env().ping()')\n lines.push(\"print('ok')\")\n try {\n await runVenvPython(lines.join('\\n'), [], 0, opts.python ?? venvPython)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(`${msg}\\n${opts.fix}`)\n }\n}\n\n/**\n * Run a bench-local python driver script (in the bench venv) while piping\n * `input` to its stdin, returning stdout. The driver's verdict JSON is its LAST\n * stdout line; callers parse that and inspect an `error` field (fail loud).\n *\n * Uses spawn + an explicit `stdin.end(input)` rather than promisify(execFile)'s\n * `input` option, because that option is NOT honored by async execFile — stdin\n * is left open and a driver that does `sys.stdin.read()` blocks forever. The\n * artifact-piping judges (commit0, appworld) MUST go through this.\n */\nexport function runVenvScriptStdin(\n scriptPath: string,\n args: string[],\n input: string,\n opts: { cwd?: string; timeoutMs?: number; python?: string } = {},\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const child = spawn(opts.python ?? venvPython, [scriptPath, ...args], {\n cwd: opts.cwd ?? benchRoot,\n ...(opts.timeoutMs ? { timeout: opts.timeoutMs } : {}),\n })\n let stdout = ''\n let stderr = ''\n let bytes = 0\n child.stdout.on('data', (c: Buffer) => {\n bytes += c.length\n if (bytes <= bigBuffer) stdout += c.toString('utf8')\n })\n child.stderr.on('data', (c: Buffer) => {\n stderr += c.toString('utf8')\n })\n child.on('error', (err) => reject(err))\n child.on('close', (code) => {\n if (code === 0) resolve(stdout)\n else reject(new Error((stderr || stdout || `exit ${code}`).slice(0, 1500)))\n })\n child.stdin.end(input)\n })\n}\n\nexport interface StagedRunSpec {\n /** mkdtemp prefix, e.g. 'swebench-' / 'commit0-'. */\n tmpPrefix: string\n /**\n * Write the artifact + any harness inputs into the temp dir. Returns nothing;\n * `argv`/`cwd` consume `dir` to point the evaluator at what was written.\n */\n stage(dir: string): Promise<void>\n /** The external evaluator to spawn. `bin` defaults to the bench venv python. */\n bin?: string\n /** argv for the evaluator, computed from the temp `dir`. */\n argv(dir: string): string[]\n /** Working directory for the evaluator. Defaults to the temp `dir`. */\n cwd?(dir: string): string\n /** Hard timeout for the evaluator (ms); 0 = none. */\n timeoutMs?: number\n /**\n * Read the evaluator's report(s) out of `dir` and map to a BenchScore. Throws\n * if the expected report is absent/malformed (fail loud — no default score).\n */\n parseReport(dir: string): Promise<BenchScore>\n /**\n * Copy the complete evaluator directory plus raw process stdout/stderr to this\n * caller-owned directory before cleanup. The destination must not exist.\n */\n capture?: StagedRunCaptureSpec\n /** Keep the temp dir on disk (debugging). Default false → always cleaned up. */\n keepTmp?: boolean\n}\n\nexport interface StagedRunCaptureSpec {\n /** Destination for `evaluator/`, `process/`, and the hashed `receipt.json`. */\n destination: string\n}\n\n/** A staged run failed after any requested evidence was durably retained. */\nexport class StagedJudgeError extends Error {\n readonly judgeArtifacts?: JudgeArtifactReceipt\n\n constructor(message: string, judgeArtifacts?: JudgeArtifactReceipt, options?: ErrorOptions) {\n super(message, options)\n this.name = 'StagedJudgeError'\n this.judgeArtifacts = judgeArtifacts\n }\n}\n\nfunction sha256(bytes: Uint8Array): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nfunction portablePath(path: string): string {\n return path.split(sep).join('/')\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nasync function collectArtifactFiles(\n root: string,\n current: string,\n): Promise<JudgeArtifactFileReceipt[]> {\n const absolute = join(root, current)\n const entries = await readdir(absolute, { withFileTypes: true })\n const files: JudgeArtifactFileReceipt[] = []\n for (const entry of entries.sort((left, right) => compareText(left.name, right.name))) {\n const relativePath = join(current, entry.name)\n const path = join(root, relativePath)\n if (entry.isDirectory()) {\n files.push(...await collectArtifactFiles(root, relativePath))\n continue\n }\n if (entry.isFile()) {\n const bytes = await readFile(path)\n files.push({\n path: portablePath(relativePath),\n byteLength: bytes.byteLength,\n sha256: sha256(bytes),\n kind: 'file',\n })\n continue\n }\n if (entry.isSymbolicLink()) {\n const targetBytes = await readlink(path, { encoding: 'buffer' })\n files.push({\n path: portablePath(relativePath),\n byteLength: targetBytes.byteLength,\n sha256: sha256(targetBytes),\n kind: 'symlink',\n })\n continue\n }\n throw new Error(`staged judge capture does not support ${relativePath}`)\n }\n return files\n}\n\nfunction isWithin(parent: string, candidate: string): boolean {\n const path = relative(parent, candidate)\n return path === '' || (!path.startsWith(`..${sep}`) && path !== '..' && !isAbsolute(path))\n}\n\nasync function assertDestinationAbsent(destination: string): Promise<void> {\n try {\n await lstat(destination)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n throw new Error(`staged judge capture destination already exists: ${destination}`)\n}\n\nasync function captureStagedRun(\n sourceDirectory: string,\n spec: StagedRunCaptureSpec,\n processOutput: Readonly<{ stdout: Buffer; stderr: Buffer }>,\n evaluatorSucceeded: boolean,\n): Promise<JudgeArtifactReceipt> {\n const source = resolve(sourceDirectory)\n const destination = resolve(spec.destination)\n if (isWithin(source, destination)) {\n throw new Error('staged judge capture destination must be outside the evaluator directory')\n }\n await mkdir(dirname(destination), { recursive: true })\n await assertDestinationAbsent(destination)\n const staging = await mkdtemp(join(dirname(destination), `.${basename(destination)}-capture-`))\n try {\n await cp(source, join(staging, 'evaluator'), {\n recursive: true,\n errorOnExist: true,\n force: false,\n preserveTimestamps: true,\n verbatimSymlinks: true,\n })\n await mkdir(join(staging, 'process'))\n await writeFile(join(staging, 'process', 'stdout.bin'), processOutput.stdout)\n await writeFile(join(staging, 'process', 'stderr.bin'), processOutput.stderr)\n\n const files = [\n ...await collectArtifactFiles(staging, 'evaluator'),\n ...await collectArtifactFiles(staging, 'process'),\n ].sort((left, right) => compareText(left.path, right.path))\n const byteLength = files.reduce((total, file) => total + file.byteLength, 0)\n const treeBytes = Buffer.from(\n files\n .map((file) => `${file.path}\\0${file.kind}\\0${file.byteLength}\\0${file.sha256}\\n`)\n .join(''),\n 'utf8',\n )\n const receipt: JudgeArtifactReceipt = {\n schema: 'agent-bench/judge-artifacts/v1',\n directory: destination,\n evaluatorDirectory: join(destination, 'evaluator'),\n manifestPath: join(destination, 'receipt.json'),\n evaluatorSucceeded,\n files,\n fileCount: files.length,\n byteLength,\n treeSha256: sha256(treeBytes),\n }\n await writeFile(join(staging, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\\n`)\n await rename(staging, destination)\n return receipt\n } catch (error) {\n await rm(staging, { recursive: true, force: true }).catch(() => {})\n throw error\n }\n}\n\nfunction processBytes(value: unknown): Buffer {\n if (Buffer.isBuffer(value)) return value\n if (value === undefined || value === null) return Buffer.alloc(0)\n return Buffer.from(String(value), 'utf8')\n}\n\n/**\n * The shared judge body: mkdtemp → stage → spawn evaluator → parseReport →\n * cleanup. The evaluator's stdout/stderr is surfaced on failure; the temp dir is\n * always removed in `finally` unless `keepTmp`.\n */\nexport async function runStagedJudge(spec: StagedRunSpec): Promise<BenchScore> {\n const dir = await mkdtemp(join(tmpdir(), spec.tmpPrefix))\n let stdout: Buffer<ArrayBufferLike> = Buffer.alloc(0)\n let stderr: Buffer<ArrayBufferLike> = Buffer.alloc(0)\n let evaluatorSucceeded = false\n let score: BenchScore | undefined\n let failure: unknown\n try {\n try {\n await spec.stage(dir)\n const bin = spec.bin ?? venvPython\n const argv = spec.argv(dir)\n try {\n const output = await execFileAsync(bin, argv, {\n cwd: spec.cwd ? spec.cwd(dir) : dir,\n encoding: 'buffer',\n maxBuffer: bigBuffer,\n ...(spec.timeoutMs ? { timeout: spec.timeoutMs } : {}),\n })\n stdout = processBytes(output.stdout)\n stderr = processBytes(output.stderr)\n evaluatorSucceeded = true\n } catch (err) {\n const e = err as { stderr?: unknown; stdout?: unknown; message?: string }\n stdout = processBytes(e.stdout)\n stderr = processBytes(e.stderr)\n const detail = processBytes(e.stderr ?? e.stdout ?? e.message ?? String(err))\n .toString('utf8')\n .slice(0, 2000)\n throw new Error(`${spec.tmpPrefix.replace(/-$/, '')} evaluator failed (${bin} ${argv.join(' ')}):\\n${detail}`)\n }\n score = await spec.parseReport(dir)\n } catch (err) {\n failure = err\n }\n } finally {\n let judgeArtifacts: JudgeArtifactReceipt | undefined\n if (spec.capture) {\n try {\n judgeArtifacts = await captureStagedRun(\n dir,\n spec.capture,\n { stdout, stderr },\n evaluatorSucceeded,\n )\n } catch (captureError) {\n failure = new Error(\n `staged judge failed to capture evaluator artifacts: ${captureError instanceof Error ? captureError.message : captureError}`,\n { cause: failure ?? captureError },\n )\n }\n }\n if (!spec.keepTmp) await rm(dir, { recursive: true, force: true }).catch(() => {})\n if (failure) {\n throw new StagedJudgeError(\n failure instanceof Error ? failure.message : String(failure),\n judgeArtifacts,\n { cause: failure },\n )\n }\n if (!score) throw new StagedJudgeError('staged judge completed without a score', judgeArtifacts)\n return judgeArtifacts ? { ...score, judgeArtifacts } : score\n }\n}\n\n/** Read + JSON.parse a report file from a staged run; throws with the path on failure. */\nexport async function readJsonReport<T>(path: string): Promise<T> {\n let raw: string\n try {\n raw = await readFile(path, 'utf8')\n } catch (err) {\n throw new Error(`expected report not written: ${path} (${err instanceof Error ? err.message : err})`)\n }\n try {\n return JSON.parse(raw) as T\n } catch (err) {\n throw new Error(`report not valid JSON at ${path}: ${err instanceof Error ? err.message : err}`)\n }\n}\n\n/** Write a UTF-8 file into a staged dir (artifact / preds.json / attempt.sh / …). */\nexport async function stageFile(path: string, content: string): Promise<void> {\n await writeFile(path, content)\n}\n\n/** Sanitize an instance id into a filesystem/run-id-safe token. */\nexport function safeRunId(prefix: string, id: string): string {\n return `${prefix}-${id}`.replace(/[^a-zA-Z0-9_.-]/g, '_')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,gBAAgB,UAAU,QAAQ;;AAGxC,SAAS,iBAAiB,WAA2B;CACnD,IAAI,UAAU,QAAQ,cAAc,SAAS,CAAC;CAC9C,OAAO,MAAM;EACX,MAAM,eAAe,KAAK,SAAS,cAAc;EACjD,IAAI,WAAW,YAAY,GACR;OAAA,KAAK,MAAM,aAAa,cAAc,MAAM,CAClD,CAAC,CAAC,SAAS,+BAA+B,OAAO;EAAA;EAE9D,MAAM,SAAS,QAAQ,OAAO;EAC9B,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,qDAAqD,WAAW;EAElF,UAAU;CACZ;AACF;;AAGA,MAAa,YAAY,iBAAiB,YAAY,GAAG;;AAGzD,SAAgB,mBACd,MAAiD,QAAQ,KACzD,OAAe,WACP;CACR,MAAM,aAAa,IAAI;CACvB,IAAI,eAAe,KAAA,GAAW,OAAO,KAAK,MAAM,SAAS,OAAO,QAAQ;CACxE,IAAI,CAAC,WAAW,UAAU,GACxB,MAAM,IAAI,MAAM,6CAA6C;CAE/D,OAAO;AACT;;AAGA,MAAa,aAAa,mBAAmB;;;;AAK7C,MAAa,gBAAgB,YAA4B,UAAU,SAAS,QAAQ;;;AAIpF,SAAgB,UAAU,SAAiB,MAAsB;CAC/D,OAAO,KAAK,QAAQ,WAAW,OAAO,GAAG,OAAO,IAAI;AACtD;;AAGA,MAAa,YAAY;;AAGzB,SAAgB,QAAQ,MAAsB;CAC5C,OAAO,UAAU,SAAS,IAAI;AAChC;;;;;;AAOA,eAAsB,cACpB,QACA,OAAiB,CAAC,GAClB,YAAY,GACZ,SAAiB,YACA;CACjB,MAAM,EAAE,WAAW,MAAM,cAAc,QA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AAO,QAAQ,CACnB;EAEF,IAAI,CAAC,OAAO,MAAM,IAAI,iBAAiB,0CAA0C,cAAc;EAC/F,OAAO,iBAAiB;GAAE,GAAG;GAAO;EAAe,IAAI;CACzD;AACF;;AAGA,eAAsB,eAAkB,MAA0B;CAChE,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,SAAS,MAAM,MAAM;CACnC,SAAS,KAAK;EACZ,MAAM,IAAI,MAAM,gCAAgC,KAAK,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,EAAE;CACtG;CACA,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,SAAS,KAAK;EACZ,MAAM,IAAI,MAAM,4BAA4B,KAAK,IAAI,eAAe,QAAQ,IAAI,UAAU,KAAK;CACjG;AACF;;AAGA,eAAsB,UAAU,MAAc,SAAgC;CAC5E,MAAM,UAAU,MAAM,OAAO;AAC/B;;AAGA,SAAgB,UAAU,QAAgB,IAAoB;CAC5D,OAAO,GAAG,OAAO,GAAG,KAAK,QAAQ,oBAAoB,GAAG;AAC1D"}
1
+ {"version":3,"file":"_harness.js","names":[],"sources":["../../src/benchmarks/_harness.ts"],"sourcesContent":["/**\n * Shared code-bench harness. The \"stage the artifact → run the benchmark's own\n * evaluator in an external process (mkdtemp / execFile / .venv python / Docker)\n * → read its JSON report → { passed, score }\" spine that swe-bench,\n * terminal-bench, commit0, programbench and aec-bench all need. Factored out so\n * the Docker/venv/report-reading logic lives in ONE place instead of being\n * copy-pasted per adapter.\n *\n * It owns NO benchmark policy: each adapter passes the argv for its evaluator\n * and a `parseReport` that maps that evaluator's report JSON → a BenchEvaluation. The\n * harness owns process spawning, temp-dir lifecycle, large-buffer/timeout config\n * and fail-loud diagnostics.\n *\n * Fail-loud: an absent .venv / harness / Docker daemon THROWS from `preflight`\n * (the adapter passes the import line + the exact fix). A staged run that exits\n * nonzero throws with the captured stderr — never a fabricated score.\n */\n\nimport { execFile, spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport {\n cp,\n lstat,\n mkdir,\n mkdtemp,\n readFile,\n readlink,\n readdir,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\nimport type {\n BenchEvaluation,\n JudgeArtifactFileReceipt,\n JudgeArtifactReceipt,\n} from './types'\n\nconst execFileAsync = promisify(execFile)\n\n/** Locate the package by identity because source files and compiled chunks have different depths. */\nfunction resolveBenchRoot(moduleUrl: string): string {\n let current = dirname(fileURLToPath(moduleUrl))\n while (true) {\n const manifestPath = join(current, 'package.json')\n if (existsSync(manifestPath)) {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { name?: unknown }\n if (manifest.name === '@tangle-network/agent-bench') return current\n }\n const parent = dirname(current)\n if (parent === current) {\n throw new Error(`Unable to locate @tangle-network/agent-bench from ${moduleUrl}`)\n }\n current = parent\n }\n}\n\n/** Package root for agent-bench, so `.venv`, scripts, and fixtures resolve. */\nexport const benchRoot = resolveBenchRoot(import.meta.url)\n\n/** Resolve the shared interpreter without requiring an installed package to contain a venv. */\nexport function resolveBenchPython(\n env: Readonly<{ AGENT_BENCH_PYTHON?: string }> = process.env,\n root: string = benchRoot,\n): string {\n const configured = env.AGENT_BENCH_PYTHON\n if (configured === undefined) return join(root, '.venv', 'bin', 'python')\n if (!isAbsolute(configured)) {\n throw new Error('AGENT_BENCH_PYTHON must be an absolute path')\n }\n return configured\n}\n\n/** The shared interpreter every Python-backed evaluator runs through. */\nexport const venvPython = resolveBenchPython()\n\n/** Interpreter for a NAMED isolated venv (e.g. `.venv-commit0`). Benches whose pip\n * deps conflict with the shared `.venv` (commit0 downgrades pydantic/sqlalchemy)\n * get their own venv and pass its python explicitly — keeping the shared one clean. */\nexport const venvPythonAt = (venvDir: string): string => venvBinAt(venvDir, 'python')\n\n/** Resolve an executable in an isolated venv. Relative venv paths are package-owned;\n * absolute paths allow installed consumers to keep large environments elsewhere. */\nexport function venvBinAt(venvDir: string, name: string): string {\n return join(resolve(benchRoot, venvDir), 'bin', name)\n}\n\n/** Report/transcript reads are large; 256 MiB matches the SWE harness budget. */\nexport const bigBuffer = 1024 * 1024 * 256\n\n/** Path to a named executable inside the bench venv (e.g. `venvBin('tb')`). */\nexport function venvBin(name: string): string {\n return venvBinAt('.venv', name)\n}\n\n/**\n * Run the bench venv python with an inline script (`-c`); return stdout. Throws\n * (with stderr) on a nonzero exit — the loaders rely on this to fail loud rather\n * than parse a partial dump.\n */\nexport async function runVenvPython(\n script: string,\n args: string[] = [],\n timeoutMs = 0,\n python: string = venvPython,\n): Promise<string> {\n const { stdout } = await execFileAsync(python, ['-c', script, ...args], {\n maxBuffer: bigBuffer,\n timeout: timeoutMs,\n })\n return stdout\n}\n\n/**\n * Preflight a python-backed harness: import the module(s) and (optionally) ping\n * Docker, all inside the bench venv. On failure THROWS the captured error joined\n * to the adapter's `fix` guidance — the contract every code-bench preflight wants.\n */\nexport async function preflightVenvImports(opts: {\n /** Module names to `import` (e.g. ['swebench']); '' entries are ignored. */\n modules: string[]\n /** Also `docker.from_env().ping()` — true for Docker-backed evaluators. */\n requireDocker?: boolean\n /** Actionable remediation appended to the thrown message. */\n fix: string\n /** Override the interpreter (e.g. an isolated `.venv-commit0`). Default: shared `.venv`. */\n python?: string\n}): Promise<void> {\n const imports = opts.modules.filter((m) => m.length > 0)\n const lines = [...imports.map((m) => `import ${m}`)]\n if (opts.requireDocker) lines.push('import docker', 'docker.from_env().ping()')\n lines.push(\"print('ok')\")\n try {\n await runVenvPython(lines.join('\\n'), [], 0, opts.python ?? venvPython)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(`${msg}\\n${opts.fix}`)\n }\n}\n\n/**\n * Run a bench-local python driver script (in the bench venv) while piping\n * `input` to its stdin, returning stdout. The driver's verdict JSON is its LAST\n * stdout line; callers parse that and inspect an `error` field (fail loud).\n *\n * Uses spawn + an explicit `stdin.end(input)` rather than promisify(execFile)'s\n * `input` option, because that option is NOT honored by async execFile — stdin\n * is left open and a driver that does `sys.stdin.read()` blocks forever. The\n * artifact-piping judges (commit0, appworld) MUST go through this.\n */\nexport function runVenvScriptStdin(\n scriptPath: string,\n args: string[],\n input: string,\n opts: { cwd?: string; timeoutMs?: number; python?: string } = {},\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const child = spawn(opts.python ?? venvPython, [scriptPath, ...args], {\n cwd: opts.cwd ?? benchRoot,\n ...(opts.timeoutMs ? { timeout: opts.timeoutMs } : {}),\n })\n let stdout = ''\n let stderr = ''\n let bytes = 0\n child.stdout.on('data', (c: Buffer) => {\n bytes += c.length\n if (bytes <= bigBuffer) stdout += c.toString('utf8')\n })\n child.stderr.on('data', (c: Buffer) => {\n stderr += c.toString('utf8')\n })\n child.on('error', (err) => reject(err))\n // A driver that exits before reading its input closes the pipe under a pending write. Its\n // exit code and output, read at close, are the failure; the closed pipe is not a second one.\n child.stdin.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code !== 'EPIPE') reject(err)\n })\n child.on('close', (code) => {\n if (code === 0) resolve(stdout)\n else reject(new Error((stderr || stdout || `exit ${code}`).slice(0, 1500)))\n })\n child.stdin.end(input)\n })\n}\n\nexport interface StagedRunSpec {\n /** mkdtemp prefix, e.g. 'swebench-' / 'commit0-'. */\n tmpPrefix: string\n /**\n * Write the artifact + any harness inputs into the temp dir. Returns nothing;\n * `argv`/`cwd` consume `dir` to point the evaluator at what was written.\n */\n stage(dir: string): Promise<void>\n /** The external evaluator to spawn. `bin` defaults to the bench venv python. */\n bin?: string\n /** argv for the evaluator, computed from the temp `dir`. */\n argv(dir: string): string[]\n /** Working directory for the evaluator. Defaults to the temp `dir`. */\n cwd?(dir: string): string\n /** Hard timeout for the evaluator (ms); 0 = none. */\n timeoutMs?: number\n /**\n * Read the evaluator's report(s) out of `dir` and map to a BenchEvaluation. Throws\n * if the expected report is absent/malformed (fail loud — no default score).\n */\n parseReport(dir: string): Promise<BenchEvaluation>\n /**\n * Copy the complete evaluator directory plus raw process stdout/stderr to this\n * caller-owned directory before cleanup. The destination must not exist.\n */\n capture?: StagedRunCaptureSpec\n /** Keep the temp dir on disk (debugging). Default false → always cleaned up. */\n keepTmp?: boolean\n}\n\nexport interface StagedRunCaptureSpec {\n /** Destination for `evaluator/`, `process/`, and the hashed `receipt.json`. */\n destination: string\n}\n\n/** A staged run failed after any requested evidence was durably retained. */\nexport class StagedJudgeError extends Error {\n readonly judgeArtifacts?: JudgeArtifactReceipt\n\n constructor(message: string, judgeArtifacts?: JudgeArtifactReceipt, options?: ErrorOptions) {\n super(message, options)\n this.name = 'StagedJudgeError'\n this.judgeArtifacts = judgeArtifacts\n }\n}\n\nfunction sha256(bytes: Uint8Array): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nfunction portablePath(path: string): string {\n return path.split(sep).join('/')\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nasync function collectArtifactFiles(\n root: string,\n current: string,\n): Promise<JudgeArtifactFileReceipt[]> {\n const absolute = join(root, current)\n const entries = await readdir(absolute, { withFileTypes: true })\n const files: JudgeArtifactFileReceipt[] = []\n for (const entry of entries.sort((left, right) => compareText(left.name, right.name))) {\n const relativePath = join(current, entry.name)\n const path = join(root, relativePath)\n if (entry.isDirectory()) {\n files.push(...await collectArtifactFiles(root, relativePath))\n continue\n }\n if (entry.isFile()) {\n const bytes = await readFile(path)\n files.push({\n path: portablePath(relativePath),\n byteLength: bytes.byteLength,\n sha256: sha256(bytes),\n kind: 'file',\n })\n continue\n }\n if (entry.isSymbolicLink()) {\n const targetBytes = await readlink(path, { encoding: 'buffer' })\n files.push({\n path: portablePath(relativePath),\n byteLength: targetBytes.byteLength,\n sha256: sha256(targetBytes),\n kind: 'symlink',\n })\n continue\n }\n throw new Error(`staged judge capture does not support ${relativePath}`)\n }\n return files\n}\n\nfunction isWithin(parent: string, candidate: string): boolean {\n const path = relative(parent, candidate)\n return path === '' || (!path.startsWith(`..${sep}`) && path !== '..' && !isAbsolute(path))\n}\n\nasync function assertDestinationAbsent(destination: string): Promise<void> {\n try {\n await lstat(destination)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n throw new Error(`staged judge capture destination already exists: ${destination}`)\n}\n\nasync function captureStagedRun(\n sourceDirectory: string,\n spec: StagedRunCaptureSpec,\n processOutput: Readonly<{ stdout: Buffer; stderr: Buffer }>,\n evaluatorSucceeded: boolean,\n): Promise<JudgeArtifactReceipt> {\n const source = resolve(sourceDirectory)\n const destination = resolve(spec.destination)\n if (isWithin(source, destination)) {\n throw new Error('staged judge capture destination must be outside the evaluator directory')\n }\n await mkdir(dirname(destination), { recursive: true })\n await assertDestinationAbsent(destination)\n const staging = await mkdtemp(join(dirname(destination), `.${basename(destination)}-capture-`))\n try {\n await cp(source, join(staging, 'evaluator'), {\n recursive: true,\n errorOnExist: true,\n force: false,\n preserveTimestamps: true,\n verbatimSymlinks: true,\n })\n await mkdir(join(staging, 'process'))\n await writeFile(join(staging, 'process', 'stdout.bin'), processOutput.stdout)\n await writeFile(join(staging, 'process', 'stderr.bin'), processOutput.stderr)\n\n const files = [\n ...await collectArtifactFiles(staging, 'evaluator'),\n ...await collectArtifactFiles(staging, 'process'),\n ].sort((left, right) => compareText(left.path, right.path))\n const byteLength = files.reduce((total, file) => total + file.byteLength, 0)\n const treeBytes = Buffer.from(\n files\n .map((file) => `${file.path}\\0${file.kind}\\0${file.byteLength}\\0${file.sha256}\\n`)\n .join(''),\n 'utf8',\n )\n const receipt: JudgeArtifactReceipt = {\n schema: 'agent-bench/judge-artifacts/v1',\n directory: destination,\n evaluatorDirectory: join(destination, 'evaluator'),\n manifestPath: join(destination, 'receipt.json'),\n evaluatorSucceeded,\n files,\n fileCount: files.length,\n byteLength,\n treeSha256: sha256(treeBytes),\n }\n await writeFile(join(staging, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\\n`)\n await rename(staging, destination)\n return receipt\n } catch (error) {\n await rm(staging, { recursive: true, force: true }).catch(() => {})\n throw error\n }\n}\n\nfunction processBytes(value: unknown): Buffer {\n if (Buffer.isBuffer(value)) return value\n if (value === undefined || value === null) return Buffer.alloc(0)\n return Buffer.from(String(value), 'utf8')\n}\n\n/**\n * The shared judge body: mkdtemp → stage → spawn evaluator → parseReport →\n * cleanup. The evaluator's stdout/stderr is surfaced on failure; the temp dir is\n * always removed in `finally` unless `keepTmp`.\n */\nexport async function runStagedJudge(spec: StagedRunSpec): Promise<BenchEvaluation> {\n const dir = await mkdtemp(join(tmpdir(), spec.tmpPrefix))\n let stdout: Buffer<ArrayBufferLike> = Buffer.alloc(0)\n let stderr: Buffer<ArrayBufferLike> = Buffer.alloc(0)\n let evaluatorSucceeded = false\n let score: BenchEvaluation | undefined\n let failure: unknown\n try {\n try {\n await spec.stage(dir)\n const bin = spec.bin ?? venvPython\n const argv = spec.argv(dir)\n try {\n const output = await execFileAsync(bin, argv, {\n cwd: spec.cwd ? spec.cwd(dir) : dir,\n encoding: 'buffer',\n maxBuffer: bigBuffer,\n ...(spec.timeoutMs ? { timeout: spec.timeoutMs } : {}),\n })\n stdout = processBytes(output.stdout)\n stderr = processBytes(output.stderr)\n evaluatorSucceeded = true\n } catch (err) {\n const e = err as { stderr?: unknown; stdout?: unknown; message?: string }\n stdout = processBytes(e.stdout)\n stderr = processBytes(e.stderr)\n const detail = processBytes(e.stderr ?? e.stdout ?? e.message ?? String(err))\n .toString('utf8')\n .slice(0, 2000)\n throw new Error(`${spec.tmpPrefix.replace(/-$/, '')} evaluator failed (${bin} ${argv.join(' ')}):\\n${detail}`)\n }\n score = await spec.parseReport(dir)\n } catch (err) {\n failure = err\n }\n } finally {\n let judgeArtifacts: JudgeArtifactReceipt | undefined\n if (spec.capture) {\n try {\n judgeArtifacts = await captureStagedRun(\n dir,\n spec.capture,\n { stdout, stderr },\n evaluatorSucceeded,\n )\n } catch (captureError) {\n failure = new Error(\n `staged judge failed to capture evaluator artifacts: ${captureError instanceof Error ? captureError.message : captureError}`,\n { cause: failure ?? captureError },\n )\n }\n }\n if (!spec.keepTmp) await rm(dir, { recursive: true, force: true }).catch(() => {})\n if (failure) {\n throw new StagedJudgeError(\n failure instanceof Error ? failure.message : String(failure),\n judgeArtifacts,\n { cause: failure },\n )\n }\n if (!score) throw new StagedJudgeError('staged judge completed without a score', judgeArtifacts)\n return judgeArtifacts ? { ...score, judgeArtifacts } : score\n }\n}\n\n/** Read + JSON.parse a report file from a staged run; throws with the path on failure. */\nexport async function readJsonReport<T>(path: string): Promise<T> {\n let raw: string\n try {\n raw = await readFile(path, 'utf8')\n } catch (err) {\n throw new Error(`expected report not written: ${path} (${err instanceof Error ? err.message : err})`)\n }\n try {\n return JSON.parse(raw) as T\n } catch (err) {\n throw new Error(`report not valid JSON at ${path}: ${err instanceof Error ? err.message : err}`)\n }\n}\n\n/** Write a UTF-8 file into a staged dir (artifact / preds.json / attempt.sh / …). */\nexport async function stageFile(path: string, content: string): Promise<void> {\n await writeFile(path, content)\n}\n\n/** Sanitize an instance id into a filesystem/run-id-safe token. */\nexport function safeRunId(prefix: string, id: string): string {\n return `${prefix}-${id}`.replace(/[^a-zA-Z0-9_.-]/g, '_')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,gBAAgB,UAAU,QAAQ;;AAGxC,SAAS,iBAAiB,WAA2B;CACnD,IAAI,UAAU,QAAQ,cAAc,SAAS,CAAC;CAC9C,OAAO,MAAM;EACX,MAAM,eAAe,KAAK,SAAS,cAAc;EACjD,IAAI,WAAW,YAAY,GACR;OAAA,KAAK,MAAM,aAAa,cAAc,MAAM,CAClD,CAAC,CAAC,SAAS,+BAA+B,OAAO;EAAA;EAE9D,MAAM,SAAS,QAAQ,OAAO;EAC9B,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,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AK;CACjG;AACF;;AAGA,eAAsB,UAAU,MAAc,SAAgC;CAC5E,MAAM,UAAU,MAAM,OAAO;AAC/B;;AAGA,SAAgB,UAAU,QAAgB,IAAoB;CAC5D,OAAO,GAAG,OAAO,GAAG,KAAK,QAAQ,oBAAoB,GAAG;AAC1D"}
@@ -1,3 +1,3 @@
1
- import { BenchmarkAdapter } from "./types.js";
2
- export declare function createAecBenchAdapter(): BenchmarkAdapter;
1
+ import { RuntimeBenchmark } from "./types.js";
2
+ export declare function createAecBenchAdapter(): RuntimeBenchmark;
3
3
  //# sourceMappingURL=aec-bench.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { benchRoot, preflightVenvImports, readJsonReport, runStagedJudge, stageFile, venvPython } from "./_harness.js";
2
+ import { runtimeBenchmark } from "./types.js";
2
3
  import { readFile } from "node:fs/promises";
3
4
  import { join } from "node:path";
4
5
  // src/benchmarks/aec-bench.ts
@@ -40,14 +41,16 @@ function recordToTask(rec) {
40
41
  };
41
42
  return {
42
43
  id: rec.id,
43
- split: rec.discipline,
44
- prompt: rec.instruction,
44
+ payload: {
45
+ subset: rec.discipline,
46
+ prompt: rec.instruction
47
+ },
45
48
  metadata: meta
46
49
  };
47
50
  }
48
51
  function readMeta(task) {
49
52
  const md = task.metadata;
50
- if (!md || typeof md.verifyPy !== "string" || typeof md.taskId !== "string") throw new Error(`aec-bench task ${task.id} missing verifier metadata — loadTasks did not populate it`);
53
+ if (!md || typeof md.verifyPy !== "string" || typeof md.taskId !== "string") throw new Error(`aec-bench task ${task.id} missing verifier metadata — loadAll did not populate it`);
51
54
  return md;
52
55
  }
53
56
  async function fetchText(url) {
@@ -107,7 +110,7 @@ async function fetchInstance(id) {
107
110
  }
108
111
  function selectFixtures(records, opts) {
109
112
  let tasks = records.map(recordToTask);
110
- if (opts.split) tasks = tasks.filter((t) => t.split === opts.split);
113
+ if (opts.subset) tasks = tasks.filter((t) => t.payload.subset === opts.subset);
111
114
  if (opts.ids) {
112
115
  const want = new Set(opts.ids);
113
116
  tasks = tasks.filter((t) => want.has(t.id));
@@ -135,7 +138,7 @@ async function loadLive(opts) {
135
138
  }
136
139
  const limit = opts.limit ?? DEFAULT_LIMIT;
137
140
  let ids = await listAllInstances();
138
- if (opts.split) ids = ids.filter((id) => id.startsWith(`${opts.split}/`));
141
+ if (opts.subset) ids = ids.filter((id) => id.startsWith(`${opts.subset}/`));
139
142
  const records = [];
140
143
  for (const id of ids) {
141
144
  if (records.length >= limit) break;
@@ -146,7 +149,7 @@ async function loadLive(opts) {
146
149
  console.warn(`[aec-bench] skipping ${id}: ${err instanceof Error ? err.message : String(err)}`);
147
150
  }
148
151
  }
149
- if (records.length === 0) throw new Error(`aec-bench loadTasks found no runnable instances for ${JSON.stringify(opts)} (no tests/verify.py matched the requested split). Set AEC_FIXTURES=1 to run offline.`);
152
+ if (records.length === 0) throw new Error(`aec-bench loadAll found no runnable instances for ${JSON.stringify(opts)} (no tests/verify.py matched the requested split). Set AEC_FIXTURES=1 to run offline.`);
150
153
  return records.map(recordToTask);
151
154
  }
152
155
  /**
@@ -179,45 +182,26 @@ async function runVerifier(meta, artifact) {
179
182
  if (typeof reward !== "number" || !Number.isFinite(reward)) throw new Error(`aec-bench verify.py wrote no numeric reward for ${meta.taskId}: ${JSON.stringify(report)}`);
180
183
  const details = await readFile(join(dir, "details.json"), "utf8").then((s) => JSON.parse(s), () => ({}));
181
184
  const score = Math.max(0, Math.min(1, reward));
185
+ const raw = {
186
+ taskId: meta.taskId,
187
+ discipline: meta.discipline,
188
+ reward,
189
+ fields: details
190
+ };
182
191
  return {
183
- resolved: score >= 1,
192
+ passed: score >= 1,
184
193
  score,
185
- detail: JSON.stringify({
186
- taskId: meta.taskId,
187
- discipline: meta.discipline,
188
- reward,
189
- fields: details
190
- })
194
+ notes: JSON.stringify(raw),
195
+ raw
191
196
  };
192
197
  }
193
198
  });
194
199
  }
195
200
  function createAecBenchAdapter() {
196
201
  const fixturesMode = process.env.AEC_FIXTURES === "1";
197
- return {
198
- name: "aec-bench",
199
- async preflight() {
200
- await preflightVenvImports({
201
- modules: [
202
- "math",
203
- "json",
204
- "re"
205
- ],
206
- requireDocker: false,
207
- fix: "Fix: python3 -m venv bench/.venv (verify.py only needs the stdlib — no pip install)."
208
- });
209
- if (fixturesMode) {
210
- await readFile(FIXTURES, "utf8").catch((err) => {
211
- throw new Error(`AEC_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`);
212
- });
213
- return;
214
- }
215
- const res = await fetch(`${RAW}/README.md`, { method: "HEAD" }).catch((err) => {
216
- throw new Error(`aec-bench preflight failed reaching ${RAW}: ${err instanceof Error ? err.message : err}\nFix: ensure network access to raw.githubusercontent.com, or set AEC_FIXTURES=1 to run offline.`);
217
- });
218
- if (!res.ok) throw new Error(`aec-bench preflight: ${REPO} README HEAD ${res.status}. Set AEC_FIXTURES=1 to run against committed fixtures.`);
219
- },
220
- async loadTasks(opts = {}) {
202
+ return runtimeBenchmark({
203
+ id: "aec-bench",
204
+ async loadAll(opts = {}) {
221
205
  if (fixturesMode) return loadFixtures(opts);
222
206
  try {
223
207
  return await loadLive(opts);
@@ -229,13 +213,36 @@ function createAecBenchAdapter() {
229
213
  throw err;
230
214
  }
231
215
  },
232
- async goldArtifact(task) {
233
- return readMeta(task).goldenPassMd ?? void 0;
234
- },
235
- async judge(task, artifact) {
216
+ async evaluate(task, artifact) {
236
217
  return runVerifier(readMeta(task), artifact);
218
+ },
219
+ runtime: {
220
+ async preflight() {
221
+ await preflightVenvImports({
222
+ modules: [
223
+ "math",
224
+ "json",
225
+ "re"
226
+ ],
227
+ requireDocker: false,
228
+ fix: "Fix: python3 -m venv bench/.venv (verify.py only needs the stdlib — no pip install)."
229
+ });
230
+ if (fixturesMode) {
231
+ await readFile(FIXTURES, "utf8").catch((err) => {
232
+ throw new Error(`AEC_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`);
233
+ });
234
+ return;
235
+ }
236
+ const res = await fetch(`${RAW}/README.md`, { method: "HEAD" }).catch((err) => {
237
+ throw new Error(`aec-bench preflight failed reaching ${RAW}: ${err instanceof Error ? err.message : err}\nFix: ensure network access to raw.githubusercontent.com, or set AEC_FIXTURES=1 to run offline.`);
238
+ });
239
+ if (!res.ok) throw new Error(`aec-bench preflight: ${REPO} README HEAD ${res.status}. Set AEC_FIXTURES=1 to run against committed fixtures.`);
240
+ },
241
+ async goldArtifact(task) {
242
+ return readMeta(task).goldenPassMd ?? void 0;
243
+ }
237
244
  }
238
- };
245
+ });
239
246
  }
240
247
  export { createAecBenchAdapter };
241
248
 
@@ -1 +1 @@
1
- {"version":3,"file":"aec-bench.js","names":[],"sources":["../../src/benchmarks/aec-bench.ts"],"sourcesContent":["/**\n * AEC-Bench adapter (TheodoreGalanos/aec-bench, MIT) — closed-form\n * Architecture/Engineering/Construction calculation tasks. Worker artifact = a\n * markdown solution ending in a fenced ```json block with the required numeric\n * fields. Judge = the task's OWN `tests/verify.py`, run with python3: it\n * recomputes ground truth from the embedded engineering formulas, extracts the\n * last JSON block from the artifact, scores each field by math.isclose within a\n * per-field rel_tol, and writes {\"reward\": mean} + per-field details.json.\n * GRADED / partial-credit, FULLY DETERMINISTIC — no LLM judge.\n *\n * Distinct from the multimodal nomic-ai/aec-bench; this is the deterministic\n * calculation platform. The runnable-instance verify.py only needs python3 (no\n * Docker, no Harbor) for the pure-calc disciplines, so the local gate runs at\n * conc<=2 without a container backend.\n *\n * Requires for a live run: network to raw.githubusercontent.com /\n * api.github.com (the in-repo tasks tree) + a python3 interpreter (the bench\n * venv) to run verify.py. For offline/CI, set AEC_FIXTURES=1 to load the\n * committed fixtures (bench/fixtures/aec-bench.json) — never a silent fallback.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { benchRoot, preflightVenvImports, readJsonReport, runStagedJudge, stageFile, venvPython } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'aec-bench.json')\n\nconst REPO = 'TheodoreGalanos/aec-bench'\nconst RAW = `https://raw.githubusercontent.com/${REPO}/main`\nconst TREE = `https://api.github.com/repos/${REPO}/git/trees/main?recursive=1`\n\n/** Matches every runnable-instance task id at ANY depth under tasks/. */\nconst verifyPathPattern = /^tasks\\/(.+)\\/tests\\/verify\\.py$/\n\n/** Default cap on tasks enumerated before a `limit` is applied. */\nconst DEFAULT_LIMIT = 10\n\ninterface AecRecord {\n /** Canonical task id `<discipline>/<task>`, e.g. 'electrical/catenary-sag'. */\n id: string\n discipline: string\n /** instruction.md — the self-contained prompt (table + required outputs + JSON schema). */\n instruction: string\n /** task.toml — metadata/difficulty/timeouts (carried for trace context). */\n task_toml: string\n /** tests/verify.py — the deterministic verifier (recomputes GT, scores fields). */\n verify_py: string\n /** tests/fixtures/golden_pass.md — the oracle artifact that scores reward 1.0,\n * when the task ships one. Null when the task only ships a non-md ground truth\n * (e.g. tests/ground_truth.json); the judge never needs it, only goldArtifact does. */\n golden_pass_md: string | null\n}\n\ninterface AecMeta {\n taskId: string\n discipline: string\n taskToml: string\n verifyPy: string\n goldenPassMd: string | null\n}\n\nfunction recordToTask(rec: AecRecord): BenchTask {\n const meta: AecMeta = {\n taskId: rec.id,\n discipline: rec.discipline,\n taskToml: rec.task_toml,\n verifyPy: rec.verify_py,\n goldenPassMd: rec.golden_pass_md,\n }\n return {\n id: rec.id,\n split: rec.discipline,\n // instruction.md is fully self-contained and already specifies the exact JSON\n // output schema + the \"write to /workspace/output.md\" contract the verifier\n // keys off — we pass it through verbatim so the verify.py extractor matches.\n prompt: rec.instruction,\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): AecMeta {\n const md = task.metadata\n // Gold is optional (goldenPassMd may be null) — only the verifier + id are required.\n if (!md || typeof md.verifyPy !== 'string' || typeof md.taskId !== 'string') {\n throw new Error(`aec-bench task ${task.id} missing verifier metadata — loadTasks did not populate it`)\n }\n return md as unknown as AecMeta\n}\n\nasync function fetchText(url: string): Promise<string> {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`aec-bench fetch ${res.status}: ${url}`)\n return res.text()\n}\n\n/** Like fetchText but returns null on a 404 (absent optional file); throws on any other non-OK. */\nasync function fetchTextOrNull(url: string): Promise<string | null> {\n const res = await fetch(url)\n if (res.status === 404) return null\n if (!res.ok) throw new Error(`aec-bench fetch ${res.status}: ${url}`)\n return res.text()\n}\n\ninterface GitTree {\n tree: Array<{ path: string; type: string }>\n}\n\n/**\n * One recursive git-tree call enumerates EVERY runnable-instance id at any depth:\n * a task is runnable iff it ships tests/verify.py. The captured group is the id\n * `tasks/<id>/tests/verify.py` → `<id>` (e.g. 'electrical/pf-droop', or a deeper\n * '<discipline>/<family>/<task>'). Throws loud on a non-OK tree response.\n */\nasync function listAllInstances(): Promise<string[]> {\n const res = await fetch(TREE)\n if (!res.ok) throw new Error(`aec-bench tree ${res.status}: ${TREE}`)\n const { tree } = (await res.json()) as GitTree\n const ids: string[] = []\n for (const entry of tree) {\n const m = verifyPathPattern.exec(entry.path)\n if (m?.[1]) ids.push(m[1])\n }\n return ids\n}\n\n/**\n * Fetch one task's instruction.md + task.toml + tests/verify.py + golden_pass.md.\n * Returns null when the dir is a SEED (no runnable verify.py) so enumeration can\n * skip it without faking a task. Gold is OPTIONAL — a task that ships a non-md\n * ground truth (e.g. tests/ground_truth.json) yields golden_pass_md=null; the\n * deterministic judge needs only verify.py.\n */\nasync function fetchInstance(id: string): Promise<AecRecord | null> {\n const base = `${RAW}/tasks/${id}`\n const verify = await fetch(`${base}/tests/verify.py`)\n if (verify.status === 404) return null\n if (!verify.ok) throw new Error(`aec-bench fetch ${verify.status}: ${id}/tests/verify.py`)\n const [instruction, task_toml, golden_pass_md] = await Promise.all([\n fetchText(`${base}/instruction.md`),\n fetchText(`${base}/task.toml`),\n fetchTextOrNull(`${base}/tests/fixtures/golden_pass.md`),\n ])\n return {\n id,\n discipline: id.split('/')[0] ?? '',\n instruction,\n task_toml,\n verify_py: await verify.text(),\n golden_pass_md,\n }\n}\n\nfunction selectFixtures(records: AecRecord[], opts: LoadOptions): BenchTask[] {\n let tasks = records.map(recordToTask)\n if (opts.split) tasks = tasks.filter((t) => t.split === opts.split)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((t) => want.has(t.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = JSON.parse(await readFile(FIXTURES, 'utf8')) as AecRecord[]\n console.warn(\n `[aec-bench] AEC_FIXTURES=1 — loading ${records.length} committed fixtures from ${FIXTURES} (no GitHub fetch)`,\n )\n return selectFixtures(records, opts)\n}\n\n/** Enumerate live tasks: explicit ids (each required — throws on a bad id), or a\n * capped slice of the recursive tree (optionally filtered to one split). Per-task\n * resilient: a single fetch failure warns + SKIPS that task, never aborting the\n * batch. Skips seed dirs (no verify.py) — never fabricates. */\nasync function loadLive(opts: LoadOptions): Promise<BenchTask[]> {\n if (opts.ids) {\n const records: AecRecord[] = []\n for (const id of opts.ids) {\n const rec = await fetchInstance(id)\n if (!rec) throw new Error(`aec-bench: ${id} has no tests/verify.py (seed-only or wrong id)`)\n records.push(rec)\n }\n return records.map(recordToTask)\n }\n const limit = opts.limit ?? DEFAULT_LIMIT\n let ids = await listAllInstances()\n if (opts.split) ids = ids.filter((id) => id.startsWith(`${opts.split}/`))\n const records: AecRecord[] = []\n for (const id of ids) {\n if (records.length >= limit) break\n try {\n const rec = await fetchInstance(id)\n if (rec) records.push(rec)\n } catch (err) {\n // One bad task must NEVER abort the batch — warn and skip it.\n console.warn(`[aec-bench] skipping ${id}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n if (records.length === 0) {\n throw new Error(\n `aec-bench loadTasks found no runnable instances for ${JSON.stringify(opts)} ` +\n `(no tests/verify.py matched the requested split). Set AEC_FIXTURES=1 to run offline.`,\n )\n }\n return records.map(recordToTask)\n}\n\n/**\n * Run the task's own verify.py with python3 over the artifact via the shared\n * staged-judge spine (mkdtemp → stage → spawn → parseReport → cleanup). verify.py\n * writes {\"reward\": mean} to --output and per-field details.json as a sibling. We\n * read both: reward → graded score; details → sub-scores for the trace-analyst.\n * Fail loud if the verifier never wrote a numeric reward (a crashed verifier is\n * NOT a silent 0 — verify.py's own except-trap writes reward 0.0, so an absent /\n * non-numeric reward.json is a real bug, surfaced by readJsonReport).\n */\nasync function runVerifier(meta: AecMeta, artifact: string): Promise<BenchScore> {\n return runStagedJudge({\n tmpPrefix: 'aecbench-',\n timeoutMs: 120_000,\n async stage(dir) {\n await Promise.all([\n stageFile(join(dir, 'output.md'), artifact),\n stageFile(join(dir, 'verify.py'), meta.verifyPy),\n ])\n },\n bin: venvPython,\n argv: (dir) => [join(dir, 'verify.py'), '--input', join(dir, 'output.md'), '--output', join(dir, 'reward.json')],\n async parseReport(dir) {\n const report = await readJsonReport<{ reward?: number }>(join(dir, 'reward.json'))\n const reward = report.reward\n if (typeof reward !== 'number' || !Number.isFinite(reward)) {\n throw new Error(`aec-bench verify.py wrote no numeric reward for ${meta.taskId}: ${JSON.stringify(report)}`)\n }\n const details = await readFile(join(dir, 'details.json'), 'utf8').then(\n (s) => JSON.parse(s) as Record<string, number>,\n () => ({}),\n )\n const score = Math.max(0, Math.min(1, reward))\n return {\n // resolved = full credit (all fields within tolerance), matching aec-bench's perfect_rate.\n resolved: score >= 1,\n score,\n detail: JSON.stringify({ taskId: meta.taskId, discipline: meta.discipline, reward, fields: details }),\n }\n },\n })\n}\n\nexport function createAecBenchAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.AEC_FIXTURES === '1'\n\n return {\n name: 'aec-bench',\n\n async preflight() {\n // The verifier is python3 over the stdlib (math/json/re) — no pip install.\n // Reuse the shared import-probe so the bench venv interpreter is proven to\n // exist + run before any judge spawns verify.py.\n await preflightVenvImports({\n modules: ['math', 'json', 're'],\n requireDocker: false,\n fix: 'Fix: python3 -m venv bench/.venv (verify.py only needs the stdlib — no pip install).',\n })\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(`AEC_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`)\n })\n return\n }\n const res = await fetch(`${RAW}/README.md`, { method: 'HEAD' }).catch((err) => {\n throw new Error(\n `aec-bench preflight failed reaching ${RAW}: ${err instanceof Error ? err.message : err}\\n` +\n `Fix: ensure network access to raw.githubusercontent.com, or set AEC_FIXTURES=1 to run offline.`,\n )\n })\n if (!res.ok) {\n throw new Error(\n `aec-bench preflight: ${REPO} README HEAD ${res.status}. Set AEC_FIXTURES=1 to run against committed fixtures.`,\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n try {\n return await loadLive(opts)\n } catch (err) {\n // A reachability failure falls back to fixtures with an explicit warn; a\n // wrong-id / seed-only error (the loader's own throw) propagates.\n if (err instanceof Error && /fetch \\d|ENOTFOUND|getaddrinfo|network/i.test(err.message)) {\n console.warn(\n `[aec-bench] live fetch failed (${err.message.slice(0, 160)}); falling back to committed fixtures at ${FIXTURES}`,\n )\n return loadFixtures(opts)\n }\n throw err\n }\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold = the task's own golden_pass.md (scores reward 1.0 through the SAME\n // verify.py the real artifact takes), proving the judge end-to-end. Tasks\n // without a golden_pass.md (non-md ground truth) have no oracle artifact.\n const meta = readMeta(task)\n return meta.goldenPassMd ?? undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n // verify.py fail-closes an empty/unparseable artifact to reward 0.0 itself,\n // so we pass it straight through (no pre-judging here).\n return runVerifier(meta, artifact)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,WAAW,KAAK,WAAW,YAAY,gBAAgB;AAE7D,MAAM,OAAO;AACb,MAAM,MAAM,qC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AK;IAGZ,IAAI,eAAe,SAAS,0CAA0C,KAAK,IAAI,OAAO,GAAG;KACvF,QAAQ,KACN,kCAAkC,IAAI,QAAQ,MAAM,GAAG,GAAG,EAAE,2CAA2C,UACzG;KACA,OAAO,aAAa,IAAI;IAC1B;IACA,MAAM;GACR;EACF;EAEA,MAAM,aAAa,MAAiB;GAKlC,OADa,SAAS,IACZ,CAAC,CAAC,gBAAgB,KAAA;EAC9B;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAIlE,OAAO,YAHM,SAAS,IAGA,GAAG,QAAQ;EACnC;CACF;AACF"}
1
+ {"version":3,"file":"aec-bench.js","names":[],"sources":["../../src/benchmarks/aec-bench.ts"],"sourcesContent":["/**\n * AEC-Bench adapter (TheodoreGalanos/aec-bench, MIT) — closed-form\n * Architecture/Engineering/Construction calculation tasks. Worker artifact = a\n * markdown solution ending in a fenced ```json block with the required numeric\n * fields. Judge = the task's OWN `tests/verify.py`, run with python3: it\n * recomputes ground truth from the embedded engineering formulas, extracts the\n * last JSON block from the artifact, scores each field by math.isclose within a\n * per-field rel_tol, and writes {\"reward\": mean} + per-field details.json.\n * GRADED / partial-credit, FULLY DETERMINISTIC — no LLM judge.\n *\n * Distinct from the multimodal nomic-ai/aec-bench; this is the deterministic\n * calculation platform. The runnable-instance verify.py only needs python3 (no\n * Docker, no Harbor) for the pure-calc disciplines, so the local gate runs at\n * conc<=2 without a container backend.\n *\n * Requires for a live run: network to raw.githubusercontent.com /\n * api.github.com (the in-repo tasks tree) + a python3 interpreter (the bench\n * venv) to run verify.py. For offline/CI, set AEC_FIXTURES=1 to load the\n * committed fixtures (bench/fixtures/aec-bench.json) — never a silent fallback.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { benchRoot, preflightVenvImports, readJsonReport, runStagedJudge, stageFile, venvPython } from './_harness'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'aec-bench.json')\n\nconst REPO = 'TheodoreGalanos/aec-bench'\nconst RAW = `https://raw.githubusercontent.com/${REPO}/main`\nconst TREE = `https://api.github.com/repos/${REPO}/git/trees/main?recursive=1`\n\n/** Matches every runnable-instance task id at ANY depth under tasks/. */\nconst verifyPathPattern = /^tasks\\/(.+)\\/tests\\/verify\\.py$/\n\n/** Default cap on tasks enumerated before a `limit` is applied. */\nconst DEFAULT_LIMIT = 10\n\ninterface AecRecord {\n /** Canonical task id `<discipline>/<task>`, e.g. 'electrical/catenary-sag'. */\n id: string\n discipline: string\n /** instruction.md — the self-contained prompt (table + required outputs + JSON schema). */\n instruction: string\n /** task.toml — metadata/difficulty/timeouts (carried for trace context). */\n task_toml: string\n /** tests/verify.py — the deterministic verifier (recomputes GT, scores fields). */\n verify_py: string\n /** tests/fixtures/golden_pass.md — the oracle artifact that scores reward 1.0,\n * when the task ships one. Null when the task only ships a non-md ground truth\n * (e.g. tests/ground_truth.json); the judge never needs it, only goldArtifact does. */\n golden_pass_md: string | null\n}\n\ninterface AecMeta {\n taskId: string\n discipline: string\n taskToml: string\n verifyPy: string\n goldenPassMd: string | null\n}\n\nfunction recordToTask(rec: AecRecord): BenchTask {\n const meta: AecMeta = {\n taskId: rec.id,\n discipline: rec.discipline,\n taskToml: rec.task_toml,\n verifyPy: rec.verify_py,\n goldenPassMd: rec.golden_pass_md,\n }\n return {\n id: rec.id,\n payload: {\n subset: rec.discipline,\n // instruction.md is fully self-contained and already specifies the exact JSON\n // output schema + the \"write to /workspace/output.md\" contract the verifier\n // keys off — we pass it through verbatim so the verify.py extractor matches.\n prompt: rec.instruction,\n },\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): AecMeta {\n const md = task.metadata\n // Gold is optional (goldenPassMd may be null) — only the verifier + id are required.\n if (!md || typeof md.verifyPy !== 'string' || typeof md.taskId !== 'string') {\n throw new Error(`aec-bench task ${task.id} missing verifier metadata — loadAll did not populate it`)\n }\n return md as unknown as AecMeta\n}\n\nasync function fetchText(url: string): Promise<string> {\n const res = await fetch(url)\n if (!res.ok) throw new Error(`aec-bench fetch ${res.status}: ${url}`)\n return res.text()\n}\n\n/** Like fetchText but returns null on a 404 (absent optional file); throws on any other non-OK. */\nasync function fetchTextOrNull(url: string): Promise<string | null> {\n const res = await fetch(url)\n if (res.status === 404) return null\n if (!res.ok) throw new Error(`aec-bench fetch ${res.status}: ${url}`)\n return res.text()\n}\n\ninterface GitTree {\n tree: Array<{ path: string; type: string }>\n}\n\n/**\n * One recursive git-tree call enumerates EVERY runnable-instance id at any depth:\n * a task is runnable iff it ships tests/verify.py. The captured group is the id\n * `tasks/<id>/tests/verify.py` → `<id>` (e.g. 'electrical/pf-droop', or a deeper\n * '<discipline>/<family>/<task>'). Throws loud on a non-OK tree response.\n */\nasync function listAllInstances(): Promise<string[]> {\n const res = await fetch(TREE)\n if (!res.ok) throw new Error(`aec-bench tree ${res.status}: ${TREE}`)\n const { tree } = (await res.json()) as GitTree\n const ids: string[] = []\n for (const entry of tree) {\n const m = verifyPathPattern.exec(entry.path)\n if (m?.[1]) ids.push(m[1])\n }\n return ids\n}\n\n/**\n * Fetch one task's instruction.md + task.toml + tests/verify.py + golden_pass.md.\n * Returns null when the dir is a SEED (no runnable verify.py) so enumeration can\n * skip it without faking a task. Gold is OPTIONAL — a task that ships a non-md\n * ground truth (e.g. tests/ground_truth.json) yields golden_pass_md=null; the\n * deterministic judge needs only verify.py.\n */\nasync function fetchInstance(id: string): Promise<AecRecord | null> {\n const base = `${RAW}/tasks/${id}`\n const verify = await fetch(`${base}/tests/verify.py`)\n if (verify.status === 404) return null\n if (!verify.ok) throw new Error(`aec-bench fetch ${verify.status}: ${id}/tests/verify.py`)\n const [instruction, task_toml, golden_pass_md] = await Promise.all([\n fetchText(`${base}/instruction.md`),\n fetchText(`${base}/task.toml`),\n fetchTextOrNull(`${base}/tests/fixtures/golden_pass.md`),\n ])\n return {\n id,\n discipline: id.split('/')[0] ?? '',\n instruction,\n task_toml,\n verify_py: await verify.text(),\n golden_pass_md,\n }\n}\n\nfunction selectFixtures(records: AecRecord[], opts: LoadOptions): BenchTask[] {\n let tasks = records.map(recordToTask)\n if (opts.subset) tasks = tasks.filter((t) => t.payload.subset === opts.subset)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((t) => want.has(t.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = JSON.parse(await readFile(FIXTURES, 'utf8')) as AecRecord[]\n console.warn(\n `[aec-bench] AEC_FIXTURES=1 — loading ${records.length} committed fixtures from ${FIXTURES} (no GitHub fetch)`,\n )\n return selectFixtures(records, opts)\n}\n\n/** Enumerate live tasks: explicit ids (each required — throws on a bad id), or a\n * capped slice of the recursive tree (optionally filtered to one split). Per-task\n * resilient: a single fetch failure warns + SKIPS that task, never aborting the\n * batch. Skips seed dirs (no verify.py) — never fabricates. */\nasync function loadLive(opts: LoadOptions): Promise<BenchTask[]> {\n if (opts.ids) {\n const records: AecRecord[] = []\n for (const id of opts.ids) {\n const rec = await fetchInstance(id)\n if (!rec) throw new Error(`aec-bench: ${id} has no tests/verify.py (seed-only or wrong id)`)\n records.push(rec)\n }\n return records.map(recordToTask)\n }\n const limit = opts.limit ?? DEFAULT_LIMIT\n let ids = await listAllInstances()\n if (opts.subset) ids = ids.filter((id) => id.startsWith(`${opts.subset}/`))\n const records: AecRecord[] = []\n for (const id of ids) {\n if (records.length >= limit) break\n try {\n const rec = await fetchInstance(id)\n if (rec) records.push(rec)\n } catch (err) {\n // One bad task must NEVER abort the batch — warn and skip it.\n console.warn(`[aec-bench] skipping ${id}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n if (records.length === 0) {\n throw new Error(\n `aec-bench loadAll found no runnable instances for ${JSON.stringify(opts)} ` +\n `(no tests/verify.py matched the requested split). Set AEC_FIXTURES=1 to run offline.`,\n )\n }\n return records.map(recordToTask)\n}\n\n/**\n * Run the task's own verify.py with python3 over the artifact via the shared\n * staged-judge spine (mkdtemp → stage → spawn → parseReport → cleanup). verify.py\n * writes {\"reward\": mean} to --output and per-field details.json as a sibling. We\n * read both: reward → graded score; details → sub-scores for the trace-analyst.\n * Fail loud if the verifier never wrote a numeric reward (a crashed verifier is\n * NOT a silent 0 — verify.py's own except-trap writes reward 0.0, so an absent /\n * non-numeric reward.json is a real bug, surfaced by readJsonReport).\n */\nasync function runVerifier(meta: AecMeta, artifact: string): Promise<BenchEvaluation> {\n return runStagedJudge({\n tmpPrefix: 'aecbench-',\n timeoutMs: 120_000,\n async stage(dir) {\n await Promise.all([\n stageFile(join(dir, 'output.md'), artifact),\n stageFile(join(dir, 'verify.py'), meta.verifyPy),\n ])\n },\n bin: venvPython,\n argv: (dir) => [join(dir, 'verify.py'), '--input', join(dir, 'output.md'), '--output', join(dir, 'reward.json')],\n async parseReport(dir) {\n const report = await readJsonReport<{ reward?: number }>(join(dir, 'reward.json'))\n const reward = report.reward\n if (typeof reward !== 'number' || !Number.isFinite(reward)) {\n throw new Error(`aec-bench verify.py wrote no numeric reward for ${meta.taskId}: ${JSON.stringify(report)}`)\n }\n const details = await readFile(join(dir, 'details.json'), 'utf8').then(\n (s) => JSON.parse(s) as Record<string, number>,\n () => ({}),\n )\n const score = Math.max(0, Math.min(1, reward))\n const raw = { taskId: meta.taskId, discipline: meta.discipline, reward, fields: details }\n return {\n // passed = full credit (all fields within tolerance), matching aec-bench's perfect_rate.\n passed: score >= 1,\n score,\n notes: JSON.stringify(raw),\n raw,\n }\n },\n })\n}\n\nexport function createAecBenchAdapter(): RuntimeBenchmark {\n const fixturesMode = process.env.AEC_FIXTURES === '1'\n\n return runtimeBenchmark({\n id: 'aec-bench',\n\n async loadAll(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n try {\n return await loadLive(opts)\n } catch (err) {\n // A reachability failure falls back to fixtures with an explicit warn; a\n // wrong-id / seed-only error (the loader's own throw) propagates.\n if (err instanceof Error && /fetch \\d|ENOTFOUND|getaddrinfo|network/i.test(err.message)) {\n console.warn(\n `[aec-bench] live fetch failed (${err.message.slice(0, 160)}); falling back to committed fixtures at ${FIXTURES}`,\n )\n return loadFixtures(opts)\n }\n throw err\n }\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n const meta = readMeta(task)\n // verify.py fail-closes an empty/unparseable artifact to reward 0.0 itself,\n // so we pass it straight through (no pre-judging here).\n return runVerifier(meta, artifact)\n },\n\n runtime: {\n async preflight() {\n // The verifier is python3 over the stdlib (math/json/re) — no pip install.\n // Reuse the shared import-probe so the bench venv interpreter is proven to\n // exist + run before any judge spawns verify.py.\n await preflightVenvImports({\n modules: ['math', 'json', 're'],\n requireDocker: false,\n fix: 'Fix: python3 -m venv bench/.venv (verify.py only needs the stdlib — no pip install).',\n })\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(`AEC_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`)\n })\n return\n }\n const res = await fetch(`${RAW}/README.md`, { method: 'HEAD' }).catch((err) => {\n throw new Error(\n `aec-bench preflight failed reaching ${RAW}: ${err instanceof Error ? err.message : err}\\n` +\n `Fix: ensure network access to raw.githubusercontent.com, or set AEC_FIXTURES=1 to run offline.`,\n )\n })\n if (!res.ok) {\n throw new Error(\n `aec-bench preflight: ${REPO} README HEAD ${res.status}. Set AEC_FIXTURES=1 to run against committed fixtures.`,\n )\n }\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold = the task's own golden_pass.md (scores reward 1.0 through the SAME\n // verify.py the real artifact takes), proving the judge end-to-end. Tasks\n // without a golden_pass.md (non-md ground truth) have no oracle artifact.\n const meta = readMeta(task)\n return meta.goldenPassMd ?? undefined\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,WAAW,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,CAAC,CAAC,OAAO,QAAQ;MAC9C,MAAM,IAAI,MAAM,sBAAsB,SAAS,eAAe,eAAe,QAAQ,IAAI,UAAU,KAAK;KAC1G,CAAC;KACD;IACF;IACA,MAAM,MAAM,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC,OAAO,QAAQ;KAC7E,MAAM,IAAI,MACR,uCAAuC,IAAI,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,iGAE1F;IACF,CAAC;IACD,IAAI,CAAC,IAAI,IACP,MAAM,IAAI,MACR,wBAAwB,KAAK,eAAe,IAAI,OAAO,wDACzD;GAEJ;GAEA,MAAM,aAAa,MAAiB;IAKlC,OADa,SAAS,IACZ,CAAC,CAAC,gBAAgB,KAAA;GAC9B;EACF;CACF,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
- import { BenchmarkAdapter } from "./types.js";
1
+ import { RuntimeBenchmark } from "./types.js";
2
2
  import { OutputAdapter } from "@tangle-network/agent-runtime/kernel";
3
3
  export declare const agentbenchAnswerOutput: OutputAdapter<string>;
4
- export declare function createAgentBenchAdapter(): BenchmarkAdapter;
4
+ export declare function createAgentBenchAdapter(): RuntimeBenchmark;
5
5
  //# sourceMappingURL=agentbench.d.ts.map