@tangle-network/agent-bench 2.0.0 → 4.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.
- package/CHANGELOG.md +27 -0
- package/README.md +32 -2
- package/dist/adapters.d.ts +3 -3
- package/dist/adapters.js +3 -5
- package/dist/adapters.js.map +1 -1
- package/dist/benchmarks/_harness.d.ts +4 -4
- package/dist/benchmarks/_harness.js +5 -2
- package/dist/benchmarks/_harness.js.map +1 -1
- package/dist/benchmarks/aec-bench.d.ts +2 -2
- package/dist/benchmarks/aec-bench.js +49 -42
- package/dist/benchmarks/aec-bench.js.map +1 -1
- package/dist/benchmarks/agentbench.d.ts +2 -2
- package/dist/benchmarks/agentbench.js +41 -34
- package/dist/benchmarks/agentbench.js.map +1 -1
- package/dist/benchmarks/appworld.d.ts +4 -4
- package/dist/benchmarks/appworld.js +67 -53
- package/dist/benchmarks/appworld.js.map +1 -1
- package/dist/benchmarks/bfcl.d.ts +2 -2
- package/dist/benchmarks/bfcl.js +52 -44
- package/dist/benchmarks/bfcl.js.map +1 -1
- package/dist/benchmarks/cad-design.d.ts +2 -2
- package/dist/benchmarks/cad-design.js +53 -44
- package/dist/benchmarks/cad-design.js.map +1 -1
- package/dist/benchmarks/cadbench.d.ts +2 -2
- package/dist/benchmarks/cadbench.js +1 -1
- package/dist/benchmarks/cadgenbench.d.ts +2 -2
- package/dist/benchmarks/cadgenbench.js +1 -1
- package/dist/benchmarks/commit0.d.ts +2 -2
- package/dist/benchmarks/commit0.js +38 -31
- package/dist/benchmarks/commit0.js.map +1 -1
- package/dist/benchmarks/crag.d.ts +2 -2
- package/dist/benchmarks/crag.js +37 -32
- package/dist/benchmarks/crag.js.map +1 -1
- package/dist/benchmarks/dabstep.d.ts +2 -2
- package/dist/benchmarks/dabstep.js +41 -34
- package/dist/benchmarks/dabstep.js.map +1 -1
- package/dist/benchmarks/finresearchbench.d.ts +4 -4
- package/dist/benchmarks/finresearchbench.js +61 -48
- package/dist/benchmarks/finresearchbench.js.map +1 -1
- package/dist/benchmarks/finsearchcomp.d.ts +3 -3
- package/dist/benchmarks/finsearchcomp.js +54 -43
- package/dist/benchmarks/finsearchcomp.js.map +1 -1
- package/dist/benchmarks/frames.d.ts +2 -2
- package/dist/benchmarks/frames.js +66 -51
- package/dist/benchmarks/frames.js.map +1 -1
- package/dist/benchmarks/hotpotqa.d.ts +2 -2
- package/dist/benchmarks/hotpotqa.js +59 -47
- package/dist/benchmarks/hotpotqa.js.map +1 -1
- package/dist/benchmarks/humaneval.d.ts +3 -3
- package/dist/benchmarks/humaneval.js +39 -35
- package/dist/benchmarks/humaneval.js.map +1 -1
- package/dist/benchmarks/mcad-bench.d.ts +2 -2
- package/dist/benchmarks/mcad-bench.js +68 -56
- package/dist/benchmarks/mcad-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-bench.d.ts +2 -2
- package/dist/benchmarks/mcad-cq-bench.js +69 -57
- package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-golds.d.ts +1 -1
- package/dist/benchmarks/mcad-cq-golds.js +1 -1
- package/dist/benchmarks/mcad-cq-golds.js.map +1 -1
- package/dist/benchmarks/mcad-golds.d.ts +1 -1
- package/dist/benchmarks/mcad-golds.js.map +1 -1
- package/dist/benchmarks/mind2web.d.ts +3 -3
- package/dist/benchmarks/mind2web.js +62 -49
- package/dist/benchmarks/mind2web.js.map +1 -1
- package/dist/benchmarks/nomiracl.d.ts +2 -2
- package/dist/benchmarks/nomiracl.js +43 -36
- package/dist/benchmarks/nomiracl.js.map +1 -1
- package/dist/benchmarks/open-rag-bench.d.ts +2 -2
- package/dist/benchmarks/open-rag-bench.js +37 -32
- package/dist/benchmarks/open-rag-bench.js.map +1 -1
- package/dist/benchmarks/programbench.d.ts +2 -2
- package/dist/benchmarks/programbench.js +28 -23
- package/dist/benchmarks/programbench.js.map +1 -1
- package/dist/benchmarks/rag-shared.d.ts +2 -2
- package/dist/benchmarks/rag-shared.js +15 -13
- package/dist/benchmarks/rag-shared.js.map +1 -1
- package/dist/benchmarks/ragbench.d.ts +2 -2
- package/dist/benchmarks/ragbench.js +34 -29
- package/dist/benchmarks/ragbench.js.map +1 -1
- package/dist/benchmarks/simpleqa.d.ts +2 -2
- package/dist/benchmarks/simpleqa.js +62 -51
- package/dist/benchmarks/simpleqa.js.map +1 -1
- package/dist/benchmarks/swe-bench.d.ts +4 -4
- package/dist/benchmarks/swe-bench.js +47 -41
- package/dist/benchmarks/swe-bench.js.map +1 -1
- package/dist/benchmarks/t2-ragbench.d.ts +2 -2
- package/dist/benchmarks/t2-ragbench.js +37 -32
- package/dist/benchmarks/t2-ragbench.js.map +1 -1
- package/dist/benchmarks/tau-bench-shared.d.ts +2 -2
- package/dist/benchmarks/tau-bench-shared.js +43 -36
- package/dist/benchmarks/tau-bench-shared.js.map +1 -1
- package/dist/benchmarks/tau2-bench.d.ts +2 -2
- package/dist/benchmarks/tau2-bench.js.map +1 -1
- package/dist/benchmarks/tau3-banking.d.ts +2 -2
- package/dist/benchmarks/tau3-banking.js.map +1 -1
- package/dist/benchmarks/terminal-bench.d.ts +2 -2
- package/dist/benchmarks/terminal-bench.js +29 -23
- package/dist/benchmarks/terminal-bench.js.map +1 -1
- package/dist/benchmarks/toollm.d.ts +2 -2
- package/dist/benchmarks/toollm.js +40 -34
- package/dist/benchmarks/toollm.js.map +1 -1
- package/dist/benchmarks/trata-hedge.d.ts +2 -2
- package/dist/benchmarks/trata-hedge.js +46 -38
- package/dist/benchmarks/trata-hedge.js.map +1 -1
- package/dist/benchmarks/types.d.ts +33 -63
- package/dist/benchmarks/types.js +36 -1
- package/dist/benchmarks/types.js.map +1 -0
- package/dist/benchmarks/webarena-verified.d.ts +2 -2
- package/dist/benchmarks/webarena-verified.js +29 -24
- package/dist/benchmarks/webarena-verified.js.map +1 -1
- package/dist/{cadbench-Byr5gO1M.js → cadbench-htzAmMaI.js} +39 -32
- package/dist/cadbench-htzAmMaI.js.map +1 -0
- package/dist/{cadgenbench-Tvk16YKT.js → cadgenbench-BLvEtnxU.js} +28 -22
- package/dist/cadgenbench-BLvEtnxU.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +667 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +43 -22
- package/dist/index.js +297 -144
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
- package/pier_agents/candidate_contract.py +226 -74
- package/pier_agents/tangle_candidate.py +79 -1
- package/pier_agents/workspace_boundary.py +29 -1
- package/scripts/enterpriseops-gym-run.sh +82 -0
- package/scripts/grade-recorded-evidence.mjs +6 -6
- package/scripts/harvey-lab-judge.py +50 -0
- package/scripts/harvey-lab-run.sh +53 -0
- package/scripts/harvey-lab-sandbox.sh +21 -0
- package/scripts/healthbench-professional-run.sh +30 -0
- package/scripts/healthbench_professional_run.py +112 -0
- package/scripts/mlcr-run.sh +17 -0
- package/scripts/mlcr_run.py +133 -0
- package/scripts/prbench-run.sh +39 -0
- package/scripts/prbench_run.py +53 -0
- package/scripts/verify-packed-consumer.mjs +32 -27
- package/scripts/verify-pier-agent.mts +142 -25
- package/src/adapters.ts +5 -7
- package/src/benchmarks/_harness.test.mts +18 -1
- package/src/benchmarks/_harness.ts +12 -7
- package/src/benchmarks/aec-bench.test.mts +14 -14
- package/src/benchmarks/aec-bench.ts +62 -56
- package/src/benchmarks/agent-eval-contract.test.mts +38 -0
- package/src/benchmarks/agentbench.ts +44 -37
- package/src/benchmarks/appworld.test.mts +7 -7
- package/src/benchmarks/appworld.ts +88 -75
- package/src/benchmarks/bfcl.ts +60 -53
- package/src/benchmarks/cad-design.ts +34 -32
- package/src/benchmarks/cadbench.ts +34 -32
- package/src/benchmarks/cadgenbench.ts +30 -28
- package/src/benchmarks/commit0.test.mts +9 -9
- package/src/benchmarks/commit0.ts +50 -43
- package/src/benchmarks/crag.ts +45 -40
- package/src/benchmarks/dabstep-official.test.mts +8 -8
- package/src/benchmarks/dabstep.test.mts +11 -11
- package/src/benchmarks/dabstep.ts +47 -40
- package/src/benchmarks/external-adapters.test.mts +43 -44
- package/src/benchmarks/finresearchbench.ts +57 -47
- package/src/benchmarks/finsearchcomp.ts +72 -67
- package/src/benchmarks/frames.ts +76 -69
- package/src/benchmarks/hotpotqa.ts +69 -64
- package/src/benchmarks/humaneval.ts +37 -35
- package/src/benchmarks/mcad-bench.test.mts +30 -30
- package/src/benchmarks/mcad-bench.ts +66 -60
- package/src/benchmarks/mcad-cq-bench.ts +69 -63
- package/src/benchmarks/mcad-cq-golds.ts +1 -1
- package/src/benchmarks/mcad-cq.test.mts +40 -40
- package/src/benchmarks/mcad-golds.ts +1 -1
- package/src/benchmarks/mind2web.ts +66 -58
- package/src/benchmarks/nomiracl.ts +53 -46
- package/src/benchmarks/open-rag-bench.ts +47 -42
- package/src/benchmarks/programbench.test.mts +10 -10
- package/src/benchmarks/programbench.ts +38 -33
- package/src/benchmarks/rag-benchmarks.test.mts +31 -31
- package/src/benchmarks/rag-shared.ts +13 -16
- package/src/benchmarks/ragbench.ts +44 -39
- package/src/benchmarks/simpleqa.ts +78 -73
- package/src/benchmarks/swe-bench.test.mts +3 -3
- package/src/benchmarks/swe-bench.ts +66 -61
- package/src/benchmarks/t2-ragbench.ts +47 -42
- package/src/benchmarks/tau-bench-shared.ts +51 -44
- package/src/benchmarks/tau-pin.test.mts +1 -1
- package/src/benchmarks/tau2-bench.ts +2 -2
- package/src/benchmarks/tau3-banking.ts +2 -2
- package/src/benchmarks/terminal-bench.test.mts +3 -3
- package/src/benchmarks/terminal-bench.ts +41 -36
- package/src/benchmarks/toollm.ts +54 -47
- package/src/benchmarks/trata-hedge.ts +57 -52
- package/src/benchmarks/types.ts +70 -59
- package/src/benchmarks/webarena-verified.ts +49 -42
- package/src/cli.ts +74 -0
- package/src/corpus-replay.mts +9 -9
- package/src/examples/benchmark-matrix.mts +13 -10
- package/src/gate-cli.mts +5 -5
- package/src/gate.test.mts +14 -12
- package/src/gate.ts +23 -22
- package/src/index.ts +20 -11
- package/src/pier-agent.ts +108 -38
- package/src/pier-trial-controller.test.mts +48 -1
- package/src/pier-trial-controller.ts +121 -8
- package/src/published.test.mts +534 -0
- package/src/published.ts +524 -0
- package/src/run-benchmarks-cli.mts +2 -2
- package/src/run-benchmarks.test.mts +58 -48
- package/src/run-benchmarks.ts +64 -57
- package/src/swe-bench-env.ts +6 -6
- package/src/worker.ts +1 -1
- package/dist/benchmarks/enterpriseops-gym.d.ts +0 -6
- package/dist/benchmarks/enterpriseops-gym.js +0 -236
- package/dist/benchmarks/enterpriseops-gym.js.map +0 -1
- package/dist/cadbench-Byr5gO1M.js.map +0 -1
- package/dist/cadgenbench-Tvk16YKT.js.map +0 -1
- package/fixtures/enterpriseops-gym.json +0 -103
- package/scripts/enterpriseops_gym_judge.py +0 -281
- package/src/benchmarks/enterpriseops-gym.test.mts +0 -77
- package/src/benchmarks/enterpriseops-gym.ts +0 -343
- package/src/eops-skills/address-every-subtask.md +0 -5
- package/src/eops-skills/exact-tools-and-args.md +0 -5
- package/src/eops-skills/full-sequence-to-goal.md +0 -5
- package/src/eops-skills/ground-every-value.md +0 -5
- package/src/eops-skills/honor-the-policies.md +0 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../src/benchmarks/types.ts"],"sourcesContent":["/**\n * agent-bench's benchmarks are agent-eval `BenchmarkAdapter`s, the one benchmark contract, each with the\n * `runtime` hooks an agent-runtime worker needs: the prompt, the deliverable parser, the in-box workspace\n * setup and extraction, and, where the benchmark's own protocol is the worker, that worker.\n *\n * The point: no self-authored judge, no invented score noise. `evaluate` is the benchmark's published\n * evaluation harness, run on the artifact the worker produced.\n *\n * A public benchmark reports every task, so each one also has `loadAll`, a loader that ignores agent-eval's\n * search/dev/holdout splits, as agent-eval's own Harbor adapter has. `loadDataset(split)` serves the same\n * tasks by agent-eval's deterministic split.\n */\n\nimport {\n type BenchmarkAdapter,\n type BenchmarkDatasetItem,\n type BenchmarkEvaluation,\n type BenchmarkLoadOptions,\n type BenchmarkRuntimeHooks,\n deterministicSplit,\n selectBenchmarkItems,\n} from '@tangle-network/agent-eval/benchmarks'\nimport type { RunSplitTag } from '@tangle-network/agent-eval'\nimport type { AgentTurnUsage } from '@tangle-network/agent-runtime/kernel'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\n\n/** What the worker is handed, and the publisher's subset (domain, category, language, dataset version) the task is in. */\nexport interface BenchPayload {\n prompt: string\n subset?: string\n}\n\n/** One benchmark instance. `metadata` carries the fields the worker and judge need (repo, base_commit, gold, …). */\nexport type BenchTask = BenchmarkDatasetItem<BenchPayload>\n\nexport interface JudgeArtifactFileReceipt {\n /** POSIX path relative to the capture directory. */\n path: string\n /** Exact byte length of the retained file or symbolic-link target. */\n byteLength: number\n /** SHA-256 over the retained file bytes or UTF-8 symbolic-link target. */\n sha256: `sha256:${string}`\n kind: 'file' | 'symlink'\n}\n\n/** Durable evidence written before a staged evaluator's temporary directory is removed. */\nexport interface JudgeArtifactReceipt {\n schema: 'agent-bench/judge-artifacts/v1'\n /** Absolute directory containing `evaluator/`, `process/`, and `receipt.json`. */\n directory: string\n /** Exact copy of the evaluator working directory. */\n evaluatorDirectory: string\n manifestPath: string\n evaluatorSucceeded: boolean\n files: JudgeArtifactFileReceipt[]\n fileCount: number\n byteLength: number\n /** SHA-256 over every sorted path, kind, byte length, and content hash. */\n treeSha256: `sha256:${string}`\n}\n\n/** agent-eval's verdict (`passed`: the judge passed; `score` 0..1 with partial credit where the harness has it;\n * `notes`), plus the evidence agent-bench's judges keep. */\nexport interface BenchEvaluation extends BenchmarkEvaluation {\n /** Present only when the caller explicitly requested durable judge evidence. */\n judgeArtifacts?: JudgeArtifactReceipt\n /** The judge model turn's exact Runtime usage record, present only when the\n * adapter's judge is itself a model call. `usdKnown: false` and\n * `tokensKnown: false` survive verbatim — an unknown judge cost stays\n * unknown instead of reading as zero. Deterministic judges never set it. */\n judgeUsage?: AgentTurnUsage\n}\n\n/** agent-eval's load options (`limit`, `ids`), plus the publisher's subset. */\nexport interface LoadOptions extends BenchmarkLoadOptions {\n subset?: string\n}\n\n/** The runtime hooks over agent-runtime's sandbox events. `workspaceSetup` runs in the box before the agent\n * shot (a non-zero exit fails the shot); `workspaceExtract` runs in the still-alive box after it, and its\n * stdout is the judged artifact (empty stdout falls back to `output`, then the final answer text). */\nexport type BenchRuntime = BenchmarkRuntimeHooks<BenchPayload, string, SandboxEvent>\n\n/** An agent-eval `BenchmarkAdapter` an agent-runtime worker runs. */\nexport interface RuntimeBenchmark extends BenchmarkAdapter<BenchTask, BenchPayload, string, SandboxEvent> {\n readonly id: string\n readonly runtime: BenchRuntime\n /** Every task in the publisher's order, ignoring agent-eval's splits. */\n loadAll(options?: LoadOptions): Promise<BenchTask[]>\n /** The benchmark's own judge on the worker's artifact. */\n evaluate(item: BenchTask, artifact: string): Promise<BenchEvaluation>\n}\n\nexport type RuntimeBenchmarkSpec = Omit<RuntimeBenchmark, 'loadDataset' | 'assignSplit' | 'runtime'> & {\n assignSplit?: RuntimeBenchmark['assignSplit']\n /** `prompt` defaults to the task's `payload.prompt`. */\n runtime?: Omit<BenchRuntime, 'prompt'> & Partial<Pick<BenchRuntime, 'prompt'>>\n}\n\n/** Build a `RuntimeBenchmark`: splits default to agent-eval's `deterministicSplit` over `<id>::<task id>`. */\nexport function runtimeBenchmark(spec: RuntimeBenchmarkSpec): RuntimeBenchmark {\n const assignSplit =\n spec.assignSplit ?? ((itemId: string): RunSplitTag => deterministicSplit(`${spec.id}::${itemId}`))\n return {\n ...spec,\n runtime: { prompt: (task) => task.payload.prompt, ...spec.runtime },\n assignSplit,\n async loadDataset(split, options) {\n const tasks = await spec.loadAll(options?.ids?.length ? { ids: options.ids } : {})\n const inSplit = tasks\n .map((task) => ({ ...task, split: task.split ?? assignSplit(task.id) }))\n .filter((task) => task.split === split)\n return selectBenchmarkItems(inSplit, options)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoGA,SAAgB,iBAAiB,MAA8C;CAC7E,MAAM,cACJ,KAAK,iBAAiB,WAAgC,mBAAmB,GAAG,KAAK,GAAG,IAAI,QAAQ;CAClG,OAAO;EACL,GAAG;EACH,SAAS;GAAE,SAAS,SAAS,KAAK,QAAQ;GAAQ,GAAG,KAAK;EAAQ;EAClE;EACA,MAAM,YAAY,OAAO,SAAS;GAEhC,MAAM,WAAU,MADI,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC,CAAC,EAAA,CAE9E,KAAK,UAAU;IAAE,GAAG;IAAM,OAAO,KAAK,SAAS,YAAY,KAAK,EAAE;GAAE,EAAE,CAAC,CACvE,QAAQ,SAAS,KAAK,UAAU,KAAK;GACxC,OAAO,qBAAqB,SAAS,OAAO;EAC9C;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RuntimeBenchmark } from "./types.js";
|
|
2
2
|
import { OutputAdapter } from "@tangle-network/agent-runtime/kernel";
|
|
3
3
|
export declare const webarenaOutputDirOutput: OutputAdapter<string>;
|
|
4
|
-
export declare function createWebArenaVerifiedAdapter():
|
|
4
|
+
export declare function createWebArenaVerifiedAdapter(): RuntimeBenchmark;
|
|
5
5
|
//# sourceMappingURL=webarena-verified.d.ts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { benchRoot, runVenvPython } from "./_harness.js";
|
|
2
|
+
import { runtimeBenchmark } from "./types.js";
|
|
2
3
|
import { access, readFile, stat } from "node:fs/promises";
|
|
3
4
|
import { join, resolve } from "node:path";
|
|
4
5
|
// src/benchmarks/webarena-verified.ts
|
|
@@ -47,7 +48,7 @@ function rowToTask(row) {
|
|
|
47
48
|
};
|
|
48
49
|
return {
|
|
49
50
|
id: String(row.task_id),
|
|
50
|
-
prompt: [
|
|
51
|
+
payload: { prompt: [
|
|
51
52
|
"Run this WebArena-Verified browser task in the official environment.",
|
|
52
53
|
`Goal: ${row.intent}`,
|
|
53
54
|
row.start_urls?.length ? `Start URL templates: ${row.start_urls.join(", ")}` : void 0,
|
|
@@ -55,13 +56,13 @@ function rowToTask(row) {
|
|
|
55
56
|
"",
|
|
56
57
|
"Return the path to the official WebArena-Verified run output directory for this task.",
|
|
57
58
|
"The judge expects that directory to contain the task response and network trace files."
|
|
58
|
-
].filter(Boolean).join("\n"),
|
|
59
|
+
].filter(Boolean).join("\n") },
|
|
59
60
|
metadata: meta
|
|
60
61
|
};
|
|
61
62
|
}
|
|
62
63
|
function readMeta(task) {
|
|
63
64
|
const md = task.metadata;
|
|
64
|
-
if (!md || typeof md.taskId !== "number") throw new Error(`webarena-verified task ${task.id} missing metadata —
|
|
65
|
+
if (!md || typeof md.taskId !== "number") throw new Error(`webarena-verified task ${task.id} missing metadata — loadAll did not populate it`);
|
|
65
66
|
return md;
|
|
66
67
|
}
|
|
67
68
|
function selectRows(rows, opts) {
|
|
@@ -108,25 +109,15 @@ print(json.dumps(json.loads(result_path.read_text())))
|
|
|
108
109
|
}
|
|
109
110
|
function createWebArenaVerifiedAdapter() {
|
|
110
111
|
const fixturesMode = process.env.WEBARENA_VERIFIED_FIXTURES === "1";
|
|
111
|
-
return {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
async preflight() {
|
|
115
|
-
if (fixturesMode) return;
|
|
116
|
-
const dir = webarenaDir();
|
|
117
|
-
if (!dir) throw new Error("WEBARENA_VERIFIED_DIR is required. Fix: clone https://github.com/ServiceNow/webarena-verified, install its deps in bench/.venv, and set WEBARENA_VERIFIED_DIR=/path/to/webarena-verified.");
|
|
118
|
-
await assertFile(join(dir, DATASET_REL), "official dataset");
|
|
119
|
-
await assertFile(join(dir, "src", "webarena_verified", "__main__.py"), "official CLI module");
|
|
120
|
-
await runVenvPython("import sys; sys.path.insert(0, sys.argv[1]); import webarena_verified; print(\"ok\")", [join(dir, "src")]);
|
|
121
|
-
},
|
|
122
|
-
async loadTasks(opts = {}) {
|
|
112
|
+
return runtimeBenchmark({
|
|
113
|
+
id: "webarena-verified",
|
|
114
|
+
async loadAll(opts = {}) {
|
|
123
115
|
if (fixturesMode) return loadFixtures(opts);
|
|
124
116
|
const dir = webarenaDir();
|
|
125
117
|
if (!dir) throw new Error("WEBARENA_VERIFIED_DIR is required to load official WebArena-Verified tasks");
|
|
126
118
|
return loadOfficialRows(dir, opts);
|
|
127
119
|
},
|
|
128
|
-
async
|
|
129
|
-
async judge(task, artifact) {
|
|
120
|
+
async evaluate(task, artifact) {
|
|
130
121
|
const dir = webarenaDir();
|
|
131
122
|
if (!dir) throw new Error("WEBARENA_VERIFIED_DIR is required to judge WebArena-Verified artifacts");
|
|
132
123
|
const outputDir = resolve(artifact.trim());
|
|
@@ -135,17 +126,31 @@ function createWebArenaVerifiedAdapter() {
|
|
|
135
126
|
const report = await runOfficialEval(dir, meta.taskId, outputDir);
|
|
136
127
|
const score = typeof report.score === "number" ? report.score : 0;
|
|
137
128
|
const status = typeof report.status === "string" ? report.status : "unknown";
|
|
129
|
+
const raw = {
|
|
130
|
+
taskId: meta.taskId,
|
|
131
|
+
status,
|
|
132
|
+
outputDir
|
|
133
|
+
};
|
|
138
134
|
return {
|
|
139
|
-
|
|
135
|
+
passed: score === 1,
|
|
140
136
|
score,
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
status,
|
|
144
|
-
outputDir
|
|
145
|
-
})
|
|
137
|
+
notes: JSON.stringify(raw),
|
|
138
|
+
raw
|
|
146
139
|
};
|
|
140
|
+
},
|
|
141
|
+
runtime: {
|
|
142
|
+
output: webarenaOutputDirOutput,
|
|
143
|
+
async preflight() {
|
|
144
|
+
if (fixturesMode) return;
|
|
145
|
+
const dir = webarenaDir();
|
|
146
|
+
if (!dir) throw new Error("WEBARENA_VERIFIED_DIR is required. Fix: clone https://github.com/ServiceNow/webarena-verified, install its deps in bench/.venv, and set WEBARENA_VERIFIED_DIR=/path/to/webarena-verified.");
|
|
147
|
+
await assertFile(join(dir, DATASET_REL), "official dataset");
|
|
148
|
+
await assertFile(join(dir, "src", "webarena_verified", "__main__.py"), "official CLI module");
|
|
149
|
+
await runVenvPython("import sys; sys.path.insert(0, sys.argv[1]); import webarena_verified; print(\"ok\")", [join(dir, "src")]);
|
|
150
|
+
},
|
|
151
|
+
async goldArtifact() {}
|
|
147
152
|
}
|
|
148
|
-
};
|
|
153
|
+
});
|
|
149
154
|
}
|
|
150
155
|
export { createWebArenaVerifiedAdapter, webarenaOutputDirOutput };
|
|
151
156
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webarena-verified.js","names":[],"sources":["../../src/benchmarks/webarena-verified.ts"],"sourcesContent":["/**\n * WebArena-Verified adapter (ServiceNow/webarena-verified).\n *\n * Worker artifact = a WebArena-Verified run output directory, not final chat text.\n * Judge = the official `webarena_verified eval-tasks` evaluator over that output\n * directory. The adapter refuses to score a plain answer so we do not turn a DOM\n * benchmark into a fake text benchmark.\n */\n\nimport { access, readFile, stat } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport type { OutputAdapter } from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot, runVenvPython } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'webarena-verified.json')\nconst DATASET_REL = join('assets', 'dataset', 'webarena-verified.json')\n\ninterface WebArenaRow {\n task_id: number\n intent: string\n intent_template_id?: number\n sites?: string[]\n start_urls?: string[]\n eval?: unknown[]\n revision?: number\n}\n\ninterface WebArenaMeta {\n taskId: number\n intentTemplateId?: number\n sites: string[]\n startUrls: string[]\n revision?: number\n eval?: unknown[]\n}\n\nconst webarenaDir = (): string | undefined => process.env.WEBARENA_VERIFIED_DIR\n\nexport const webarenaOutputDirOutput: OutputAdapter<string> = {\n parse(events) {\n let text = ''\n for (const ev of events) {\n const d = (ev as { data?: Record<string, unknown> })?.data\n const t = d?.finalText ?? d?.text ?? d?.result\n if (typeof t === 'string' && t.length > 0) text = t\n }\n const fences = [...text.matchAll(/```(?:text|path)?\\s*\\n([\\s\\S]*?)```/g)]\n return (fences.at(-1)?.[1] ?? text).trim()\n },\n}\n\nasync function assertFile(path: string, label: string): Promise<void> {\n try {\n await access(path)\n } catch (err) {\n throw new Error(`WebArena-Verified: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nasync function assertDir(path: string, label: string): Promise<void> {\n try {\n const s = await stat(path)\n if (!s.isDirectory()) throw new Error('not a directory')\n } catch (err) {\n throw new Error(`WebArena-Verified: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nfunction rowToTask(row: WebArenaRow): BenchTask {\n const meta: WebArenaMeta = {\n taskId: row.task_id,\n intentTemplateId: row.intent_template_id,\n sites: row.sites ?? [],\n startUrls: row.start_urls ?? [],\n revision: row.revision,\n eval: row.eval,\n }\n return {\n id: String(row.task_id),\n prompt: [\n 'Run this WebArena-Verified browser task in the official environment.',\n `Goal: ${row.intent}`,\n row.start_urls?.length ? `Start URL templates: ${row.start_urls.join(', ')}` : undefined,\n row.sites?.length ? `Sites: ${row.sites.join(', ')}` : undefined,\n '',\n 'Return the path to the official WebArena-Verified run output directory for this task.',\n 'The judge expects that directory to contain the task response and network trace files.',\n ]\n .filter(Boolean)\n .join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): WebArenaMeta {\n const md = task.metadata\n if (!md || typeof md.taskId !== 'number') {\n throw new Error(`webarena-verified task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as WebArenaMeta\n}\n\nfunction selectRows(rows: WebArenaRow[], opts: LoadOptions): BenchTask[] {\n let tasks = rows.map(rowToTask)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((task) => want.has(task.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n if (tasks.length === 0) throw new Error(`WebArena-Verified: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as WebArenaRow[]\n console.warn(`[webarena-verified] WEBARENA_VERIFIED_FIXTURES=1 — loading ${rows.length} adapter fixtures`)\n return selectRows(rows, opts)\n}\n\nasync function loadOfficialRows(dir: string, opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(join(dir, DATASET_REL), 'utf8')) as WebArenaRow[]\n return selectRows(rows, opts)\n}\n\nasync function runOfficialEval(root: string, taskId: number, outputDir: string): Promise<Record<string, unknown>> {\n const script = `\nimport json, os, subprocess, sys\nfrom pathlib import Path\n\nroot = Path(sys.argv[1])\ntask_id = sys.argv[2]\noutput_dir = Path(sys.argv[3])\nenv = os.environ.copy()\nenv[\"PYTHONPATH\"] = str(root / \"src\") + os.pathsep + env.get(\"PYTHONPATH\", \"\")\ncmd = [sys.executable, \"-m\", \"webarena_verified\", \"eval-tasks\", \"--task-ids\", task_id, \"--output-dir\", str(output_dir)]\nproc = subprocess.run(cmd, cwd=root, env=env, text=True, capture_output=True)\nif proc.returncode != 0:\n raise SystemExit((proc.stderr or proc.stdout or f\"exit {proc.returncode}\")[:2000])\nresult_path = output_dir / task_id / \"eval_result.json\"\nif not result_path.exists():\n raise SystemExit(f\"official evaluator did not write {result_path}\")\nprint(json.dumps(json.loads(result_path.read_text())))\n`\n const stdout = await runVenvPython(script, [root, String(taskId), outputDir], 0)\n return JSON.parse(stdout.trim().split('\\n').at(-1) ?? '{}') as Record<string, unknown>\n}\n\nexport function createWebArenaVerifiedAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.WEBARENA_VERIFIED_FIXTURES === '1'\n\n return {\n name: 'webarena-verified',\n output: webarenaOutputDirOutput,\n\n async preflight() {\n if (fixturesMode) return\n const dir = webarenaDir()\n if (!dir) {\n throw new Error(\n 'WEBARENA_VERIFIED_DIR is required. Fix: clone https://github.com/ServiceNow/webarena-verified, install its deps in bench/.venv, and set WEBARENA_VERIFIED_DIR=/path/to/webarena-verified.',\n )\n }\n await assertFile(join(dir, DATASET_REL), 'official dataset')\n await assertFile(join(dir, 'src', 'webarena_verified', '__main__.py'), 'official CLI module')\n await runVenvPython(\n 'import sys; sys.path.insert(0, sys.argv[1]); import webarena_verified; print(\"ok\")',\n [join(dir, 'src')],\n )\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const dir = webarenaDir()\n if (!dir) throw new Error('WEBARENA_VERIFIED_DIR is required to load official WebArena-Verified tasks')\n return loadOfficialRows(dir, opts)\n },\n\n async goldArtifact() {\n return undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const dir = webarenaDir()\n if (!dir) throw new Error('WEBARENA_VERIFIED_DIR is required to judge WebArena-Verified artifacts')\n const outputDir = resolve(artifact.trim())\n await assertDir(outputDir, 'run output directory')\n const meta = readMeta(task)\n const report = await runOfficialEval(dir, meta.taskId, outputDir)\n const score = typeof report.score === 'number' ? report.score : 0\n const status = typeof report.status === 'string' ? report.status : 'unknown'\n return {\n resolved: score === 1,\n score,\n detail: JSON.stringify({ taskId: meta.taskId, status, outputDir }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,WAAW,KAAK,WAAW,YAAY,wBAAwB;AACrE,MAAM,cAAc,KAAK,UAAU,WAAW,wBAAwB;AAqBtE,MAAM,oBAAwC,QAAQ,IAAI;AAE1D,MAAa,0BAAiD,EAC5D,MAAM,QAAQ;CACZ,IAAI,OAAO;CACX,KAAK,MAAM,MAAM,QAAQ;EACvB,MAAM,IAAK,IAA2C;EACtD,MAAM,IAAI,GAAG,aAAa,GAAG,QAAQ,GAAG;EACxC,IAAI,OAAO,MAAM,YAAY,EAAE,SAAS,GAAG,OAAO;CACpD;CAEA,QAAQ,CADQ,GAAG,KAAK,SAAS,sCAAsC,CAC1D,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,KAAA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C,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,MAAM,MAAM,YAAY;GACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,4EAA4E;GACtG,OAAO,iBAAiB,KAAK,IAAI;EACnC;EAEA,MAAM,eAAe,CAErB;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,MAAM,YAAY;GACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,wEAAwE;GAClG,MAAM,YAAY,QAAQ,SAAS,KAAK,CAAC;GACzC,MAAM,UAAU,WAAW,sBAAsB;GACjD,MAAM,OAAO,SAAS,IAAI;GAC1B,MAAM,SAAS,MAAM,gBAAgB,KAAK,KAAK,QAAQ,SAAS;GAChE,MAAM,QAAQ,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ;GAChE,MAAM,SAAS,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;GACnE,OAAO;IACL,UAAU,UAAU;IACpB;IACA,QAAQ,KAAK,UAAU;KAAE,QAAQ,KAAK;KAAQ;KAAQ;IAAU,CAAC;GACnE;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"webarena-verified.js","names":[],"sources":["../../src/benchmarks/webarena-verified.ts"],"sourcesContent":["/**\n * WebArena-Verified adapter (ServiceNow/webarena-verified).\n *\n * Worker artifact = a WebArena-Verified run output directory, not final chat text.\n * Judge = the official `webarena_verified eval-tasks` evaluator over that output\n * directory. The adapter refuses to score a plain answer so we do not turn a DOM\n * benchmark into a fake text benchmark.\n */\n\nimport { access, readFile, stat } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport type { OutputAdapter } from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot, runVenvPython } from './_harness'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'webarena-verified.json')\nconst DATASET_REL = join('assets', 'dataset', 'webarena-verified.json')\n\ninterface WebArenaRow {\n task_id: number\n intent: string\n intent_template_id?: number\n sites?: string[]\n start_urls?: string[]\n eval?: unknown[]\n revision?: number\n}\n\ninterface WebArenaMeta {\n taskId: number\n intentTemplateId?: number\n sites: string[]\n startUrls: string[]\n revision?: number\n eval?: unknown[]\n}\n\nconst webarenaDir = (): string | undefined => process.env.WEBARENA_VERIFIED_DIR\n\nexport const webarenaOutputDirOutput: OutputAdapter<string> = {\n parse(events) {\n let text = ''\n for (const ev of events) {\n const d = (ev as { data?: Record<string, unknown> })?.data\n const t = d?.finalText ?? d?.text ?? d?.result\n if (typeof t === 'string' && t.length > 0) text = t\n }\n const fences = [...text.matchAll(/```(?:text|path)?\\s*\\n([\\s\\S]*?)```/g)]\n return (fences.at(-1)?.[1] ?? text).trim()\n },\n}\n\nasync function assertFile(path: string, label: string): Promise<void> {\n try {\n await access(path)\n } catch (err) {\n throw new Error(`WebArena-Verified: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nasync function assertDir(path: string, label: string): Promise<void> {\n try {\n const s = await stat(path)\n if (!s.isDirectory()) throw new Error('not a directory')\n } catch (err) {\n throw new Error(`WebArena-Verified: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nfunction rowToTask(row: WebArenaRow): BenchTask {\n const meta: WebArenaMeta = {\n taskId: row.task_id,\n intentTemplateId: row.intent_template_id,\n sites: row.sites ?? [],\n startUrls: row.start_urls ?? [],\n revision: row.revision,\n eval: row.eval,\n }\n return {\n id: String(row.task_id),\n payload: {\n prompt: [\n 'Run this WebArena-Verified browser task in the official environment.',\n `Goal: ${row.intent}`,\n row.start_urls?.length ? `Start URL templates: ${row.start_urls.join(', ')}` : undefined,\n row.sites?.length ? `Sites: ${row.sites.join(', ')}` : undefined,\n '',\n 'Return the path to the official WebArena-Verified run output directory for this task.',\n 'The judge expects that directory to contain the task response and network trace files.',\n ]\n .filter(Boolean)\n .join('\\n'),\n },\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): WebArenaMeta {\n const md = task.metadata\n if (!md || typeof md.taskId !== 'number') {\n throw new Error(`webarena-verified task ${task.id} missing metadata — loadAll did not populate it`)\n }\n return md as unknown as WebArenaMeta\n}\n\nfunction selectRows(rows: WebArenaRow[], opts: LoadOptions): BenchTask[] {\n let tasks = rows.map(rowToTask)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((task) => want.has(task.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n if (tasks.length === 0) throw new Error(`WebArena-Verified: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as WebArenaRow[]\n console.warn(`[webarena-verified] WEBARENA_VERIFIED_FIXTURES=1 — loading ${rows.length} adapter fixtures`)\n return selectRows(rows, opts)\n}\n\nasync function loadOfficialRows(dir: string, opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(join(dir, DATASET_REL), 'utf8')) as WebArenaRow[]\n return selectRows(rows, opts)\n}\n\nasync function runOfficialEval(root: string, taskId: number, outputDir: string): Promise<Record<string, unknown>> {\n const script = `\nimport json, os, subprocess, sys\nfrom pathlib import Path\n\nroot = Path(sys.argv[1])\ntask_id = sys.argv[2]\noutput_dir = Path(sys.argv[3])\nenv = os.environ.copy()\nenv[\"PYTHONPATH\"] = str(root / \"src\") + os.pathsep + env.get(\"PYTHONPATH\", \"\")\ncmd = [sys.executable, \"-m\", \"webarena_verified\", \"eval-tasks\", \"--task-ids\", task_id, \"--output-dir\", str(output_dir)]\nproc = subprocess.run(cmd, cwd=root, env=env, text=True, capture_output=True)\nif proc.returncode != 0:\n raise SystemExit((proc.stderr or proc.stdout or f\"exit {proc.returncode}\")[:2000])\nresult_path = output_dir / task_id / \"eval_result.json\"\nif not result_path.exists():\n raise SystemExit(f\"official evaluator did not write {result_path}\")\nprint(json.dumps(json.loads(result_path.read_text())))\n`\n const stdout = await runVenvPython(script, [root, String(taskId), outputDir], 0)\n return JSON.parse(stdout.trim().split('\\n').at(-1) ?? '{}') as Record<string, unknown>\n}\n\nexport function createWebArenaVerifiedAdapter(): RuntimeBenchmark {\n const fixturesMode = process.env.WEBARENA_VERIFIED_FIXTURES === '1'\n\n return runtimeBenchmark({\n id: 'webarena-verified',\n\n async loadAll(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const dir = webarenaDir()\n if (!dir) throw new Error('WEBARENA_VERIFIED_DIR is required to load official WebArena-Verified tasks')\n return loadOfficialRows(dir, opts)\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n const dir = webarenaDir()\n if (!dir) throw new Error('WEBARENA_VERIFIED_DIR is required to judge WebArena-Verified artifacts')\n const outputDir = resolve(artifact.trim())\n await assertDir(outputDir, 'run output directory')\n const meta = readMeta(task)\n const report = await runOfficialEval(dir, meta.taskId, outputDir)\n const score = typeof report.score === 'number' ? report.score : 0\n const status = typeof report.status === 'string' ? report.status : 'unknown'\n const raw = { taskId: meta.taskId, status, outputDir }\n return {\n passed: score === 1,\n score,\n notes: JSON.stringify(raw),\n raw,\n }\n },\n\n runtime: {\n output: webarenaOutputDirOutput,\n\n async preflight() {\n if (fixturesMode) return\n const dir = webarenaDir()\n if (!dir) {\n throw new Error(\n 'WEBARENA_VERIFIED_DIR is required. Fix: clone https://github.com/ServiceNow/webarena-verified, install its deps in bench/.venv, and set WEBARENA_VERIFIED_DIR=/path/to/webarena-verified.',\n )\n }\n await assertFile(join(dir, DATASET_REL), 'official dataset')\n await assertFile(join(dir, 'src', 'webarena_verified', '__main__.py'), 'official CLI module')\n await runVenvPython(\n 'import sys; sys.path.insert(0, sys.argv[1]); import webarena_verified; print(\"ok\")',\n [join(dir, 'src')],\n )\n },\n\n async goldArtifact() {\n return undefined\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;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 +1,4 @@
|
|
|
1
|
+
import { runtimeBenchmark } from "./benchmarks/types.js";
|
|
1
2
|
import { t as runBenchRouterTurn } from "./router-turn-DNbQ_GjQ.js";
|
|
2
3
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
4
|
import { join } from "node:path";
|
|
@@ -219,24 +220,9 @@ function createCadBenchAdapter() {
|
|
|
219
220
|
});
|
|
220
221
|
return cache;
|
|
221
222
|
}
|
|
222
|
-
return {
|
|
223
|
-
|
|
224
|
-
async
|
|
225
|
-
const { execFile } = await import("node:child_process");
|
|
226
|
-
const { promisify } = await import("node:util");
|
|
227
|
-
const exec = promisify(execFile);
|
|
228
|
-
try {
|
|
229
|
-
await exec("xvfb-run", [
|
|
230
|
-
"-a",
|
|
231
|
-
"blender",
|
|
232
|
-
"--version"
|
|
233
|
-
], { timeout: 3e4 });
|
|
234
|
-
} catch (err) {
|
|
235
|
-
throw new Error(`cadbench preflight failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}\nFix: install Blender + Xvfb (sudo apt-get install -y blender xvfb). The judge runs \`xvfb-run -a blender --background --python\`.`);
|
|
236
|
-
}
|
|
237
|
-
await load();
|
|
238
|
-
},
|
|
239
|
-
async loadTasks(opts = {}) {
|
|
223
|
+
return runtimeBenchmark({
|
|
224
|
+
id: "cadbench",
|
|
225
|
+
async loadAll(opts = {}) {
|
|
240
226
|
let rows = await load();
|
|
241
227
|
if (opts.ids) rows = rows.filter((r) => opts.ids.includes(r.id));
|
|
242
228
|
const t = process.env.CADBENCH_TYPE;
|
|
@@ -244,39 +230,60 @@ function createCadBenchAdapter() {
|
|
|
244
230
|
if (opts.limit != null) rows = rows.slice(0, opts.limit);
|
|
245
231
|
return rows.map((r) => ({
|
|
246
232
|
id: r.id,
|
|
247
|
-
prompt: r.instruction,
|
|
233
|
+
payload: { prompt: r.instruction },
|
|
248
234
|
metadata: r.meta
|
|
249
235
|
}));
|
|
250
236
|
},
|
|
251
|
-
async
|
|
252
|
-
async judge(task, artifact) {
|
|
237
|
+
async evaluate(task, artifact) {
|
|
253
238
|
const criteria = task.metadata.criteria ?? [];
|
|
254
239
|
if (!artifact.trim()) return {
|
|
255
|
-
|
|
240
|
+
passed: false,
|
|
256
241
|
score: 0,
|
|
257
|
-
|
|
242
|
+
notes: "empty artifact",
|
|
243
|
+
raw: {}
|
|
258
244
|
};
|
|
259
245
|
if (criteria.length === 0) return {
|
|
260
|
-
|
|
246
|
+
passed: false,
|
|
261
247
|
score: 0,
|
|
262
|
-
|
|
248
|
+
notes: "task has no criteria",
|
|
249
|
+
raw: {}
|
|
263
250
|
};
|
|
264
251
|
const r = await renderBpy(artifact, { views: 4 });
|
|
265
252
|
if (!r.built) return {
|
|
266
|
-
|
|
253
|
+
passed: false,
|
|
267
254
|
score: 0,
|
|
268
|
-
|
|
255
|
+
notes: `did not build/render: ${r.error ?? "no mesh"}`,
|
|
256
|
+
raw: {}
|
|
269
257
|
};
|
|
270
|
-
const { passed, note } = await judgeCriteria(task.prompt, artifact, criteria, r.renders);
|
|
258
|
+
const { passed, note } = await judgeCriteria(task.payload.prompt, artifact, criteria, r.renders);
|
|
271
259
|
const score = passed.filter(Boolean).length / criteria.length;
|
|
272
260
|
return {
|
|
273
|
-
|
|
261
|
+
passed: score === 1,
|
|
274
262
|
score,
|
|
275
|
-
|
|
263
|
+
notes: note,
|
|
264
|
+
raw: {}
|
|
276
265
|
};
|
|
266
|
+
},
|
|
267
|
+
runtime: {
|
|
268
|
+
async preflight() {
|
|
269
|
+
const { execFile } = await import("node:child_process");
|
|
270
|
+
const { promisify } = await import("node:util");
|
|
271
|
+
const exec = promisify(execFile);
|
|
272
|
+
try {
|
|
273
|
+
await exec("xvfb-run", [
|
|
274
|
+
"-a",
|
|
275
|
+
"blender",
|
|
276
|
+
"--version"
|
|
277
|
+
], { timeout: 3e4 });
|
|
278
|
+
} catch (err) {
|
|
279
|
+
throw new Error(`cadbench preflight failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}\nFix: install Blender + Xvfb (sudo apt-get install -y blender xvfb). The judge runs \`xvfb-run -a blender --background --python\`.`);
|
|
280
|
+
}
|
|
281
|
+
await load();
|
|
282
|
+
},
|
|
283
|
+
async goldArtifact() {}
|
|
277
284
|
}
|
|
278
|
-
};
|
|
285
|
+
});
|
|
279
286
|
}
|
|
280
287
|
export { createCadBenchAdapter as t };
|
|
281
288
|
|
|
282
|
-
//# sourceMappingURL=cadbench-
|
|
289
|
+
//# sourceMappingURL=cadbench-htzAmMaI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cadbench-htzAmMaI.js","names":[],"sources":["../src/worker-blender.ts","../src/benchmarks/cadbench.ts"],"sourcesContent":["/**\n * BlenderLLM / CADBench worker. The deliverable for a CADBench task is a Blender\n * `bpy` Python script that builds the described 3D model. We author it via the\n * router, execute it headless in Blender (Cycles CPU, no GPU), auto-frame the\n * produced geometry, and render N standardized views — the images the CADBench\n * criteria judge scores. The authoring directive is the GEPA-optimizable surface.\n *\n * Requires `blender` + `xvfb-run` on PATH (apt blender 4.x). No GPU: Cycles CPU\n * with denoising off (the apt build ships without OpenImageDenoise).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { Span } from '@tangle-network/agent-eval'\nimport type { BenchTask } from './benchmarks/types'\nimport { DEFAULT_BLENDER_DIRECTIVE } from './directives'\nimport { runRefineLoop } from './refine-loop'\nimport { runBenchRouterTurn } from './router-turn'\n\nconst execFileAsync = promisify(execFile)\n\nasync function runLocal(cmd: string, args: string[], cwd: string, timeoutMs = 180_000): Promise<{ code: number; stdout: string; stderr: string }> {\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, maxBuffer: 1 << 26, timeout: timeoutMs })\n return { code: 0, stdout, stderr }\n } catch (err) {\n const e = err as { code?: number; stdout?: string; stderr?: string; message?: string }\n return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '', stderr: e.stderr ?? e.message ?? String(err) }\n }\n}\n\n\n/** Strip markdown fences so we keep just the Python. */\nfunction extractPy(text: string): string {\n const fence = /```(?:python|py)?\\s*\\n([\\s\\S]*?)```/i.exec(text)\n return (fence ? fence[1] : text).trim()\n}\n\n/**\n * The standardized Blender runner (written to a temp file per run). It clears the\n * scene, executes the agent's bpy script, auto-frames the produced meshes, sets\n * up neutral lighting, and renders N azimuth views with Cycles CPU.\n */\nconst RUNNER_PY = `\nimport bpy, sys, math, mathutils, traceback, os\nagent_script, outdir, nviews = sys.argv[-3], sys.argv[-2], int(sys.argv[-1])\nbpy.ops.object.select_all(action='SELECT'); bpy.ops.object.delete()\nok=True\ntry:\n g={'bpy':bpy,'math':math,'mathutils':mathutils,'__name__':'__main__'}\n exec(compile(open(agent_script).read(), agent_script, 'exec'), g)\nexcept Exception as e:\n traceback.print_exc(); print('AGENT_SCRIPT_ERROR:'+repr(e)); ok=False\nmeshes=[o for o in bpy.context.scene.objects if o.type=='MESH']\nif not meshes:\n print('NO_MESH'); sys.exit(0 if ok else 3)\nmn=[1e18]*3; mx=[-1e18]*3\nfor o in meshes:\n for c in o.bound_box:\n w=o.matrix_world @ mathutils.Vector(c)\n for i in range(3): mn[i]=min(mn[i],w[i]); mx[i]=max(mx[i],w[i])\ncenter=mathutils.Vector(((mn[0]+mx[0])/2,(mn[1]+mx[1])/2,(mn[2]+mx[2])/2))\nsize=max(mx[i]-mn[i] for i in range(3)) or 1.0\n# standardize: drop any agent-added cameras/lights\nfor o in list(bpy.context.scene.objects):\n if o.type in ('CAMERA','LIGHT'): bpy.data.objects.remove(o, do_unlink=True)\nw=bpy.context.scene.world or bpy.data.worlds.new('W'); bpy.context.scene.world=w\nw.use_nodes=True\ntry: w.node_tree.nodes['Background'].inputs[1].default_value=0.6\nexcept Exception: pass\nbpy.ops.object.light_add(type='SUN'); sun=bpy.context.object; sun.data.energy=4.0; sun.rotation_euler=mathutils.Euler((0.6,0.2,0.4))\nbpy.ops.object.camera_add(); cam=bpy.context.object; bpy.context.scene.camera=cam\nsc=bpy.context.scene\nsc.render.engine='CYCLES'; sc.cycles.samples=20; sc.cycles.device='CPU'; sc.cycles.use_denoising=False\nsc.render.resolution_x=640; sc.render.resolution_y=640; sc.render.film_transparent=False\ndist=size*2.4\nel=math.radians(58)\nfor v in range(nviews):\n az=math.radians(40 + v*360.0/nviews)\n cam.location=center+mathutils.Vector((math.cos(az)*math.sin(el), math.sin(az)*math.sin(el), math.cos(el)))*dist\n d=(center-cam.location); cam.rotation_euler=d.to_track_quat('-Z','Y').to_euler()\n sc.render.filepath=os.path.join(outdir, 'view_%d.png'%v); bpy.ops.render.render(write_still=True)\nprint('RENDER_DONE')\n`.trim()\n\n/** Execute a bpy script headless + render N standardized views — no authoring.\n * Used by the CADBench judge to render an artifact before vision-scoring it. */\nexport async function renderBpy(script: string, opts: { views?: number } = {}): Promise<{ built: boolean; renders: string[]; error?: string }> {\n const views = Math.max(1, opts.views ?? 4)\n const dir = await mkdtemp(join(tmpdir(), 'blender-judge-'))\n const runnerPath = join(dir, 'runner.py')\n const scriptPath = join(dir, 'model.py')\n try {\n await writeFile(runnerPath, RUNNER_PY)\n await writeFile(scriptPath, script)\n const run = await runLocal('xvfb-run', ['-a', 'blender', '--background', '--python', runnerPath, '--', scriptPath, dir, String(views)], dir)\n const out = `${run.stdout}\\n${run.stderr}`\n const built = /RENDER_DONE/.test(out)\n if (!built) return { built: false, renders: [], error: (/(AGENT_SCRIPT_ERROR:.*|NO_MESH)/.exec(out)?.[0] ?? out.trim().slice(-400)) }\n const renders: string[] = []\n for (let v = 0; v < views; v++) {\n const buf = await readFile(join(dir, `view_${v}.png`)).catch(() => undefined)\n if (buf) renders.push(`data:image/png;base64,${buf.toString('base64')}`)\n }\n return { built: renders.length > 0, renders }\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {})\n }\n}\n\ninterface BlenderLocalConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n rounds?: number\n /** N standardized views to render (CADBench uses 4). Default 4. */\n views?: number\n /** The bpy authoring directive — the GEPA-optimizable surface. */\n directive?: string\n}\n\ninterface BlenderShot {\n /** The bpy script the agent wrote — the artifact. */\n artifact: string\n /** Rendered view PNGs as data URIs (the images the criteria judge scores). */\n renders: string[]\n trace: Span[]\n usage: { input: number; output: number }\n ok: boolean\n /** True if the script executed and produced at least one mesh. */\n built: boolean\n detail?: string\n}\n","/**\n * CADBench / BlenderLLM adapter (FreedomIntelligence/CADBench, arXiv:2412.14203).\n * Task = NL instruction → a Blender `bpy` script. Score = the paper's criteria\n * eval: render the produced model to standardized views, then a vision judge\n * (GPT-4o-class) marks each per-task criterion bullet pass/fail against the\n * rendered images + the script text. score = fraction of criteria satisfied.\n *\n * Data: the published dataset's `criteria` flattened to a bullet list (700 tasks,\n * 500 Simulative + 200 Wild). Point CADBENCH_PATH at the cleaned JSONL\n * ({id,name,instruction,type,criteria:string[]} per line). Judge creds from\n * TANGLE_API_KEY / ROUTER_BASE / JUDGE_MODEL (default gpt-4o).\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\nimport { renderBpy } from '../worker-blender'\nimport { runBenchRouterTurn } from '../router-turn'\n\ninterface CadBenchMeta {\n name: string\n type: string\n criteria: string[]\n}\n\nfunction must(name: string): string {\n const v = process.env[name]\n if (!v) throw new Error(`env ${name} is required for the CADBench judge`)\n return v\n}\n\n/** One batched vision call: rendered views + the bpy script + the numbered\n * criteria → a JSON array of booleans (true = satisfied). Faithful to the\n * paper's combined image+script evaluation. Throws on transport failure (never\n * a silent zero); a parse miss falls back to \"all fail\" with a note. */\nasync function judgeCriteria(\n instruction: string,\n script: string,\n criteria: string[],\n renders: string[],\n): Promise<{ passed: boolean[]; note: string }> {\n const base = (process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1').replace(/\\/$/, '')\n const key = must('TANGLE_API_KEY')\n const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'\n const numbered = criteria.map((c, i) => `${i + 1}. ${c}`).join('\\n')\n const text =\n `You are strictly grading a 3D model that was built by a Blender bpy script for this instruction:\\n\"${instruction}\"\\n\\n` +\n `Below are ${renders.length} rendered views of the produced model, and the script that built it. ` +\n `For EACH numbered criterion, decide whether it is satisfied (judge geometry/shape/proportion/structure from the IMAGES; judge color/size/material reasonableness from the SCRIPT where the images are ambiguous). ` +\n `Return ONLY a JSON array of exactly ${criteria.length} booleans (true=satisfied, false=not), in order, no prose.\\n\\nCRITERIA:\\n${numbered}\\n\\nSCRIPT:\\n\\`\\`\\`python\\n${script.slice(0, 6000)}\\n\\`\\`\\``\n const content: unknown[] = [{ type: 'text', text }]\n for (const url of renders) content.push({ type: 'image_url', image_url: { url } })\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: base,\n routerKey: key,\n profile: {\n name: 'cadbench-vision-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: model,\n maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500),\n metadata: { temperature: 0 },\n },\n },\n },\n { messages: [{ role: 'user', content }] },\n )\n const raw = turn.finalText\n const m = /\\[\\s*(?:true|false)[\\s\\S]*?\\]/i.exec(raw)\n if (!m) return { passed: criteria.map(() => false), note: `judge returned no parseable verdict: ${raw.slice(0, 80)}` }\n let arr: unknown\n try {\n arr = JSON.parse(m[0].toLowerCase())\n } catch {\n return { passed: criteria.map(() => false), note: 'judge verdict not valid JSON' }\n }\n const bools = Array.isArray(arr) ? arr.map((x) => x === true) : []\n // Pad/truncate to criteria length (a short array scores the missing as fail).\n const passed = criteria.map((_, i) => bools[i] === true)\n return { passed, note: `${passed.filter(Boolean).length}/${criteria.length} criteria` }\n}\n\nexport function createCadBenchAdapter(): RuntimeBenchmark {\n let cache: Array<{ id: string; instruction: string; meta: CadBenchMeta }> | null = null\n\n async function load(): Promise<typeof cache & object> {\n if (cache) return cache\n const path = process.env.CADBENCH_PATH\n if (!path) throw new Error('CADBENCH_PATH must point at the cleaned CADBench JSONL ({id,instruction,type,criteria:[]} per line)')\n const text = await readFile(path, 'utf8')\n cache = text\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => {\n const r = JSON.parse(l) as { id: string; name?: string; instruction: string; type?: string; criteria: string[] }\n return { id: r.id, instruction: r.instruction, meta: { name: r.name ?? '', type: r.type ?? '', criteria: r.criteria } }\n })\n return cache\n }\n\n return runtimeBenchmark({\n id: 'cadbench',\n\n async loadAll(opts: LoadOptions = {}) {\n let rows = await load()\n if (opts.ids) rows = rows.filter((r) => opts.ids!.includes(r.id))\n // TYPE filter (Simulative|Wild) via env, applied before limit.\n const t = process.env.CADBENCH_TYPE\n if (t) rows = rows.filter((r) => r.meta.type.toLowerCase() === t.toLowerCase())\n if (opts.limit != null) rows = rows.slice(0, opts.limit)\n return rows.map((r): BenchTask => ({ id: r.id, payload: { prompt: r.instruction }, metadata: r.meta as unknown as Record<string, unknown> }))\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n const meta = task.metadata as unknown as CadBenchMeta\n const criteria = meta.criteria ?? []\n if (!artifact.trim()) return { passed: false, score: 0, notes: 'empty artifact', raw: {} }\n if (criteria.length === 0) return { passed: false, score: 0, notes: 'task has no criteria', raw: {} }\n const r = await renderBpy(artifact, { views: 4 })\n if (!r.built) return { passed: false, score: 0, notes: `did not build/render: ${r.error ?? 'no mesh'}`, raw: {} }\n const { passed, note } = await judgeCriteria(task.payload.prompt, artifact, criteria, r.renders)\n const score = passed.filter(Boolean).length / criteria.length\n return { passed: score === 1, score, notes: note, raw: {} }\n },\n\n runtime: {\n async preflight() {\n const { execFile } = await import('node:child_process')\n const { promisify } = await import('node:util')\n const exec = promisify(execFile)\n try {\n await exec('xvfb-run', ['-a', 'blender', '--version'], { timeout: 30_000 })\n } catch (err) {\n throw new Error(\n `cadbench preflight failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}\\n` +\n `Fix: install Blender + Xvfb (sudo apt-get install -y blender xvfb). The judge runs \\`xvfb-run -a blender --background --python\\`.`,\n )\n }\n await load()\n },\n\n async goldArtifact() {\n return undefined // no reference bpy script ships with the benchmark\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,MAAM,gBAAgB,UAAU,QAAQ;AAExC,eAAe,SAAS,KAAa,MAAgB,KAAa,YAAY,MAAoE;CAChJ,IAAI;EACF,MAAM,EAAE,QAAQ,WAAW,MAAM,cAAc,KAAK,MAAM;GAAE;GAAK,WAAW,KAAK;GAAI,SAAS;EAAU,CAAC;EACzG,OAAO;GAAE,MAAM;GAAG;GAAQ;EAAO;CACnC,SAAS,KAAK;EACZ,MAAM,IAAI;EACV,OAAO;GAAE,MAAM,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO;GAAG,QAAQ,EAAE,UAAU;GAAI,QAAQ,EAAE,UAAU,EAAE,WAAW,OAAO,GAAG;EAAE;CAC/H;AACF;;;;;;AAcA,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwChB,KAAK;;;AAIP,eAAsB,UAAU,QAAgB,OAA2B,CAAC,GAAmE;CAC7I,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,SAAS,CAAC;CACzC,MAAM,MAAM,MAAM,QAAQ,KAAK,OAAO,GAAG,gBAAgB,CAAC;CAC1D,MAAM,aAAa,KAAK,KAAK,WAAW;CACxC,MAAM,aAAa,KAAK,KAAK,UAAU;CACvC,IAAI;EACF,MAAM,UAAU,YAAY,SAAS;EACrC,MAAM,UAAU,YAAY,MAAM;EAClC,MAAM,MAAM,MAAM,SAAS,YAAY;GAAC;GAAM;GAAW;GAAgB;GAAY;GAAY;GAAM;GAAY;GAAK,OAAO,KAAK;EAAC,GAAG,GAAG;EAC3I,MAAM,MAAM,GAAG,IAAI,OAAO,IAAI,IAAI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AAQ,OAAO,OAAO,OAAO,CAAC,CAAC,SAAS,SAAS;GACvD,OAAO;IAAE,QAAQ,UAAU;IAAG;IAAO,OAAO;IAAM,KAAK,CAAC;GAAE;EAC5D;EAEA,SAAS;GACP,MAAM,YAAY;IAChB,MAAM,EAAE,aAAa,MAAM,OAAO;IAClC,MAAM,EAAE,cAAc,MAAM,OAAO;IACnC,MAAM,OAAO,UAAU,QAAQ;IAC/B,IAAI;KACF,MAAM,KAAK,YAAY;MAAC;MAAM;MAAW;KAAW,GAAG,EAAE,SAAS,IAAO,CAAC;IAC5E,SAAS,KAAK;KACZ,MAAM,IAAI,MACR,+BAA+B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAA,CAAG,MAAM,GAAG,GAAG,EAAE,oIAEjG;IACF;IACA,MAAM,KAAK;GACb;GAEA,MAAM,eAAe,CAErB;EACF;CACF,CAAC;AACH"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { runtimeBenchmark } from "./benchmarks/types.js";
|
|
1
2
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { execFile } from "node:child_process";
|
|
@@ -31,7 +32,7 @@ const CGB_DIR = process.env.CADGENBENCH_DIR ?? "/tmp/cadgenbench";
|
|
|
31
32
|
* The official task set (private GT, server-side graded) isn't released yet, so
|
|
32
33
|
* tasks here are seeded from the repo's dimension-named geometry fixtures (real
|
|
33
34
|
* GT STEPs scored by the real scorer). When CADGENBENCH_DATA_DIR is set, swap
|
|
34
|
-
*
|
|
35
|
+
* loadAll to read the published fixtures' description.yaml + ground_truth.step.
|
|
35
36
|
*
|
|
36
37
|
* Requires the CADGenBench venv (CADGENBENCH_VENV) + clone (CADGENBENCH_DIR) +
|
|
37
38
|
* xvfb (the scorer's alignment renders need a display).
|
|
@@ -79,16 +80,9 @@ function fixtureTasks() {
|
|
|
79
80
|
];
|
|
80
81
|
}
|
|
81
82
|
function createCadGenBenchAdapter() {
|
|
82
|
-
return {
|
|
83
|
-
|
|
84
|
-
async
|
|
85
|
-
const r = await execFileAsync(CGB_VENV_PY, ["-c", "import cadgenbench.eval.evaluate, build123d, trimesh, manifold3d; print(\"ok\")"], { timeout: 6e4 }).catch((e) => ({
|
|
86
|
-
stdout: "",
|
|
87
|
-
stderr: e instanceof Error ? e.message : String(e)
|
|
88
|
-
}));
|
|
89
|
-
if (!/ok/.test(r.stdout)) throw new Error(`cadgenbench preflight failed (venv=${CGB_VENV_PY}): ${r.stderr.slice(0, 200)}\nFix: git clone https://github.com/huggingface/cadgenbench ${CGB_DIR}; python3 -m venv $CADGENBENCH_VENV; $CADGENBENCH_VENV/bin/pip install -e ${CGB_DIR}`);
|
|
90
|
-
},
|
|
91
|
-
async loadTasks(opts = {}) {
|
|
83
|
+
return runtimeBenchmark({
|
|
84
|
+
id: "cadgenbench",
|
|
85
|
+
async loadAll(opts = {}) {
|
|
92
86
|
let tasks = fixtureTasks();
|
|
93
87
|
const hard = process.env.CGB_HARD_DIR;
|
|
94
88
|
if (hard) {
|
|
@@ -103,17 +97,17 @@ function createCadGenBenchAdapter() {
|
|
|
103
97
|
});
|
|
104
98
|
return tasks.map((t) => ({
|
|
105
99
|
id: t.id,
|
|
106
|
-
prompt: t.prompt,
|
|
100
|
+
payload: { prompt: t.prompt },
|
|
107
101
|
metadata: meta(t.gtStep)
|
|
108
102
|
}));
|
|
109
103
|
},
|
|
110
|
-
async
|
|
111
|
-
async judge(task, artifact) {
|
|
104
|
+
async evaluate(task, artifact) {
|
|
112
105
|
const { gtStep, resolveThreshold } = task.metadata;
|
|
113
106
|
if (!artifact.includes("ISO-10303-21")) return {
|
|
114
|
-
|
|
107
|
+
passed: false,
|
|
115
108
|
score: 0,
|
|
116
|
-
|
|
109
|
+
notes: "artifact is not a STEP file",
|
|
110
|
+
raw: {}
|
|
117
111
|
};
|
|
118
112
|
const dir = await mkdtemp(join(tmpdir(), "cgb-judge-"));
|
|
119
113
|
const cand = join(dir, "candidate.step");
|
|
@@ -136,16 +130,18 @@ function createCadGenBenchAdapter() {
|
|
|
136
130
|
}));
|
|
137
131
|
const m = /CGB_SCORE (\{.*\})/.exec(r.stdout);
|
|
138
132
|
if (!m) return {
|
|
139
|
-
|
|
133
|
+
passed: false,
|
|
140
134
|
score: 0,
|
|
141
|
-
|
|
135
|
+
notes: `scorer produced no verdict: ${(r.stderr || r.stdout).slice(0, 160)}`,
|
|
136
|
+
raw: {}
|
|
142
137
|
};
|
|
143
138
|
const v = JSON.parse(m[1]);
|
|
144
139
|
const score = typeof v.cad_score === "number" ? v.cad_score : 0;
|
|
145
140
|
return {
|
|
146
|
-
|
|
141
|
+
passed: score >= resolveThreshold,
|
|
147
142
|
score,
|
|
148
|
-
|
|
143
|
+
notes: `cad_score=${score.toFixed(3)} status=${v.status}${v.error ? ` (${v.error})` : ""}`,
|
|
144
|
+
raw: {}
|
|
149
145
|
};
|
|
150
146
|
} finally {
|
|
151
147
|
await rm(dir, {
|
|
@@ -153,9 +149,19 @@ function createCadGenBenchAdapter() {
|
|
|
153
149
|
force: true
|
|
154
150
|
}).catch(() => {});
|
|
155
151
|
}
|
|
152
|
+
},
|
|
153
|
+
runtime: {
|
|
154
|
+
async preflight() {
|
|
155
|
+
const r = await execFileAsync(CGB_VENV_PY, ["-c", "import cadgenbench.eval.evaluate, build123d, trimesh, manifold3d; print(\"ok\")"], { timeout: 6e4 }).catch((e) => ({
|
|
156
|
+
stdout: "",
|
|
157
|
+
stderr: e instanceof Error ? e.message : String(e)
|
|
158
|
+
}));
|
|
159
|
+
if (!/ok/.test(r.stdout)) throw new Error(`cadgenbench preflight failed (venv=${CGB_VENV_PY}): ${r.stderr.slice(0, 200)}\nFix: git clone https://github.com/huggingface/cadgenbench ${CGB_DIR}; python3 -m venv $CADGENBENCH_VENV; $CADGENBENCH_VENV/bin/pip install -e ${CGB_DIR}`);
|
|
160
|
+
},
|
|
161
|
+
async goldArtifact() {}
|
|
156
162
|
}
|
|
157
|
-
};
|
|
163
|
+
});
|
|
158
164
|
}
|
|
159
165
|
export { createCadGenBenchAdapter as t };
|
|
160
166
|
|
|
161
|
-
//# sourceMappingURL=cadgenbench-
|
|
167
|
+
//# sourceMappingURL=cadgenbench-BLvEtnxU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cadgenbench-BLvEtnxU.js","names":[],"sources":["../src/worker-build123d.ts","../src/benchmarks/cadgenbench.ts"],"sourcesContent":["/**\n * CADGenBench worker. The deliverable is a STEP B-rep solid (output.step). We\n * author a build123d (Python on the OpenCascade kernel) script via the router,\n * execute it in the CADGenBench venv, and read back the produced output.step —\n * exactly the reference baseline's contract. The artifact returned IS the STEP\n * text, which the CADGenBench geometric scorer grades against the ground truth.\n *\n * The build123d authoring directive is the GEPA-optimizable surface; the\n * build123d API cheat sheet (shipped in the cadgenbench package) is appended as\n * fixed reference context. Requires the CADGenBench venv (CADGENBENCH_VENV) +\n * its clone (CADGENBENCH_DIR for the cheat sheet).\n */\n\nimport { execFile } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { Span } from '@tangle-network/agent-eval'\nimport type { BenchTask } from './benchmarks/types'\nimport { DEFAULT_BUILD123D_DIRECTIVE } from './directives'\nimport { runRefineLoop } from './refine-loop'\nimport { runBenchRouterTurn } from './router-turn'\n\nconst execFileAsync = promisify(execFile)\n\nexport const CGB_VENV_PY = process.env.CADGENBENCH_VENV ?? '/tmp/cgb-venv/bin/python'\nexport const CGB_DIR = process.env.CADGENBENCH_DIR ?? '/tmp/cadgenbench'\n\nasync function runLocal(cmd: string, args: string[], cwd: string, timeoutMs = 120_000): Promise<{ code: number; stdout: string; stderr: string }> {\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, maxBuffer: 1 << 26, timeout: timeoutMs })\n return { code: 0, stdout, stderr }\n } catch (err) {\n const e = err as { code?: number; stdout?: string; stderr?: string; message?: string }\n return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '', stderr: e.stderr ?? e.message ?? String(err) }\n }\n}\n\nfunction extractPy(text: string): string {\n const fence = /```(?:python|py)?\\s*\\n([\\s\\S]*?)```/i.exec(text)\n return (fence ? fence[1] : text).trim()\n}\n\nlet _cheat: string | null = null\nfunction cheatSheet(): string {\n if (_cheat != null) return _cheat\n const p = join(CGB_DIR, 'src/cadgenbench/baseline/build123d_cheat_sheet.md')\n _cheat = existsSync(p) ? readFileSync(p, 'utf8').slice(0, 12000) : ''\n return _cheat\n}\n\ninterface Build123dConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n rounds?: number\n /** The build123d authoring directive — the GEPA-optimizable surface. */\n directive?: string\n}\n\ninterface Build123dShot {\n /** The produced STEP text (the artifact the CADGenBench scorer grades). */\n artifact: string\n /** The Python source the agent wrote. */\n source: string\n trace: Span[]\n usage: { input: number; output: number }\n ok: boolean\n built: boolean\n detail?: string\n}\n","/**\n * CADGenBench adapter (huggingface/cadgenbench, Apache-2.0). Task = a part\n * description → a STEP B-rep solid (output.step). Score = the benchmark's OWN\n * deterministic geometric metric (cad_score): validity gate → PCA/ICP align to\n * the ground truth → point-cloud F1 + volume IoU + edge F1 + topology match.\n * NOT an LLM judge, NOT self-defined checks — the published CAD kernel decides.\n *\n * The official task set (private GT, server-side graded) isn't released yet, so\n * tasks here are seeded from the repo's dimension-named geometry fixtures (real\n * GT STEPs scored by the real scorer). When CADGENBENCH_DATA_DIR is set, swap\n * loadAll to read the published fixtures' description.yaml + ground_truth.step.\n *\n * Requires the CADGenBench venv (CADGENBENCH_VENV) + clone (CADGENBENCH_DIR) +\n * xvfb (the scorer's alignment renders need a display).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\nimport { CGB_DIR, CGB_VENV_PY } from '../worker-build123d'\n\nconst execFileAsync = promisify(execFile)\n\n/** Self-contained scorer wrapper (written to a temp file, run in the venv).\n * Scores a candidate STEP against a ground-truth STEP via the benchmark's own\n * evaluate_result, printing the cad_score line. */\nconst SCORE_PY = `\nimport sys, json, tempfile, shutil\nfrom pathlib import Path\nfrom cadgenbench.eval.evaluate import evaluate_result\ncand, gt = Path(sys.argv[1]), Path(sys.argv[2])\nwith tempfile.TemporaryDirectory() as rd, tempfile.TemporaryDirectory() as gd:\n rd, gd = Path(rd), Path(gd)\n (rd / 'result.json').write_text('{}')\n shutil.copy(gt, gd / 'ground_truth.step')\n try:\n evaluate_result(rd, gd, candidate_step=cand)\n d = json.loads((rd / 'result.json').read_text())\n print('CGB_SCORE ' + json.dumps({'cad_score': d.get('cad_score', 0.0), 'status': d.get('status', 'unknown')}))\n except Exception as e:\n print('CGB_SCORE ' + json.dumps({'cad_score': 0.0, 'status': 'error', 'error': str(e)[:200]}))\n`.trim()\n\ninterface CgbMeta {\n gtStep: string\n resolveThreshold: number\n}\n\n/** Fixture-seeded tasks (real GT STEPs from the repo, dim-named so the spec is\n * exact). Replaced by the published dataset when CADGENBENCH_DATA_DIR is set. */\nfunction fixtureTasks(): Array<{ id: string; prompt: string; gtStep: string }> {\n const g = join(CGB_DIR, 'tests/fixtures/geometry')\n return [\n { id: 'box-10x20x30', prompt: 'A rectangular solid box, 10 units wide (X), 20 units deep (Y), and 30 units tall (Z).', gtStep: join(g, 'box_10_20_30.step') },\n { id: 'cube-10', prompt: 'A cube, 10 units on every side.', gtStep: join(g, 'box_10_10_10.step') },\n { id: 'sphere-10', prompt: 'A sphere of radius 10 units, centered at the origin.', gtStep: join(g, 'sphere_10.step') },\n ]\n}\n\nexport function createCadGenBenchAdapter(): RuntimeBenchmark {\n return runtimeBenchmark({\n id: 'cadgenbench',\n\n async loadAll(opts: LoadOptions = {}) {\n // CGB_HARD_DIR (a dir with tasks.json = [{id,prompt,gtStep}]) overrides the\n // trivial fixture primitives with hard multi-feature parts (real headroom).\n let tasks = fixtureTasks()\n const hard = process.env.CGB_HARD_DIR\n if (hard) {\n const { readFile } = await import('node:fs/promises')\n tasks = JSON.parse(await readFile(join(hard, 'tasks.json'), 'utf8')) as Array<{ id: string; prompt: string; gtStep: string }>\n }\n if (opts.ids) tasks = tasks.filter((t) => opts.ids!.includes(t.id))\n if (opts.limit != null) tasks = tasks.slice(0, opts.limit)\n const meta = (gtStep: string): CgbMeta => ({ gtStep, resolveThreshold: Number(process.env.CGB_RESOLVE_THRESHOLD ?? 0.9) })\n return tasks.map((t): BenchTask => ({ id: t.id, payload: { prompt: t.prompt }, metadata: meta(t.gtStep) as unknown as Record<string, unknown> }))\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n const { gtStep, resolveThreshold } = task.metadata as unknown as CgbMeta\n if (!artifact.includes('ISO-10303-21')) return { passed: false, score: 0, notes: 'artifact is not a STEP file', raw: {} }\n const dir = await mkdtemp(join(tmpdir(), 'cgb-judge-'))\n const cand = join(dir, 'candidate.step')\n const scorer = join(dir, 'score.py')\n try {\n await writeFile(cand, artifact)\n await writeFile(scorer, SCORE_PY)\n // xvfb: the scorer's alignment step renders; needs a display.\n const r = await execFileAsync('xvfb-run', ['-a', CGB_VENV_PY, scorer, cand, gtStep], { maxBuffer: 1 << 26, timeout: 180_000 }).catch(\n (e) => ({ stdout: (e as { stdout?: string }).stdout ?? '', stderr: e instanceof Error ? e.message : String(e) }),\n )\n const m = /CGB_SCORE (\\{.*\\})/.exec(r.stdout)\n if (!m) return { passed: false, score: 0, notes: `scorer produced no verdict: ${(r.stderr || r.stdout).slice(0, 160)}`, raw: {} }\n const v = JSON.parse(m[1]) as { cad_score: number; status: string; error?: string }\n const score = typeof v.cad_score === 'number' ? v.cad_score : 0\n return { passed: score >= resolveThreshold, score, notes: `cad_score=${score.toFixed(3)} status=${v.status}${v.error ? ` (${v.error})` : ''}`, raw: {} }\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {})\n }\n },\n\n runtime: {\n async preflight() {\n const r = await execFileAsync(CGB_VENV_PY, ['-c', 'import cadgenbench.eval.evaluate, build123d, trimesh, manifold3d; print(\"ok\")'], { timeout: 60_000 }).catch(\n (e) => ({ stdout: '', stderr: e instanceof Error ? e.message : String(e) }),\n )\n if (!/ok/.test(r.stdout)) {\n throw new Error(\n `cadgenbench preflight failed (venv=${CGB_VENV_PY}): ${r.stderr.slice(0, 200)}\\n` +\n `Fix: git clone https://github.com/huggingface/cadgenbench ${CGB_DIR}; python3 -m venv $CADGENBENCH_VENV; $CADGENBENCH_VENV/bin/pip install -e ${CGB_DIR}`,\n )\n }\n },\n\n async goldArtifact() {\n return undefined // GT is a STEP file scored by the kernel, not a returnable artifact\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBsB,UAAU,QAAQ;AAExC,MAAa,cAAc,QAAQ,IAAI,oBAAoB;AAC3D,MAAa,UAAU,QAAQ,IAAI,mBAAmB;;;;;;;;;;;;;;;;;ACJtD,MAAM,gBAAgB,UAAU,QAAQ;;;;AAKxC,MAAM,WAAW;;;;;;;;;;;;;;;EAef,KAAK;;;AASP,SAAS,eAAsE;CAC7E,MAAM,IAAI,KAAK,SAAS,yBAAyB;CACjD,OAAO;EACL;GAAE,IAAI;GAAgB,QAAQ;GAAyF,QAAQ,KAAK,GAAG,mBAAmB;EAAE;EAC5J;GAAE,IAAI;GAAW,QAAQ;GAAmC,QAAQ,KAAK,GAAG,mBAAmB;EAAE;EACjG;GAAE,IAAI;GAAa,QAAQ;GAAwD,QAAQ,KAAK,GAAG,gBAAgB;EAAE;CACvH;AACF;AAEA,SAAgB,2BAA6C;CAC3D,OAAO,iBAAiB;EACtB,IAAI;EAEJ,MAAM,QAAQ,OAAoB,CAAC,GAAG;GAGpC,IAAI,QAAQ,a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