@tangle-network/agent-bench 0.14.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/README.md +2 -3
- package/dist/adapters.d.ts +2 -5
- package/dist/adapters.js +3 -4
- package/dist/benchmarks/_harness.d.ts +17 -20
- package/dist/benchmarks/_harness.js +4 -4
- package/dist/benchmarks/_harness.js.map +1 -1
- package/dist/benchmarks/aec-bench.d.ts +1 -4
- package/dist/benchmarks/aec-bench.js +1 -2
- package/dist/benchmarks/agentbench.d.ts +2 -5
- package/dist/benchmarks/agentbench.js +1 -2
- package/dist/benchmarks/appworld.d.ts +8 -10
- package/dist/benchmarks/appworld.js +23 -23
- package/dist/benchmarks/appworld.js.map +1 -1
- package/dist/benchmarks/bfcl.d.ts +2 -5
- package/dist/benchmarks/bfcl.js +1 -2
- package/dist/benchmarks/cad-design.d.ts +2 -5
- package/dist/benchmarks/cad-design.js +2 -3
- package/dist/benchmarks/cad-design.js.map +1 -1
- package/dist/benchmarks/cadbench.d.ts +1 -4
- package/dist/benchmarks/cadbench.js +1 -2
- package/dist/benchmarks/cadgenbench.d.ts +1 -4
- package/dist/benchmarks/cadgenbench.js +1 -2
- package/dist/benchmarks/commit0.d.ts +2 -5
- package/dist/benchmarks/commit0.js +1 -2
- package/dist/benchmarks/crag.d.ts +1 -4
- package/dist/benchmarks/crag.js +3 -3
- package/dist/benchmarks/crag.js.map +1 -1
- package/dist/benchmarks/dabstep.d.ts +2 -5
- package/dist/benchmarks/dabstep.js +2 -3
- package/dist/benchmarks/dabstep.js.map +1 -1
- package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
- package/dist/benchmarks/enterpriseops-gym.js +1 -2
- package/dist/benchmarks/finresearchbench.d.ts +2 -5
- package/dist/benchmarks/finresearchbench.js +2 -3
- package/dist/benchmarks/finsearchcomp.d.ts +2 -5
- package/dist/benchmarks/finsearchcomp.js +4 -4
- package/dist/benchmarks/finsearchcomp.js.map +1 -1
- package/dist/benchmarks/frames.d.ts +3 -19
- package/dist/benchmarks/frames.js +13 -39
- package/dist/benchmarks/frames.js.map +1 -1
- package/dist/benchmarks/hotpotqa.d.ts +4 -14
- package/dist/benchmarks/hotpotqa.js +12 -32
- package/dist/benchmarks/hotpotqa.js.map +1 -1
- package/dist/benchmarks/humaneval.d.ts +9 -12
- package/dist/benchmarks/humaneval.js +2 -3
- package/dist/benchmarks/humaneval.js.map +1 -1
- package/dist/benchmarks/mcad-bench.d.ts +13 -16
- package/dist/benchmarks/mcad-bench.js +2 -3
- package/dist/benchmarks/mcad-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
- package/dist/benchmarks/mcad-cq-bench.js +2 -3
- package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
- package/dist/benchmarks/mcad-cq-golds.js +1 -2
- package/dist/benchmarks/mcad-golds.d.ts +1 -4
- package/dist/benchmarks/mcad-golds.js +0 -1
- package/dist/benchmarks/mcad-tasks.d.ts +5 -8
- package/dist/benchmarks/mcad-tasks.js +7 -8
- package/dist/benchmarks/mcad-tasks.js.map +1 -1
- package/dist/benchmarks/mind2web.d.ts +3 -5
- package/dist/benchmarks/mind2web.js +2 -3
- package/dist/benchmarks/mind2web.js.map +1 -1
- package/dist/benchmarks/nomiracl.d.ts +1 -4
- package/dist/benchmarks/nomiracl.js +1 -2
- package/dist/benchmarks/open-rag-bench.d.ts +1 -4
- package/dist/benchmarks/open-rag-bench.js +3 -3
- package/dist/benchmarks/open-rag-bench.js.map +1 -1
- package/dist/benchmarks/programbench.d.ts +2 -5
- package/dist/benchmarks/programbench.js +1 -2
- package/dist/benchmarks/rag-shared.d.ts +30 -22
- package/dist/benchmarks/rag-shared.js +8 -2
- package/dist/benchmarks/rag-shared.js.map +1 -1
- package/dist/benchmarks/ragbench.d.ts +1 -4
- package/dist/benchmarks/ragbench.js +3 -3
- package/dist/benchmarks/ragbench.js.map +1 -1
- package/dist/benchmarks/simpleqa.d.ts +2 -18
- package/dist/benchmarks/simpleqa.js +5 -31
- package/dist/benchmarks/simpleqa.js.map +1 -1
- package/dist/benchmarks/swe-bench.d.ts +7 -10
- package/dist/benchmarks/swe-bench.js +4 -4
- package/dist/benchmarks/swe-bench.js.map +1 -1
- package/dist/benchmarks/t2-ragbench.d.ts +1 -4
- package/dist/benchmarks/t2-ragbench.js +3 -3
- package/dist/benchmarks/t2-ragbench.js.map +1 -1
- package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
- package/dist/benchmarks/tau-bench-shared.js +4 -4
- package/dist/benchmarks/tau-bench-shared.js.map +1 -1
- package/dist/benchmarks/tau2-bench.d.ts +2 -5
- package/dist/benchmarks/tau2-bench.js +1 -2
- package/dist/benchmarks/tau3-banking.d.ts +1 -4
- package/dist/benchmarks/tau3-banking.js +1 -2
- package/dist/benchmarks/terminal-bench.d.ts +1 -4
- package/dist/benchmarks/terminal-bench.js +4 -4
- package/dist/benchmarks/terminal-bench.js.map +1 -1
- package/dist/benchmarks/toollm.d.ts +2 -5
- package/dist/benchmarks/toollm.js +1 -2
- package/dist/benchmarks/trata-hedge.d.ts +1 -4
- package/dist/benchmarks/trata-hedge.js +2 -3
- package/dist/benchmarks/types.d.ts +6 -9
- package/dist/benchmarks/webarena-verified.d.ts +2 -5
- package/dist/benchmarks/webarena-verified.js +1 -2
- package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
- package/dist/cadbench-DhAndllg.js.map +1 -0
- package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
- package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
- package/dist/index.d.ts +8 -18
- package/dist/index.js +16 -24
- package/dist/index.js.map +1 -1
- package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
- package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
- package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
- package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
- package/package.json +10 -10
- package/pier_agents/tangle_candidate.py +15 -23
- package/scripts/run-package-tests.mjs +8 -15
- package/scripts/verify-packed-consumer.mjs +0 -1
- package/src/atom-mcp-e2e.mts +16 -4
- package/src/benchmarks/frames.ts +10 -44
- package/src/benchmarks/hotpotqa.ts +9 -29
- package/src/benchmarks/rag-shared.ts +12 -0
- package/src/benchmarks/simpleqa.ts +2 -36
- package/src/commit0-prereqs.sh +0 -0
- package/src/corpus-replay.mts +8 -8
- package/src/corpus-report.mts +21 -21
- package/src/corpus.test.mts +5 -5
- package/src/corpus.ts +16 -16
- package/src/directives.ts +0 -38
- package/src/examples/lean-verify.ts +1 -1
- package/src/gate.ts +8 -8
- package/src/generate-eval/certify.ts +2 -2
- package/src/index.ts +1 -0
- package/src/refine-loop.ts +5 -5
- package/src/resolve-client.ts +1 -1
- package/src/router-turn.ts +3 -11
- package/src/run-benchmarks.test.mts +0 -4
- package/src/run-pool.ts +1 -1
- package/src/runtime-hook-recorder.ts +2 -2
- package/src/search-bench/tasks.ts +1 -1
- package/src/selector.test.mts +13 -13
- package/src/selector.ts +19 -19
- package/src/swe-bench-env.ts +4 -12
- package/src/swe-jail.ts +5 -156
- package/src/swe-structural-judge-policy.ts +3 -3
- package/src/swe-structural-policy.ts +3 -3
- package/src/swe-structural-provenance.ts +4 -4
- package/src/terminal-compare.ts +10 -10
- package/src/worker-blender.ts +2 -106
- package/src/worker-build123d.ts +2 -81
- package/tb_agents/opencode_router_agent.py +1 -1
- package/dist/cadbench-BRF-59Mt.js.map +0 -1
- package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
- package/dist/router-turn-uTYO6KQ1.js.map +0 -1
- package/scripts/cadbench_prepare.py +0 -22
- package/scripts/cadgenbench_hard_parts.py +0 -48
- package/scripts/clbench_codebase_judge.py +0 -73
- package/scripts/render-gate-chart.mjs +0 -176
- package/scripts/trata-hedge/README.md +0 -57
- package/scripts/trata-hedge/run.sh +0 -64
- package/src/browser/adapters/bad-design-audit.ts +0 -153
- package/src/browser/adapters/bad-design-audit.verify.ts +0 -85
- package/src/browser/adapters/bad.ts +0 -165
- package/src/browser/agent-adapter.ts +0 -145
- package/src/browser/process-adapter.ts +0 -146
- package/src/browser/run-to-spans.ts +0 -105
- package/src/browser/run-to-spans.verify.ts +0 -89
- package/src/browser/ui-reviewer.ts +0 -200
- package/src/browser/ui-reviewer.verify.ts +0 -94
- package/src/browser/verify.ts +0 -96
- package/src/clbench-codebase-gate.mts +0 -314
- package/src/clbench-context-gate.mts +0 -341
- package/src/cloud-loop.mts +0 -156
- package/src/commit0-env-run.mts +0 -62
- package/src/commit0-env.ts +0 -172
- package/src/commit0-gate.mts +0 -558
- package/src/coordination-mcp-container-reach.mts +0 -182
- package/src/egress-probe.mts +0 -26
- package/src/fleet.mts +0 -143
- package/src/hev-structural.mts +0 -697
- package/src/humaneval-gate.mts +0 -220
- package/src/humaneval-repair-gate.mts +0 -182
- package/src/mbpp-structural.mts +0 -676
- package/src/mcp-mount-probe.mts +0 -139
- package/src/profile-coordinates.ts +0 -134
- package/src/profiles.ts +0 -128
- package/src/research-gate.mts +0 -132
- package/src/research-shot.ts +0 -144
- package/src/router-executor.ts +0 -51
- package/src/run-benchmarks-report.ts +0 -66
- package/src/sandbox-run.ts +0 -108
- package/src/search-bench/bridge.ts +0 -182
- package/src/search-bench/export.mts +0 -0
- package/src/search-bench/parametric-check.mts +0 -78
- package/src/search-bench/profiles.ts +0 -113
- package/src/search-bench/run.mts +0 -286
- package/src/search-bench/tasks-fresh.ts +0 -688
- package/src/skill-sandbox-smoke.mts +0 -101
- package/src/smoke-structural-rollout.mts +0 -415
- package/src/stats.mts +0 -90
- package/src/supervisor-arena.mts +0 -825
- package/src/swe-code-improve.mts +0 -306
- package/src/swe-emit-patch.mts +0 -125
- package/src/swe-improve.mts +0 -284
- package/src/swe-local-proof.mts +0 -265
- package/src/swe-repro-calibrate.mts +0 -451
- package/src/swe-stream.mts +0 -1561
- package/src/swe-structural.mts +0 -707
- package/src/tb-container-executor.mts +0 -266
- package/src/tb-container-executor.test.mts +0 -134
- package/src/tb-supervisor-sidecar.mts +0 -208
- package/src/trajectory-assemble.mjs +0 -130
- package/src/trata-gepa.mts +0 -381
- package/src/trata-hedge-solve.mts +0 -81
- package/src/worker-browser.ts +0 -115
- package/src/worker-cad.ts +0 -470
- package/src/workspace-loop.mts +0 -133
- package/tb_agents/opencode_refine_agent.py +0 -117
- package/tb_agents/opencode_supervisor_agent.py +0 -239
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"appworld.js","names":[],"sources":["../../src/benchmarks/appworld.ts"],"sourcesContent":["/**\n * AppWorld adapter (StonyBrookNLP/appworld). Worker artifact = the agent's\n * Python solution that calls the simulated apps' APIs (the same `apis.<app>.<fn>`\n * surface AppWorld exposes inside `world.execute(...)`), ending in\n * `apis.supervisor.complete_task()`. Judge = AppWorld's OWN programmatic\n * evaluator: a driver runs the solution in a fresh `AppWorld(task_id=...)` world,\n * then `world.evaluate().to_dict()` reports `success` (binary TGC), `num_tests`\n * (per-requirement total) and the `passes`/`failures` lists. Score =\n * passes / num_tests — GRADED; resolved = success. Fully deterministic — no LLM judge.\n *\n * loadTasks enumerates the real task suite via `load_task_ids(split)`\n * (train|dev|test_normal|test_challenge); the prompt = `world.task.instruction`.\n * The OutputAdapter is stream-only, so the worker emits its solution as a fenced\n * ```python block which the driver executes.\n *\n * Requires for a live run: the bench `.venv` with `appworld` installed + the\n * unpacked engine + downloaded data (`appworld install` ; `appworld download\n * data`). preflight + loadTasks + judge all fail loud with the exact step when the\n * engine/data is absent — never a fabricated score.\n */\n\nimport { spawn } from 'node:child_process'\nimport { join } from 'node:path'\nimport { createInterface } from 'node:readline'\nimport {\n collectAgentTurn,\n createExecutor,\n type OutputAdapter,\n streamAgentTurn,\n type ToolSpec,\n} from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot, preflightVenvImports, runVenvScriptStdin, venvPython } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst DRIVER = join(benchRoot, 'scripts', 'appworld_driver.py')\n\n/** AppWorld splits; only the test splits ship evaluation-only (no setup/solution). */\nconst DEFAULT_SPLIT = 'test_normal'\n\ninterface AppWorldMeta {\n taskId: string\n split: string\n}\n\n/** Worker solution code = the last fenced ```python block, else the raw text. */\nexport const appworldSolutionOutput: 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(/```(?:python|py)?\\s*\\n([\\s\\S]*?)```/g)]\n return (fences.at(-1)?.[1] ?? text).trim()\n },\n}\n\nconst WORKER_CONTRACT = [\n '',\n 'Solve this by writing Python that calls the available app APIs (the `apis.<app>.<function>(...)` surface). You may inspect API docs with `apis.api_docs.show_api_descriptions(app_name=...)` and `apis.api_docs.show_api_doc(app_name=..., api_name=...)`.',\n 'Authenticate where needed via the supervisor-provided credentials, perform every step the task requires, and FINISH with `apis.supervisor.complete_task()`.',\n 'Emit your COMPLETE solution as the LAST thing in your reply, in a single fenced ```python block. Nothing after the closing fence.',\n].join('\\n')\n\nfunction readMeta(task: BenchTask): AppWorldMeta {\n const md = task.metadata\n if (!md || typeof md.taskId !== 'string') {\n throw new Error(`appworld task ${task.id} missing metadata.taskId — loadTasks did not populate it`)\n }\n return md as unknown as AppWorldMeta\n}\n\n/**\n * Run the appworld engine driver with a subcommand; JSON on the LAST stdout line.\n * The solution code (evaluate) is piped to stdin via the shared stdin-aware runner —\n * execFile's `input` option is not honored async and hangs the driver's\n * sys.stdin.read() forever. `load` ignores stdin, so an empty pipe is harmless.\n */\nasync function driver(args: string[], input = ''): Promise<unknown> {\n let stdout: string\n try {\n stdout = await runVenvScriptStdin(DRIVER, args, input, { cwd: benchRoot })\n } catch (err) {\n const e = err as { message?: string }\n throw new Error(`appworld driver failed (${args.join(' ')}): ${(e.message || String(err)).slice(0, 1500)}`)\n }\n const last = stdout.trim().split('\\n').at(-1) ?? '{}'\n const parsed = JSON.parse(last) as { error?: string }\n if (parsed.error) throw new Error(`appworld driver error: ${parsed.error}`)\n return parsed\n}\n\nexport function createAppWorldAdapter(): BenchmarkAdapter {\n return {\n name: 'appworld',\n output: appworldSolutionOutput,\n\n async preflight() {\n await preflightVenvImports({\n modules: ['appworld'],\n requireDocker: false,\n fix:\n 'Fix: bench/.venv/bin/pip install appworld ; ' +\n 'bench/.venv/bin/appworld install ; bench/.venv/bin/appworld download data ' +\n '(unpacks the engine + downloads the simulated-app data/tasks). ' +\n 'Set APPWORLD_ROOT to the data root if not the default.',\n })\n },\n\n async loadTasks(opts: LoadOptions = {}): Promise<BenchTask[]> {\n const split = opts.split ?? DEFAULT_SPLIT\n const out = (await driver([\n 'load',\n '--split', split,\n ...(opts.limit !== undefined ? ['--limit', String(opts.limit)] : []),\n ...(opts.ids ? ['--ids', opts.ids.join(',')] : []),\n ])) as { tasks?: Array<{ task_id: string; instruction: string }> }\n const tasks = out.tasks ?? []\n if (tasks.length === 0) {\n throw new Error(`appworld loadTasks returned no tasks for split=${split} ${JSON.stringify(opts)}`)\n }\n return tasks.map(\n (t): BenchTask => ({\n id: t.task_id,\n split,\n prompt: t.instruction + WORKER_CONTRACT,\n metadata: { taskId: t.task_id, split } as unknown as Record<string, unknown>,\n }),\n )\n },\n\n async goldArtifact() {\n // Reference solution code ships only for train/dev, and only inside the\n // engine's decrypted `.bundle` (it is not a portable string this adapter can\n // emit across splits). The test splits are evaluation-only. So verify-judge\n // here requires a real solve on a train/dev task through the live engine\n // rather than a synthetic gold — returning a fabricated artifact would be a\n // fake. Returns undefined.\n return undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const out = (await driver(['evaluate', '--task-id', meta.taskId, '--split', meta.split], artifact)) as {\n success?: boolean\n passes?: number\n fails?: number\n num_tests?: number\n failure_names?: string[]\n }\n const passes = out.passes ?? 0\n const fails = out.fails ?? 0\n // num_tests is the evaluator's authoritative per-requirement count; prefer it\n // over passes+fails (which can disagree if a requirement neither passed nor\n // failed). Never default the total to a phantom denominator.\n const total = out.num_tests ?? passes + fails\n const score = total > 0 ? passes / total : 0\n // failure_names = WHICH sub-tests failed — the evidence a trace analyst\n // steers on. Carried in `detail` so it reaches the verdict's `notes`.\n const failures = Array.isArray(out.failure_names) ? out.failure_names : []\n return {\n resolved: out.success === true,\n score,\n detail: JSON.stringify({\n taskId: meta.taskId,\n success: out.success,\n passes,\n fails,\n total,\n ...(failures.length ? { failures } : {}),\n }),\n }\n },\n }\n}\n\n/**\n * AppWorld in its NATIVE protocol, run by OUR runtime: the worker is\n * Runtime's profile-bound `router-tools` executor with one tool —\n * `execute_python` — bound to a persistent AppWorld world session. The driver's\n * `session` subcommand is a dumb world shim (stdin JSONL: execute → output,\n * evaluate → verdict); every inference turn, the metering, and the typed\n * toolTrace the analyst steers on belong to the runtime, so runtime\n * improvements are what this benchmark measures.\n *\n * The one-shot codegen adapter above plays a strictly harder game (no execution\n * feedback — the first wrong API call kills the whole program at judge time),\n * which flatlines the score against ANY steering; this mode is what the\n * benchmark's published baselines use, where behavior can move sub-tests.\n *\n * Protocol: the round task string is `@appworld-react <taskId> <split>` on\n * line 1; everything after line 1 is the steer (an analyst correction, a push\n * directive) appended to the system prompt — so the existing arms steer this\n * worker without modification. The artifact is the episode evaluation JSON\n * (AppWorld's evaluator ran in-world); judge() parses it, never re-executes.\n */\n\nexport interface ReactResult {\n success?: boolean\n passes?: number\n fails?: number\n num_tests?: number\n failure_names?: string[]\n turns?: number\n input_tokens?: number\n output_tokens?: number\n cost_usd?: number\n transcript?: string\n}\n\ninterface ReactRuntimeUsage {\n input: number\n output: number\n costUsd?: number\n tokensKnown?: boolean\n usdKnown?: boolean\n}\n\n/** Preserve a completed scientific/task result even when one accounting dimension is incomplete.\n * Unknown usage fields stay absent; later comparison/reporting can refuse a cost claim without\n * discarding the episode's task evidence. */\nexport function appworldReactResultWithUsage(\n verdict: ReactResult,\n usage: ReactRuntimeUsage,\n turns: number | undefined,\n transcript: string,\n): ReactResult {\n return {\n ...verdict,\n ...(turns !== undefined ? { turns } : {}),\n ...(usage.tokensKnown === false\n ? {}\n : { input_tokens: usage.input, output_tokens: usage.output }),\n ...(usage.usdKnown === false || usage.costUsd === undefined\n ? {}\n : { cost_usd: usage.costUsd }),\n transcript,\n }\n}\n\n/** Emit only usage the Runtime actually knows. Catalog estimates never become observed dollars. */\nexport function appworldReactUsageEvent(\n result: ReactResult,\n model: string,\n): { type: 'llm_call'; data: Record<string, unknown> } | undefined {\n const hasTokens =\n typeof result.input_tokens === 'number' && typeof result.output_tokens === 'number'\n const hasCost = typeof result.cost_usd === 'number'\n if (!hasTokens && !hasCost) return undefined\n return {\n type: 'llm_call',\n data: {\n model,\n ...(hasTokens\n ? { tokensIn: result.input_tokens, tokensOut: result.output_tokens }\n : {}),\n ...(hasCost ? { costUsd: result.cost_usd } : {}),\n },\n }\n}\n\nconst REACT_HEADER = /^@appworld-react (\\S+) (\\S+)\\n?/\n\nconst SESSION_SYSTEM = [\n 'You are completing a task in AppWorld, a simulated multi-app environment.',\n 'Use the execute_python tool to run Python that calls the app APIs (the `apis.<app>.<function>(...)` surface).',\n 'Inspect API docs with `apis.api_docs.show_api_descriptions(app_name=...)` and `apis.api_docs.show_api_doc(app_name=..., api_name=...)`.',\n 'Authenticate where needed via the supervisor-provided credentials (`apis.supervisor.show_account_passwords()`).',\n 'Work incrementally: small snippets, read each output, correct course.',\n 'When every step of the task is done, run `apis.supervisor.complete_task()` and then reply WITHOUT calling the tool again.',\n].join('\\n')\n\nconst EXECUTE_TOOL: ToolSpec = {\n type: 'function',\n function: {\n name: 'execute_python',\n description:\n 'Execute a Python snippet in the persistent AppWorld world. State persists across calls. Returns the execution output (API results or errors).',\n parameters: {\n type: 'object',\n properties: { code: { type: 'string', description: 'Python code calling apis.<app>.<fn>(...)' } },\n required: ['code'],\n },\n },\n}\n\n/** One persistent world session: line-JSONL request/response over the driver. */\nasync function withWorldSession<T>(\n taskId: string,\n split: string,\n signal: AbortSignal,\n fn: (call: (cmd: Record<string, unknown>) => Promise<Record<string, unknown>>, instruction: string) => Promise<T>,\n): Promise<T> {\n signal.throwIfAborted()\n const child = spawn(venvPython, [DRIVER, 'session', '--task-id', taskId, '--split', split], {\n cwd: benchRoot,\n })\n const stopChild = (): void => {\n if (!child.killed) child.kill('SIGTERM')\n }\n signal.addEventListener('abort', stopChild, { once: true })\n const rl = createInterface({ input: child.stdout })\n const pending: Array<(line: string) => void> = []\n const backlog: string[] = []\n rl.on('line', (l) => {\n const next = pending.shift()\n if (next) next(l)\n else backlog.push(l)\n })\n let stderr = ''\n child.stderr.on('data', (c: Buffer) => {\n stderr += c.toString('utf8')\n })\n const nextLine = (timeoutMs: number): Promise<string> =>\n new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason)\n return\n }\n const fromBacklog = backlog.shift()\n if (fromBacklog !== undefined) return resolve(fromBacklog)\n const t = setTimeout(\n () => reject(new Error(`appworld session: no response in ${timeoutMs}ms; stderr: ${stderr.slice(-400)}`)),\n timeoutMs,\n )\n // One exit listener per await leaks (25-turn episodes blow the listener\n // cap) — remove it on the resolve path.\n const onExit = (code: number | null): void => {\n clearTimeout(t)\n signal.removeEventListener('abort', onAbort)\n reject(\n signal.aborted\n ? signal.reason\n : new Error(`appworld session exited (${code}); stderr: ${stderr.slice(-400)}`),\n )\n }\n const onAbort = (): void => {\n clearTimeout(t)\n child.removeListener('exit', onExit)\n const index = pending.indexOf(onLine)\n if (index >= 0) pending.splice(index, 1)\n reject(signal.reason)\n }\n const onLine = (line: string): void => {\n clearTimeout(t)\n child.removeListener('exit', onExit)\n signal.removeEventListener('abort', onAbort)\n resolve(line)\n }\n pending.push(onLine)\n child.once('exit', onExit)\n signal.addEventListener('abort', onAbort, { once: true })\n })\n try {\n const ready = JSON.parse(await nextLine(120_000)) as { ready?: boolean; instruction?: string; error?: string }\n if (!ready.ready) throw new Error(`appworld session failed to start: ${ready.error ?? 'no ready line'}`)\n const call = async (cmd: Record<string, unknown>): Promise<Record<string, unknown>> => {\n child.stdin.write(`${JSON.stringify(cmd)}\\n`)\n const res = JSON.parse(await nextLine(180_000)) as Record<string, unknown>\n if (typeof res.error === 'string') throw new Error(`appworld session op failed: ${res.error}`)\n return res\n }\n return await fn(call, ready.instruction ?? '')\n } finally {\n signal.removeEventListener('abort', stopChild)\n child.stdin.end()\n stopChild()\n }\n}\n\ntype AppWorldWorldSession = typeof withWorldSession\ntype AppWorldComplete = (\n body: Record<string, unknown>,\n request?: {\n readonly headers: Readonly<Record<string, string>>\n readonly signal?: AbortSignal\n },\n) => Promise<unknown>\n\n/** SandboxClient whose leaf is Runtime's profile-bound Router executor driving a world session. */\nexport function appworldToolLoopClient(cfg: {\n model: string\n routerBaseUrl: string\n routerKey: string\n maxTurns?: number\n /** Offline-test seam; production always uses the Python AppWorld session above. */\n runWorldSession?: AppWorldWorldSession\n /** Offline-test seam; production uses Runtime's Router HTTP transport. */\n complete?: AppWorldComplete\n}): unknown {\n const maxTurns = cfg.maxTurns ?? Number(process.env.REACT_MAX_TURNS ?? 40)\n const runWorldSession = cfg.runWorldSession ?? withWorldSession\n let seq = 0\n return {\n async create() {\n const id = `appworld-toolloop-${seq++}`\n return {\n id,\n async *streamPrompt(prompt: string, promptOpts?: { signal?: AbortSignal }) {\n const signal = promptOpts?.signal ?? new AbortController().signal\n signal.throwIfAborted()\n const m = prompt.match(REACT_HEADER)\n if (!m) {\n throw new Error(\n `appworld-react leaf: prompt missing '@appworld-react <taskId> <split>' header — got: ${prompt.slice(0, 120)}`,\n )\n }\n const [, taskId, split] = m\n const directive = prompt.replace(REACT_HEADER, '').trim()\n const out = await runWorldSession(taskId as string, split as string, signal, async (call, instruction) => {\n const system = directive ? `${SESSION_SYSTEM}\\n\\n${directive}` : SESSION_SYSTEM\n const transcriptSteps: Array<{ args: string; result: string }> = []\n const profile = {\n name: 'appworld-react-worker',\n harness: 'cli-base' as const,\n model: {\n provider: 'tangle-router',\n default: cfg.model,\n metadata: { maxTurns },\n },\n prompt: { systemPrompt: system },\n tools: { execute_python: true },\n }\n const factory = createExecutor({\n backend: 'router-tools',\n routerBaseUrl: cfg.routerBaseUrl,\n routerKey: cfg.routerKey,\n ...(cfg.complete ? { complete: cfg.complete } : {}),\n tools: [EXECUTE_TOOL],\n executeToolCall: async (name, args) => {\n if (name !== 'execute_python') return `error: unknown tool ${name}`\n const res = await call({ op: 'execute', code: String(args.code ?? '') })\n const done = res.task_completed === true\n const result = `${String(res.output ?? '')}${done ? '\\n\\n[TASK MARKED COMPLETE — reply with a final summary and do not call the tool again]' : ''}`\n transcriptSteps.push({ args: JSON.stringify(args), result })\n return result\n },\n })\n const loop = await collectAgentTurn(\n streamAgentTurn(\n { kind: 'executor', factory, profile },\n { prompt: `Task: ${instruction}` },\n { signal },\n ),\n )\n if (loop.status !== 'completed') {\n throw new Error(loop.error?.message ?? `AppWorld turn ended with ${loop.status}`)\n }\n const verdict = (await call({ op: 'evaluate' })) as unknown as ReactResult\n const transcript = transcriptSteps\n .slice(-3)\n .map((t) => `CODE:\\n${t.args.slice(0, 600)}\\nOUTPUT:\\n${t.result.slice(0, 600)}`)\n .join('\\n---\\n')\n .slice(0, 1600)\n const finalEvent = loop.events.at(-1)\n const resultMetadata =\n finalEvent?.type === 'final' && finalEvent.metadata?.result\n ? (finalEvent.metadata.result as { spent?: { iterations?: number } })\n : undefined\n return appworldReactResultWithUsage(\n verdict,\n loop.usage,\n resultMetadata?.spent?.iterations,\n transcript,\n )\n })\n const usageEvent = appworldReactUsageEvent(out, cfg.model)\n if (usageEvent) yield usageEvent\n yield { type: 'result', data: { finalText: JSON.stringify(out) } }\n },\n async delete() {},\n }\n },\n }\n}\n\n/** Artifact = the episode's evaluation JSON, verbatim (no fence extraction). */\nconst reactEpisodeOutput: 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\n if (typeof t === 'string' && t.length > 0) text = t\n }\n return text\n },\n}\n\nexport function createAppWorldReactAdapter(): BenchmarkAdapter {\n const base = createAppWorldAdapter()\n return {\n name: 'appworld-react',\n output: reactEpisodeOutput,\n preflight: () => base.preflight(),\n\n async loadTasks(opts: LoadOptions = {}): Promise<BenchTask[]> {\n const tasks = await base.loadTasks(opts)\n return tasks.map((t) => {\n const meta = readMeta(t)\n return {\n ...t,\n // Header carries task identity to the leaf; the body (empty at round 0)\n // is the directive slot the arms append their steer into.\n prompt: `@appworld-react ${meta.taskId} ${meta.split}\\n`,\n }\n })\n },\n\n goldArtifact: () => Promise.resolve(undefined),\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n let out: ReactResult\n try {\n out = JSON.parse(artifact) as ReactResult\n } catch {\n throw new Error(\n `appworld-react judge: artifact is not the episode's evaluation JSON (task ${meta.taskId}): ${artifact.slice(0, 200)}`,\n )\n }\n if (typeof out.success !== 'boolean' || typeof out.num_tests !== 'number') {\n throw new Error(\n `appworld-react judge: episode JSON missing success/num_tests (task ${meta.taskId}): ${artifact.slice(0, 200)}`,\n )\n }\n const passes = out.passes ?? 0\n const total = out.num_tests\n const failures = Array.isArray(out.failure_names) ? out.failure_names : []\n return {\n resolved: out.success === true,\n score: total > 0 ? passes / total : 0,\n detail: JSON.stringify({\n taskId: meta.taskId,\n success: out.success,\n passes,\n fails: out.fails ?? 0,\n total,\n turns: out.turns,\n ...(failures.length ? { failures } : {}),\n ...(out.transcript ? { transcriptTail: out.transcript.slice(-800) } : {}),\n }),\n }\n },\n\n leafClient: (c) => appworldToolLoopClient(c),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,SAAS,KAAK,WAAW,WAAW,oBAAo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,MAAM,QAAQ,IAAI;GAClB,MAAM,WAAW,MAAM,QAAQ,IAAI,aAAa,IAAI,IAAI,gBAAgB,CAAC;GACzE,OAAO;IACL,UAAU,IAAI,YAAY;IAC1B,OAAO,QAAQ,IAAI,SAAS,QAAQ;IACpC,QAAQ,KAAK,UAAU;KACrB,QAAQ,KAAK;KACb,SAAS,IAAI;KACb;KACA,OAAO,IAAI,SAAS;KACpB;KACA,OAAO,IAAI;KACX,GAAI,SAAS,SAAS,EAAE,SAAS,IAAI,CAAC;KACtC,GAAI,IAAI,aAAa,EAAE,gBAAgB,IAAI,WAAW,MAAM,IAAI,EAAE,IAAI,CAAC;IACzE,CAAC;GACH;EACF;EAEA,aAAa,MAAM,uBAAuB,CAAC;CAC7C;AACF"}
|
|
1
|
+
{"version":3,"file":"appworld.js","names":[],"sources":["../../src/benchmarks/appworld.ts"],"sourcesContent":["/**\n * AppWorld adapter (StonyBrookNLP/appworld). Worker artifact = the agent's\n * Python solution that calls the simulated apps' APIs (the same `apis.<app>.<fn>`\n * surface AppWorld exposes inside `world.execute(...)`), ending in\n * `apis.supervisor.complete_task()`. Judge = AppWorld's OWN programmatic\n * evaluator: a driver runs the solution in a fresh `AppWorld(task_id=...)` world,\n * then `world.evaluate().to_dict()` reports `success` (binary TGC), `num_tests`\n * (per-requirement total) and the `passes`/`failures` lists. Score =\n * passes / num_tests — GRADED; resolved = success. Fully deterministic — no LLM judge.\n *\n * loadTasks enumerates the real task suite via `load_task_ids(split)`\n * (train|dev|test_normal|test_challenge); the prompt = `world.task.instruction`.\n * The OutputAdapter is stream-only, so the worker emits its solution as a fenced\n * ```python block which the driver executes.\n *\n * Requires for a live run: the bench `.venv` with `appworld` installed + the\n * unpacked engine + downloaded data (`appworld install` ; `appworld download\n * data`). preflight + loadTasks + judge all fail loud with the exact step when the\n * engine/data is absent — never a fabricated score.\n */\n\nimport { spawn } from 'node:child_process'\nimport { join } from 'node:path'\nimport { createInterface } from 'node:readline'\nimport {\n collectAgentTurn,\n createExecutor,\n type OutputAdapter,\n streamAgentTurn,\n type ToolSpec,\n} from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot, preflightVenvImports, runVenvScriptStdin, venvPython } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst DRIVER = join(benchRoot, 'scripts', 'appworld_driver.py')\n\n/** AppWorld splits; only the test splits ship evaluation-only (no setup/solution). */\nconst DEFAULT_SPLIT = 'test_normal'\n\ninterface AppWorldMeta {\n taskId: string\n split: string\n}\n\n/** Worker solution code = the last fenced ```python block, else the raw text. */\nexport const appworldSolutionOutput: 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(/```(?:python|py)?\\s*\\n([\\s\\S]*?)```/g)]\n return (fences.at(-1)?.[1] ?? text).trim()\n },\n}\n\nconst WORKER_CONTRACT = [\n '',\n 'Solve this by writing Python that calls the available app APIs (the `apis.<app>.<function>(...)` surface). You may inspect API docs with `apis.api_docs.show_api_descriptions(app_name=...)` and `apis.api_docs.show_api_doc(app_name=..., api_name=...)`.',\n 'Authenticate where needed via the supervisor-provided credentials, perform every step the task requires, and FINISH with `apis.supervisor.complete_task()`.',\n 'Emit your COMPLETE solution as the LAST thing in your reply, in a single fenced ```python block. Nothing after the closing fence.',\n].join('\\n')\n\nfunction readMeta(task: BenchTask): AppWorldMeta {\n const md = task.metadata\n if (!md || typeof md.taskId !== 'string') {\n throw new Error(`appworld task ${task.id} missing metadata.taskId — loadTasks did not populate it`)\n }\n return md as unknown as AppWorldMeta\n}\n\n/**\n * Run the appworld engine driver with a subcommand; JSON on the LAST stdout line.\n * The solution code (evaluate) is piped to stdin via the shared stdin-aware runner —\n * execFile's `input` option is not honored async and hangs the driver's\n * sys.stdin.read() forever. `load` ignores stdin, so an empty pipe is harmless.\n */\nasync function driver(args: string[], input = ''): Promise<unknown> {\n let stdout: string\n try {\n stdout = await runVenvScriptStdin(DRIVER, args, input, { cwd: benchRoot })\n } catch (err) {\n const e = err as { message?: string }\n throw new Error(`appworld driver failed (${args.join(' ')}): ${(e.message || String(err)).slice(0, 1500)}`)\n }\n const last = stdout.trim().split('\\n').at(-1) ?? '{}'\n const parsed = JSON.parse(last) as { error?: string }\n if (parsed.error) throw new Error(`appworld driver error: ${parsed.error}`)\n return parsed\n}\n\nexport function createAppWorldAdapter(): BenchmarkAdapter {\n return {\n name: 'appworld',\n output: appworldSolutionOutput,\n\n async preflight() {\n await preflightVenvImports({\n modules: ['appworld'],\n requireDocker: false,\n fix:\n 'Fix: bench/.venv/bin/pip install appworld ; ' +\n 'bench/.venv/bin/appworld install ; bench/.venv/bin/appworld download data ' +\n '(unpacks the engine + downloads the simulated-app data/tasks). ' +\n 'Set APPWORLD_ROOT to the data root if not the default.',\n })\n },\n\n async loadTasks(opts: LoadOptions = {}): Promise<BenchTask[]> {\n const split = opts.split ?? DEFAULT_SPLIT\n const out = (await driver([\n 'load',\n '--split', split,\n ...(opts.limit !== undefined ? ['--limit', String(opts.limit)] : []),\n ...(opts.ids ? ['--ids', opts.ids.join(',')] : []),\n ])) as { tasks?: Array<{ task_id: string; instruction: string }> }\n const tasks = out.tasks ?? []\n if (tasks.length === 0) {\n throw new Error(`appworld loadTasks returned no tasks for split=${split} ${JSON.stringify(opts)}`)\n }\n return tasks.map(\n (t): BenchTask => ({\n id: t.task_id,\n split,\n prompt: t.instruction + WORKER_CONTRACT,\n metadata: { taskId: t.task_id, split } as unknown as Record<string, unknown>,\n }),\n )\n },\n\n async goldArtifact() {\n // Reference solution code ships only for train/dev, and only inside the\n // engine's decrypted `.bundle` (it is not a portable string this adapter can\n // emit across splits). The test splits are evaluation-only. So verify-judge\n // here requires a real solve on a train/dev task through the live engine\n // rather than a synthetic gold — returning a fabricated artifact would be a\n // fake. Returns undefined.\n return undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const out = (await driver(['evaluate', '--task-id', meta.taskId, '--split', meta.split], artifact)) as {\n success?: boolean\n passes?: number\n fails?: number\n num_tests?: number\n failure_names?: string[]\n }\n const passes = out.passes ?? 0\n const fails = out.fails ?? 0\n // num_tests is the evaluator's authoritative per-requirement count; prefer it\n // over passes+fails (which can disagree if a requirement neither passed nor\n // failed). Never default the total to a phantom denominator.\n const total = out.num_tests ?? passes + fails\n const score = total > 0 ? passes / total : 0\n // failure_names = WHICH sub-tests failed — the evidence a trace analyst\n // steers on. Carried in `detail` so it reaches the verdict's `notes`.\n const failures = Array.isArray(out.failure_names) ? out.failure_names : []\n return {\n resolved: out.success === true,\n score,\n detail: JSON.stringify({\n taskId: meta.taskId,\n success: out.success,\n passes,\n fails,\n total,\n ...(failures.length ? { failures } : {}),\n }),\n }\n },\n }\n}\n\n/**\n * AppWorld in its NATIVE protocol, run by OUR runtime: the worker is\n * Runtime's profile-bound `router-tools` executor with one tool —\n * `execute_python` — bound to a persistent AppWorld world session. The driver's\n * `session` subcommand is a dumb world shim (stdin JSONL: execute → output,\n * evaluate → verdict); every inference turn, the metering, and the typed\n * toolTrace the analyst steers on belong to the runtime, so runtime\n * improvements are what this benchmark measures.\n *\n * The one-shot codegen adapter above plays a strictly harder game (no execution\n * feedback — the first wrong API call kills the whole program at judge time),\n * which flatlines the score against ANY steering; this mode is what the\n * benchmark's published baselines use, where behavior can move sub-tests.\n *\n * Protocol: the round task string is `@appworld-react <taskId> <split>` on\n * line 1; everything after line 1 is the steer (an analyst correction, a push\n * directive) appended to the system prompt — so the existing arms steer this\n * worker without modification. The artifact is the episode evaluation JSON\n * (AppWorld's evaluator ran in-world); judge() parses it, never re-executes.\n */\n\nexport interface ReactResult {\n success?: boolean\n passes?: number\n fails?: number\n num_tests?: number\n failure_names?: string[]\n turns?: number\n input_tokens?: number\n output_tokens?: number\n cost_usd?: number\n transcript?: string\n}\n\ninterface ReactRuntimeUsage {\n input: number\n output: number\n costUsd?: number\n tokensKnown?: boolean\n usdKnown?: boolean\n}\n\n/** Preserve a completed scientific/task result even when one accounting dimension is incomplete.\n * Unknown usage fields stay absent; later comparison/reporting can refuse a cost claim without\n * discarding the episode's task evidence. */\nexport function appworldReactResultWithUsage(\n verdict: ReactResult,\n usage: ReactRuntimeUsage,\n turns: number | undefined,\n transcript: string,\n): ReactResult {\n return {\n ...verdict,\n ...(turns !== undefined ? { turns } : {}),\n ...(usage.tokensKnown === false\n ? {}\n : { input_tokens: usage.input, output_tokens: usage.output }),\n ...(usage.usdKnown === false || usage.costUsd === undefined\n ? {}\n : { cost_usd: usage.costUsd }),\n transcript,\n }\n}\n\n/** Emit only usage the Runtime actually knows. Catalog estimates never become observed dollars. */\nexport function appworldReactUsageEvent(\n result: ReactResult,\n model: string,\n): { type: 'llm_call'; data: Record<string, unknown> } | undefined {\n const hasTokens =\n typeof result.input_tokens === 'number' && typeof result.output_tokens === 'number'\n const hasCost = typeof result.cost_usd === 'number'\n if (!hasTokens && !hasCost) return undefined\n return {\n type: 'llm_call',\n data: {\n model,\n ...(hasTokens\n ? { tokensIn: result.input_tokens, tokensOut: result.output_tokens }\n : {}),\n ...(hasCost ? { costUsd: result.cost_usd } : {}),\n },\n }\n}\n\nconst REACT_HEADER = /^@appworld-react (\\S+) (\\S+)\\n?/\n\nconst SESSION_SYSTEM = [\n 'You are completing a task in AppWorld, a simulated multi-app environment.',\n 'Use the execute_python tool to run Python that calls the app APIs (the `apis.<app>.<function>(...)` surface).',\n 'Inspect API docs with `apis.api_docs.show_api_descriptions(app_name=...)` and `apis.api_docs.show_api_doc(app_name=..., api_name=...)`.',\n 'Authenticate where needed via the supervisor-provided credentials (`apis.supervisor.show_account_passwords()`).',\n 'Work incrementally: small snippets, read each output, correct course.',\n 'When every step of the task is done, run `apis.supervisor.complete_task()` and then reply WITHOUT calling the tool again.',\n].join('\\n')\n\nconst EXECUTE_TOOL: ToolSpec = {\n type: 'function',\n function: {\n name: 'execute_python',\n description:\n 'Execute a Python snippet in the persistent AppWorld world. State persists across calls. Returns the execution output (API results or errors).',\n parameters: {\n type: 'object',\n properties: { code: { type: 'string', description: 'Python code calling apis.<app>.<fn>(...)' } },\n required: ['code'],\n },\n },\n}\n\n/** One persistent world session: line-JSONL request/response over the driver. */\nasync function withWorldSession<T>(\n taskId: string,\n split: string,\n signal: AbortSignal,\n fn: (call: (cmd: Record<string, unknown>) => Promise<Record<string, unknown>>, instruction: string) => Promise<T>,\n): Promise<T> {\n signal.throwIfAborted()\n const child = spawn(venvPython, [DRIVER, 'session', '--task-id', taskId, '--split', split], {\n cwd: benchRoot,\n })\n const stopChild = (): void => {\n if (!child.killed) child.kill('SIGTERM')\n }\n signal.addEventListener('abort', stopChild, { once: true })\n const rl = createInterface({ input: child.stdout })\n const pending: Array<(line: string) => void> = []\n const backlog: string[] = []\n rl.on('line', (l) => {\n const next = pending.shift()\n if (next) next(l)\n else backlog.push(l)\n })\n let stderr = ''\n child.stderr.on('data', (c: Buffer) => {\n stderr += c.toString('utf8')\n })\n const nextLine = (timeoutMs: number): Promise<string> =>\n new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason)\n return\n }\n const fromBacklog = backlog.shift()\n if (fromBacklog !== undefined) return resolve(fromBacklog)\n const t = setTimeout(\n () => reject(new Error(`appworld session: no response in ${timeoutMs}ms; stderr: ${stderr.slice(-400)}`)),\n timeoutMs,\n )\n // One exit listener per await leaks (25-turn episodes blow the listener\n // cap) — remove it on the resolve path.\n const onExit = (code: number | null): void => {\n clearTimeout(t)\n signal.removeEventListener('abort', onAbort)\n reject(\n signal.aborted\n ? signal.reason\n : new Error(`appworld session exited (${code}); stderr: ${stderr.slice(-400)}`),\n )\n }\n const onAbort = (): void => {\n clearTimeout(t)\n child.removeListener('exit', onExit)\n const index = pending.indexOf(onLine)\n if (index >= 0) pending.splice(index, 1)\n reject(signal.reason)\n }\n const onLine = (line: string): void => {\n clearTimeout(t)\n child.removeListener('exit', onExit)\n signal.removeEventListener('abort', onAbort)\n resolve(line)\n }\n pending.push(onLine)\n child.once('exit', onExit)\n signal.addEventListener('abort', onAbort, { once: true })\n })\n try {\n const ready = JSON.parse(await nextLine(120_000)) as { ready?: boolean; instruction?: string; error?: string }\n if (!ready.ready) throw new Error(`appworld session failed to start: ${ready.error ?? 'no ready line'}`)\n const call = async (cmd: Record<string, unknown>): Promise<Record<string, unknown>> => {\n child.stdin.write(`${JSON.stringify(cmd)}\\n`)\n const res = JSON.parse(await nextLine(180_000)) as Record<string, unknown>\n if (typeof res.error === 'string') throw new Error(`appworld session op failed: ${res.error}`)\n return res\n }\n return await fn(call, ready.instruction ?? '')\n } finally {\n signal.removeEventListener('abort', stopChild)\n child.stdin.end()\n stopChild()\n }\n}\n\ntype AppWorldWorldSession = typeof withWorldSession\ntype AppWorldComplete = (\n body: Record<string, unknown>,\n request?: {\n readonly headers: Readonly<Record<string, string>>\n readonly signal?: AbortSignal\n },\n) => Promise<unknown>\n\n/** SandboxClient whose leaf is Runtime's profile-bound Router executor driving a world session. */\nexport function appworldToolLoopClient(cfg: {\n model: string\n routerBaseUrl: string\n routerKey: string\n maxTurns?: number\n /** Offline-test seam; production always uses the Python AppWorld session above. */\n runWorldSession?: AppWorldWorldSession\n /** Offline-test seam; production uses Runtime's Router HTTP transport. */\n complete?: AppWorldComplete\n}): unknown {\n const maxTurns = cfg.maxTurns ?? Number(process.env.REACT_MAX_TURNS ?? 40)\n const runWorldSession = cfg.runWorldSession ?? withWorldSession\n let seq = 0\n return {\n async create() {\n const id = `appworld-toolloop-${seq++}`\n return {\n id,\n async *streamPrompt(prompt: string, promptOpts?: { signal?: AbortSignal }) {\n const signal = promptOpts?.signal ?? new AbortController().signal\n signal.throwIfAborted()\n const m = prompt.match(REACT_HEADER)\n if (!m) {\n throw new Error(\n `appworld-react leaf: prompt missing '@appworld-react <taskId> <split>' header — got: ${prompt.slice(0, 120)}`,\n )\n }\n const [, taskId, split] = m\n const directive = prompt.replace(REACT_HEADER, '').trim()\n const out = await runWorldSession(taskId as string, split as string, signal, async (call, instruction) => {\n const system = directive ? `${SESSION_SYSTEM}\\n\\n${directive}` : SESSION_SYSTEM\n const transcriptSteps: Array<{ args: string; result: string }> = []\n const profile = {\n name: 'appworld-react-worker',\n harness: 'cli-base' as const,\n model: {\n provider: 'tangle-router',\n default: cfg.model,\n metadata: { maxTurns },\n },\n prompt: { systemPrompt: system },\n tools: { execute_python: true },\n }\n const factory = createExecutor({\n backend: 'router-tools',\n routerBaseUrl: cfg.routerBaseUrl,\n routerKey: cfg.routerKey,\n ...(cfg.complete ? { complete: cfg.complete } : {}),\n tools: [EXECUTE_TOOL],\n executeToolCall: async (name, args) => {\n if (name !== 'execute_python') return `error: unknown tool ${name}`\n const res = await call({ op: 'execute', code: String(args.code ?? '') })\n const done = res.task_completed === true\n const result = `${String(res.output ?? '')}${done ? '\\n\\n[TASK MARKED COMPLETE — reply with a final summary and do not call the tool again]' : ''}`\n transcriptSteps.push({ args: JSON.stringify(args), result })\n return result\n },\n })\n const loop = await collectAgentTurn(\n streamAgentTurn(\n { kind: 'executor', factory, profile },\n { prompt: `Task: ${instruction}` },\n { signal },\n ),\n )\n if (loop.status !== 'completed') {\n throw new Error(loop.error?.message ?? `AppWorld turn ended with ${loop.status}`)\n }\n const verdict = (await call({ op: 'evaluate' })) as unknown as ReactResult\n const transcript = transcriptSteps\n .slice(-3)\n .map((t) => `CODE:\\n${t.args.slice(0, 600)}\\nOUTPUT:\\n${t.result.slice(0, 600)}`)\n .join('\\n---\\n')\n .slice(0, 1600)\n const finalEvent = loop.events.at(-1)\n const resultMetadata =\n finalEvent?.type === 'final' && finalEvent.metadata?.result\n ? (finalEvent.metadata.result as { spent?: { iterations?: number } })\n : undefined\n return appworldReactResultWithUsage(\n verdict,\n loop.usage,\n resultMetadata?.spent?.iterations,\n transcript,\n )\n })\n const usageEvent = appworldReactUsageEvent(out, cfg.model)\n if (usageEvent) yield usageEvent\n yield { type: 'result', data: { finalText: JSON.stringify(out) } }\n },\n async delete() {},\n }\n },\n }\n}\n\n/** Artifact = the episode's evaluation JSON, verbatim (no fence extraction). */\nconst reactEpisodeOutput: 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\n if (typeof t === 'string' && t.length > 0) text = t\n }\n return text\n },\n}\n\nexport function createAppWorldReactAdapter(): BenchmarkAdapter {\n const base = createAppWorldAdapter()\n return {\n name: 'appworld-react',\n output: reactEpisodeOutput,\n preflight: () => base.preflight(),\n\n async loadTasks(opts: LoadOptions = {}): Promise<BenchTask[]> {\n const tasks = await base.loadTasks(opts)\n return tasks.map((t) => {\n const meta = readMeta(t)\n return {\n ...t,\n // Header carries task identity to the leaf; the body (empty at round 0)\n // is the directive slot the arms append their steer into.\n prompt: `@appworld-react ${meta.taskId} ${meta.split}\\n`,\n }\n })\n },\n\n goldArtifact: () => Promise.resolve(undefined),\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n let out: ReactResult\n try {\n out = JSON.parse(artifact) as ReactResult\n } catch {\n throw new Error(\n `appworld-react judge: artifact is not the episode's evaluation JSON (task ${meta.taskId}): ${artifact.slice(0, 200)}`,\n )\n }\n if (typeof out.success !== 'boolean' || typeof out.num_tests !== 'number') {\n throw new Error(\n `appworld-react judge: episode JSON missing success/num_tests (task ${meta.taskId}): ${artifact.slice(0, 200)}`,\n )\n }\n const passes = out.passes ?? 0\n const total = out.num_tests\n const failures = Array.isArray(out.failure_names) ? out.failure_names : []\n return {\n resolved: out.success === true,\n score: total > 0 ? passes / total : 0,\n detail: JSON.stringify({\n taskId: meta.taskId,\n success: out.success,\n passes,\n fails: out.fails ?? 0,\n total,\n turns: out.turns,\n ...(failures.length ? { failures } : {}),\n ...(out.transcript ? { transcriptTail: out.transcript.slice(-800) } : {}),\n }),\n }\n },\n\n leafClient: (c) => appworldToolLoopClient(c),\n }\n}\n"],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,KAAK,OAAO,KAAK,SAAS,MAAM,GAAG,GAAG,GAC9G;GAEF,MAAM,SAAS,IAAI,UAAU;GAC7B,MAAM,QAAQ,IAAI;GAClB,MAAM,WAAW,MAAM,QAAQ,IAAI,aAAa,IAAI,IAAI,gBAAgB,CAAC;GACzE,OAAO;IACL,UAAU,IAAI,YAAY;IAC1B,OAAO,QAAQ,IAAI,SAAS,QAAQ;IACpC,QAAQ,KAAK,UAAU;KACrB,QAAQ,KAAK;KACb,SAAS,IAAI;KACb;KACA,OAAO,IAAI,SAAS;KACpB;KACA,OAAO,IAAI;KACX,GAAI,SAAS,SAAS,EAAE,SAAS,IAAI,CAAC;KACtC,GAAI,IAAI,aAAa,EAAE,gBAAgB,IAAI,WAAW,MAAM,IAAI,EAAE,IAAI,CAAC;IACzE,CAAC;GACH;EACF;EAEA,aAAa,MAAM,uBAAuB,CAAC;CAC7C;AACF"}
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { BenchmarkAdapter } from "./types.js";
|
|
2
2
|
import { OutputAdapter } from "@tangle-network/agent-runtime/kernel";
|
|
3
|
-
|
|
4
|
-
declare
|
|
5
|
-
declare function createBfclAdapter(): BenchmarkAdapter;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { bfclOutput, createBfclAdapter };
|
|
3
|
+
export declare const bfclOutput: OutputAdapter<string>;
|
|
4
|
+
export declare function createBfclAdapter(): BenchmarkAdapter;
|
|
8
5
|
//# sourceMappingURL=bfcl.d.ts.map
|
package/dist/benchmarks/bfcl.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { benchRoot } from "./_harness.js";
|
|
2
2
|
import { readFile, stat } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
|
|
4
|
+
// src/benchmarks/bfcl.ts
|
|
5
5
|
/**
|
|
6
6
|
* Berkeley Function Calling Leaderboard adapter.
|
|
7
7
|
*
|
|
@@ -259,7 +259,6 @@ function createBfclAdapter() {
|
|
|
259
259
|
}
|
|
260
260
|
};
|
|
261
261
|
}
|
|
262
|
-
//#endregion
|
|
263
262
|
export { bfclOutput, createBfclAdapter };
|
|
264
263
|
|
|
265
264
|
//# sourceMappingURL=bfcl.js.map
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { BenchmarkAdapter } from "./types.js";
|
|
2
|
-
//#region src/benchmarks/cad-design.d.ts
|
|
3
2
|
/** Spec assertions a CAD task can require. All are deterministic + geometric. */
|
|
4
|
-
interface CadSpec {
|
|
3
|
+
export interface CadSpec {
|
|
5
4
|
volumes?: [number, number];
|
|
6
5
|
bbox?: {
|
|
7
6
|
x?: [number, number];
|
|
@@ -14,7 +13,5 @@ interface CadSpec {
|
|
|
14
13
|
/** Printed solid volume must be < this fraction of the bbox volume (hollow). */
|
|
15
14
|
hollowBelow?: number;
|
|
16
15
|
}
|
|
17
|
-
declare function createCadDesignAdapter(): BenchmarkAdapter;
|
|
18
|
-
//#endregion
|
|
19
|
-
export { CadSpec, createCadDesignAdapter };
|
|
16
|
+
export declare function createCadDesignAdapter(): BenchmarkAdapter;
|
|
20
17
|
//# sourceMappingURL=cad-design.d.ts.map
|
|
@@ -3,7 +3,7 @@ import { join } from "node:path";
|
|
|
3
3
|
import { execFile } from "node:child_process";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
|
-
|
|
6
|
+
// src/benchmarks/cad-design.ts
|
|
7
7
|
/**
|
|
8
8
|
* CAD-Design adapter. Worker artifact = OpenSCAD source (`.scad`). Judge = the
|
|
9
9
|
* REAL OpenSCAD engine: compile + export STL, then measure the produced solid
|
|
@@ -37,7 +37,7 @@ async function openscad(args, cwd) {
|
|
|
37
37
|
...args
|
|
38
38
|
], {
|
|
39
39
|
cwd,
|
|
40
|
-
maxBuffer:
|
|
40
|
+
maxBuffer: 67108864,
|
|
41
41
|
timeout: 12e4
|
|
42
42
|
});
|
|
43
43
|
return {
|
|
@@ -507,7 +507,6 @@ function createCadDesignAdapter() {
|
|
|
507
507
|
}
|
|
508
508
|
};
|
|
509
509
|
}
|
|
510
|
-
//#endregion
|
|
511
510
|
export { createCadDesignAdapter };
|
|
512
511
|
|
|
513
512
|
//# sourceMappingURL=cad-design.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cad-design.js","names":[],"sources":["../../src/benchmarks/cad-design.ts"],"sourcesContent":["/**\n * CAD-Design adapter. Worker artifact = OpenSCAD source (`.scad`). Judge = the\n * REAL OpenSCAD engine: compile + export STL, then measure the produced solid\n * geometry against the task's spec. Fully deterministic — the authoritative CAD\n * kernel is the gate, not an LLM and not the agent's own claim.\n *\n * This is verifiable-reward CAD: an agent is far better at *writing* exact\n * parametric code than at clicking a GUI, and the kernel either produces the\n * specified geometry or it doesn't. Every judged artifact also renders a PNG,\n * so a refine loop's attempts become a watchable \"model getting better\" reel\n * (run-capsule consumes the renders).\n *\n * Spec checks are geometric and ungameable:\n * - compiles : `openscad -o out.stl` exits 0 (hard gate)\n * - volumes : disconnected-solid count within [min,max]\n * - bbox : overall X/Y/Z extent within bounds (the thing is the right size)\n * - detail : triangle count ≥ floor (not a degenerate single cube)\n * - pitchedRoof : the top band's XY footprint NARROWS vs the base — a flat\n * box can't fake this; a real gabled/hipped roof tapers\n * - hollow : interior cavity present (walls, not a solid block) — the\n * bbox volume materially exceeds the printed solid volume\n *\n * Requires only `openscad` + `xvfb-run` on PATH (no venv, no Docker, no network).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\n\n/** Spec assertions a CAD task can require. All are deterministic + geometric. */\nexport interface CadSpec {\n volumes?: [number, number]\n bbox?: { x?: [number, number]; y?: [number, number]; z?: [number, number] }\n minTriangles?: number\n /** Top-band XY footprint must be < this fraction of the base footprint. */\n pitchedRoof?: number\n /** Printed solid volume must be < this fraction of the bbox volume (hollow). */\n hollowBelow?: number\n}\n\ninterface CadTaskMeta {\n spec: CadSpec\n /** A known-good .scad that satisfies the spec — the oracle for verify-judge. */\n gold: string\n}\n\n/** Run openscad with xvfb (it needs a GL context even headless). */\nasync function openscad(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> {\n // -a => auto-pick a free display; openscad writes Facets/Volumes to stderr.\n const { stdout, stderr } = await execFileAsync('xvfb-run', ['-a', 'openscad', ...args], {\n cwd,\n maxBuffer: 1024 * 1024 * 64,\n timeout: 120_000,\n })\n return { stdout, stderr }\n}\n\ninterface Geometry {\n triangles: number\n volumes: number\n bbox: { x: number; y: number; z: number }\n /** XY footprint area (extent_x * extent_y) of the bottom 60% and top 25% z-bands. */\n baseFootprint: number\n topFootprint: number\n /** Convex-ish solid volume estimate from the STL (sum of signed tetra volumes). */\n solidVolume: number\n bboxVolume: number\n}\n\n/** Parse an ASCII STL into the geometric measures the spec checks. Pure. */\nfunction measureStl(stl: string, volumesFromStderr: number): Geometry {\n const verts: Array<[number, number, number]> = []\n const tris: Array<[[number, number, number], [number, number, number], [number, number, number]]> = []\n const re = /vertex\\s+(-?[\\d.eE+]+)\\s+(-?[\\d.eE+]+)\\s+(-?[\\d.eE+]+)/g\n let m: RegExpExecArray | null\n const flat: Array<[number, number, number]> = []\n while ((m = re.exec(stl))) flat.push([Number(m[1]), Number(m[2]), Number(m[3])])\n for (let i = 0; i + 2 < flat.length; i += 3) tris.push([flat[i]!, flat[i + 1]!, flat[i + 2]!])\n for (const v of flat) verts.push(v)\n\n const xs = verts.map((v) => v[0])\n const ys = verts.map((v) => v[1])\n const zs = verts.map((v) => v[2])\n const min = (a: number[]) => Math.min(...a)\n const max = (a: number[]) => Math.max(...a)\n const minZ = min(zs)\n const maxZ = max(zs)\n const h = maxZ - minZ || 1\n\n // Footprint of a z-band = XY extent of the vertices within it.\n const footprint = (lo: number, hi: number): number => {\n const band = verts.filter((v) => v[2] >= minZ + lo * h && v[2] <= minZ + hi * h)\n if (band.length < 3) return 0\n const bx = band.map((v) => v[0])\n const by = band.map((v) => v[1])\n return (max(bx) - min(bx)) * (max(by) - min(by))\n }\n\n // Signed volume via the divergence theorem over triangles (|Σ v0·(v1×v2)/6|).\n let vol6 = 0\n for (const [a, b, c] of tris) {\n vol6 +=\n a[0] * (b[1] * c[2] - b[2] * c[1]) -\n a[1] * (b[0] * c[2] - b[2] * c[0]) +\n a[2] * (b[0] * c[1] - b[1] * c[0])\n }\n const bbox = { x: max(xs) - min(xs), y: max(ys) - min(ys), z: maxZ - minZ }\n return {\n triangles: tris.length,\n volumes: volumesFromStderr,\n bbox,\n baseFootprint: footprint(0, 0.6),\n topFootprint: footprint(0.75, 1),\n solidVolume: Math.abs(vol6) / 6,\n bboxVolume: bbox.x * bbox.y * bbox.z || 1,\n }\n}\n\nfunction inRange(v: number, [lo, hi]: [number, number]): boolean {\n return v >= lo && v <= hi\n}\n\n/** Score the geometry against the spec — each check is a named pass/fail. */\nfunction scoreGeometry(g: Geometry, spec: CadSpec): { checks: Record<string, boolean>; score: number } {\n const checks: Record<string, boolean> = {}\n if (spec.volumes) checks.volumes = inRange(g.volumes, spec.volumes)\n if (spec.minTriangles != null) checks.detail = g.triangles >= spec.minTriangles\n if (spec.bbox?.x) checks.bboxX = inRange(g.bbox.x, spec.bbox.x)\n if (spec.bbox?.y) checks.bboxY = inRange(g.bbox.y, spec.bbox.y)\n if (spec.bbox?.z) checks.bboxZ = inRange(g.bbox.z, spec.bbox.z)\n if (spec.pitchedRoof != null)\n checks.pitchedRoof = g.baseFootprint > 0 && g.topFootprint < spec.pitchedRoof * g.baseFootprint\n if (spec.hollowBelow != null) checks.hollow = g.solidVolume < spec.hollowBelow * g.bboxVolume\n const vals = Object.values(checks)\n const score = vals.length ? vals.filter(Boolean).length / vals.length : 0\n return { checks, score }\n}\n\n/** A parametric multi-story gabled building — the gold generator for the\n * building-family tasks. They share geometry (hollow stacked shells + a gabled\n * roof that tapers to a ridge + cut openings) and differ only in dimensions, so\n * one verified generator yields a spec-passing oracle for each. */\nfunction buildingGold(w: number, d: number, sh: number, ns: number, rh: number, t = 3): string {\n return `\nw=${w}; d=${d}; sh=${sh}; ns=${ns}; rh=${rh}; t=${t};\nmodule shell(w,d,h,t){ difference(){ cube([w,d,h]); translate([t,t,-1]) cube([w-2*t,d-2*t,h+2]); } }\nmodule roof(w,d,h){ rotate([90,0,90]) linear_extrude(height=w) polygon([[0,0],[d,0],[d/2,h]]); }\nunion(){\n for(s=[0:ns-1]) translate([0,0,s*sh]) shell(w,d,sh,t);\n for(s=[0:ns]) translate([0,0,s*sh-0.5]) cube([w,d,1]);\n translate([0,0,ns*sh]) roof(w,d,rh);\n for(s=[0:ns-1]) for(i=[0:floor((w-28)/22)]) translate([14+i*22,-1,s*sh+10]) cube([10,t+2,12]);\n translate([w/2-7,-1,2]) cube([14,t+2,20]);\n}\n`.trim()\n}\n\n/** Build a building-family task (prompt + spec + gold) from its dimensions.\n * The spec's bbox is derived from the dims with a ±~18% tolerance so the agent\n * must respect the brief's size; the gold (buildingGold) lands exactly on the\n * nominal dims, so it passes by construction. Keep rh > ns*sh/3 (else the roof\n * base sits inside the top-25% band and pitchedRoof fails). */\nfunction buildingTask(o: { id: string; desc: string; w: number; d: number; sh: number; ns: number; rh: number }): {\n id: string\n prompt: string\n meta: CadTaskMeta\n} {\n const { id, desc, w, d, sh, ns, rh } = o\n const totalWall = ns * sh\n const totalH = totalWall + rh\n const r = Math.round\n const spec: CadSpec = {\n volumes: [1, ns * 4 + 6],\n bbox: {\n x: [r(w * 0.82), r(w * 1.18)],\n y: [r(d * 0.82), r((d + 1) * 1.2)],\n z: [r(totalH * 0.82), r((totalH + 1) * 1.2)],\n },\n minTriangles: 50,\n pitchedRoof: 0.55,\n hollowBelow: 0.72,\n }\n const prompt = [\n `Write OpenSCAD source for ${desc}.`,\n 'Requirements:',\n `- footprint roughly ${w} (X) by ${d} (Y) units`,\n ns > 1 ? `- ${ns} stories, total wall height ~${totalWall} units` : `- one story, wall height ~${sh} units`,\n '- a PITCHED / gabled roof on top that tapers toward a ridge (NOT flat)',\n '- hollow shell (walls with an interior cavity), not a solid block',\n '- a door opening and several windows',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n')\n return { id, prompt, meta: { spec, gold: buildingGold(w, d, sh, ns, rh) } }\n}\n\n/** The building family — one parametric skill (hit the bbox + pitched roof +\n * hollow shell), sampled across footprints, heights, story counts, roof rises. */\nconst BUILDING_CONFIGS: Array<{ id: string; desc: string; w: number; d: number; sh: number; ns: number; rh: number }> = [\n { id: 'cottage', desc: 'a single-story cottage', w: 50, d: 40, sh: 30, ns: 1, rh: 18 },\n { id: 'cabin', desc: 'a small one-room cabin', w: 44, d: 36, sh: 26, ns: 1, rh: 22 },\n { id: 'bungalow', desc: 'a wide single-story bungalow', w: 70, d: 52, sh: 28, ns: 1, rh: 20 },\n { id: 'barn', desc: 'a long deep barn', w: 60, d: 96, sh: 42, ns: 1, rh: 26 },\n { id: 'warehouse', desc: 'a large warehouse', w: 110, d: 80, sh: 40, ns: 1, rh: 26 },\n { id: 'chapel', desc: 'a narrow tall chapel with a steep roof', w: 40, d: 72, sh: 48, ns: 1, rh: 34 },\n { id: 'farmhouse', desc: 'a two-story farmhouse', w: 72, d: 56, sh: 30, ns: 2, rh: 26 },\n { id: 'two-story-manor', desc: 'a wide two-story manor', w: 96, d: 64, sh: 32, ns: 2, rh: 28 },\n { id: 'townhouse', desc: 'a narrow three-story townhouse', w: 42, d: 52, sh: 30, ns: 3, rh: 34 },\n { id: 'watchtower', desc: 'a tall narrow three-story watchtower', w: 34, d: 34, sh: 30, ns: 3, rh: 32 },\n]\n\n/** A hollow cylindrical water tower with a conical roof — a non-box shape that\n * still exercises pitched-roof (the cone tapers to an apex) + hollow + bbox. */\nconst WATER_TOWER_GOLD = `\n$fn=48; r=24; bh=72; t=3; ch=26;\nunion(){\n difference(){ cylinder(h=bh, r=r); translate([0,0,t]) cylinder(h=bh, r=r-t); }\n translate([0,0,bh]) cylinder(h=ch, r1=r, r2=0);\n}\n`.trim()\n\n/** An A-frame: the steep roof IS the walls — a hollow triangular prism. The most\n * extreme taper in the set; tests that the agent can build a non-rectangular shell. */\nconst AFRAME_GOLD = `\nw=44; d=60; h=66; t=3;\nmodule tri(w,d,h){ rotate([90,0,90]) linear_extrude(height=w) polygon([[0,0],[d,0],[d/2,h]]); }\nunion(){\n difference(){ tri(w,d,h); translate([t,0,0]) tri(w-2*t,d,h-2*t*h/d); }\n translate([w/2-7,-1,0]) cube([14,t+2,24]);\n}\n`.trim()\n\nconst TASKS: Array<{ id: string; prompt: string; meta: CadTaskMeta }> = [\n {\n id: 'two-story-house',\n prompt: [\n 'Write OpenSCAD source for a two-story house.',\n 'Requirements:',\n '- footprint roughly 80 (X) by 60 (Y) units',\n '- two stories, total wall height ~68 units',\n '- a PITCHED / gabled roof on top (NOT a flat roof) — the roof must taper toward a ridge',\n '- hollow shell (walls with an interior cavity), not a solid block',\n '- at least one door opening and several windows',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 12],\n bbox: { x: [70, 110], y: [50, 80], z: [80, 130] },\n minTriangles: 60,\n pitchedRoof: 0.55,\n hollowBelow: 0.7,\n },\n gold: `\nw=80; d=60; sh=34; t=3; rh=28;\nmodule shell(w,d,h,t){ difference(){ cube([w,d,h]); translate([t,t,-1]) cube([w-2*t,d-2*t,h+2]); } }\nmodule roof(w,d,h){ translate([0,0,0]) rotate([90,0,90]) linear_extrude(height=w) polygon([[0,0],[d,0],[d/2,h]]); }\nunion(){\n for(s=[0,1]) translate([0,0,s*sh]) shell(w,d,sh,t);\n for(s=[0,1,2]) translate([0,0,s*sh-1]) cube([w,d,1]);\n translate([0,0,2*sh]) roof(w,d,rh);\n for(s=[0,1]) for(i=[0:2]) translate([16+i*22,-1,s*sh+10]) cube([12,t+2,14]);\n translate([w/2-8,-1,2]) cube([16,t+2,22]);\n}\n`.trim(),\n },\n },\n ...BUILDING_CONFIGS.map(buildingTask),\n {\n id: 'water-tower',\n prompt: [\n 'Write OpenSCAD source for a water tower: a tall hollow cylindrical tank with a conical roof.',\n 'Requirements:',\n '- a hollow cylindrical tank, ~48 units in diameter, ~72 units tall, with an interior cavity',\n '- a CONICAL roof on top that tapers to a point (a pitched roof)',\n '- wall thickness around 3 units',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 4],\n bbox: { x: [40, 56], y: [40, 56], z: [88, 110] },\n minTriangles: 60,\n pitchedRoof: 0.55,\n hollowBelow: 0.8,\n },\n gold: WATER_TOWER_GOLD,\n },\n },\n {\n id: 'a-frame-cabin',\n prompt: [\n 'Write OpenSCAD source for an A-frame cabin: a steep triangular shell where the roof forms the walls.',\n 'Requirements:',\n '- footprint roughly 44 (X) by 60 (Y) units',\n '- a STEEP triangular cross-section ~66 units tall that tapers to a ridge at the top',\n '- hollow inside (an interior cavity), not a solid wedge',\n '- a door opening at the front',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 4],\n bbox: { x: [36, 52], y: [50, 74], z: [56, 80] },\n minTriangles: 30,\n pitchedRoof: 0.45,\n hollowBelow: 0.8,\n },\n gold: AFRAME_GOLD,\n },\n },\n {\n id: 'hex-planter',\n prompt: [\n 'Write OpenSCAD source for a hexagonal planter pot.',\n 'Requirements:',\n '- a hollow hexagonal prism (6-sided), outer width ~50 units across, height ~45',\n '- open at the top, closed at the bottom (a cavity for soil)',\n '- a wall thickness around 3 units',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 3],\n bbox: { x: [40, 60], y: [40, 60], z: [40, 55] },\n minTriangles: 30,\n hollowBelow: 0.7,\n },\n gold: `\n$fn=6; or=25; h=45; t=3;\ndifference(){\n cylinder(h=h, r=or);\n translate([0,0,t]) cylinder(h=h, r=or-t);\n}\n`.trim(),\n },\n },\n]\n\nexport function createCadDesignAdapter(): BenchmarkAdapter {\n return {\n name: 'cad-design',\n\n async preflight() {\n try {\n await execFileAsync('xvfb-run', ['-a', 'openscad', '--version'], { timeout: 30_000 })\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(\n `cad-design preflight failed: ${msg}\\n` +\n `Fix: install OpenSCAD + Xvfb (Debian/Ubuntu: sudo apt-get install -y openscad xvfb). ` +\n `The judge runs \\`xvfb-run -a openscad -o out.stl model.scad\\` — both must be on PATH.`,\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let tasks = TASKS\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 return tasks.map((t): BenchTask => ({ id: t.id, prompt: t.prompt, metadata: t.meta as unknown as Record<string, unknown> }))\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = task.metadata as unknown as CadTaskMeta | undefined\n return meta?.gold\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const spec = (task.metadata as unknown as CadTaskMeta).spec\n const src = artifact.trim()\n if (!src) return { resolved: false, score: 0, detail: 'empty artifact' }\n\n const dir = await mkdtemp(join(tmpdir(), 'cad-'))\n const scad = join(dir, 'model.scad')\n const stlPath = join(dir, 'model.stl')\n const pngPath = join(dir, 'model.png')\n await writeFile(scad, src)\n\n // GATE 1: compile + export STL. Nonzero exit / CGAL error => does not compile.\n let stderr = ''\n try {\n const r = await openscad(['-o', stlPath, scad], dir)\n stderr = r.stderr\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { resolved: false, score: 0, detail: `compile failed: ${msg.slice(0, 300)}` }\n }\n\n // Render a PNG alongside (the artifact run-capsule animates). Non-fatal.\n try {\n await openscad(\n ['-o', pngPath, '--imgsize=1100,850', '--camera=40,30,40,55,0,25,260', '--colorscheme=Tomorrow', scad],\n dir,\n )\n } catch {\n /* render is for the reel; geometry gate already has the STL */\n }\n\n let stl: string\n try {\n stl = await readFile(stlPath, 'utf8')\n } catch {\n return { resolved: false, score: 0, detail: 'compiled but produced no STL (empty geometry)' }\n }\n const volumes = Number(/Volumes:\\s*(\\d+)/.exec(stderr)?.[1] ?? '1')\n const geo = measureStl(stl, volumes)\n const { checks, score } = scoreGeometry(geo, spec)\n const resolved = score === 1\n const detail = JSON.stringify({\n checks,\n geo: {\n triangles: geo.triangles,\n volumes: geo.volumes,\n bbox: { x: +geo.bbox.x.toFixed(1), y: +geo.bbox.y.toFixed(1), z: +geo.bbox.z.toFixed(1) },\n hollowRatio: +(geo.solidVolume / geo.bboxVolume).toFixed(3),\n topVsBaseFootprint: geo.baseFootprint ? +(geo.topFootprint / geo.baseFootprint).toFixed(3) : null,\n },\n renderPath: pngPath,\n stlPath,\n })\n return { resolved, score, detail }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,gBAAgB,UAAU,QAAQ;;AAoBxC,eAAe,SAAS,MAAgB,KAA0D;CAEhG,MAAM,EAAE,QAAQ,WAAW,MAAM,cAAc,YAAY;EAAC;EAAM;EAAY,GAAG;CAAI,GAAG;EACtF;EACA,WAAW,OAAO,OAAO;EACzB,SAAS;CACX,CAAC;CACD,OAAO;EAAE;EAAQ;CAAO;AAC1B;;AAeA,SAAS,WAAW,KAAa,mBAAqC;CACpE,MAAM,QAAyC,CAAC;CAChD,MAAM,OAA8F,CAAC;CACrG,MAAM,KAAK;CACX,IAAI;CACJ,MAAM,OAAwC,CAAC;CAC/C,OAAQ,IAAI,GAAG,KAAK,GAAG,GAAI,KAAK,KAAK;EAAC,OAAO,EAAE,EAAE;EAAG,OAAO,EAAE,EAAE;EAAG,OAAO,EAAE,EAAE;CAAC,CAAC;CAC/E,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,QAAQ,KAAK,GAAG,KAAK,K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;OAAE,GAAG,CAAC,IAAI,KAAK,EAAE,QAAQ,CAAC;OAAG,GAAG,CAAC,IAAI,KAAK,EAAE,QAAQ,CAAC;OAAG,GAAG,CAAC,IAAI,KAAK,EAAE,QAAQ,CAAC;MAAE;MACxF,aAAa,EAAE,IAAI,cAAc,IAAI,WAAA,CAAY,QAAQ,CAAC;MAC1D,oBAAoB,IAAI,gBAAgB,EAAE,IAAI,eAAe,IAAI,cAAA,CAAe,QAAQ,CAAC,IAAI;KAC/F;KACA,YAAY;KACZ;IACF,CAC+B;GAAE;EACnC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"cad-design.js","names":[],"sources":["../../src/benchmarks/cad-design.ts"],"sourcesContent":["/**\n * CAD-Design adapter. Worker artifact = OpenSCAD source (`.scad`). Judge = the\n * REAL OpenSCAD engine: compile + export STL, then measure the produced solid\n * geometry against the task's spec. Fully deterministic — the authoritative CAD\n * kernel is the gate, not an LLM and not the agent's own claim.\n *\n * This is verifiable-reward CAD: an agent is far better at *writing* exact\n * parametric code than at clicking a GUI, and the kernel either produces the\n * specified geometry or it doesn't. Every judged artifact also renders a PNG,\n * so a refine loop's attempts become a watchable \"model getting better\" reel\n * (run-capsule consumes the renders).\n *\n * Spec checks are geometric and ungameable:\n * - compiles : `openscad -o out.stl` exits 0 (hard gate)\n * - volumes : disconnected-solid count within [min,max]\n * - bbox : overall X/Y/Z extent within bounds (the thing is the right size)\n * - detail : triangle count ≥ floor (not a degenerate single cube)\n * - pitchedRoof : the top band's XY footprint NARROWS vs the base — a flat\n * box can't fake this; a real gabled/hipped roof tapers\n * - hollow : interior cavity present (walls, not a solid block) — the\n * bbox volume materially exceeds the printed solid volume\n *\n * Requires only `openscad` + `xvfb-run` on PATH (no venv, no Docker, no network).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\n\n/** Spec assertions a CAD task can require. All are deterministic + geometric. */\nexport interface CadSpec {\n volumes?: [number, number]\n bbox?: { x?: [number, number]; y?: [number, number]; z?: [number, number] }\n minTriangles?: number\n /** Top-band XY footprint must be < this fraction of the base footprint. */\n pitchedRoof?: number\n /** Printed solid volume must be < this fraction of the bbox volume (hollow). */\n hollowBelow?: number\n}\n\ninterface CadTaskMeta {\n spec: CadSpec\n /** A known-good .scad that satisfies the spec — the oracle for verify-judge. */\n gold: string\n}\n\n/** Run openscad with xvfb (it needs a GL context even headless). */\nasync function openscad(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> {\n // -a => auto-pick a free display; openscad writes Facets/Volumes to stderr.\n const { stdout, stderr } = await execFileAsync('xvfb-run', ['-a', 'openscad', ...args], {\n cwd,\n maxBuffer: 1024 * 1024 * 64,\n timeout: 120_000,\n })\n return { stdout, stderr }\n}\n\ninterface Geometry {\n triangles: number\n volumes: number\n bbox: { x: number; y: number; z: number }\n /** XY footprint area (extent_x * extent_y) of the bottom 60% and top 25% z-bands. */\n baseFootprint: number\n topFootprint: number\n /** Convex-ish solid volume estimate from the STL (sum of signed tetra volumes). */\n solidVolume: number\n bboxVolume: number\n}\n\n/** Parse an ASCII STL into the geometric measures the spec checks. Pure. */\nfunction measureStl(stl: string, volumesFromStderr: number): Geometry {\n const verts: Array<[number, number, number]> = []\n const tris: Array<[[number, number, number], [number, number, number], [number, number, number]]> = []\n const re = /vertex\\s+(-?[\\d.eE+]+)\\s+(-?[\\d.eE+]+)\\s+(-?[\\d.eE+]+)/g\n let m: RegExpExecArray | null\n const flat: Array<[number, number, number]> = []\n while ((m = re.exec(stl))) flat.push([Number(m[1]), Number(m[2]), Number(m[3])])\n for (let i = 0; i + 2 < flat.length; i += 3) tris.push([flat[i]!, flat[i + 1]!, flat[i + 2]!])\n for (const v of flat) verts.push(v)\n\n const xs = verts.map((v) => v[0])\n const ys = verts.map((v) => v[1])\n const zs = verts.map((v) => v[2])\n const min = (a: number[]) => Math.min(...a)\n const max = (a: number[]) => Math.max(...a)\n const minZ = min(zs)\n const maxZ = max(zs)\n const h = maxZ - minZ || 1\n\n // Footprint of a z-band = XY extent of the vertices within it.\n const footprint = (lo: number, hi: number): number => {\n const band = verts.filter((v) => v[2] >= minZ + lo * h && v[2] <= minZ + hi * h)\n if (band.length < 3) return 0\n const bx = band.map((v) => v[0])\n const by = band.map((v) => v[1])\n return (max(bx) - min(bx)) * (max(by) - min(by))\n }\n\n // Signed volume via the divergence theorem over triangles (|Σ v0·(v1×v2)/6|).\n let vol6 = 0\n for (const [a, b, c] of tris) {\n vol6 +=\n a[0] * (b[1] * c[2] - b[2] * c[1]) -\n a[1] * (b[0] * c[2] - b[2] * c[0]) +\n a[2] * (b[0] * c[1] - b[1] * c[0])\n }\n const bbox = { x: max(xs) - min(xs), y: max(ys) - min(ys), z: maxZ - minZ }\n return {\n triangles: tris.length,\n volumes: volumesFromStderr,\n bbox,\n baseFootprint: footprint(0, 0.6),\n topFootprint: footprint(0.75, 1),\n solidVolume: Math.abs(vol6) / 6,\n bboxVolume: bbox.x * bbox.y * bbox.z || 1,\n }\n}\n\nfunction inRange(v: number, [lo, hi]: [number, number]): boolean {\n return v >= lo && v <= hi\n}\n\n/** Score the geometry against the spec — each check is a named pass/fail. */\nfunction scoreGeometry(g: Geometry, spec: CadSpec): { checks: Record<string, boolean>; score: number } {\n const checks: Record<string, boolean> = {}\n if (spec.volumes) checks.volumes = inRange(g.volumes, spec.volumes)\n if (spec.minTriangles != null) checks.detail = g.triangles >= spec.minTriangles\n if (spec.bbox?.x) checks.bboxX = inRange(g.bbox.x, spec.bbox.x)\n if (spec.bbox?.y) checks.bboxY = inRange(g.bbox.y, spec.bbox.y)\n if (spec.bbox?.z) checks.bboxZ = inRange(g.bbox.z, spec.bbox.z)\n if (spec.pitchedRoof != null)\n checks.pitchedRoof = g.baseFootprint > 0 && g.topFootprint < spec.pitchedRoof * g.baseFootprint\n if (spec.hollowBelow != null) checks.hollow = g.solidVolume < spec.hollowBelow * g.bboxVolume\n const vals = Object.values(checks)\n const score = vals.length ? vals.filter(Boolean).length / vals.length : 0\n return { checks, score }\n}\n\n/** A parametric multi-story gabled building — the gold generator for the\n * building-family tasks. They share geometry (hollow stacked shells + a gabled\n * roof that tapers to a ridge + cut openings) and differ only in dimensions, so\n * one verified generator yields a spec-passing oracle for each. */\nfunction buildingGold(w: number, d: number, sh: number, ns: number, rh: number, t = 3): string {\n return `\nw=${w}; d=${d}; sh=${sh}; ns=${ns}; rh=${rh}; t=${t};\nmodule shell(w,d,h,t){ difference(){ cube([w,d,h]); translate([t,t,-1]) cube([w-2*t,d-2*t,h+2]); } }\nmodule roof(w,d,h){ rotate([90,0,90]) linear_extrude(height=w) polygon([[0,0],[d,0],[d/2,h]]); }\nunion(){\n for(s=[0:ns-1]) translate([0,0,s*sh]) shell(w,d,sh,t);\n for(s=[0:ns]) translate([0,0,s*sh-0.5]) cube([w,d,1]);\n translate([0,0,ns*sh]) roof(w,d,rh);\n for(s=[0:ns-1]) for(i=[0:floor((w-28)/22)]) translate([14+i*22,-1,s*sh+10]) cube([10,t+2,12]);\n translate([w/2-7,-1,2]) cube([14,t+2,20]);\n}\n`.trim()\n}\n\n/** Build a building-family task (prompt + spec + gold) from its dimensions.\n * The spec's bbox is derived from the dims with a ±~18% tolerance so the agent\n * must respect the brief's size; the gold (buildingGold) lands exactly on the\n * nominal dims, so it passes by construction. Keep rh > ns*sh/3 (else the roof\n * base sits inside the top-25% band and pitchedRoof fails). */\nfunction buildingTask(o: { id: string; desc: string; w: number; d: number; sh: number; ns: number; rh: number }): {\n id: string\n prompt: string\n meta: CadTaskMeta\n} {\n const { id, desc, w, d, sh, ns, rh } = o\n const totalWall = ns * sh\n const totalH = totalWall + rh\n const r = Math.round\n const spec: CadSpec = {\n volumes: [1, ns * 4 + 6],\n bbox: {\n x: [r(w * 0.82), r(w * 1.18)],\n y: [r(d * 0.82), r((d + 1) * 1.2)],\n z: [r(totalH * 0.82), r((totalH + 1) * 1.2)],\n },\n minTriangles: 50,\n pitchedRoof: 0.55,\n hollowBelow: 0.72,\n }\n const prompt = [\n `Write OpenSCAD source for ${desc}.`,\n 'Requirements:',\n `- footprint roughly ${w} (X) by ${d} (Y) units`,\n ns > 1 ? `- ${ns} stories, total wall height ~${totalWall} units` : `- one story, wall height ~${sh} units`,\n '- a PITCHED / gabled roof on top that tapers toward a ridge (NOT flat)',\n '- hollow shell (walls with an interior cavity), not a solid block',\n '- a door opening and several windows',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n')\n return { id, prompt, meta: { spec, gold: buildingGold(w, d, sh, ns, rh) } }\n}\n\n/** The building family — one parametric skill (hit the bbox + pitched roof +\n * hollow shell), sampled across footprints, heights, story counts, roof rises. */\nconst BUILDING_CONFIGS: Array<{ id: string; desc: string; w: number; d: number; sh: number; ns: number; rh: number }> = [\n { id: 'cottage', desc: 'a single-story cottage', w: 50, d: 40, sh: 30, ns: 1, rh: 18 },\n { id: 'cabin', desc: 'a small one-room cabin', w: 44, d: 36, sh: 26, ns: 1, rh: 22 },\n { id: 'bungalow', desc: 'a wide single-story bungalow', w: 70, d: 52, sh: 28, ns: 1, rh: 20 },\n { id: 'barn', desc: 'a long deep barn', w: 60, d: 96, sh: 42, ns: 1, rh: 26 },\n { id: 'warehouse', desc: 'a large warehouse', w: 110, d: 80, sh: 40, ns: 1, rh: 26 },\n { id: 'chapel', desc: 'a narrow tall chapel with a steep roof', w: 40, d: 72, sh: 48, ns: 1, rh: 34 },\n { id: 'farmhouse', desc: 'a two-story farmhouse', w: 72, d: 56, sh: 30, ns: 2, rh: 26 },\n { id: 'two-story-manor', desc: 'a wide two-story manor', w: 96, d: 64, sh: 32, ns: 2, rh: 28 },\n { id: 'townhouse', desc: 'a narrow three-story townhouse', w: 42, d: 52, sh: 30, ns: 3, rh: 34 },\n { id: 'watchtower', desc: 'a tall narrow three-story watchtower', w: 34, d: 34, sh: 30, ns: 3, rh: 32 },\n]\n\n/** A hollow cylindrical water tower with a conical roof — a non-box shape that\n * still exercises pitched-roof (the cone tapers to an apex) + hollow + bbox. */\nconst WATER_TOWER_GOLD = `\n$fn=48; r=24; bh=72; t=3; ch=26;\nunion(){\n difference(){ cylinder(h=bh, r=r); translate([0,0,t]) cylinder(h=bh, r=r-t); }\n translate([0,0,bh]) cylinder(h=ch, r1=r, r2=0);\n}\n`.trim()\n\n/** An A-frame: the steep roof IS the walls — a hollow triangular prism. The most\n * extreme taper in the set; tests that the agent can build a non-rectangular shell. */\nconst AFRAME_GOLD = `\nw=44; d=60; h=66; t=3;\nmodule tri(w,d,h){ rotate([90,0,90]) linear_extrude(height=w) polygon([[0,0],[d,0],[d/2,h]]); }\nunion(){\n difference(){ tri(w,d,h); translate([t,0,0]) tri(w-2*t,d,h-2*t*h/d); }\n translate([w/2-7,-1,0]) cube([14,t+2,24]);\n}\n`.trim()\n\nconst TASKS: Array<{ id: string; prompt: string; meta: CadTaskMeta }> = [\n {\n id: 'two-story-house',\n prompt: [\n 'Write OpenSCAD source for a two-story house.',\n 'Requirements:',\n '- footprint roughly 80 (X) by 60 (Y) units',\n '- two stories, total wall height ~68 units',\n '- a PITCHED / gabled roof on top (NOT a flat roof) — the roof must taper toward a ridge',\n '- hollow shell (walls with an interior cavity), not a solid block',\n '- at least one door opening and several windows',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 12],\n bbox: { x: [70, 110], y: [50, 80], z: [80, 130] },\n minTriangles: 60,\n pitchedRoof: 0.55,\n hollowBelow: 0.7,\n },\n gold: `\nw=80; d=60; sh=34; t=3; rh=28;\nmodule shell(w,d,h,t){ difference(){ cube([w,d,h]); translate([t,t,-1]) cube([w-2*t,d-2*t,h+2]); } }\nmodule roof(w,d,h){ translate([0,0,0]) rotate([90,0,90]) linear_extrude(height=w) polygon([[0,0],[d,0],[d/2,h]]); }\nunion(){\n for(s=[0,1]) translate([0,0,s*sh]) shell(w,d,sh,t);\n for(s=[0,1,2]) translate([0,0,s*sh-1]) cube([w,d,1]);\n translate([0,0,2*sh]) roof(w,d,rh);\n for(s=[0,1]) for(i=[0:2]) translate([16+i*22,-1,s*sh+10]) cube([12,t+2,14]);\n translate([w/2-8,-1,2]) cube([16,t+2,22]);\n}\n`.trim(),\n },\n },\n ...BUILDING_CONFIGS.map(buildingTask),\n {\n id: 'water-tower',\n prompt: [\n 'Write OpenSCAD source for a water tower: a tall hollow cylindrical tank with a conical roof.',\n 'Requirements:',\n '- a hollow cylindrical tank, ~48 units in diameter, ~72 units tall, with an interior cavity',\n '- a CONICAL roof on top that tapers to a point (a pitched roof)',\n '- wall thickness around 3 units',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 4],\n bbox: { x: [40, 56], y: [40, 56], z: [88, 110] },\n minTriangles: 60,\n pitchedRoof: 0.55,\n hollowBelow: 0.8,\n },\n gold: WATER_TOWER_GOLD,\n },\n },\n {\n id: 'a-frame-cabin',\n prompt: [\n 'Write OpenSCAD source for an A-frame cabin: a steep triangular shell where the roof forms the walls.',\n 'Requirements:',\n '- footprint roughly 44 (X) by 60 (Y) units',\n '- a STEEP triangular cross-section ~66 units tall that tapers to a ridge at the top',\n '- hollow inside (an interior cavity), not a solid wedge',\n '- a door opening at the front',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 4],\n bbox: { x: [36, 52], y: [50, 74], z: [56, 80] },\n minTriangles: 30,\n pitchedRoof: 0.45,\n hollowBelow: 0.8,\n },\n gold: AFRAME_GOLD,\n },\n },\n {\n id: 'hex-planter',\n prompt: [\n 'Write OpenSCAD source for a hexagonal planter pot.',\n 'Requirements:',\n '- a hollow hexagonal prism (6-sided), outer width ~50 units across, height ~45',\n '- open at the top, closed at the bottom (a cavity for soil)',\n '- a wall thickness around 3 units',\n 'Output ONLY the .scad source, no prose, no code fences.',\n ].join('\\n'),\n meta: {\n spec: {\n volumes: [1, 3],\n bbox: { x: [40, 60], y: [40, 60], z: [40, 55] },\n minTriangles: 30,\n hollowBelow: 0.7,\n },\n gold: `\n$fn=6; or=25; h=45; t=3;\ndifference(){\n cylinder(h=h, r=or);\n translate([0,0,t]) cylinder(h=h, r=or-t);\n}\n`.trim(),\n },\n },\n]\n\nexport function createCadDesignAdapter(): BenchmarkAdapter {\n return {\n name: 'cad-design',\n\n async preflight() {\n try {\n await execFileAsync('xvfb-run', ['-a', 'openscad', '--version'], { timeout: 30_000 })\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(\n `cad-design preflight failed: ${msg}\\n` +\n `Fix: install OpenSCAD + Xvfb (Debian/Ubuntu: sudo apt-get install -y openscad xvfb). ` +\n `The judge runs \\`xvfb-run -a openscad -o out.stl model.scad\\` — both must be on PATH.`,\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let tasks = TASKS\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 return tasks.map((t): BenchTask => ({ id: t.id, prompt: t.prompt, metadata: t.meta as unknown as Record<string, unknown> }))\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = task.metadata as unknown as CadTaskMeta | undefined\n return meta?.gold\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const spec = (task.metadata as unknown as CadTaskMeta).spec\n const src = artifact.trim()\n if (!src) return { resolved: false, score: 0, detail: 'empty artifact' }\n\n const dir = await mkdtemp(join(tmpdir(), 'cad-'))\n const scad = join(dir, 'model.scad')\n const stlPath = join(dir, 'model.stl')\n const pngPath = join(dir, 'model.png')\n await writeFile(scad, src)\n\n // GATE 1: compile + export STL. Nonzero exit / CGAL error => does not compile.\n let stderr = ''\n try {\n const r = await openscad(['-o', stlPath, scad], dir)\n stderr = r.stderr\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { resolved: false, score: 0, detail: `compile failed: ${msg.slice(0, 300)}` }\n }\n\n // Render a PNG alongside (the artifact run-capsule animates). Non-fatal.\n try {\n await openscad(\n ['-o', pngPath, '--imgsize=1100,850', '--camera=40,30,40,55,0,25,260', '--colorscheme=Tomorrow', scad],\n dir,\n )\n } catch {\n /* render is for the reel; geometry gate already has the STL */\n }\n\n let stl: string\n try {\n stl = await readFile(stlPath, 'utf8')\n } catch {\n return { resolved: false, score: 0, detail: 'compiled but produced no STL (empty geometry)' }\n }\n const volumes = Number(/Volumes:\\s*(\\d+)/.exec(stderr)?.[1] ?? '1')\n const geo = measureStl(stl, volumes)\n const { checks, score } = scoreGeometry(geo, spec)\n const resolved = score === 1\n const detail = JSON.stringify({\n checks,\n geo: {\n triangles: geo.triangles,\n volumes: geo.volumes,\n bbox: { x: +geo.bbox.x.toFixed(1), y: +geo.bbox.y.toFixed(1), z: +geo.bbox.z.toFixed(1) },\n hollowRatio: +(geo.solidVolume / geo.bboxVolume).toFixed(3),\n topVsBaseFootprint: geo.baseFootprint ? +(geo.topFootprint / geo.baseFootprint).toFixed(3) : null,\n },\n renderPath: pngPath,\n stlPath,\n })\n return { resolved, score, detail }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,gBAAgB,UAAU,QAAQ;;AAoBxC,eAAe,SAAS,MAAgB,KAA0D;CAEhG,MAAM,EAAE,QAAQ,WAAW,MAAM,cAAc,YAAY;EAAC;EAAM;EAAY,GAAG;CAAI,GAAG;EACtF;EACA,WAAW;EACX,SAAS;CACX,CAAC;CACD,OAAO;EAAE;EAAQ;CAAO;AAC1B;;AAeA,SAAS,WAAW,KAAa,mBAAqC;CACpE,MAAM,QAAyC,CAAC;CAChD,MAAM,OAA8F,CAAC;CACrG,MAAM,KAAK;CACX,IAAI;CACJ,MAAM,OAAwC,CAAC;CAC/C,OAAQ,IAAI,GAAG,KAAK,GAAG,GA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O;GACnC,MAAM,EAAE,QAAQ,UAAU,cAAc,KAAK,IAAI;GAcjD,OAAO;IAAE,UAbQ,UAAU;IAaR;IAAO,QAZX,KAAK,UAAU;KAC5B;KACA,KAAK;MACH,WAAW,IAAI;MACf,SAAS,IAAI;MACb,MAAM;OAAE,GAAG,CAAC,IAAI,KAAK,EAAE,QAAQ,CAAC;OAAG,GAAG,CAAC,IAAI,KAAK,EAAE,QAAQ,CAAC;OAAG,GAAG,CAAC,IAAI,KAAK,EAAE,QAAQ,CAAC;MAAE;MACxF,aAAa,EAAE,IAAI,cAAc,IAAI,WAAA,CAAY,QAAQ,CAAC;MAC1D,oBAAoB,IAAI,gBAAgB,EAAE,IAAI,eAAe,IAAI,cAAA,CAAe,QAAQ,CAAC,IAAI;KAC/F;KACA,YAAY;KACZ;IACF,CAC+B;GAAE;EACnC;CACF;AACF"}
|
|
@@ -1,6 +1,3 @@
|
|
|
1
1
|
import { BenchmarkAdapter } from "./types.js";
|
|
2
|
-
|
|
3
|
-
declare function createCadBenchAdapter(): BenchmarkAdapter;
|
|
4
|
-
//#endregion
|
|
5
|
-
export { createCadBenchAdapter };
|
|
2
|
+
export declare function createCadBenchAdapter(): BenchmarkAdapter;
|
|
6
3
|
//# sourceMappingURL=cadbench.d.ts.map
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { createCadBenchAdapter };
|
|
1
|
+
export { t as createCadBenchAdapter } from "../cadbench-DhAndllg.js";
|
|
@@ -1,6 +1,3 @@
|
|
|
1
1
|
import { BenchmarkAdapter } from "./types.js";
|
|
2
|
-
|
|
3
|
-
declare function createCadGenBenchAdapter(): BenchmarkAdapter;
|
|
4
|
-
//#endregion
|
|
5
|
-
export { createCadGenBenchAdapter };
|
|
2
|
+
export declare function createCadGenBenchAdapter(): BenchmarkAdapter;
|
|
6
3
|
//# sourceMappingURL=cadgenbench.d.ts.map
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { createCadGenBenchAdapter };
|
|
1
|
+
export { t as createCadGenBenchAdapter } from "../cadgenbench-Tvk16YKT.js";
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import { BenchmarkAdapter } from "./types.js";
|
|
2
2
|
import { OutputAdapter } from "@tangle-network/agent-runtime/kernel";
|
|
3
|
-
//#region src/benchmarks/commit0.d.ts
|
|
4
3
|
/** Reuse the SWE patch extractor shape: last fenced diff/patch, else raw text. */
|
|
5
|
-
declare const commit0DiffOutput: OutputAdapter<string>;
|
|
6
|
-
declare function createCommit0Adapter(): BenchmarkAdapter;
|
|
7
|
-
//#endregion
|
|
8
|
-
export { commit0DiffOutput, createCommit0Adapter };
|
|
4
|
+
export declare const commit0DiffOutput: OutputAdapter<string>;
|
|
5
|
+
export declare function createCommit0Adapter(): BenchmarkAdapter;
|
|
9
6
|
//# sourceMappingURL=commit0.d.ts.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { benchRoot, preflightVenvImports, runVenvScriptStdin, venvPythonAt } from "./_harness.js";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
|
|
4
|
+
// src/benchmarks/commit0.ts
|
|
5
5
|
/**
|
|
6
6
|
* Commit0 adapter (wentingzhao/commit0_combined) — implement-a-library-from-scratch.
|
|
7
7
|
* Each record is a Python repo stubbed at `base_commit` (public function bodies
|
|
@@ -182,7 +182,6 @@ function createCommit0Adapter() {
|
|
|
182
182
|
}
|
|
183
183
|
};
|
|
184
184
|
}
|
|
185
|
-
//#endregion
|
|
186
185
|
export { commit0DiffOutput, createCommit0Adapter };
|
|
187
186
|
|
|
188
187
|
//# sourceMappingURL=commit0.js.map
|
|
@@ -1,6 +1,3 @@
|
|
|
1
1
|
import { BenchmarkAdapter } from "./types.js";
|
|
2
|
-
|
|
3
|
-
declare function createCragAdapter(): BenchmarkAdapter;
|
|
4
|
-
//#endregion
|
|
5
|
-
export { createCragAdapter };
|
|
2
|
+
export declare function createCragAdapter(): BenchmarkAdapter;
|
|
6
3
|
//# sourceMappingURL=crag.d.ts.map
|
package/dist/benchmarks/crag.js
CHANGED
|
@@ -2,7 +2,7 @@ import { benchRoot } from "./_harness.js";
|
|
|
2
2
|
import { FINAL_ANSWER_SENTINEL, allStrings, answerScoreToBenchScore, firstString, isObject, ragAnswerOutput, readJsonRows, scoreAnswerArtifact, selectTasks, stringFrom } from "./rag-shared.js";
|
|
3
3
|
import { readFile } from "node:fs/promises";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
|
|
5
|
+
// src/benchmarks/crag.ts
|
|
6
6
|
/**
|
|
7
7
|
* CRAG adapter (Comprehensive RAG Benchmark).
|
|
8
8
|
*
|
|
@@ -96,7 +96,8 @@ function createCragAdapter() {
|
|
|
96
96
|
},
|
|
97
97
|
async judge(task, artifact) {
|
|
98
98
|
const meta = readMeta(task);
|
|
99
|
-
|
|
99
|
+
const score = scoreAnswerArtifact(artifact, meta.goldAnswers);
|
|
100
|
+
return answerScoreToBenchScore(score, {
|
|
100
101
|
benchmark: meta.benchmark,
|
|
101
102
|
domain: meta.domain,
|
|
102
103
|
questionType: meta.questionType,
|
|
@@ -105,7 +106,6 @@ function createCragAdapter() {
|
|
|
105
106
|
}
|
|
106
107
|
};
|
|
107
108
|
}
|
|
108
|
-
//#endregion
|
|
109
109
|
export { createCragAdapter };
|
|
110
110
|
|
|
111
111
|
//# sourceMappingURL=crag.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crag.js","names":[],"sources":["../../src/benchmarks/crag.ts"],"sourcesContent":["/**\n * CRAG adapter (Comprehensive RAG Benchmark).\n *\n * Live mode expects an official or compatible CRAG JSON/JSONL export. The\n * adapter preserves CRAG domain/type/dynamism tags in metadata and scores final\n * answers deterministically against the provided gold answer list.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { benchRoot } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\nimport {\n FINAL_ANSWER_SENTINEL,\n allStrings,\n answerScoreToBenchScore,\n firstString,\n isObject,\n ragAnswerOutput,\n readJsonRows,\n scoreAnswerArtifact,\n selectTasks,\n stringFrom,\n} from './rag-shared'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'crag.json')\n\ninterface CragMeta {\n benchmark: 'crag'\n query: string\n goldAnswers: string[]\n domain: string\n questionType: string\n dynamism: string\n}\n\nconst dataFile = (): string | undefined => process.env.CRAG_DATA_FILE\n\nfunction rowToTask(raw: unknown, index: number): BenchTask {\n if (!isObject(raw)) throw new Error(`CRAG row ${index} must be an object`)\n const query = firstString(raw, ['query', 'question', 'prompt'])\n const goldAnswers = allStrings(raw, ['answer', 'answers', 'gold', 'gold_answer', 'expected_answer'])\n if (!query) throw new Error(`CRAG row ${index} missing query`)\n if (goldAnswers.length === 0) throw new Error(`CRAG row ${index} missing gold answer`)\n const domain = stringFrom(raw.domain) ?? 'unknown'\n const questionType = stringFrom(raw.question_type) ?? stringFrom(raw.questionType) ?? 'unknown'\n const dynamism = stringFrom(raw.static_or_dynamic) ?? stringFrom(raw.dynamism) ?? 'unknown'\n const id = stringFrom(raw.id) ?? stringFrom(raw.query_id) ?? `crag-${index}`\n const meta: CragMeta = {\n benchmark: 'crag',\n query,\n goldAnswers,\n domain,\n questionType,\n dynamism,\n }\n return {\n id,\n split: stringFrom(raw.split) ?? domain,\n prompt: [\n 'Answer this CRAG factual question.',\n 'Return a concise answer and do not guess when the evidence is insufficient.',\n 'End with a single final line: `FINAL ANSWER: <answer>`.',\n '',\n `Question: ${query}`,\n `Domain: ${domain}`,\n `Question type: ${questionType}`,\n `Dynamism: ${dynamism}`,\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): CragMeta {\n const md = task.metadata\n if (!md || !Array.isArray(md.goldAnswers)) {\n throw new Error(`CRAG task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as CragMeta\n}\n\nasync function loadRows(path: string): Promise<unknown[]> {\n const rows = await readJsonRows(path)\n if (rows.length === 0) throw new Error(`CRAG: no rows in ${path}`)\n return rows\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as unknown[]\n console.warn(`[crag] CRAG_FIXTURES=1 — loading ${rows.length} adapter fixtures`)\n return selectTasks(rows.map(rowToTask), opts, 'CRAG')\n}\n\nexport function createCragAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.CRAG_FIXTURES === '1'\n\n return {\n name: 'crag',\n output: ragAnswerOutput,\n\n async preflight() {\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8')\n return\n }\n const path = dataFile()\n if (!path) {\n throw new Error(\n 'CRAG_DATA_FILE is required. Fix: export facebookresearch/CRAG rows to JSONL and set CRAG_DATA_FILE=/path/to/crag.jsonl, or set CRAG_FIXTURES=1 for adapter plumbing.',\n )\n }\n await loadRows(path)\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const path = dataFile()\n if (!path) throw new Error('CRAG_DATA_FILE is required to load CRAG tasks')\n return selectTasks((await loadRows(path)).map(rowToTask), opts, 'CRAG')\n },\n\n async goldArtifact(task: BenchTask) {\n return `${FINAL_ANSWER_SENTINEL} ${readMeta(task).goldAnswers[0] ?? ''}`\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const score = scoreAnswerArtifact(artifact, meta.goldAnswers)\n return answerScoreToBenchScore(score, {\n benchmark: meta.benchmark,\n domain: meta.domain,\n questionType: meta.questionType,\n dynamism: meta.dynamism,\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,MAAM,WAAW,KAAK,WAAW,YAAY,WAAW;AAWxD,MAAM,iBAAqC,QAAQ,IAAI;AAEvD,SAAS,UAAU,KAAc,OAA0B;CACzD,IAAI,CAAC,SAAS,GAAG,GAAG,MAAM,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O,kBAAkB;CAC/E,OAAO,YAAY,KAAK,IAAI,SAAS,GAAG,MAAM,MAAM;AACtD;AAEA,SAAgB,oBAAsC;CACpD,MAAM,eAAe,QAAQ,IAAI,kBAAkB;CAEnD,OAAO;EACL,MAAM;EACN,QAAQ;EAER,MAAM,YAAY;GAChB,IAAI,cAAc;IAChB,MAAM,SAAS,UAAU,MAAM;IAC/B;GACF;GACA,MAAM,OAAO,SAAS;GACtB,IAAI,CAAC,MACH,MAAM,IAAI,MACR,sKACF;GAEF,MAAM,SAAS,IAAI;EACrB;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,MAAM,OAAO,SAAS;GACtB,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,+CAA+C;GAC1E,OAAO,aAAa,MAAM,SAAS,IAAI,EAAA,CAAG,IAAI,SAAS,GAAG,MAAM,MAAM;EACxE;EAEA,MAAM,aAAa,MAAiB;GAClC,OAAO,GAAG,sBAAsB,GAAG,SAAS,IAAI,CAAC,CAAC,YAAY,MAAM;EACtE;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;
|
|
1
|
+
{"version":3,"file":"crag.js","names":[],"sources":["../../src/benchmarks/crag.ts"],"sourcesContent":["/**\n * CRAG adapter (Comprehensive RAG Benchmark).\n *\n * Live mode expects an official or compatible CRAG JSON/JSONL export. The\n * adapter preserves CRAG domain/type/dynamism tags in metadata and scores final\n * answers deterministically against the provided gold answer list.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { benchRoot } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\nimport {\n FINAL_ANSWER_SENTINEL,\n allStrings,\n answerScoreToBenchScore,\n firstString,\n isObject,\n ragAnswerOutput,\n readJsonRows,\n scoreAnswerArtifact,\n selectTasks,\n stringFrom,\n} from './rag-shared'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'crag.json')\n\ninterface CragMeta {\n benchmark: 'crag'\n query: string\n goldAnswers: string[]\n domain: string\n questionType: string\n dynamism: string\n}\n\nconst dataFile = (): string | undefined => process.env.CRAG_DATA_FILE\n\nfunction rowToTask(raw: unknown, index: number): BenchTask {\n if (!isObject(raw)) throw new Error(`CRAG row ${index} must be an object`)\n const query = firstString(raw, ['query', 'question', 'prompt'])\n const goldAnswers = allStrings(raw, ['answer', 'answers', 'gold', 'gold_answer', 'expected_answer'])\n if (!query) throw new Error(`CRAG row ${index} missing query`)\n if (goldAnswers.length === 0) throw new Error(`CRAG row ${index} missing gold answer`)\n const domain = stringFrom(raw.domain) ?? 'unknown'\n const questionType = stringFrom(raw.question_type) ?? stringFrom(raw.questionType) ?? 'unknown'\n const dynamism = stringFrom(raw.static_or_dynamic) ?? stringFrom(raw.dynamism) ?? 'unknown'\n const id = stringFrom(raw.id) ?? stringFrom(raw.query_id) ?? `crag-${index}`\n const meta: CragMeta = {\n benchmark: 'crag',\n query,\n goldAnswers,\n domain,\n questionType,\n dynamism,\n }\n return {\n id,\n split: stringFrom(raw.split) ?? domain,\n prompt: [\n 'Answer this CRAG factual question.',\n 'Return a concise answer and do not guess when the evidence is insufficient.',\n 'End with a single final line: `FINAL ANSWER: <answer>`.',\n '',\n `Question: ${query}`,\n `Domain: ${domain}`,\n `Question type: ${questionType}`,\n `Dynamism: ${dynamism}`,\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): CragMeta {\n const md = task.metadata\n if (!md || !Array.isArray(md.goldAnswers)) {\n throw new Error(`CRAG task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as CragMeta\n}\n\nasync function loadRows(path: string): Promise<unknown[]> {\n const rows = await readJsonRows(path)\n if (rows.length === 0) throw new Error(`CRAG: no rows in ${path}`)\n return rows\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as unknown[]\n console.warn(`[crag] CRAG_FIXTURES=1 — loading ${rows.length} adapter fixtures`)\n return selectTasks(rows.map(rowToTask), opts, 'CRAG')\n}\n\nexport function createCragAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.CRAG_FIXTURES === '1'\n\n return {\n name: 'crag',\n output: ragAnswerOutput,\n\n async preflight() {\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8')\n return\n }\n const path = dataFile()\n if (!path) {\n throw new Error(\n 'CRAG_DATA_FILE is required. Fix: export facebookresearch/CRAG rows to JSONL and set CRAG_DATA_FILE=/path/to/crag.jsonl, or set CRAG_FIXTURES=1 for adapter plumbing.',\n )\n }\n await loadRows(path)\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const path = dataFile()\n if (!path) throw new Error('CRAG_DATA_FILE is required to load CRAG tasks')\n return selectTasks((await loadRows(path)).map(rowToTask), opts, 'CRAG')\n },\n\n async goldArtifact(task: BenchTask) {\n return `${FINAL_ANSWER_SENTINEL} ${readMeta(task).goldAnswers[0] ?? ''}`\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const score = scoreAnswerArtifact(artifact, meta.goldAnswers)\n return answerScoreToBenchScore(score, {\n benchmark: meta.benchmark,\n domain: meta.domain,\n questionType: meta.questionType,\n dynamism: meta.dynamism,\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,MAAM,WAAW,KAAK,WAAW,YAAY,WAAW;AAWxD,MAAM,iBAAqC,QAAQ,IAAI;AAEvD,SAAS,UAAU,KAAc,OAA0B;CACzD,IAAI,CAAC,SAAS,GAAG,GAAG,MAAM,IAAI,MAAM,YAAY,MAAM,mBAAmB;CACzE,MAAM,QAAQ,YAAY,KAAK;EAAC;EAAS;EAAY;CAAQ,CAAC;CAC9D,MAAM,cAAc,WAAW,KAAK;EAAC;EAAU;EAAW;EAAQ;EAAe;CAAi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QAAQ;EAER,MAAM,YAAY;GAChB,IAAI,cAAc;IAChB,MAAM,SAAS,UAAU,MAAM;IAC/B;GACF;GACA,MAAM,OAAO,SAAS;GACtB,IAAI,CAAC,MACH,MAAM,IAAI,MACR,sKACF;GAEF,MAAM,SAAS,IAAI;EACrB;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,MAAM,OAAO,SAAS;GACtB,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,+CAA+C;GAC1E,OAAO,aAAa,MAAM,SAAS,IAAI,EAAA,CAAG,IAAI,SAAS,GAAG,MAAM,MAAM;EACxE;EAEA,MAAM,aAAa,MAAiB;GAClC,OAAO,GAAG,sBAAsB,GAAG,SAAS,IAAI,CAAC,CAAC,YAAY,MAAM;EACtE;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,MAAM,QAAQ,oBAAoB,UAAU,KAAK,WAAW;GAC5D,OAAO,wBAAwB,OAAO;IACpC,WAAW,KAAK;IAChB,QAAQ,KAAK;IACb,cAAc,KAAK;IACnB,UAAU,KAAK;GACjB,CAAC;EACH;CACF;AACF"}
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { BenchmarkAdapter } from "./types.js";
|
|
2
2
|
import { OutputAdapter } from "@tangle-network/agent-runtime/kernel";
|
|
3
|
-
|
|
4
|
-
declare
|
|
5
|
-
declare function createDabstepAdapter(): BenchmarkAdapter;
|
|
6
|
-
//#endregion
|
|
7
|
-
export { createDabstepAdapter, dabstepAnswerOutput };
|
|
3
|
+
export declare const dabstepAnswerOutput: OutputAdapter<string>;
|
|
4
|
+
export declare function createDabstepAdapter(): BenchmarkAdapter;
|
|
8
5
|
//# sourceMappingURL=dabstep.d.ts.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { benchRoot, runVenvPython, runVenvScriptStdin } from "./_harness.js";
|
|
2
2
|
import { access, readFile, stat } from "node:fs/promises";
|
|
3
3
|
import { isAbsolute, join } from "node:path";
|
|
4
|
-
|
|
4
|
+
// src/benchmarks/dabstep.ts
|
|
5
5
|
/**
|
|
6
6
|
* DABStep adapter (EnvCommons/DABStep) — data-analysis questions over synthetic
|
|
7
7
|
* payment files. Worker artifact = final answer text. Judge = the official
|
|
@@ -160,7 +160,7 @@ function createDabstepAdapter() {
|
|
|
160
160
|
async preflight() {
|
|
161
161
|
if (fixturesMode) return;
|
|
162
162
|
const dir = dabstepDir();
|
|
163
|
-
if (!dir) throw new Error("DABSTEP_DIR is required. Fix: clone https://github.com/EnvCommons/DABStep and set DABSTEP_DIR=/path/to/DABStep.
|
|
163
|
+
if (!dir) throw new Error("DABSTEP_DIR is required. Fix: clone https://github.com/EnvCommons/DABStep and set DABSTEP_DIR=/path/to/DABStep. " + datasetAcquisitionHint);
|
|
164
164
|
await assertOfficialFiles(dir, DEFAULT_SPLIT);
|
|
165
165
|
await loadOfficialTasks(dir, { limit: 1 }, DEFAULT_SPLIT);
|
|
166
166
|
},
|
|
@@ -200,7 +200,6 @@ function createDabstepAdapter() {
|
|
|
200
200
|
}
|
|
201
201
|
};
|
|
202
202
|
}
|
|
203
|
-
//#endregion
|
|
204
203
|
export { createDabstepAdapter, dabstepAnswerOutput };
|
|
205
204
|
|
|
206
205
|
//# sourceMappingURL=dabstep.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dabstep.js","names":[],"sources":["../../src/benchmarks/dabstep.ts"],"sourcesContent":["/**\n * DABStep adapter (EnvCommons/DABStep) — data-analysis questions over synthetic\n * payment files. Worker artifact = final answer text. Judge = the official\n * DABStep `grade.py` normalization/matching function. No LLM judge.\n *\n * Live tasks require `DABSTEP_DIR` pointing at an official DABStep checkout\n * (https://github.com/EnvCommons/DABStep) for `splits/*.txt`, `files/*`, and\n * `grade.py`, plus the released `dataset.csv` task rows — beside the checkout\n * or anywhere via `DABSTEP_DATASET_CSV`. The checkout does not ship\n * `dataset.csv`; see the preflight error text for where the rows come from.\n * The adapter exposes `metadata.resourceRoot` so runners can mount the\n * benchmark files into AgentProfile.resources.files; it does not paste the\n * dataset into prompt text.\n */\n\nimport { isAbsolute, join } from 'node:path'\nimport { access, readFile, stat } from 'node:fs/promises'\nimport type { OutputAdapter } from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot, runVenvPython, runVenvScriptStdin } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'dabstep.json')\nconst DEFAULT_SPLIT = 'easy'\n\ninterface DabstepFixtureRow {\n task_id: number\n instructions: string\n all_golds_by_task: Array<Record<string, unknown>>\n}\n\ninterface DabstepMeta {\n taskId: number\n split: string\n golds: Array<Record<string, unknown>>\n resourceRoot?: string\n}\n\nconst dabstepDir = (): string | undefined => process.env.DABSTEP_DIR\nconst gradeFile = (dir: string): string => join(dir, 'grade.py')\nconst resourceRoot = (dir: string): string => join(dir, 'files')\n\n/**\n * Where the released task rows come from. The EnvCommons/DABStep git checkout\n * carries grade.py, splits/, and files/ but not dataset.csv: the row file\n * (task_id,question,guidelines,all_golds_by_task) ships with the OpenReward\n * DABStep environment, mounted at /orwd_data/dataset.csv on that platform.\n * The public https://huggingface.co/datasets/adyen/DABstep release holds the\n * same task rows without golds (data/tasks/all.jsonl; answers withheld for the\n * leaderboard) and a 10-task dev split with reference answers\n * (data/tasks/dev.jsonl).\n */\nconst datasetAcquisitionHint =\n 'The DABStep checkout ships grade.py, splits/, and files/ but not dataset.csv. ' +\n 'dataset.csv (task_id,question,guidelines,all_golds_by_task) is distributed with the OpenReward DABStep environment ' +\n '(mounted at /orwd_data/dataset.csv on that platform); the public https://huggingface.co/datasets/adyen/DABstep release ' +\n 'carries the task rows without golds (data/tasks/all.jsonl) and a 10-task dev split with reference answers (data/tasks/dev.jsonl). ' +\n 'Place dataset.csv beside the checkout, or point DABSTEP_DATASET_CSV at it.'\n\n/** The released row file: `<dir>/dataset.csv`, or the `DABSTEP_DATASET_CSV` override so checkout and export can live apart. */\nfunction datasetFile(dir: string): string {\n const override = process.env.DABSTEP_DATASET_CSV\n if (override === undefined) return join(dir, 'dataset.csv')\n if (!isAbsolute(override)) throw new Error('DABSTEP_DATASET_CSV must be an absolute path')\n return override\n}\n\nasync function assertFile(path: string, label: string): Promise<void> {\n try {\n await access(path)\n } catch (err) {\n throw new Error(`DABStep: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nasync function assertOfficialFiles(dir: string, split: string): Promise<void> {\n const dataset = datasetFile(dir)\n try {\n await access(dataset)\n } catch (err) {\n throw new Error(\n `DABStep: missing released dataset.csv at ${dataset} (${err instanceof Error ? err.message : err}). ${datasetAcquisitionHint}`,\n )\n }\n await assertFile(join(dir, 'splits', `${split}.txt`), `${split} split file`)\n await assertFile(gradeFile(dir), 'official grade.py')\n const files = resourceRoot(dir)\n try {\n const s = await stat(files)\n if (!s.isDirectory()) throw new Error('not a directory')\n } catch (err) {\n throw new Error(`DABStep: missing benchmark files directory at ${files} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nexport const dabstepAnswerOutput: 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|answer)?\\s*\\n([\\s\\S]*?)```/g)]\n return (fences.at(-1)?.[1] ?? text).trim()\n },\n}\n\nfunction rowToTask(row: DabstepFixtureRow, split: string, dir?: string): BenchTask {\n const meta: DabstepMeta = {\n taskId: row.task_id,\n split,\n golds: row.all_golds_by_task,\n ...(dir ? { resourceRoot: resourceRoot(dir) } : {}),\n }\n return {\n id: String(row.task_id),\n split,\n prompt: [\n 'Solve this DABStep data-analysis task using the mounted payment files.',\n 'Use code or shell commands as needed, then return only the final answer.',\n '',\n row.instructions,\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): DabstepMeta {\n const md = task.metadata\n if (!md || typeof md.taskId !== 'number' || !Array.isArray(md.golds)) {\n throw new Error(`dabstep task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as DabstepMeta\n}\n\nfunction selectRows(rows: DabstepFixtureRow[], opts: LoadOptions, split: string, dir?: string): BenchTask[] {\n let tasks = rows.map((row) => rowToTask(row, split, dir))\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(`DABStep: no tasks matched ${JSON.stringify(opts)} for split=${split}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions, split: string): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as DabstepFixtureRow[]\n console.warn(`[dabstep] DABSTEP_FIXTURES=1 — loading ${rows.length} adapter fixtures from ${FIXTURES}`)\n return selectRows(rows, opts, split)\n}\n\nasync function loadOfficialTasks(dir: string, opts: LoadOptions, split: string): Promise<BenchTask[]> {\n const script = `\nimport ast, csv, json, sys\nfrom pathlib import Path\n\nroot = Path(sys.argv[1])\nsplit = sys.argv[2]\nlimit = None if sys.argv[3] == \"\" else int(sys.argv[3])\nids = set(json.loads(sys.argv[4]))\ndataset = Path(sys.argv[5])\nsplit_file = root / \"splits\" / f\"{split}.txt\"\nif not dataset.exists():\n raise SystemExit(f\"missing official DABStep dataset.csv at {dataset}; the checkout does not ship it — see the adapter preflight error for acquisition\")\nif not split_file.exists():\n raise SystemExit(f\"missing official DABStep split file at {split_file}\")\nsplit_ids = {int(line.strip()) for line in split_file.read_text().splitlines() if line.strip()}\nout = []\nwith dataset.open(newline=\"\") as f:\n for row in csv.DictReader(f):\n task_id = int(row[\"task_id\"])\n if task_id not in split_ids:\n continue\n if ids and str(task_id) not in ids:\n continue\n out.append({\n \"task_id\": task_id,\n \"instructions\": f\"{row['question']}\\\\n{row['guidelines']}\",\n \"all_golds_by_task\": ast.literal_eval(str(row[\"all_golds_by_task\"])),\n })\n if limit is not None and len(out) >= limit:\n break\nif not out:\n raise SystemExit(f\"no DABStep rows matched split={split} ids={sorted(ids)} limit={limit}\")\nprint(json.dumps(out))\n`\n const stdout = await runVenvPython(script, [\n dir,\n split,\n opts.limit === undefined ? '' : String(opts.limit),\n JSON.stringify(opts.ids ?? []),\n datasetFile(dir),\n ])\n return selectRows(JSON.parse(stdout) as DabstepFixtureRow[], opts, split, dir)\n}\n\nexport function createDabstepAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.DABSTEP_FIXTURES === '1'\n\n return {\n name: 'dabstep',\n output: dabstepAnswerOutput,\n\n async preflight() {\n if (fixturesMode) return\n const dir = dabstepDir()\n if (!dir) {\n throw new Error(\n 'DABSTEP_DIR is required. Fix: clone https://github.com/EnvCommons/DABStep and set DABSTEP_DIR=/path/to/DABStep. ' +\n datasetAcquisitionHint,\n )\n }\n await assertOfficialFiles(dir, DEFAULT_SPLIT)\n await loadOfficialTasks(dir, { limit: 1 }, DEFAULT_SPLIT)\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n const split = opts.split ?? DEFAULT_SPLIT\n if (fixturesMode) return loadFixtures(opts, split)\n const dir = dabstepDir()\n if (!dir) throw new Error('DABSTEP_DIR is required to load official DABStep tasks')\n return loadOfficialTasks(dir, opts, split)\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n const first = meta.golds[0]\n if (!first) return undefined\n const value = first.value\n return value === undefined ? undefined : String(value)\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const dir = dabstepDir()\n if (!dir) throw new Error('DABSTEP_DIR is required to judge DABStep tasks with the official grade.py')\n const stdout = await runVenvScriptStdin(\n join(benchRoot, 'scripts', 'dabstep_judge.py'),\n ['--grade-file', gradeFile(dir)],\n JSON.stringify({ prediction: artifact, golds: meta.golds }),\n { cwd: benchRoot },\n )\n const report = JSON.parse(stdout.trim().split('\\n').at(-1) ?? '{}') as { correct?: boolean; score?: number; error?: string }\n if (report.error) throw new Error(`DABStep judge error for ${task.id}: ${report.error}`)\n const score = typeof report.score === 'number' ? report.score : 0\n return {\n resolved: report.correct === true,\n score,\n detail: JSON.stringify({ taskId: meta.taskId, split: meta.split, correct: report.correct }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,MAAM,WAAW,KAAK,WAAW,YAAY,cAAc;AAC3D,MAAM,gBAAgB;AAetB,MAAM,mBAAuC,QAAQ,IAAI;AACzD,MAAM,aAAa,QAAwB,KAAK,KAAK,UAAU;AAC/D,MAAM,gBAAgB,QAAwB,KAAK,KAAK,OAAO;;;;;;;;;;;AAY/D,MAAM,yBACJ;;AAOF,SAAS,YAAY,KAAqB;CACxC,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,KAAA,GAAW,OAAO,KAAK,KAAK,aAAa;CAC1D,IAAI,CAAC,WAAW,QAAQ,GAAG,MAAM,IAAI,MAAM,8CAA8C;CACzF,OAAO;AACT;AAEA,eAAe,WAAW,MAAc,OAA8B;CACpE,IAAI;EACF,MAAM,OAAO,IAAI;CACnB,SAAS,KAAK;EACZ,MAAM,IAAI,MAAM,oBAAoB,MAAM,MAAM,KAAK,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,EAAE;CACtG;AACF;AAEA,eAAe,oBAAoB,KAAa,OAA8B;CAC5E,MAAM,UAAU,YAAY,GAAG;CAC/B,IAAI;EACF,MAAM,OAAO,OAAO;CACtB,SAAS,KAAK;EACZ,MAAM,IAAI,MACR,4CAA4C,QAAQ,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,KAAK,wBACxG;CACF;CACA,MAAM,WAAW,KAAK,KAAK,UAAU,GAAG,MAAM,KAAK,GAAG,GAAG,MAAM,YAAY;CAC3E,MAAM,WAAW,U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AAM,KAAK;GACjD,MAAM,MAAM,WAAW;GACvB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,wDAAwD;GAClF,OAAO,kBAAkB,KAAK,MAAM,KAAK;EAC3C;EAEA,MAAM,aAAa,MAAiB;GAElC,MAAM,QADO,SAAS,IACL,CAAC,CAAC,MAAM;GACzB,IAAI,CAAC,OAAO,OAAO,KAAA;GACnB,MAAM,QAAQ,MAAM;GACpB,OAAO,UAAU,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK;EACvD;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,MAAM,MAAM,WAAW;GACvB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,2EAA2E;GACrG,MAAM,SAAS,MAAM,mBACnB,KAAK,WAAW,WAAW,kBAAkB,GAC7C,CAAC,gBAAgB,UAAU,GAAG,CAAC,GAC/B,KAAK,UAAU;IAAE,YAAY;IAAU,OAAO,KAAK;GAAM,CAAC,GAC1D,EAAE,KAAK,UAAU,CACnB;GACA,MAAM,SAAS,KAAK,MAAM,OAAO,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,EAAE,KAAK,IAAI;GAClE,IAAI,OAAO,OAAO,MAAM,IAAI,MAAM,2BAA2B,KAAK,GAAG,IAAI,OAAO,OAAO;GACvF,MAAM,QAAQ,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ;GAChE,OAAO;IACL,UAAU,OAAO,YAAY;IAC7B;IACA,QAAQ,KAAK,UAAU;KAAE,QAAQ,KAAK;KAAQ,OAAO,KAAK;KAAO,SAAS,OAAO;IAAQ,CAAC;GAC5F;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dabstep.js","names":[],"sources":["../../src/benchmarks/dabstep.ts"],"sourcesContent":["/**\n * DABStep adapter (EnvCommons/DABStep) — data-analysis questions over synthetic\n * payment files. Worker artifact = final answer text. Judge = the official\n * DABStep `grade.py` normalization/matching function. No LLM judge.\n *\n * Live tasks require `DABSTEP_DIR` pointing at an official DABStep checkout\n * (https://github.com/EnvCommons/DABStep) for `splits/*.txt`, `files/*`, and\n * `grade.py`, plus the released `dataset.csv` task rows — beside the checkout\n * or anywhere via `DABSTEP_DATASET_CSV`. The checkout does not ship\n * `dataset.csv`; see the preflight error text for where the rows come from.\n * The adapter exposes `metadata.resourceRoot` so runners can mount the\n * benchmark files into AgentProfile.resources.files; it does not paste the\n * dataset into prompt text.\n */\n\nimport { isAbsolute, join } from 'node:path'\nimport { access, readFile, stat } from 'node:fs/promises'\nimport type { OutputAdapter } from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot, runVenvPython, runVenvScriptStdin } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'dabstep.json')\nconst DEFAULT_SPLIT = 'easy'\n\ninterface DabstepFixtureRow {\n task_id: number\n instructions: string\n all_golds_by_task: Array<Record<string, unknown>>\n}\n\ninterface DabstepMeta {\n taskId: number\n split: string\n golds: Array<Record<string, unknown>>\n resourceRoot?: string\n}\n\nconst dabstepDir = (): string | undefined => process.env.DABSTEP_DIR\nconst gradeFile = (dir: string): string => join(dir, 'grade.py')\nconst resourceRoot = (dir: string): string => join(dir, 'files')\n\n/**\n * Where the released task rows come from. The EnvCommons/DABStep git checkout\n * carries grade.py, splits/, and files/ but not dataset.csv: the row file\n * (task_id,question,guidelines,all_golds_by_task) ships with the OpenReward\n * DABStep environment, mounted at /orwd_data/dataset.csv on that platform.\n * The public https://huggingface.co/datasets/adyen/DABstep release holds the\n * same task rows without golds (data/tasks/all.jsonl; answers withheld for the\n * leaderboard) and a 10-task dev split with reference answers\n * (data/tasks/dev.jsonl).\n */\nconst datasetAcquisitionHint =\n 'The DABStep checkout ships grade.py, splits/, and files/ but not dataset.csv. ' +\n 'dataset.csv (task_id,question,guidelines,all_golds_by_task) is distributed with the OpenReward DABStep environment ' +\n '(mounted at /orwd_data/dataset.csv on that platform); the public https://huggingface.co/datasets/adyen/DABstep release ' +\n 'carries the task rows without golds (data/tasks/all.jsonl) and a 10-task dev split with reference answers (data/tasks/dev.jsonl). ' +\n 'Place dataset.csv beside the checkout, or point DABSTEP_DATASET_CSV at it.'\n\n/** The released row file: `<dir>/dataset.csv`, or the `DABSTEP_DATASET_CSV` override so checkout and export can live apart. */\nfunction datasetFile(dir: string): string {\n const override = process.env.DABSTEP_DATASET_CSV\n if (override === undefined) return join(dir, 'dataset.csv')\n if (!isAbsolute(override)) throw new Error('DABSTEP_DATASET_CSV must be an absolute path')\n return override\n}\n\nasync function assertFile(path: string, label: string): Promise<void> {\n try {\n await access(path)\n } catch (err) {\n throw new Error(`DABStep: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nasync function assertOfficialFiles(dir: string, split: string): Promise<void> {\n const dataset = datasetFile(dir)\n try {\n await access(dataset)\n } catch (err) {\n throw new Error(\n `DABStep: missing released dataset.csv at ${dataset} (${err instanceof Error ? err.message : err}). ${datasetAcquisitionHint}`,\n )\n }\n await assertFile(join(dir, 'splits', `${split}.txt`), `${split} split file`)\n await assertFile(gradeFile(dir), 'official grade.py')\n const files = resourceRoot(dir)\n try {\n const s = await stat(files)\n if (!s.isDirectory()) throw new Error('not a directory')\n } catch (err) {\n throw new Error(`DABStep: missing benchmark files directory at ${files} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nexport const dabstepAnswerOutput: 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|answer)?\\s*\\n([\\s\\S]*?)```/g)]\n return (fences.at(-1)?.[1] ?? text).trim()\n },\n}\n\nfunction rowToTask(row: DabstepFixtureRow, split: string, dir?: string): BenchTask {\n const meta: DabstepMeta = {\n taskId: row.task_id,\n split,\n golds: row.all_golds_by_task,\n ...(dir ? { resourceRoot: resourceRoot(dir) } : {}),\n }\n return {\n id: String(row.task_id),\n split,\n prompt: [\n 'Solve this DABStep data-analysis task using the mounted payment files.',\n 'Use code or shell commands as needed, then return only the final answer.',\n '',\n row.instructions,\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): DabstepMeta {\n const md = task.metadata\n if (!md || typeof md.taskId !== 'number' || !Array.isArray(md.golds)) {\n throw new Error(`dabstep task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as DabstepMeta\n}\n\nfunction selectRows(rows: DabstepFixtureRow[], opts: LoadOptions, split: string, dir?: string): BenchTask[] {\n let tasks = rows.map((row) => rowToTask(row, split, dir))\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(`DABStep: no tasks matched ${JSON.stringify(opts)} for split=${split}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions, split: string): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as DabstepFixtureRow[]\n console.warn(`[dabstep] DABSTEP_FIXTURES=1 — loading ${rows.length} adapter fixtures from ${FIXTURES}`)\n return selectRows(rows, opts, split)\n}\n\nasync function loadOfficialTasks(dir: string, opts: LoadOptions, split: string): Promise<BenchTask[]> {\n const script = `\nimport ast, csv, json, sys\nfrom pathlib import Path\n\nroot = Path(sys.argv[1])\nsplit = sys.argv[2]\nlimit = None if sys.argv[3] == \"\" else int(sys.argv[3])\nids = set(json.loads(sys.argv[4]))\ndataset = Path(sys.argv[5])\nsplit_file = root / \"splits\" / f\"{split}.txt\"\nif not dataset.exists():\n raise SystemExit(f\"missing official DABStep dataset.csv at {dataset}; the checkout does not ship it — see the adapter preflight error for acquisition\")\nif not split_file.exists():\n raise SystemExit(f\"missing official DABStep split file at {split_file}\")\nsplit_ids = {int(line.strip()) for line in split_file.read_text().splitlines() if line.strip()}\nout = []\nwith dataset.open(newline=\"\") as f:\n for row in csv.DictReader(f):\n task_id = int(row[\"task_id\"])\n if task_id not in split_ids:\n continue\n if ids and str(task_id) not in ids:\n continue\n out.append({\n \"task_id\": task_id,\n \"instructions\": f\"{row['question']}\\\\n{row['guidelines']}\",\n \"all_golds_by_task\": ast.literal_eval(str(row[\"all_golds_by_task\"])),\n })\n if limit is not None and len(out) >= limit:\n break\nif not out:\n raise SystemExit(f\"no DABStep rows matched split={split} ids={sorted(ids)} limit={limit}\")\nprint(json.dumps(out))\n`\n const stdout = await runVenvPython(script, [\n dir,\n split,\n opts.limit === undefined ? '' : String(opts.limit),\n JSON.stringify(opts.ids ?? []),\n datasetFile(dir),\n ])\n return selectRows(JSON.parse(stdout) as DabstepFixtureRow[], opts, split, dir)\n}\n\nexport function createDabstepAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.DABSTEP_FIXTURES === '1'\n\n return {\n name: 'dabstep',\n output: dabstepAnswerOutput,\n\n async preflight() {\n if (fixturesMode) return\n const dir = dabstepDir()\n if (!dir) {\n throw new Error(\n 'DABSTEP_DIR is required. Fix: clone https://github.com/EnvCommons/DABStep and set DABSTEP_DIR=/path/to/DABStep. ' +\n datasetAcquisitionHint,\n )\n }\n await assertOfficialFiles(dir, DEFAULT_SPLIT)\n await loadOfficialTasks(dir, { limit: 1 }, DEFAULT_SPLIT)\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n const split = opts.split ?? DEFAULT_SPLIT\n if (fixturesMode) return loadFixtures(opts, split)\n const dir = dabstepDir()\n if (!dir) throw new Error('DABSTEP_DIR is required to load official DABStep tasks')\n return loadOfficialTasks(dir, opts, split)\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n const first = meta.golds[0]\n if (!first) return undefined\n const value = first.value\n return value === undefined ? undefined : String(value)\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const dir = dabstepDir()\n if (!dir) throw new Error('DABSTEP_DIR is required to judge DABStep tasks with the official grade.py')\n const stdout = await runVenvScriptStdin(\n join(benchRoot, 'scripts', 'dabstep_judge.py'),\n ['--grade-file', gradeFile(dir)],\n JSON.stringify({ prediction: artifact, golds: meta.golds }),\n { cwd: benchRoot },\n )\n const report = JSON.parse(stdout.trim().split('\\n').at(-1) ?? '{}') as { correct?: boolean; score?: number; error?: string }\n if (report.error) throw new Error(`DABStep judge error for ${task.id}: ${report.error}`)\n const score = typeof report.score === 'number' ? report.score : 0\n return {\n resolved: report.correct === true,\n score,\n detail: JSON.stringify({ taskId: meta.taskId, split: meta.split, correct: report.correct }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,MAAM,WAAW,KAAK,WAAW,YAAY,cAAc;AAC3D,MAAM,gBAAgB;AAetB,MAAM,mBAAuC,QAAQ,IAAI;AACzD,MAAM,aAAa,QAAwB,KAAK,KAAK,UAAU;AAC/D,MAAM,gBAAgB,QAAwB,KAAK,KAAK,OAAO;;;;;;;;;;;AAY/D,MAAM,yBACJ;;AAOF,SAAS,YAAY,KAAqB;CACxC,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,KAAA,GAAW,OAAO,KAAK,KAAK,aAAa;CAC1D,IAAI,CAAC,WAAW,QAAQ,GAAG,MAAM,IAAI,MAAM,8CAA8C;CACzF,OAAO;AACT;AAEA,eAAe,WAAW,MAAc,OAA8B;CACpE,IAAI;EACF,MAAM,OAAO,IAAI;CACnB,SAAS,KAAK;EACZ,MAAM,IAAI,MAAM,oBAAoB,MAAM,MAAM,KAAK,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,EAAE;CACtG;AACF;AAEA,eAAe,oBAAoB,KAAa,OAA8B;CAC5E,MAAM,UAAU,YAAY,GAAG;CAC/B,IAAI;EACF,MAAM,OAAO,OAAO;CACtB,SAAS,KAAK;EACZ,MAAM,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